Android API Reference

Android API Reference

#Overview

The Magic SDK for Android is your entry-point to secure, passwordless authentication for your mobile app. This guide will cover some important topics for getting started with Android APIs and to make the most of Magic's features.

Magic can support either server-based or serverless web applications. It is up to the developers to implement the Admin SDK to validate the DID Token.

#Getting Started

The Magic class is the entry-point to the Magic SDK. It must be instantiated with a Magic publishable key.

#Constructor

#Magic()

Parameter

Type

Definition

context

Context

Android Context object

apiKey

String

Your publishable API Key retrieved from the Magic Dashboard.

network?

String | Object

(String): A representation of the connected Ethereum network (mainnet, rinkeby, kovan, or ropsten).

⁠(Object): A custom Ethereum Node configuration with the following shape:

rpcUrl (String): A URL pointing to your custom Ethereum Node.

chainId? (Number): Some Node infrastructures require you to pass an explicit chain ID. If you are aware that your Node requires this configuration, pass it here as an integer.

#Installation

Magic SDK is available in mavenCentral. Simply add the following line to the build.gradle in your Android project:

Groovy
01dependencies {
02    implementation 'link.magic:magic-android:4.0.0'
03    implementation 'org.web3j:core:4.8.8-android' 
04}
05
06repositories {
07    mavenCentral()
08}

Sync the project with new dependencies settings.

#Initialization

Initialize Magic instance.

Kotlin
01class MagicDemoApp: Application() {
02
03    lateinit var magic: Magic
04    override fun onCreate() {
05        // Construct with an API key:
06        magic = Magic(this, "YOUR_PUBLISHABLE_KEY")
07        // Construct with an API key with options:
08        magic = Magic(this, "YOUR_PUBLISHABLE_KEY", {network: "mainnet" })
09// Construct with an API key with custom node options:
10        magic = Magic(this, "YOUR_PUBLISHABLE_KEY", {network: 
11         {
12⁠          rpcUrl: 'https://polygon-rpc.com', // your mainnet/testnet rpc URL
13          chainId: 137 // corresponding chainId for your rpc url
14         }
15        })
16        super.onCreate()
17    }
18}

#Auth Module

The Auth Module and its members are accessible on the Magic SDK instance by the auth property.

Kotlin
01import link.magic.android.Magic
02
03var magic: Magic
04
05magic.auth;
06magic.auth.loginWithSMS;
07magic.auth.loginWithEmailOTP;

#loginWithSMS

Authenticate a user passwordlessly using a one-time code sent to the specified phone number.

List of Currently Blocked Country Codes

#Public Methods

Methods
loginWithSMS(context: Context, configuration: LoginWithSMSConfiguration): CompletableFuture<DIDToken>

#Returns

DIDToken: Response<String>()

The function resolves upon authentication request success and rejects with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.

#Example

Kotlin
01class MagicActivity: AppCompatActivity() {
02
03    lateinit var magic: Magic
04
05    override fun onCreate(savedInstanceState: Bundle?) {
06        super.onCreate(savedInstanceState)
07
08        magic = Magic(this, "YOUR_PUBLISHABLE_API_KEY")
09    }
10
11   fun login(v: View) {
12        val phoneNumber = findViewById<EditText>(R.id.phone_number_input)
13        val configuration = LoginWithSMSConfiguration(phoneNumber.text.toString())
14        val completable = magic.auth.loginWithSMS(configuration)
15
16        // Logging in
17        completable.whenComplete { response: DIDToken?, error: Throwable? ->
18            if (error != null) {
19                // Handle error
20            }
21            if (response != null && !response.hasError()) {
22                Log.d("Magic", "You're logged in!" + response.result)
23            } else {
24                Log.d("Magic", "Not Logged in")
25            }
26        }
27    }
28}

#Associated Class

LoginWithSMSConfiguration(phoneNumber: String)

  • phoneNumber The phone number to log in with

#loginWithEmailOTP

Authenticate a user passwordlessly using an email one-time code sent to the specified user's email address.

#Public Methods

Methods
loginWithEmailOTP(context: Context, configuration: LoginWithEmailOTPConfiguration): CompletableFuture<DIDToken>

#Returns

DIDToken: Response<String>()

The function resolves upon authentication request success and rejects with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.

#Example

