首页 > 解决方案 > 访问google pay api for pass时如何解决身份验证错误?

问题描述

我一直在按照此处此处的步骤尝试使用服务帐户密钥文件来访问 Google pay api 并插入 LoyaltyClass。Google Pay 库建议使用 1.1.1 版的 Google api 客户端库,这就是我在这里所做的:

$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/wallet_object.issuer');
$client->setApplicationName("Test");
$client->setDeveloperKey("My service account key");
$test_class = new LoyaltyClass;
$service = new Google_Service_Walletobjects($client);
$wallet_object = $test_class->create_wallet_class();
$service->loyaltyclass->insert($wallet_object);

我得到这个错误:

PHP Fatal error:  Uncaught Google_Service_Exception: Error calling POST https://www.googleapis.com/walletobjects/v1/loyaltyClass?key=2ee78c76d17cabcdce22c4e89af27ab73ad694a4: (401) Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. in /var/www/html/google-api-php-client/src/Google/Http/REST.php:76

云 api 控制台记录我已经使用正确的服务帐户访问了 api,但没有记录任何请求。他们建议的链接指示我提示用户登录,但我想在没有用户输入的情况下访问这个 api,只是我的服务帐户。有没有办法做到这一点?

标签: phpgoogle-pay

解决方案


你供应setDeveloperKey什么?

文档使用setAuthConfigFile而不是setDeveloperKey

$client = new Google_Client();
$client->setApplicationName('Wallet Objects App');
$client->setScopes(array('https://www.googleapis.com/auth/wallet_object.issuer'));
$client->setAuthConfigFile('/example/path/to/privatekey.json');

有一个GitHub 示例项目Google_Client,它使用以下代码初始化该类:

$this->client = new Google_Client();

// do OAuth2.0 via service account file.
// See https://developers.google.com/api-client-library/php/auth/service-accounts#authorizingrequests
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . SERVICE_ACCOUNT_FILE); // for Google_Client() initialization for server-to-server
$this->client->useApplicationDefaultCredentials();
// Set application name.
$this->client->setApplicationName(APPLICATION_NAME);
// Set Api scopes.
$this->client->setScopes(array(SCOPES));

SEVICE_ACCOUNT_FILE中定义Config.php

如果您想要与 Passes API 集成的分步教程,您可以遵循一个代码实验室:https ://codelabs.developers.google.com/passes-loyaltyapi

它是为 NodeJS 编写的,但大多数概念仍应适用于 PHP。

编辑:更新以参考setAuthConfigFileGoogle Pay 开发者网站。

编辑:更新以包含来自 GitHub 的 PHP 示例代码


推荐阅读