Search code examples
google-apps-scriptspotify

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?


Solution

  • 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

    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');
      }
    }