Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

spotify webapi auth and requests

spotify webapi auth and requests

for the past few weeks ive been trying to implement spotify webapi on my app to auth users, get their pfp and handler and also get their currently playing track name and artist name but had no success. id appreciate any help.

AuthViewModel:

package com.example.grooveshare.viewmodels

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.lifecycle.ViewModel
import net.openid.appauth.AuthorizationException
import net.openid.appauth.AuthorizationRequest
import net.openid.appauth.AuthorizationService
import net.openid.appauth.AuthorizationServiceConfiguration
import net.openid.appauth.AuthorizationResponse
import net.openid.appauth.ResponseTypeValues
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64

class SpotifyAuthViewModel : ViewModel() {

private val clientId = ""
private val redirectUri = "myapp://callback"
private val authorizationEndpoint = "https://accounts.spotify.com/authorize"
private val tokenEndpoint = "https://accounts.spotify.com/api/token"
private val codeVerifier = generateCodeVerifier()
private lateinit var authService: AuthorizationService

fun initializeAuthService(context: Context) {
authService = AuthorizationService(context)
Log.d("SpotifyAuth", "AuthorizationService initialized")
}

private fun generateCodeVerifier(): String {
val secureRandom = SecureRandom()
val codeVerifier = ByteArray(32)
secureRandom.nextBytes(codeVerifier)
return Base64.getUrlEncoder().withoutPadding().encodeToString(codeVerifier)
}

private fun generateCodeChallenge(verifier: String): String {
val bytes = verifier.toByteArray(Charsets.US_ASCII)
val messageDigest = MessageDigest.getInstance("SHA-256")
val digest = messageDigest.digest(bytes)
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest)
}

fun authenticate(authResultLauncher: ActivityResultLauncher<Intent>) {
if (!::authService.isInitialized) {
Log.e("SpotifyAuth", "AuthorizationService is not initialized")
return
}

val serviceConfig = AuthorizationServiceConfiguration(
Uri.parse(authorizationEndpoint),
Uri.parse(tokenEndpoint)
)

val authRequest = AuthorizationRequest.Builder(
serviceConfig,
clientId,
ResponseTypeValues.CODE,
Uri.parse(redirectUri)
).setCodeVerifier(codeVerifier, generateCodeChallenge(codeVerifier), "S256")
.setScope("user-read-currently-playing user-read-email user-read-private")
.build()

Log.d("SpotifyAuth", "Authorization Request URI: ${authRequest.toUri()}")

val authIntent = authService.getAuthorizationRequestIntent(authRequest)
authResultLauncher.launch(authIntent) // Launch the auth intent using the Activity Result API
}

fun handleAuthResponse(intent: Intent?) {
Log.d("SpotifyAuth", "Received Intent: $intent")
Log.d("SpotifyAuth", "Intent Action: ${intent?.action}")
Log.d("SpotifyAuth", "Intent Data: ${intent?.data}")

if (intent == null || intent.data == null) {
Log.e("SpotifyAuth", "Intent or data is null")
return
}

val authorizationResponse = AuthorizationResponse.fromIntent(intent)
val authorizationException = AuthorizationException.fromIntent(intent)

if (authorizationResponse != null) {
Log.d("SpotifyAuth", "Authorization Response: ${authorizationResponse.jsonSerializeString()}")
val tokenRequest = authorizationResponse.createTokenExchangeRequest()

authService.performTokenRequest(tokenRequest) { tokenResponse, exception ->
if (tokenResponse != null) {
Log.d("SpotifyAuth", "Token Response: ${tokenResponse.jsonSerializeString()}")
val accessToken = tokenResponse.accessToken
Log.d("SpotifyAuth", "Access Token: $accessToken")
// TODO: Use the access token to fetch user profile and currently playing track
} else {
Log.e("SpotifyAuth", "Token Exchange Failed: ${exception?.errorDescription}")
}
}
} else {
Log.e("SpotifyAuth", "Authorization Failed: ${authorizationException?.errorDescription}")
}
}

override fun onCleared() {
super.onCleared()
if (::authService.isInitialized) {
authService.dispose()
}
}
}

 

the logs i get everytime the app runs are the following:

19:22:45.582 7422-7422 SpotifyAuth com.example.grooveshare D AuthorizationService initialized
19:22:48.116 7422-7422 SpotifyAuth com.example.grooveshare D Authorization Request URI: https://accounts.spotify.com/authorize?redirect_uri=myapp%3A%2F%2Fcallback&client_id=&response_type=code&state=x4_BWl8fKVPqz_kydQ0Xgw&nonce=f_Cn98xXWNyuRBW_upaJrw&scope=user-read-currently-playing%20user-read-email%20user-read-private&code_challenge=B6V3YAprIgNR3g7tpxFdaBGbKGozViF6F_JVOPNGsMk&code_challenge_method=S256
19:22:52.199 7422-7422 SpotifyAuth com.example.grooveshare D Received Intent: null
19:22:52.199 7422-7422 SpotifyAuth com.example.grooveshare D Intent Action: null
19:22:52.199 7422-7422 SpotifyAuth com.example.grooveshare D Intent Data: null
19:22:52.199 7422-7422 SpotifyAuth com.example.grooveshare E Intent or data is null

 

steps ive taken so far:

made sure my redirect uri stated in the viewmodel is the same w the one stated in spotify dashboard and also that the intent is correctly established in AndroidManifest.xml

 

Reply
0 Replies

Suggested posts

Type a product name