如何通过编程获取访问令牌,用PHP将API调用发送到Google商家中心(Google Shopping)


How to programmatically get the access token to send API call to Google Merchant Center (Google Shopping) with PHP?

我最近与谷歌商家产品取得了联系,将我的所有网站产品同步到谷歌商家中。当我遵循API文档的结构时https://developers.google.com/shopping-content/v2/quickstart到授权部分,我复制他们的库并复制要使用的示例代码。它确实有效!然而,当我进行测试以加载该身份验证页面时,它要求我登录到开发人员帐户以获取访问令牌并将其保存到会话中。

有没有可能我可以跳过登录部分自动进行,然后我可以做玉米系统每小时运行一次同步(更新产品的详细信息)?

我尝试将我的帐户登录API密钥硬入我的代码中,如下所示:

$client = new Google_Client();
$client->setApplicationName('Sample Content API application');
//add my api key here
$client->setDeveloperKey(MY_API_KEY);
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('YOUR_REDIRECT_URI');
$client->setScopes('https://www.googleapis.com/auth/content');

但它不起作用,仍然需要我登录。

您需要为此使用服务帐户。

Google OAuth 2.0系统支持服务器到服务器的交互,例如web应用程序和Google服务之间的交互。对于这种情况,您需要一个服务帐户,该帐户属于您的应用程序,而不是单个最终用户。您的应用程序代表服务帐户调用GoogleAPI,因此用户不会直接参与其中。这种情况有时被称为"两条腿的OAuth"或"2LO"。(相关术语"三条腿的OAauth"指的是应用程序代表最终用户调用Google API的情况,有时需要用户同意。)

下面是一个使用PHP通过服务帐户进行身份验证的工作示例。

先决条件

  1. 安装";用于购物的内容API"库,您可以在这里下载。有关安装,请参见此处
  2. 创建您的服务帐户。在这里你可以找到完整的程序

此时,您将获得身份验证所需的JSON文件

如谷歌建议:

重要:保护允许服务帐户的*.json密钥文件访问其已获得授权的谷歌服务。是的允许服务帐户只访问一个Google API的良好做法每个这是一种预防措施,可以减少攻击者可以在服务帐户的*.json密钥文件被泄露。

您现在可以使用以下函数来获取API调用的访问令牌:

// gets access token for API call to Google Merchant Center
function gets_access_token_for_API_call() {
    // load the "Google APIs Client Library for PHP"
    require_once ( '/path/to/google-api-php-client/vendor/autoload.php' );
    // gets the JSON key of the service account
    $credentialsFilePath = '/path/to/merchant-center-123456789-987654321.json';
    $client = new Google_Client();
    $client->setAuthConfig($credentialsFilePath);
    $client->addScope( 'https://www.googleapis.com/auth/content' );
    // fetches a fresh access token with a given assertion token.
    $client->fetchAccessTokenWithAssertion(); // the deprecated alias: "refreshTokenWithAssertion()"
    $token = $client->getAccessToken();
    return $token;
}

返回的结果将是一个类似于的数组

{
    "access_token": "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
    "scope": "https://www.googleapis.com/auth/content"
    "token_type": "Bearer",
    "expires_in": 3600
}

该代码已经过测试并运行