从响应 url 中提取令牌 - Spotify API [英] Extract token from response url - Spotify API

查看:37
本文介绍了从响应 url 中提取令牌 - Spotify API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码从 Spotify 的 Web 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}

太好了!但是如何从响应中提取{token}"并将其用作 API 请求中的参数?例如在对 https://api.spotify.com/v1/users/ 的请求中{user_id}/playlists 需要标头字段中的令牌.

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.

谢谢!

推荐答案

您需要解码 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