从响应URL中提取令牌

时间:2016-08-10 06:39:38

标签: php api

我使用此代码从Web API获取令牌:

<?php
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';

$credentials = "{Client ID}:{Client Secret}";

$headers = array(
        "Accept: */*",
        "Content-Type: application/x-www-form-urlencoded",
        "User-Agent: runscope/0.1",
        "Authorization: Basic " . base64_encode($credentials));
$data = 'grant_type=client_credentials';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($ch);
?>

结果显示在浏览器中:

{"access_token":"{token}","token_type":"Bearer","expires_in":3600}
Great! But how do I extract "{token}"
来自响应的

并将其用作API请求中的参数?

1 个答案:

答案 0 :(得分:0)

试试这个:

$response = '{"access_token":"{token}","token_type":"Bearer","expires_in":3600}';

$arr = json_decode($response);

echo $arr->access_token;