Extract token from response url - Spotify API

☆樱花仙子☆ 提交于 2019-12-20 03:11:45

问题


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}

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.

Thanks!


回答1:


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.



来源:https://stackoverflow.com/questions/24519788/extract-token-from-response-url-spotify-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!