Skip to content

Instantly share code, notes, and snippets.

@neilmenon
Created December 30, 2022 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilmenon/867cbe079c09ed44612b8cfcec400b05 to your computer and use it in GitHub Desktop.
Save neilmenon/867cbe079c09ed44612b8cfcec400b05 to your computer and use it in GitHub Desktop.
Spotify Token Authorization in PHP
<?php
$client_id = "your client id";
$client_secret = "your client secret";
$redirect_uri = "redirect URI, should be the URL to this PHP file after placed on a web server (e.g. http://localhost:9000/spotify_auth.php)";
if(isset($_GET["code"])) { // return the auth details
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.spotify.com/api/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=authorization_code&redirect_uri=" . $redirect_uri . "&code=" . $_GET["code"]);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic " . base64_encode($client_id . ":" . $client_secret)));
// for local developement, do not use elsewhere.
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
header('Content-Type: application/json; charset=utf-8');
echo $result;
} else { // redirect to spotify auth page
$auth_headers = (object) [
"client_id" => $client_id,
"response_type" => "code",
"redirect_uri" => $redirect_uri,
"scope" => "user-library-read user-read-email"
];
header("Location: https://accounts.spotify.com/authorize?" . http_build_query($auth_headers));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment