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.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化