从响应URL中提取令牌 - Spotify的API [英] Extract token from response url - Spotify API
问题描述
我使用这个code获得来自Spotify的网络API令牌:
I'm using this code to get a token from Spotify's 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);
?>
这导致此示出了在浏览器上:
That results in this showing up in the browser:
{"access_token":"{token}","token_type":"Bearer","expires_in":3600}
大!但我怎么从响应中提取{}令牌,并在该API的请求把它作为一个参数?例如,在请求 https://api.spotify.com/v1/users/ {} USER_ID /播放列表,需要在报头字段的标记。
Great! But how do I extract "{token}" from the response and use it as a parameter in a request to the API? For example in the request to https://api.spotify.com/v1/users/{user_id}/playlists which needs the token in the header field.
谢谢!
推荐答案
您需要取消code中的JSON:
You need to decode the JSON:
$response = json_decode($response, true);
那么你就必须用值的数组。
Then you'll have an array with the values.
$token = $response['access_token'];
另外,你缺少一个必要的选项来获得这样的回应:
Also, you're missing a necessary option to obtain the response in this way:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
如果没有定义,你会得到一个布尔值,而不是响应。
If not defined, you will get a boolean value instead of the response.
这篇关于从响应URL中提取令牌 - Spotify的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!