1

我正在尝试在 Drupal 网站上使用谷歌索引 API。我不断收到 403 权限被拒绝错误。

我启用了 API,创建了一个服务帐户,使用元标记验证了网站所有权,为服务帐户设置了所有者权限,并下载了 google-api-php-client 库以使事情变得更容易。我把php文件放在服务器上。当我转到该页面时,我收到 403 错误。没有权限。

require_once DRUPAL_ROOT . '/google-api-php-client/vendor/autoload.php';

//Set up service account credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS='. DRUPAL_ROOT . '/myjsonfile.json');

$client = new Google_Client();

// service_account_file.json is the private key that you created for your service account.
//-----USING DEFAULT CREDENTIALS SET BY JSON FILE INSTEAD-----
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/indexing');

// Get a Guzzle HTTP Client
$httpClient = $client->authorize();
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';

// Define contents here. The structure of the content is described in the next step.
$content = "{
  \"url\": \"urlToUpdate\",
  \"type\": \"URL_UPDATED\"
}";

$response = $httpClient->post($endpoint, [ 'body' => $content ]);
$status_code = $response->getStatusCode();

编辑:我也尝试过使用 $client->setAuthConfig() 方法,如此处显示的 googles 文档所示:Google indexing api

这是google api之后的替代代码

require_once DRUPAL_ROOT . '/google-api-php-client/vendor/autoload.php';

$client = new Google_Client();

// service_account_file.json is the private key that you created for your service account.
$client->setAuthConfig('myjsonfile.json');
$client->addScope('https://www.googleapis.com/auth/indexing');

// Get a Guzzle HTTP Client
$httpClient = $client->authorize();
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';

// Define contents here. The structure of the content is described in the next step.
$content = "{
  \"url\": \"urlToUpdate\",
  \"type\": \"URL_UPDATED\"
}";

$response = $httpClient->post($endpoint, [ 'body' => $content ]);
$status_code = $response->getStatusCode();
4

1 回答 1

1

不久前我已经找到了我的问题的答案,所以我将在这里发布答案。令我愤怒的是,它没有进行身份验证的原因是因为我在谷歌控制台中注册了http://url而不是https://url。所以它不承认我是该网站的所有者。代码很好,只需四次检查以确保您正确注册了服务帐户。

于 2019-08-13T18:56:19.880 回答