【发布时间】:2019-11-05 11:56:17
【问题描述】:
我正在构建一个小工具来一次管理多个 GMB 位置,但我遇到了 google php api client 的问题。
我正在从我的数据库中获取多个用户/位置的访问令牌,并希望循环更新它们,但 google php api 客户端在第二次使用 setAccesstoken 的请求中没有更改使用的访问令牌。
第一次循环之后的每次运行都将继续使用第一次运行的访问令牌,即使getAccesstoken() 返回正确的访问令牌。似乎内部使用的 GuzzleClient 没有更新以将新令牌用于下一个请求。
不幸的是,我找不到强制 sdk 更新 GuzzleClient 或重新创建它的方法。我希望你能帮助我。
foreach($this->getLocationsToUpdate() as $location){
$oldAccessToken = $this->google->getClient()->getAccessToken();
$placeData = $this->places->getFullPathAndToken($location);
if($placeData !== null){
try{
//only sets the token correct on the first run.
$this->google->setAccessToken($placeData['access_token']);
$this->updateReviews($placeData);
$this->updateQuestions($placeData);
$this->updateMedia($placeData);
// returns the correct token, but api requests in the methods above fail, since the auth header from the guzzle requests still use the token from the first run.
var_dump($this->google->getClient()->getAccessToken());
$this->google->setAccessToken($oldAccessToken);
}catch(\Exception $e){
$this->google->setAccessToken($oldAccessToken);
}
}
}
编辑:
我做了另一个例子来从我自己的代码中删除所有变量。请求 1 工作正常,请求 2 失败,因为它仍然使用 $token1,如果我删除请求 1,请求 2 工作正常。
<?php
define('BASE_DIR', dirname(__FILE__));
require_once BASE_DIR.'/vendor/autoload.php';
$token1 = '.....';
$token2 = '.....';
$name1 = 'accounts/115224257627719644685/locations/12065626487534884042';
$name2 = 'accounts/115299736292976731655/locations/295582818900206145';
$client = new \Google_Client();
$client->setAuthConfig(BASE_DIR.'/Config/Google/credentials.json');
$client->setRedirectUri('https://...../login/callback.html');
$client->setAccessType("offline");
$client->setPrompt('consent');
$client->addScope(\Google_Service_Oauth2::USERINFO_EMAIL);
$client->addScope(\Google_Service_Oauth2::USERINFO_PROFILE);
$client->addScope("https://www.googleapis.com/auth/plus.business.manage");
// Request 1
$client->setAccessToken($token1);
$gmb = new \Google_Service_MyBusiness($client);
$media = $gmb->accounts_locations_media->listAccountsLocationsMedia($name1);
var_dump($media);
// Request 2 -- Fails because it still uses $token1
$client->setAccessToken($token2);
$gmb = new \Google_Service_MyBusiness($client);
$media = $gmb->accounts_locations_media->listAccountsLocationsMedia($name2);
var_dump($media);
【问题讨论】:
-
看起来(在google客户端的
getHttpClient()方法中)更改令牌后没有重新创建guzzle客户端,我没有找到任何可以强制客户端重置它的方法。我认为谷歌客户端不是为使用这种方式而设计的。您是否尝试为每个用户/令牌创建一个新的谷歌客户端实例?它会不那么优雅,但它可能会工作.. -
创建新实例工作正常,但会产生我想避免的不必要的开销,我来自 facebook php sdk,它可以轻而易举地处理 accesstoken 更改。
-
在设置新的访问令牌后尝试调用客户端
authorize方法。我不完全确定,但看起来它正在使用当前的访问令牌。像这样:$client->setAccessToken($token2); $client->authorize(null); -
authorize()从getHttpClient()获取它的http 客户端,getHttpClient()一旦设置就返回$this->http,所以不幸的是无法通过这种方式重新生成使用过的http客户端,设置一个新的访问令牌应该只需设置$this->http = null;,一切都会好起来,并在再次需要时重新生成。 -
所以授权方法中的这一行没有任何区别对吧?
$http = $authHandler->attachToken($http, $token, (array) $scopes);
标签: php google-api-php-client google-authentication google-my-business-api