Last updated on: May 27, 2023
Today, I’m going to show you have to add a Spotify Login button to your app as a sign-in method for your users.
Contents
Let’s get started
First, go to developer.spotify.com/dashboard and login with your Spotify account. (You don’t need Spotify Premium to have access to Spotify for Developers.)
Next, create a new app by pressing the box.
In the new window, fill in all the required fields, like app name, description e.t.c., and press NEXT.
…next step, choose if it’s a commercial app or not. In this example, the answer is NO.
Check the boxes and press SUBMIT.
Once you get to the dashboard of your app, go to EDIT SETTINGS.
In the new window, add your website (if you have one), as Redirect URIs add the name of your app and at the end add :// , for this example is spotifysigninexample://, and lastly, in Android Packages add your package name and your SHA1 Fingerprint and press SAVE
Creating the Spotify Login Button
First, add a Button to your XML file. In this example, we have a button, with Spotify‘s green color, in the middle of the activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
tools:context=".MainActivity">
<Button
android:id="@+id/spotify_login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/rounded_corners"
android:drawablePadding="8dp"
android:drawableStart="@drawable/spotify_icon"
android:drawableLeft="@drawable/spotify_icon"
android:padding="8dp"
android:text="Log in with Spotify"
android:textAllCaps="false"
android:textColor="@android:color/white" />
</RelativeLayout>
Code language: HTML, XML (xml)
Create a new Kotlin object file by right-clicking on your app’s package name on the left side and go New > Kotlin File/Class.
Give it the name SpotifyConstants, choose Object and press OK.
Inside the new file, copy and paste the following code and replace the CLIENT_ID and REDIRECT_URI with yours.
object SpotifyConstants {
val CLIENT_ID = "MY_CLIENT_ID"
val AUTH_TOKEN_REQUEST_CODE = 0x10
val REDIRECT_URI = "MY_REDIRECT_URI"
}
Code language: Kotlin (kotlin)
Add the following dependencies in your build.gradle(Module: app)
dependencies {
// ...
implementation 'com.spotify.android:auth:1.1.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
//...
}
Code language: Kotlin (kotlin)
In the Kotlin class of your Activity, MainActivity in this example, add a listener to your button and create the authentication request.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
spotify_login_btn.setOnClickListener {
val request = getAuthenticationRequest(AuthenticationResponse.Type.TOKEN)
AuthenticationClient.openLoginActivity(
this,
SpotifyConstants.AUTH_TOKEN_REQUEST_CODE,
request
)
}
}
private fun getAuthenticationRequest(type: AuthenticationResponse.Type): AuthenticationRequest {
return AuthenticationRequest.Builder(SpotifyConstants.CLIENT_ID, type, SpotifyConstants.REDIRECT_URI)
.setShowDialog(false)
.setScopes(arrayOf("user-read-email"))
.build()
}
Code language: Kotlin (kotlin)
Here, we use the scopes user-read-email to get the user’s email address.
There’s a list with all the authorization scopes here if you want to get more info from users.
After the user has completed the authorization, it returns the access token through the onActivityResult method and the app gets the data by making an HTTP GET request to https://api.spotify.com/v1/me
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (SpotifyConstants.AUTH_TOKEN_REQUEST_CODE == requestCode) {
val response = AuthenticationClient.getResponse(resultCode, data)
val accessToken: String? = response.accessToken
fetchSpotifyUserProfile(accessToken)
}
}
private fun fetchSpotifyUserProfile(token: String?) {
Log.d("Status: ", "Please Wait...")
if (token == null) {
Log.i("Status: ", "Something went wrong - No Access Token found")
return
}
val getUserProfileURL = "https://api.spotify.com/v1/me"
GlobalScope.launch(Dispatchers.Default) {
val url = URL(getUserProfileURL)
val httpsURLConnection = withContext(Dispatchers.IO) {url.openConnection() as HttpsURLConnection}
httpsURLConnection.requestMethod = "GET"
httpsURLConnection.setRequestProperty("Authorization", "Bearer $token")
httpsURLConnection.doInput = true
httpsURLConnection.doOutput = false
val response = httpsURLConnection.inputStream.bufferedReader()
.use { it.readText() } // defaults to UTF-8
withContext(Dispatchers.Main) {
val jsonObject = JSONObject(response)
// Spotify Id
val spotifyId = jsonObject.getString("id")
Log.d("Spotify Id :", spotifyId)
// Spotify Display Name
val spotifyDisplayName = jsonObject.getString("display_name")
Log.d("Spotify Display Name :", spotifyDisplayName)
// Spotify Email
val spotifyEmail = jsonObject.getString("email")
Log.d("Spotify Email :", spotifyEmail)
val spotifyAvatarArray = jsonObject.getJSONArray("images")
//Check if user has Avatar
var spotifyAvatarURL = ""
if (spotifyAvatarArray.length() > 0) {
spotifyAvatarURL = spotifyAvatarArray.getJSONObject(0).getString("url")
Log.d("Spotify Avatar : ", spotifyAvatarURL)
}
Log.d("Spotify AccessToken :", token)
}
}
}
Code language: Kotlin (kotlin)
That’s it! Done!
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!