Kotlin
01class MagicActivity: AppCompatActivity() {
02
03    lateinit var magic: Magic
04
05    override fun onCreate(savedInstanceState: Bundle?) {
06        super.onCreate(savedInstanceState)
07
08        magic = Magic(this, "YOUR_PUBLISHABLE_API_KEY")
09    }
10
11   fun login(v: View) {
12        val email = findViewById<EditText>(R.id.email_input)
13        val configuration = LoginWithEmailOTPConfiguration(email.text.toString())
14        val completable = magic.auth.loginWithEmailOTP(configuration)
15
16        // Logging in
17        completable.whenComplete { response: DIDToken?, error: Throwable? ->
18            if (error != null) {
19                // Handle error
20            }
21            if (response != null && !response.hasError()) {
22                Log.d("Magic", "You're logged in!" + response.result)
23            } else {
24                Log.d("Magic", "Not Logged in")
25            }
26        }
27    }
28}

#Associated Class

LoginWithEmailOTPConfiguration(email: String)

  • email The user email to log in with.

#User Module

The User Module and its members are accessible on the Magic SDK instance by the user property.

Typescript
01import MagicSDK
02
03let magic = Magic.shared
04
05magic.user
06magic.user.getIdToken
07magic.user.generateIdToken
08magic.user.getMetadata
09magic.user.updateEmail
10magic.user.isLoggedIn
11magic.user.logout

#updateEmail

Initiates the update email flow that allows a user to change to a new email

#Public Methods

Methods
updateEmail(context: Context, configuration: UpdateEmailConfiguration) -> CompletableFuture<UpdateEmailResponse>

#Returns

UpdateEmailResponse: Response<Boolean>()

The Completable resolves with a true boolean value if update email is successful and rejects with a specific error code if the request fails.

#Example

Kotlin
01class MagicActivity: AppCompatActivity() {
02
03    lateinit var magic: Magic
04
05    override fun onCreate(savedInstanceState: Bundle?) {
06        super.onCreate(savedInstanceState)
07
08        magic = Magic(this, "YOUR_PUBLISHABLE_KEY")
09    }
10
11    // ⭐️ Assuming user is logged in
12    fun updateEmail(v: View) {
13
14        val configuration = UpdateEmailConfiguration("[email protected]")
15        val completable = magic.user.updateEmail(this, configuration)
16        completable.whenComplete { response: UpdateEmailResponse?, error: Throwable? ->
17            if (response != null) {
18                Log.d("Magic", response.result.toString()) // "True"
19            } else {
20                // handle error
21            }
22        }
23    }
24}

#Associated Class

UpdateEmailConfiguration(showUI: Boolean? = true, email: String)

  • email The user email to update with.
  • showUI If true, show an out-of-the-box pending UI while the request is in flight.

#getIdToken

Generates a Decentralized Id Token which acts as proof of authentication to resource servers.

#Public Methods

Methods
getIdToken(configuration: GetIdTokenConfiguration?): CompletableFuture<GetIdTokenResponse>

#Returns

GetIdTokenResponse: Response<String>()

The Completable resolves with a true boolean value if the update email is successful and rejects with a specific error code if the request fails.

Kotlin
01class MagicActivity: AppCompatActivity() {
02    lateinit var magic: Magic
03
04    override fun onCreate(savedInstanceState: Bundle?) {
05        super.onCreate(savedInstanceState)
06
07        magic = Magic(this, "YOUR_PUBLISHABLE_KEY")
08    }
09
10    // ⭐️Assuming user is logged in
11    fun getIdToken(v: View) {
12        val configuration = GetIdTokenConfiguration(lifespan = 900)
13        val completable = magic.user.getIdToken(configuration)
14        completable.whenComplete { response: GetIdTokenResponse?, error: Throwable? ->
15            if (response != null) {
16                Log.d("Magic", response.result)
17            } else {
18                // handle Error
19            }
20        }
21    }
22}

#Associated Class

GetIdTokenConfiguration(lifespan: Long? = 900)

  • lifespan? : will set the lifespan of the generated token. Defaults to 900s (15 mins)

#generateIdToken

Generates a Decentralized Id Token with optional serialized data.

#Public Methods

Methods
generateIdToken(configuration: GenerateIdTokenConfiguration?): CompletableFuture<GenerateIdTokenResponse>

#Returns

GenerateIdTokenResponse: Response<String>()

Base64-encoded string representation of a JSON tuple representing [proof, claim]

#Example

