首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >免费使用谷歌OAuth +谷歌API

免费使用谷歌OAuth +谷歌API
EN

Stack Overflow用户
提问于 2021-01-04 05:14:18
回答 1查看 216关注 0票数 0

我尝试下面的事情已经很长一段时间了,并且非常挣扎……

在一个网站上,我首先想使用OAuth验证一个用户的谷歌帐户。因此,我使用的是this库。为了使其正常工作,我使用$f3->set('AUTOLOAD','vendor/ikkez/f3-opauth/lib/opauth/');加载PHP文件,然后使用以下代码创建路由并使身份验证成为可能:

代码语言:javascript
运行
复制
$f3 = \Base::instance();
// load opauth config (allow token resolve)
$f3->config('vendor/ikkez/f3-opauth/lib/opauth/opauth.ini', TRUE);

// init with config
$opauth = OpauthBridge::instance($f3->opauth);

// define login handler
$opauth->onSuccess(function($data){
    header('Content-Type: text');

    //$data['credentials']['token'];
});

// define error handler
$opauth->onAbort(function($data){
    header('Content-Type: text');
    echo 'Auth request was canceled.'."\n";
    print_r($data);
});

到目前为止,一切都很好,一旦从Google获得许可,我就会得到正确的回调,还包括登录令牌。

现在下一步是,在用户允许之后(通过身份验证),我想检查用户是否订阅了Youtube上的特定频道(然后将该信息保存到我的数据库中,不过在第一步打印它就足够了)。

现在我做了好几个小时的功课,试图弄清楚它是如何工作的……

我(通常发现)下面的curl请求应该会给出我想要的结果:

代码语言:javascript
运行
复制
curl \
  'https://youtube.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&forChannelId=UC_x5XG1OV2P6uZZ5FSM9Ttw&mine=true&key=[YOUR_API_KEY]' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --compressed

然后,我尝试用PHP发送这个curl请求,用我的Google API密钥替换API键,用我从OAUTH得到的令牌替换"YOUR_ACCESS_TOKEN“。然而,它抛出了一个错误,说“请求没有足够的身份验证作用域”...这似乎是因为在检查来自谷歌的PHP示例时,我必须提供我正在使用的作用域--在我的例子中是https://www.googleapis.com/auth/youtube.readonly

Google提供的PHP代码如下:

代码语言:javascript
运行
复制
<?php

/**
 * Sample PHP code for youtube.subscriptions.list
 * See instructions for running these code samples locally:
 * https://developers.google.com/explorer-help/guides/code_samples#php
 */

if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
    'https://www.googleapis.com/auth/youtube.readonly',
]);

// TODO: For this request to work, you must replace
//       "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
//       client_secret.json file. For more information, see
//       https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('YOUR_CLIENT_SECRET_FILE.json');
$client->setAccessType('offline');

// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:\n%s\n", $authUrl);
print('Enter verification code: ');
$authCode = trim(fgets(STDIN));

// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);

// Define service object for making API requests.
$service = new Google_Service_YouTube($client);

$queryParams = [
    'forChannelId' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw',
    'mine' => true
];

$response = $service->subscriptions->listSubscriptions('snippet,contentDetails', $queryParams);
print_r($response);

这让我遇到了一个新的问题。尝试使用此代码时,我遇到错误,Google_Client不是已知的类……然后,我使用Composer安装了谷歌客户端,并尝试使用vendor/autoload.php来使用这个类……但是,当包含autoload.php时,我得到错误Fatal error: Cannot declare class Prefab, because the name is already in use...看起来是这样的,因为f3-opauth已经声明了这个Prefab类,然后google apiclient尝试再次声明它……然而,在没有自动加载的情况下,我没有设法包括google apiclient ...

你看,我真的试了很多,今天我已经为此工作了大约5-6个小时,只得到了一个API请求,我不知道还可以尝试什么……

任何关于如何让它工作的提示都将不胜感激--如果有任何关于以一种完全不同的方式完成它的提示,我也愿意改变它,因为项目本身才刚刚开始。

综上所述,我试图做的是:->用户可以登录网站与他的Youtube/谷歌帐户->认证时,它被选中,如果用户是一个特定渠道的订阅者。下一步还将检查他是否是该特定频道的频道成员。这两个信息都需要保存到数据库中

->之后,用户始终可以再次登录到他在谷歌的帐户,并在数据库中,您可以找到信息,如果用户是该渠道的订阅者和/或渠道成员。

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2021-01-05 00:04:45

我不确定这是否会对你的实际用例有所帮助,但我过去曾使用过Google API和Fat-Free。我不能马上让它工作,所以我安装了它,并用Google客户端/API/SDK让它工作。一旦我让它工作,然后我反向工作,看看我是否可以用Fat-Free使它工作。我注意到我遇到的一件事是在Oauth请求中缺少字段。和approval_prompt一样,access_type也让我着迷。我知道你说到目前为止你已经得到了你的访问令牌,所以它可能不适用,但它可以用于未来的请求。下面是我为Google登录生成oauth URL的一些示例代码,然后处理请求并调用userinfo部分。

代码语言:javascript
运行
复制
<?php 

class App_Auth {
    public static function generateOauthUrl() {
        $fw = Base::instance();
        $Oauth = new \Web\OAuth2();
        $Oauth->set('client_id', $fw->get('google.client_id'));
        $Oauth->set('scope', 'profile email');
        $Oauth->set('response_type', 'code');
        $Oauth->set('access_type', 'online');
        $Oauth->set('approval_prompt', 'auto');
        $Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
        return $Oauth->uri('https://accounts.google.com/o/oauth2/auth', true);
    }

    public static function processAuthCodeAndGetToken($auth_code) {
        $fw = Base::instance();
        $Oauth = new \Web\OAuth2();
        $Oauth->set('client_id', $fw->get('google.client_id'));
        $Oauth->set('client_secret', $fw->get('google.client_secret'));
        $Oauth->set('scope', 'profile email');
        $Oauth->set('access_type', 'online');
        $Oauth->set('grant_type', 'authorization_code');
        $Oauth->set('code', $auth_code);
        $Oauth->set('approval_prompt', 'auto');
        $Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
        return $Oauth->request('https://oauth2.googleapis.com/token', 'POST');
    }

    public static function getOauthUserInfo($access_token) {
        $Oauth_User_Info = new \Web\OAuth2();
        return $Oauth_User_Info->request('https://www.googleapis.com/oauth2/v2/userinfo', 'GET', $access_token);
    }

另一个让我头疼的错误是,我们将从Google获取访问令牌,然后将其存储在数据库中,以供后续请求使用。我们会得到你提到的request had insufficient authentication scopes的作用域错误。我们最终发现access_token比我们的数据库字段更长(如果我没记错的话,是VARCHAR(32)),所以我们需要让数据库字段更长,这样它才能存储整个内容。

希望其中的一个能让你解决你的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65555002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档