假设我想在获取授权代码后编写一个php命令来兑换授权代码。
假设我使用guzzle来发出请求,我正在使用以下代码,其中参数应该是正确的。
<?php
namespace Pherserk\PHPGMailCommander\Command;
use Guzzle\Http\Client;
/**
* Class ExchangeAuthorizationToken
* @package Pherserk\PHPGmailCommander\Command
*/
class ExchangeAuthorizationToken
{
private $url;
private $path;
private $grantType;
private $clientId;
private $clientSecret;
private $redirectUri;
public function __construct(array $config)
{
$this->url = $config['authorization_token']['code_exchange_uri'];
$this->path = $config['authorization_token']['code_exchange_path'];
$this->grantType = $config['authorization_token']['grant_type'];
$this->clientId = $config['client_id'];
$this->clientSecret = $config['client_secret'];
$this->redirectUri = $config['redirect_uri'];
}
/**
* @param string $accessToken
*/
public function run($accessToken = '4/the-authorization-token-here_hasbEen.obscured')
{
$client = new Client();
$client->setBaseUrl($this->url);
$client->setSslVerification(true);
$request = $client->post($this->path, null, null, ['exceptions' => false]);
$request->addHeader('Content-Type', 'application/x-www-form-urlencoded');
$query = $request->getQuery();
$query['code'] = $accessToken;
$query['client_id'] = $this->clientId;
$query['client_secret'] = $this->clientSecret;
$query['redirect_uri'] = $this->redirectUri;
$query['grant_type'] = $this->grantType;
$response = $request->send();
var_dump($response->getBody(true));
}
}
我收到400状态代码,动机为invalid_grant。我收到了用户授权提示和重定向后我正在使用的授权码。 我错过了什么?
答案 0 :(得分:0)
经过一段时间的辩论,我明白了原因。 代码已被重新兑换。
以这种方式调整代码
$response = $request->send();
$decodedResponse = $response->json();
if (isset($decodedResponse['error'])) {
echo $decodedResponse['error_description'];
return false;
}
return true;
我注意到了错误。