简体   繁体   English

获取Spotify API OAuth 2.0 token with PHP

[英]Obtain Spotify API OAuth 2.0 token with PHP

I am trying to obtain a OAuth 2.0 token for the Spotify API using the following guide: https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/我正在尝试使用以下指南为 Spotify API 获取OAuth 2.0令牌: https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/

I have the following PHP code:我有以下 PHP 代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  'Content-Type: application/x-www-form-urlencoded',
  'Authorization: Basic ' . base64_encode('MY_CLIENT_CODE:MY_CLIENT_SECRET')
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
  'grant_type' => 'client_credentials'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($result);

But the result is:但结果是:

Array ( [error] => unsupported_grant_type [error_description] => grant_type parameter is missing )

Their example code is JavaScript and apparently I don't understand it well enough to translate it to PHP. Does anybody know what I'm doing wrong?他们的示例代码是 JavaScript ,显然我不太了解它,无法将其翻译成 PHP。有人知道我做错了什么吗?

You are json encoding the form fields, you should build a query parameter.您正在对表单字段进行 json 编码,您应该构建一个查询参数。

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
  'grant_type' => 'client_credentials'
]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM