1

I'm a premium user yet I'm getting a 403 Premium account needed using this snippet.

Is it just me or is playing a spotify song from the commandline an incredible hard thing to do?

#!/bin/bash
TRACK_ID="0hCB0YR03f65y1YKr59OSs" # Zeppelin
# Spotify App Credentials
CLIENT_ID="my_id"
CLIENT_SECRET="my_secret"
# Obtain token
TOKEN="$(\
curl -X POST "https://accounts.spotify.com/api/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET"| jq -r '.access_token')" 
# Play a song on the Spotify player
curl -s -X "PUT" "https://api.spotify.com/v1/me/player/play" \
     --data "{\"uris\": [\"spotify:track:$TRACK_ID\"]}" \
     -H "Accept: application/json" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer ${TOKEN}"

P.S. Spotipy returns the same error

jjk
  • 592
  • 1
  • 6
  • 23
  • Have you checked hitting the same url from postman. if that works it may be because of bot fight mode enabled on spotify website. Try passing User Agent Header to make your request look like it is coming from a browser. – axcl Apr 14 '23 at 09:50

1 Answers1

1

You can't play a song by curl command. Your try method is Client Credentials Flow. This method can get artist, album, and song information.

The play of a song needs the Authorization Code Flow. It can do users play songs, and get user information as related user APIs.

It should get the token by "redirect_URI".

Here are examples in here

Python 1

Python 2

Code Overview

enter image description here

Demo code - using express on node.js Save as play-song.js You need to launch the Spotify App or logged in to Spotify by the browser.

const axios = require('axios')
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())

// for raw JSON of Body
app.use(express.json())

const REDIRECT_URI = '<your redirect URL>' // mine is http://localhost:3000/callback
const CLIENT_ID = '<your client id>'
const CLIENT_SECRET = '<your client secret>'
const SCOPE = ['playlist-modify-private', 'user-read-currently-playing', 'user-read-playback-state', 'user-modify-playback-state']

app.get("/login", (request, response) => {
    const redirect_url = `https://accounts.spotify.com/authorize?response_type=code&client_id=${CLIENT_ID}&scope=${SCOPE}&state=123456&redirect_uri=${REDIRECT_URI}&prompt=consent`
    response.redirect(redirect_url);
})

app.get("/callback", async (request, response) => {
    const code = request.query["code"]
    await axios.post(
        url = 'https://accounts.spotify.com/api/token',
        data = new URLSearchParams({
            'grant_type': 'authorization_code',
            'redirect_uri': REDIRECT_URI,
            'code': code
        }),
        config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            params: {
                'grant_type': 'client_credentials'
            },
            auth: {
                username: CLIENT_ID,
                password: CLIENT_SECRET
            }
        })
        .then(resp1 => {
            axios.get(
                url = 'https://api.spotify.com/v1/me/player/devices',
                config = {
                    headers: {
                        'Accept-Encoding': 'application/json',
                        Authorization: `Bearer ${resp1.data.access_token}`
                    }
                }
            ).then(resp2 => {
                const device_id = resp2.data.devices[0].id
                const track_id = '7pKfPomDEeI4TPT6EOYjn9' // Imagine-Remastered 2010
                const access_token = resp1.data.access_token;
                axios.put(`https://api.spotify.com/v1/me/player/play?device_id=${device_id}`, {
                    uris: [`spotify:track:${track_id}`]
                }, {
                    headers: {
                        'Authorization': `Bearer ${access_token}`,
                        'Content-Type': 'application/json'
                    }
                })
                    .then(data => {
                        response.send(JSON.stringify({"device id": device_id}))
                    })
                    .catch(error => {
                        console.error(error)
                    });
            })
        });

})
// use your <redirect URL>'s port
app.listen(3000, () => { console.log("Listening on : 3000") })

install dependencies

npm install axios express cors

Run it

node play-song.js

Then open browser, access this URL

localhost:3000/login

Remember the port number should be use your port number in your dashboard

Result

the left is Spotify

the right top is the browser

the right bottom is terminal

The center top is the Sound panel in Windows - You can see visualize the sound through the movement of the bar after playing a track.

enter image description here

Reference

Play Song API

Bench Vue
  • 5,257
  • 2
  • 10
  • 14