dongyan1548
2014-11-18 19:42
浏览 55
已采纳

如何解决oAuth 2.0 Google Spreadsheets身份验证问题?

I'm building a server-side application that would need to authenticate with Google Spreadsheets API and read data from it. Using this PHP client with Google APIs client.

What I need to do is to authenticate with Google without user interaction.

Installed everything with composer and loaded with autoloader.php.

The problem I'm having is, in this section of the documentation, an $accessToken variable is used which I can't generate. I created a project in Google Developers Console and oAuth 2.0 credentials with service account client ID. As a result, I got two files - JSON and p12, alongside with the CLIENT ID, EMAIL ADDRESS and PUBLIC KEY FINGERPRINTS credentials, which I don't know how to use to obtain the authorization token.

Also, I'm facing a redirect_uri_mismatch error and I can't set it up in Google Developers Console.

The authenticate method in OAuth2.php is requiring a $code variable which I don't have and don't know how to obtain.

If I could obtain that $accessToken variable, I could try to debug further.

Any help is highly appreciated.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzaizai2015 2014-11-18 20:22
    已采纳

    This is what worked for me:

    $client = new Google_Client();
    $client->setApplicationName(GOOGLE_APPLICATION_NAME);
    $client->setClientId(GOOGLE_CLIENT_ID);
    
    $key = file_get_contents(GOOGLE_KEY_FILE);
    $cred = new Google_Auth_AssertionCredentials(
        GOOGLE_CLIENT_EMAIL,
        array(GOOGLE_SPREADSHEETS_URL),
        $key
    );
    
    $client->setAssertionCredentials($cred);
    
    if($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    
    $service_token = json_decode($client->getAccessToken());
    $accessToken = $service_token->access_token;
    
    use Google\Spreadsheet\DefaultServiceRequest;
    use Google\Spreadsheet\ServiceRequestFactory;
    
    $serviceRequest = new DefaultServiceRequest($accessToken);
    ServiceRequestFactory::setInstance($serviceRequest);
    
    $spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
    $spreadsheetFeed = $spreadsheetService->getSpreadsheets();
    

    GOOGLE_SPREADSHEETS_URL is https://spreadsheets.google.com/feeds and GOOGLE_KEY_FILE is the location of your XXX.p12 file.

    I do hope this will help somebody in a similar situation.

    点赞 评论

相关推荐 更多相似问题