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

如何解决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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!