我正在尝试在Drupal网站上使用Google索引API。我不断收到403拒绝权限错误。
我已经启用了API,创建了服务帐户,使用meta标签验证了网站所有权,为服务帐户设置了所有者权限,并下载了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();
答案 0 :(得分:1)
我已经找到问题的答案了,所以我将在这里发布答案。令我恼火的是,它未通过身份验证是因为我在Google控制台中注册了http://url而不是https://url。因此它不承认我是该网站的所有者。该代码很好,只需进行四次检查即可确保您正确注册了服务帐户。