Kotlin
01class MagicActivity: AppCompatActivity() {
02
03    lateinit var magic: Magic
04
05    override fun onCreate(savedInstanceState: Bundle?) {
06        super.onCreate(savedInstanceState)
07
08        magic = Magic(this, "YOUR_PUBLISHABLE_KEY")
09    }
10
11    // ⭐️Assuming user is logged in
12    fun generateIdToken(v: View) {
13        val configuration = GenerateIdTokenConfiguration(lifespan = 900, attachment = "none")
14        val completable = magic.user.generateIdToken(configuration)
15
16        completable.whenComplete { response: GenerateIdTokenResponse?, error: Throwable? ->
17            if (response != null) {
18                Log.d("Magic", response.result)
19            } else {
20                // handle Error
21            }
22        }
23    }
24}

#Associated Class

GenerateIdTokenConfiguration(attachment: String? = "none", lifespan: Long? = 900)

  • lifespan : will set the lifespan of the generated token. Defaults to 900s (15 mins)
  • attachment : will set a signature of serialized data in the generated token. Defaults to "none"

#getMetadata

Retrieves information for the authenticated user.

#Public Methods

Methods
getMetadata(): CompletableFuture<GetMetadataResponse>

#Returns

GetMetadataResponse: Response<UserMetadataResponse>()

The Completable containing the issuer, email and cryptographic public address of the authenticated user.

Kotlin
01class UserMetadataResponse {
02    var issuer: String? = null
03    var publicAddress: String? = null
04    var email: String? = null
05}
  • issuer : The Decentralized ID of the user. In server-side use-cases, we recommend this value to be used as the user ID in your own tables.
  • email : Email address of the authenticated user.
  • publicAddress: The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.

#Example

Kotlin
01class MagicActivity: AppCompatActivity() {
02
03    lateinit var magic: Magic
04
05    override fun onCreate(savedInstanceState: Bundle?) {
06        super.onCreate(savedInstanceState)
07
08        magic = Magic(this, "YOUR_PUBLISHABLE_KEY")
09    }
10
11    // ⭐️Assuming user is logged in
12    fun getMetadata(v: View) {
13        val completable = magic.user.getMetadata()
14        completable.whenComplete { response: GetMetadataResponse?, error: Throwable? ->
15            if (response != null) {
16                Log.d("Magic", "Email: " + response.result.email)
17                Log.d("Magic", "Issuer: " + response.result.issuer)
18            } else {
19                // handle Error
20            }
21        }
22    }
23}

#isLoggedIn

Checks if a user is currently logged in to the Magic SDK.

#Public Methods

Methods
isLoggedIn(): CompletableFuture<IsLoggedInResponse>

#Returns

IsLoggedInResponse: Response<Boolean>()

#Example

Kotlin
01class MagicActivity: AppCompatActivity() {
02
03    lateinit var magic: Magic
04
05    override fun onCreate(savedInstanceState: Bundle?) {
06        super.onCreate(savedInstanceState)
07
08        magic = Magic(this, "YOUR_PUBLISHABLE_KEY")
09    }
10
11    // ⭐️ Assuming user is logged in
12    fun isLoggedIn(v: View) {
13        val completable = magic.user.isLoggedIn()
14        completable.whenComplete { response: IsLoggedInResponse?, error: Throwable? ->
15            if (response != null && response.result) {
16                Log.d("Magic", "You're Logged In")
17            }
18            if (error != null) {
19                // handle Error
20            }
21        }
22    }
23}

#logout

Logs out the currently authenticated Magic user

#Public Methods

Methods
logout(): CompletableFuture<LogoutResponse>

#Returns

LogoutResponse: Response<Boolean>()

#Example

Kotlin
01class MagicActivity: AppCompatActivity() {
02
03    lateinit var magic: Magic
04
05    override fun onCreate(savedInstanceState: Bundle?) {
06        super.onCreate(savedInstanceState)
07
08        magic = Magic(this, "YOUR_PUBLISHABLE_KEY")
09    }
10
11    // ⭐️Assuming user is logged in
12    fun logout(v: View) {
13        val completable = magic.user.logout()
14        completable.whenComplete { response: LogoutResponse?, error: Throwable? ->
15            if (response != null && response.result) {
16                Log.d("Magic", "You're logged out!")
17            }
18            if (error != null) {
19                // handle Error
20            }
21        }
22    }
23}

#Resources