TwitterOAuth解析PHP卷曲响应以获取访问令牌

时间:2015-04-21 15:01:26

标签: php json curl twitter

我正在使用TwitterOAuth访问我的时间轴并获取最后三条推文。我用Curl调用oauth2 / token,它返回一个包含bearer访问令牌的字符串。问题是如何解析响应以获取access_token?我可以使用String函数,但似乎应该有更好的方法。

这是我的代码:

$headers = array( 
    "POST /oauth2/token HTTP/1.1", 
    "Host: api.twitter.com", 
    "User-Agent: my Twitter App v.1",
    "Authorization: Basic ". $base64_encoded_bearer_token ."",
    "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", 
    "Content-Length: 29"
); 

$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "https://api.twitter.com/oauth2/token");
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$header = curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($curl);
curl_close ($curl);

这是$ curlResponse变量:

string(1018) "HTTP/1.1 200 OK cache-control: no-cache, no-store,
must-revalidate, pre-check=0, post-check=0 content-disposition: 
attachment; filename=json.json content-length: 153 content-type:
application/json;charset=utf-8 date: Tue, 21 Apr 2015 14:58:59 GMT
expires: Tue, 31 Mar 1981 05:00:00 GMT last-modified: Tue, 21 Apr 2015
14:58:59 GMT ml: S pragma: no-cache server: tsa_a set-cookie: 
guest_id=v1%3A142962833975637457; Domain=.twitter.com; Path=/;    
Expires=Thu, 20-Apr-2017 14:58:59 UTC status: 200 OK strict-transport-
security: max-age=631138519 x-connection-hash: 
128fc5244a58ab23aa3b42c1827d6748 x-content-type-options: nosniff x-frame-
options: SAMEORIGIN x-response-time: 10 x-transaction: 073ddea9feba6654
x-tsa-request-body-time: 0 x-twitter-response-tags: BouncerCompliant
x-ua-compatible: IE=edge,chrome=1 x-xss-protection: 1; mode=block   
{"token_type":"bearer","access_token":"AAAAAAAAAAAA  
AAAAAAAAAGYrfQAAAAAAODa03 sxJgQuYFOyapqOCaSy7mQA%3D  
IFQZOFEENVMMTosGadfagztbJyZ7bc7ID8wRENK1exJVw48adM6J"}"

1 个答案:

答案 0 :(得分:1)

您可以通过标题大小从响应中提取正文,然后使用json_decode将其解析为对象。

$headers = array(
    "POST /oauth2/token HTTP/1.1",
    "Host: api.twitter.com",
    "User-Agent: my Twitter App v.1",
    "Authorization: Basic " . $base64_encoded_bearer_token . "",
    "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
    "Content-Length: 29"
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.twitter.com/oauth2/token");
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($curl);
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
curl_close($curl);

$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);

var_dump(json_decode($body));