从Guzzle Oauth身份验证获取访问令牌
问题描述:
我目前正在尝试通过使用Guzzle通过Oauth开发与Reddit API的连接。我到了在Reddit中进行身份验证的地步,然后到达授权令牌,但我无法从Guzzle响应中获取访问令牌,因此我可以将其设置为cookie并在随后的请求中使用。我当前的代码如下所示:从Guzzle Oauth身份验证获取访问令牌
public function __construct(){
if(isset($_COOKIE['reddit_token'])){
$token_info = explode(":", $_COOKIE['reddit_token']);
$this->token_type = $token_info[0];
$this->access_token = $token_info[1];
} else {
if (isset($_GET['code'])){
//capture code from auth
$code = $_GET["code"];
//construct POST object for access token fetch request
$postvals = sprintf("code=%s&redirect_uri=%s&grant_type=authorization_code",
$code,
redditConfig::$ENDPOINT_OAUTH_REDIRECT);
//get JSON access token object (with refresh_token parameter)
$token = self::runCurl(redditConfig::$ENDPOINT_OAUTH_TOKEN, $postvals, null, true);
//store token and type
if (isset($token->access_token)){
$this->access_token = $token->access_token;
$this->token_type = $token->token_type;
//set token cookie for later use
$cookie_time = 60 * 59 + time(); //seconds * minutes = 59 minutes (token expires in 1hr)
setcookie('reddit_token', "{$this->token_type}:{$this->access_token}", $cookie_time);
}
} else {
$state = rand();
$urlAuth = sprintf("%s?response_type=code&client_id=%s&redirect_uri=%s&scope=%s&state=%s",
redditConfig::$ENDPOINT_OAUTH_AUTHORIZE,
redditConfig::$CLIENT_ID,
redditConfig::$ENDPOINT_OAUTH_REDIRECT,
redditConfig::$SCOPES,
$state);
//forward user to PayPal auth page
header("Location: $urlAuth");
}
}
这是我的认证流程。在我有一个要做出狂饮请求runCurl方法:
private function runCurl($url, $postVals = null, $headers = null, $auth = false){
$options = array(
'timeout' => 10,
'verify' => false,
'headers' => ['User-Agent' => 'testing/1.0']
);
$requestType = 'GET';
if ($postVals != null){
$options['body'] = $postVals;
$requestType = "POST";
}
if ($this->auth_mode == 'oauth'){
$options['headers'] = [
'User-Agent' => 'testing/1.0',
'Authorization' => "{$this->token_type} {$this->access_token}"];
}
if ($auth){
$options['auth'] = [redditConfig::$CLIENT_ID, redditConfig::$CLIENT_SECRET];
}
$client = new \GuzzleHttp\Client();
$response = $client->request($requestType, $url, $options);
$body = $response->getBody();
return $body;
}
的问题在于这里的getBody()方法返回一个流,如果我使用getBody() - > getContents()我得到一个字符串,其中没有一个可以帮助我。
我如何能获得访问令牌,所以我可以完成认证过程的任何想法?
答
要回答这个问题本身 - 你只需要投$body
字符串。它应该是一个json,所以你还需要json_decode它将它用作上面代码中的一个对象。因此,而不是return $body;
在runCurl
,你需要做的:
return json_decode((string)$body);
我会建议使用官方客户端寿。问题中的代码有一些不相关的问题,这会使维护成本变得很高。
https://github.com/reddit/reddit/wiki/OAuth2-PHP-Example –