编程语言
首页 > 编程语言> > php-从响应URL中提取令牌-Spotify API

php-从响应URL中提取令牌-Spotify API

作者:互联网

我正在使用以下代码从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} /播放列表的请求中,该请求需要标题字段中的令牌.

谢谢!

解决方法:

您需要解码JSON:

$response = json_decode($response, true);

然后,您将获得一个包含值的数组.

$token = $response['access_token'];

另外,您缺少以这种方式获取响应的必要选项:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

如果未定义,则将获得布尔值而不是响应.

标签:spotify,php,curl,api,token
来源: https://codeday.me/bug/20191011/1890549.html