Home > Net >  Obtain Spotify API OAuth 2.0 token with PHP
Obtain Spotify API OAuth 2.0 token with PHP

Time:03-07

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/

I have the following PHP code:

$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?

CodePudding user response:

You are json encoding the form fields, you should build a query parameter.

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