401 嘗試在 PHP 中存取 Google Search Console API 時的遺憾无效



>我正在尝试在Laravel中设置Google Search Console API,但我正在努力使其与我新生成的凭据一起工作。我已经在控制台中设置了一个 API 密钥并将其插入到我的代码中,但是在尝试获取数据时,应用程序返回401 Invalid credentials.我为无法让它工作而感到非常愚蠢,因为我假设复制 API 密钥并将其插入我的代码中就可以完成这项工作。从 Search Console API 验证和检索数据需要哪个密钥?

我尝试设置一个新的API密钥并在setAccessToken字段中使用该密钥。我甚至尝试设置 Oauth 2.0 并使用这些凭据进行身份验证。似乎程序在"setAccessToken"处崩溃。我应用的唯一另一个密钥是开发人员密钥($client->setDeveloperKey())

public static function debugSiteData() {
// Dates (YYYY-mm-DD)
$fromDate = date('Y-m-d', strtotime('-3 months'));
$toDate = date('Y-m-d', strtotime('-1 day'));
$client = new Google_Client();
$client->setApplicationName("application_name");
$client->setDeveloperKey('AIza(...)');
$client->addScope(Google_Service_Webmasters::WEBMASTERS_READONLY);
$webmaster = new Google_Service_Webmasters($client);
$searchConsole = new SearchConsoleClient($client);
$searchConsole->setAccessToken("ACCESS TOKEN"); 
// $debugData = var_export($searchConsole);
$search = new Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$search->setStartDate($fromDate);
$search->setEndDate($toDate);
$console = $webmaster->urlcrawlerrorscounts->query('http://www.website.com/', array())->getCountPerTypes();
return '<pre>' . $console . '</pre>';
}

使用上面的方法,我收到一个401 Invalid credentials错误。我觉得这是一件非常简单的事情,但我现在似乎无法弄清楚。

使用 Oauth 是触发 Google API 的好主意,在您的情况下,您需要在 Oauth 回调、access_tokenrefresh_tokenexpires_in之后将凭据存储在数据库中,然后您需要使用这些凭据来使用 Google API 的

$client = new Google_Client();
// Set Client Id (From Google Cloud Console)
$client->setClientId($client_id);
// Set Client Secret (From Google Cloud Console)
$client->setClientSecret($client_secret);
// Set Access Token With Oauth credentials (form DB)
$client->setAccessToken([
'access_token'  => $token, 
'refresh_token' => $refresh_token,
'expires_in'    => $expires_in
]);
// Check if the access token is expired
if ($client->isAccessTokenExpired()) {
// This will refresh the token automatically
$token = $client->refreshToken(null);
$this->setAccessToken($token);
}

最新更新