401尝试访问PHP中的Google搜索控制台API时凭据无效

401尝试访问PHP中的Google搜索控制台API时凭据无效,php,laravel,api,google-search-console,Php,Laravel,Api,Google Search Console,我正在尝试在Laravel中设置Google搜索控制台API,我正在努力让它与我新生成的凭据一起工作。我在控制台中设置了一个API密钥,并将其插入到代码中,但是在尝试获取数据时,应用程序返回401无效凭据。我觉得自己真的很愚蠢,因为我认为复制API密钥并将其插入到代码中就可以了。从搜索控制台API验证和检索数据需要哪个密钥 我尝试设置一个新的API密钥,并在setAccessToken字段中使用该密钥。我甚至尝试设置OAuth2.0并使用这些凭据进行身份验证。程序似乎在“setAccessTok

我正在尝试在Laravel中设置Google搜索控制台API,我正在努力让它与我新生成的凭据一起工作。我在控制台中设置了一个API密钥,并将其插入到代码中,但是在尝试获取数据时,应用程序返回
401无效凭据
。我觉得自己真的很愚蠢,因为我认为复制API密钥并将其插入到代码中就可以了。从搜索控制台API验证和检索数据需要哪个密钥

我尝试设置一个新的API密钥,并在setAccessToken字段中使用该密钥。我甚至尝试设置OAuth2.0并使用这些凭据进行身份验证。程序似乎在“setAccessToken”处崩溃。我应用的唯一其他键是开发者键(
$client->setDeveloperKey()

公共静态函数debugSiteData(){
//日期(YYYY-mm-DD)
$fromDate=日期('Y-m-d',标准时间('-3个月');
$toDate=日期('Y-m-d',标准时间('-1天');
$client=新的Google_客户端();
$client->setApplicationName(“应用程序名称”);
$client->setDeveloperKey('AIza(…)');
$client->addScope(Google\u服务\u网站管理员::网站管理员\u只读);
$webmaster=新谷歌服务\网站管理员($client);
$searchConsole=新的SearchConsoleClient($client);
$searchConsole->setAccessToken(“访问令牌”);
//$debugData=var_导出($searchConsole);
$search=new\Google\u服务\u网站管理员\u SearchAnalyticsQueryRequest();
$search->setStartDate($fromDate);
$search->setEndDate($toDate);
$console=$webmaster->urlcawlerrorscounts->query('http://www.website.com/,数组())->getCountPerTypes();
返回“.$console.”;
$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);
}
}

使用上面的方法,我得到了一个
401无效凭证
错误。我觉得这是一件非常简单的事情,但我现在似乎无法理解。

使用Oauth触发Google API是一个好主意,在您的情况下,您需要在Oauth回调后将凭据存储在数据库中,
访问令牌
刷新令牌
过期
,然后您需要使用这些凭据来使用GoogleAPI的


使用Oauth触发Google API是一个好主意,在您的情况下,您需要在Oauth回调、
access\u token
refresh\u token
expires\u 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);
}