Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spotify API User Authorization from Google Apps Script

I would like to manipulate my Spotify playlists from a Google Apps script. I managed so far to access the Spotify API using a "client credentials" token. This way, I can search for songs and retrieve all kinds of audio analysis.

Now, in order to manipulate my playlists, I need to obtain another kind of access, involving OAuth2 and the notion of a redirect url.

I can find some examples on how to do this for e.g. Python programs running on my own PC, but not how to handle it from a Google Apps script.

Can anyone give some pointers or even better, some sample code?

like image 567
Keld Hammerum Avatar asked May 25 '26 02:05

Keld Hammerum


1 Answers

OAuth2 is a library you can add into Google Apps Script. The setup section of this describes it decently well. Libraries > Add a Library > enter the Script ID mentioned here: https://github.com/googleworkspace/apps-script-oauth2

Then in Spotify developer dashboard of your app you'll need to enter your redirect url

  • It should look something like:
  • https://script.google.com/macros/d/{ScriptID}/usercallback
  • Where the {ScriptID} can be found in the Project Settings section of your Google Apps Script UI, copy and paste it, it's quite long

Your code can override that callback function like this:

function getSpotifyService_() {
 return OAuth2.createService('Spotify')
  .setAuthorizationBaseUrl('https://accounts.spotify.com/authorize')
  .setTokenUrl('https://accounts.spotify.com/api/token')
  .setClientId(SPOTIFY_CLIENT_ID)
  .setClientSecret(SPOTIFY_CLIENT_SECRET)
  .setCallbackFunction('authCallback')
  .setPropertyStore(PropertiesService.getUserProperties())
  .setScope('user-library-read');
}
function authCallback(request) {
  var spotifyService = getSpotifyService_();
  var isAuthorized = spotifyService.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this tab');
  }
}
like image 76
Ben Petersen Avatar answered May 27 '26 17:05

Ben Petersen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!