如何使用 Google 的 OAuth API 为用户获取 API 密钥?

How to get API key for user using Google's OAuth API?

也许我不明白 Youtube 数据 API 应该如何工作。但是如果我有一个 PHP 应用程序将生成 oauth 请求并接收回调(我有),它发回的数据不是用户的 API 密钥。

所以我不知道我是不是做错了,或者是什么,但是他们的文档让我很头疼,我搜索了又搜索,我什至不知道我的流程是否在这里:

Web 服务器/OAuth 请求(php)

require_once 'vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig('oauth.json');
$client->setAccessType("offline");        // offline access
$client->setIncludeGrantedScopes(true);   // incremental auth
$client->addScope(Google_Service_YouTube::YOUTUBE_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');

$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

客户授权我的申请

Google 发回(不管这是什么)

  'code' => string 'BLABLABLABLABLA' (length=89)
  'scope' => string 'https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile' (length=224)

用户的 API 密钥在哪里,如何获取?这是不正确的,还是我只是把东西弄乱了?

您在使用 OAuth 时不会获得 API 密钥。你得到一个访问令牌。 API 密钥是从用户的 Google 开发者控制台获得的。

查看 PHP Quickstart 以获取 PHP 中的快速 Youtube API OAuth 参考。

您的 oauth2callback.php 应该看起来像这样。它将获取代码并将其交换为访问令牌。

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

代码从我在 github

上的示例项目中删除