1

我最近与 Google 商家产品取得联系,将我所有的网站产品同步到 Google Merchant。当我按照 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');

但它不起作用Жшt仍然需要我登录。

4

2 回答 2

1

您想为此使用服务帐户

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

于 2015-04-09T02:28:02.967 回答
1

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

先决条件

  1. 安装可在此处下载的“Content API for Shopping”库。有关安装,请参见此处
  2. 创建您的服务帐户。在这里您将找到完整的程序。

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

正如谷歌所建议的:

重要提示:保护 *.json 密钥文件,该文件允许服务帐户访问已获得授权的 Google 服务。允许服务帐户每个只能访问一个 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
}

该代码已经过测试并且可以工作。

于 2021-03-20T10:59:47.533 回答