使用 PHP 获取 Spotify API OAuth 2.0 令牌

Obtain Spotify API OAuth 2.0 token with PHP

我正在尝试使用以下指南为 Spotify API 获取 OAuth 2.0 令牌: https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/

我有以下 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);

但结果是:

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

他们的 example code is JavaScript 显然我对它的理解还不够好,无法将其翻译成 PHP。有人知道我做错了什么吗?

您正在 json 对表单字段进行编码,您应该构建一个查询参数。

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