Skip to content

Instantly share code, notes, and snippets.

@yodaluca23
Created March 16, 2025 03:38
Show Gist options
  • Save yodaluca23/a50271492d3e99192f55972fdf74dc99 to your computer and use it in GitHub Desktop.
Save yodaluca23/a50271492d3e99192f55972fdf74dc99 to your computer and use it in GitHub Desktop.
SpotToken
import http.client
import json
import hmac
import hashlib
import time
# Function to get the access token
def get_access_token():
# Thank you to https://github.com/Aran404/SpotAPI/blob/main/spotapi/client.py for parts of the following code.
_TOTP_SECRET = bytearray([53, 53, 48, 55, 49, 52, 53, 56, 53, 51, 52, 56, 55, 52, 57, 57, 53, 57, 50, 50, 52, 56, 54, 51, 48, 51, 50, 57, 51, 52, 55])
def generate_totp(secret: bytes = _TOTP_SECRET):
# Generate the TOTP code
counter = int(time.time()) // 30
hmac_result = hmac.new(secret, counter.to_bytes(8, byteorder="big"), hashlib.sha1).digest()
offset = hmac_result[-1] & 15
truncated_value = (
(hmac_result[offset] & 127) << 24
| (hmac_result[offset + 1] & 255) << 16
| (hmac_result[offset + 2] & 255) << 8
| (hmac_result[offset + 3] & 255)
)
return str(truncated_value % 10**6).zfill(6), counter * 30000
# Generate TOTP token
totp, timestamp = generate_totp()
# Define the query parameters
query = {
"reason": "init",
"productType": "web-player",
"totp": totp,
"totpVer": 5,
"ts": timestamp,
}
# Generate the URL path with query parameters
base_path = "/get_access_token"
query_string = f"reason={query['reason']}&productType={query['productType']}&totp={query['totp']}&totpVer={query['totpVer']}&ts={query['ts']}"
url_path = f"{base_path}?{query_string}"
# Send the GET request to get the access token
conn = http.client.HTTPSConnection("open.spotify.com")
conn.request("GET", url_path)
response = conn.getresponse()
if response.status != 200:
raise Exception(f"Failed to retrieve access token. Status Code: {response.status}")
# Parse the response JSON
data = json.loads(response.read().decode())
# Close the connection
conn.close()
# Extract access token and client ID
access_token = data.get("accessToken")
client_id = data.get("clientId")
if access_token and client_id:
return access_token, client_id
else:
raise Exception("Could not extract access token or client ID from response.")
if __name__ == "__main__":
token, client_id = get_access_token()
print(f"Access Token: {token}")
print(f"Client ID: {client_id}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment