Skip to content

Instantly share code, notes, and snippets.

@ayal
Created October 22, 2021 14:28
Show Gist options
  • Save ayal/e973e4e47311c7f8337f83e783b502c0 to your computer and use it in GitHub Desktop.
Save ayal/e973e4e47311c7f8337f83e783b502c0 to your computer and use it in GitHub Desktop.
velo spotify integration markdown

Spotify Integration

Setup

Configuration

1 - spotify_client_secret stored in Velo secret manager value should be the Client Secret generated after registering your application

2 - spotify-integration-config.json

{
    "redirect_uri": <The URI to redirect to after the user grants or denies permission>,
    "scope": <A space-separated list of scopes>,
    "client_id": <The Client ID generated after registering your application>
}

read more: https://developer.spotify.com/documentation/general/guides/authorization/code-flow/

3 - Button with id #spotifyButton

4 - "tokens" collection with admin permissions

Simple Use of the Package in your Site

1 - Create a button with id #spotifyButton

2 - In your page-code do the following:

import { init } from '@ayalg5/spotify-integration';
$w.onReady(async function () {
    const initData = await init();
    const apiData = await spoti_get('<SOME SPOTIFY API ENDPOINT>', initData.token.access_token)
    console.log('spotify api data', apiData) // do something with this data
});

Examples

Get current user recently-played tracks:

import { init } from '@ayalg5/spotify-integration';
$w.onReady(async function () {
    const initData = await init();
    const apiData = await spoti_get('me/player/recently-played?limit=5', initData.token.access_token)
    console.log('spotify api data', apiData) // do something with this data
});

Show all connected users' recently-played tracks:

import { init } from '@ayalg5/spotify-integration';
import { getAllUsersData } from '@ayalg5/spotify-integration-backend';

$w.onReady(async function () {
    const initData = await init();

    $w("#repeater1").onItemReady(($item, data, index) => {
        // track data
        $item("#button2").label = `${data.item.track.name} by ${data.item.track.artists[0].name}`;
        $item("#button2").link = data.item.track.external_urls.spotify;
        $item("#text6").text = data.item.played_at; // can format this with moment().fromNow()
        $item("#image1").src = data.item.track.album.images[0]?.url;

        // user identity
        $item("#text5").text = data.me.display_name;
        $item("#image2").src = data.me.images[0]?.url;
    });

    const allUsersRecentlyPlayed = await getAllUsersData('me/player/recently-played?limit=3')
    const repeaterData = allUsersRecentlyPlayed
        ?.sort((a, b) => (new Date(b.item.played_at).getTime() - new Date(a.item.played_at).getTime()))
        ?.map(({ item, me }) => ({ item, me, _id: item.track.id }));
    if (repeaterData) {
        $w("#repeater1").data = repeaterData;
        $w("#repeater1").show();
    }
});

API

Client

saveLocalToken(tokenObj:{access_token:string, refresh_token:string}) // save token to local-storage
async getLocalToken():{access_token:string, refresh_token:string} // get token from local-storage, returns refreshed token
async spoti_get_local(path:string):any // spotify api get request with current user's token (if exists)
async init() // inits spotify integration: uses oauth code (if exists) to authenticate, saves token to db, saves token to local storage, shows connect button if no token

Backend

spoti_connect():string // builds spotify authorization url using config scope, redirect_uri, client_id
async spoti_get(path:string, token:string):any // spotify api get request with given token
async spoti_refreshToken(tokenObj:{access_token:string, refresh_token:string}):{access_token:string, refresh_token:string} // refreshes given token
async spoti_auth(code:string):{access_token:string, refresh_token:string} // authenticates with OAuth code, returns token
async saveToken(tokenObj:{access_token:string, refresh_token:string}) // saves token to db with spotify user idenity
async getAllUsersData(path:string):any[] // for each user token issues a spoti_get request for `path`

Useful links:

Docs: https://developer.spotify.com/documentation/

Auth flow documentation: https://developer.spotify.com/documentation/general/guides/authorization/code-flow/

Endpoints documentation https://developer.spotify.com/documentation/web-api/reference/#/operations/get-current-users-profile

Playground: https://developer.spotify.com/console/get-current-user/

App dashboard: https://www.spotify.com/us/account/apps/

Scopes: https://developer.spotify.com/documentation/general/guides/authorization/scopes/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment