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.

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料