我正在构建一个小工具来一次管理多个 GMB 位置,但我遇到了google php api 客户端的问题。
我正在从我的数据库中获取多个用户/位置的访问令牌,并希望循环更新它们,但是谷歌 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);