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

时间:2014-11-18 19:42:45

标签: php authentication oauth google-sheets token

我正在构建一个服务器端应用程序,需要使用Google Spreadsheets API进行身份验证并从中读取数据。将此PHP clientGoogle APIs client一起使用。

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

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

我遇到的问题是,在文档的this section中,使用了$accessToken变量,我无法生成该变量。我在Google Developers Console中创建了一个项目,并使用服务帐户客户端ID创建了oAuth 2.0凭据。因此,我收到了两个文件 - JSON and p12,以及CLIENT IDEMAIL ADDRESSPUBLIC KEY FINGERPRINTS凭据,我不知道如何使用这些凭据授权令牌。

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

authenticate中的OAuth2.php方法需要$code变量,我不知道该变量,也不知道如何获取。

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

这对我有用:

$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文件的位置。

我希望这能帮助处于类似情况的人。