我正在使用此代码从Spotify的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}
大!但是如何从响应中提取“{token}”并将其用作API请求中的参数?例如,在https://api.spotify.com/v1/users/ {user_id} /播放列表的请求中,需要标题字段中的标记。
谢谢!
答案 0 :(得分:1)
您需要解码JSON:
$response = json_decode($response, true);
然后你将拥有一个包含值的数组。
$token = $response['access_token'];
此外,您错过了以这种方式获取回复的必要选项:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
如果未定义,您将获得布尔值而不是响应。
答案 1 :(得分:0)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
在执行 curl 之前也使用此行,然后它会为您提供正确的 json