微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Fat Free 使用 Google OAuth + Google API

如何解决Fat Free 使用 Google OAuth + Google API

我正在尝试以下事情很长一段时间并且正在努力挣扎......

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

$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 请求应该给我想要的结果:

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”......但是,它抛出了一个错误,说“请求没有足够的身份验证范围”...这似乎是因为在检查 Google 的 PHP 示例时,我必须提供我正在使用的范围 - 在我的情况下为 https://www.googleapis.com/auth/youtube.readonly

Google 提供的 PHP 代码如下:

<?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 安装 Google Client 并尝试使用 vendor/autoload.PHP 以使用该类......但是,当包含 autoload.PHP 时,我收到错误 Fatal error: Cannot declare class Prefab,because the name is already in use......这似乎是这种情况,因为 {{ 1}} 已经声明了这个 Prefab 类,然后 f3-opauth 尝试再次声明它......但是,我没有设法在没有自动加载的情况下包含 Google Apiclient......

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

>

任何有关如何使其工作的提示都将不胜感激 - 如果有任何关于以完全不同的方式进行操作的提示,我也愿意更改它,因为项目本身才刚刚开始。

总而言之,我正在尝试做的是以下内容: -> 用户可以使用他的 Youtube/Google 帐户登录网站 -> 验证时,检查用户是否是特定频道的订阅者。下一步还要检查他是否是该特定频道的频道成员。这两个信息都需要保存到数据库

-> 之后,用户总是可以再次登录他的 Google 帐户,并且在数据库中,您可以找到该用户是否是该频道的订阅者和/或频道成员的信息..

提前致谢!

解决方法

我不确定这是否对您的具体用例有帮助,但我过去曾使用 Fat-Free 使用过 Google API。我无法立即让它工作,所以我安装了它并让它与 Google Client/API/SDK 一起工作。一旦我开始工作,然后我向后工作,看看我是否可以让它与 Fat-Free 一起工作。我注意到我遇到的一件事是 Oauth 请求中缺少字段。 access_type 是一个让我和 approval_prompt 一样的人。我知道你说到目前为止你已经获得了访问令牌,所以它可能不适用,但它可以用于未来的请求。下面是一些示例代码,我正在为 Google Sign in 生成一个 oauth URL,然后处理请求并调用 userinfo 部分。

<?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',$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) 如果我没记错的话)所以我们需要让我们的数据库字段更长,以便它可以存储整个内容。

希望其中之一能触发某些事情让您找出问题所在。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。