首页 > 解决方案 > Google PHP SDK 未更改 setAccessToken 上的 Accesstoken

问题描述

我正在构建一个小工具来一次管理多个 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);

标签: phpgoogle-api-php-clientgoogle-authenticationgoogle-my-business-api

解决方案


这似乎是 google php api 客户端中的错误/不存在的功能。

我在 github 上报告了一个问题,并希望在那里得到澄清。

https://github.com/googleapis/google-api-php-client/issues/1672

编辑:

我在 Github 上得到了解决问题的回复。设置新的 accesstoken 后需要手动清除缓存。

嗨@Fredyy90,

客户端将缓存访问令牌以调用具有相同范围的相同服务。要更改令牌,您可以清除此缓存:

$client->setAccessToken($token1); // <call 1>

$client->getCache()->clear();

$client->setAccessToken($token2); // <call 2> 

我们将了解如何使这种行为更清晰,并为希望修改令牌的人提供更多控制。


推荐阅读