【问题标题】:How to resolve oAuth 2.0 Google Spreadsheets authentication issue?如何解决 oAuth 2.0 Google 电子表格身份验证问题?
【发布时间】:2014-11-18 19:42:45
【问题描述】:

我正在构建一个需要通过 Google 电子表格 API 进行身份验证并从中读取数据的服务器端应用程序。将此PHP client 与Google APIs client 一起使用。

我需要做的是在没有用户交互的情况下通过 Google 进行身份验证。

使用composer 安装所有内容并使用 autoloader.php 加载。

我遇到的问题是,在文档的this section 中,使用了我无法生成的$accessToken 变量。我在 Google Developers Console 中创建了一个项目,并使用服务帐户客户端 ID 创建了 oAuth 2.0 凭据。结果,我得到了两个文件 - JSON and p12,以及 CLIENT ID、EMAIL ADDRESS 和 PUBLIC KEY FINGERPRINTS 凭据,我不知道如何使用它们来获取授权令牌。

另外,我遇​​到了redirect_uri_mismatch 错误,我无法在 Google Developers Console 中进行设置。

OAuth2.php 中的 authenticate 方法需要一个 $code 变量,我没有并且不知道如何获得。

如果我能获得$accessToken 变量,我可以尝试进一步调试。

非常感谢任何帮助。

【问题讨论】:

    标签: php authentication oauth google-sheets token


    【解决方案1】:

    这对我有用:

    $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 是 https://spreadsheets.google.com/feeds,GOOGLE_KEY_FILE 是您的 XXX.p12 文件的位置。

    我确实希望这会对处于类似情况的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 2022-08-04
      • 2012-11-08
      • 2014-12-24
      • 1970-01-01
      相关资源
      最近更新 更多