401 尝试访问 PHP 中的 Google Search Console API 时凭据无效

401 Invalid credentials when trying to reach the Google Search Console API in PHP

我正在尝试在 Laravel 中设置 Google Search Console API,但我正在努力让它与我新生成的凭据一起使用。我在控制台中设置了一个 API 键并将其插入到我的代码中,但是在尝试获取数据时应用程序 returns 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 APIs 的好主意,在您的情况下,您需要在 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);
}