使用来自js客户端的授权代码通过php从用户那里获取数据(离线访问)

时间:2019-02-03 17:19:27

标签: javascript php laravel google-api

我尝试使用google API js库通过php后端获取数据。

第一步,用户将通过前端的OAuth授权应用

const scopes = [
        'https://www.googleapis.com/auth/analytics',
        'https://www.googleapis.com/auth/analytics.readonly',
        'https://www.googleapis.com/auth/analytics.edit',
]

gapi.load('client:auth2', () => {
        this.gaAuth = gapi.auth2.init({
            client_id: '965399848242-skdqgktduruufpqtcuhvm9oqlpk21qq4.apps.googleusercontent.com',

            scope: scopes.join(' ')
        }).grantOfflineAccess().then(
            success => {

                // send and save authorization code to server/database

            },
            error => {
            });
    });

现在,我想使用授权代码通过php获取分析数据,该代码将从前端接收(请参见下面的代码)

  $googleClient = new Google_Client();
  $googleClient->setAuthConfig(storage_path('google/client_secret.json'));
  $googleClient->fetchAccessTokenWithAuthCode($authorizationCodeFromFrontend);

  $googleClient->setScopes([
        'https://www.googleapis.com/auth/analytics.readonly',
        'https://www.googleapis.com/auth/analytics.edit',
        'https://www.googleapis.com/auth/analytics'
   ]);

  $analyticsClient = new Google_Service_Analytics($googleClient); 

  return response()->json($analyticsClient
            ->management_accounts
            ->listManagementAccounts()
            ->getItems());

但是我收到以下错误消息:

{"error":{"errors":[{"domain":"global","reason":"required","message":"Login Required","locationType":"header","location":"Authorization"}],"code":401,"message":"Login Required"}}

编辑: 经过一些调试后,我发现我从 fetchAccessTokenWithAuthCode 方法中收到错误:

 'error' => 'invalid_grant',
 'error_description' => 'Bad Request', 

0 个答案:

没有答案