Php 如何使用Drupal站点上的服务帐户验证google索引

Php 如何使用Drupal站点上的服务帐户验证google索引,php,drupal,google-api-php-client,google-indexing-api,Php,Drupal,Google Api Php Client,Google Indexing Api,我试图在Drupal站点上使用google索引API。我一直收到一个403权限被拒绝的错误 我启用了API,创建了一个服务帐户,使用meta标记验证了站点所有权,设置了服务帐户的所有者权限,并下载了GoogleAPI php客户端库,使事情变得更简单。我把php文件放在服务器上。当我转到页面时,我得到一个403错误。拒绝许可 require_once DRUPAL_ROOT . '/google-api-php-client/vendor/autoload.php'; //Set up ser

我试图在Drupal站点上使用google索引API。我一直收到一个403权限被拒绝的错误

我启用了API,创建了一个服务帐户,使用meta标记验证了站点所有权,设置了服务帐户的所有者权限,并下载了GoogleAPI php客户端库,使事情变得更简单。我把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()方法,如谷歌文档所示:

下面是遵循GoogleAPI的替代代码

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();

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

当我转到页面时@代码所在的php页面。它只是回显$status\u代码让我看到。不幸的是,它一直返回403:(您是否检查了
DRUPAL\u ROOT./myjsonfile.json'
是否可以被您的脚本读取(文件权限)?@EricLavault当我检查函数file\u exists()和is\u readable(),我会发现json文件存在并且是可读的。