# Android SDK

This is the Android SDK for VYou (opens new window), a service to provide user identity to your applications. This library includes a client SDK along with some artifacts and a sample to streamline your workflow.

The SDK is written in Kotlin using Kotlin Cross-Platform to provide support for Android and iOS applications.

# Overview

The SDK consist of various artifacts:

  • KMM-Client: Client to manage operations with VYou authentication server.
  • Android-Google: Library to sign in/up in VYou through Google libraries.
  • Android-Facebook: Library to sign in/up in VYou through Facebook libraries.
  • Android-Stripe: Library to make payments and subscriptions through Stripe.

To support iOS implementation, the KMM Client generates a framework that is pushed to another repository along with the ios artifacts. If you are interested in the iOS implementation, you can go here (opens new window).

Additionally, we created an application sample (opens new window) using Jetpack Compose to check how can be implemented each artifact.

# Client

# Installation

The library is available from Amazon S3, before updating your repositories in the settings.gradle file include this repository:

dependencyResolutionManagement {
    repositories {
        // Your repositories
        maven {
            url = uri("https://vyou-sdks.s3.eu-west-1.amazonaws.com/releases")
        }
    }
}

If you are using an older project configuration, add the repository in your build.gradle file at project level.

allprojects {
    repositories {
        // Your repositories
        maven {
            url = uri("https://vyou-sdks.s3.eu-west-1.amazonaws.com/releases")
        }
    }
}

To add the client library to your app, open your module's build.gradle file and add the following:

dependencies {
    // Your dependencies
    implementation "com.vyou:android-client:$vyou_version"
}

# Getting Started

Before we start, we need to update the module's AndroidManifest.xml file and add the following permission, to perform network operations:


<uses-permission android:name="android.permission.INTERNET" />

# Initialize the client

The first step is to initialise the VYou class, which is the main entry point for all the operations in the library. VYou is a class that contains all the operations you can perform using the SDK; you will use this method once, generate a single instance and use the rest of the methods in your application.

To create the client, we need to invoke the builder class related with VYou class and pass it the required parameters:

VYou.Builder(clientId = "$VYOU_CLIENT_ID", serverUrl = "$VYOU_SERVER_URL") {
    androidContext(applicationContext)
}

These variables are provided by the VYou staff, the approach used in the samples is including this data through the application level build.gradle file, such as:

resValue "string", "vyou_client_id", "${VYOU_CLIENT_ID}"
resValue "string", "vyou_server_url", "${VYOU_SERVER_URL}"

This allows you to setup those values by environment read them from any external file (such as local.properties) in case you need to.

Also, notice that the builder needs a KoinAppDeclaration because we use Koin (opens new window) as our Dependency Injector in the client, the only needed is to pass a lambda with the androidContext as explained previously.

Additionally, the builder can be configurated with some optional functions. If you are using Koin in your project, you must initialize Koin from our implementation and you can import your own koin modules through our addModule and addModules functions and you can add as many as you want.

builder.addModule(module)
//also
builder.addModules(listOfModules)

Also to help you to track the network operations you can change the log level, by default is none.

builder.enableNetworkLogs(VYouLogLevel.all)

VYouLogLevel is a enum class and you can select between all, info, headers, body or none they will affect to our Ktor (opens new window) implementation used by the client.

Lastly, we have two callbacks, first we have addOnRefreshTokenFailure when the refresh token is invalidated by the server and addOnSignOut after the signOut is completed successfully. Both callbacks aims to help you manage the application status when these events occur.

builder.addOnRefreshTokenFailure { throwable ->
    //To do after event
}
builder.addOnSignOut {
    //To do after event
}

Even if you use the optional functions or not, to finally initialize the client you need to invoke the initialize function of the builder.

builder.initialize()

A recommended practice is to initialize VYou in the Application class:

class App : Application() {
    override fun onCreate() {
        super.onCreate()
        initializeVYou()
    }

    private fun initializeVYou() {
        VYou.Builder(clientId = "{VYOU_CLIENT_ID}", serverUrl = "{VYOU_SERVER_URL}") {
            androidContext(applicationContext)
        }
            //additional functions if needed
            .initialize()
    }
}

# Using the client

After initialize the client, we can use it through the application calling VYou.instance(). If the client is not initialized before call instance method, will throw an error related. The client provides functionality to authenticate an user and manage the user's information.

All the methods related with network operations are suspend functions using coroutines in order to use SDK, you must use coroutines in the application.

# Sign in

//Ex: VYou.instance().signIn(params)

//VYouSignInParams(username, password)
suspend fun signIn(params: VYouSignInParams): VYouCredentials

//VYouSignInSocialParams(googleIdToken)
suspend fun signInGoogle(params: VYouSignInSocialParams): VYouCredentials

//VYouSignInSocialParams(facebookAccessToken)
suspend fun signInFacebook(params: VYouSignInSocialParams): VYouCredentials

Each method returns a VYouCredentials class that contains the information to authorize any call covered by VYou auth server. Internally, this information is being saved in a encrypted shared preferences and can be recovered through these credentials methods along helper methods to check the user's session.

//Ex: VYou.instance().accessToken()
fun isLoggedIn(): Boolean
fun tokenType(): String
fun accessToken(): String
fun credentials(): VYouCredentials
fun isValidToken(): Boolean

If you have already a Google or Facebook implementation in your application, you can use these methods to sign in into VYou, further we will explain the social artifacts mentioned at the overview that covers the implementation of social libraries.

# Sign up

To register a new user in the platform, the following three steps are required. Firstly, the new user is registered by providing an email along with the acceptance of the required terms of use and privacy policy provided by the application, optionally a boolean information can be added for any marketing purpose.

//Ex: VYou.instance().signUp(params)

//VYouSignUpParams(email, termsOfUseAccepted, privacyPolicyAccepted, infoAccepted)
suspend fun signUp(params: VYouSignUpParams)

After signing up, the user will receive a confirmation code in the email provided in the previous step. The user must copy this code and enter it to verify registration.

//Ex: VYou.instance().signUpVerify(params)

//VYouSignUpVerifyParams(code)
suspend fun signUpVerify(params: VYouSignUpVerifyParams)

Lastly, if the code provided is valid, the user must register a password related with the email provided using this method:

//Ex: VYou.instance().signUpPassword(params)

//VYouSignUpPasswordParams(password)
suspend fun signUpPassword(params: VYouSignUpPasswordParams)

All these steps are needed to ensure all security steps related to the OAuth protocol. After password successful registration, the user can use sign in method to log in to the platform.

# Profile

Users have access to the information they provide to the application via VYou. To retrieve the current information they have the following method.

//Ex: VYou.instance().getProfile()

suspend fun getProfile(): VYouProfile

VYouProfile is a class containing the registered email, custom fields and the compliance status related to the tenant. If the status is false, the application should request the required fields from the user.

To update your information you have another method to modify the custom fields related to the tenant.

//Ex: VYou.instance().editProfile(params)

//VYouEditProfileParams(fields)
suspend fun editProfile(params: VYouEditProfileParams): VYouProfile

Is not required to provide all the fields, only the ones you want to be modified.

# Payments

To make payments through Stripe, the SDK provides two methods to create payments through the VYou platform.

//Ex: VYou.instance().createPayment(params)

//VYouPaymentParams(amount: Long (in cents))
suspend fun createPayment(params: VYouPaymentParams): String
suspend fun createAnonymousPayment(params: VYouPaymentParams): String

Both methods require the amount desired in cents and will return the secret key requested by the Stripe payment SDK to display the payment sheet. In case that you don't have a integration with Stripe, the VYouStripe library explained below covers all Stripe integration through the VYou platform.

# Subscriptions

To make subscriptions through Stripe, the SDK provide a few methods to manage the whole subscription process.

Firstly, we have the method to return all the products related to the tenant, along with their price range, further the priceId field will be required to create any subscription.

//Ex: VYou.instance().subscriptionProducts()

//VYouProduct(name, description, prices)
//VYouPrice(priceId, amount, currency, interval, intervalCount)
suspend fun subscriptionProducts(): List<VYouProduct>

So, to create a subscription, similar to payments, we have a method that will return the secret key, but in this case we need the priceId related with the desire interval and product. Also, this functionality is covered in the VYouStripe library.

//Ex: VYou.instance().createSubscription(params)

//VYouSubscriptionParams(priceId)
suspend fun createSubscription(params: VYouSubscriptionParams): String

Also, there is a method to display the subscriptions to which a user is subscribed.

//Ex: VYou.instance().mySubscriptions()

//VYouSubscription(subscriptionId, productName, amount, currency, nextBillingDate, created)
suspend fun mySubscriptions(): List<VYouSubscription>

Finally, a user can cancel a subscription by the following method

//Ex: VYou.instance().cancelSubscription(params)

//VYouSubscriptionCancelParams(subscriptionId)
suspend fun cancelSubscription(params: VYouSubscriptionCancelParams)

# Other methods

To log out from the platform and clear the saved credentials, there is a sign out method

//Ex: VYou.instance().signOut()

suspend fun signOut()

Users can also reset password using the following method, after a successful call they will receive an email with a confirmation token and they must proceed as in the sign up process after register the email.

//Ex: VYou.instance().resetPassword(params)

//VYouResetPasswordParams(email)
suspend fun resetPassword(params: VYouResetPasswordParams)

If any call returns a 401 - Forbidden http code, it means that the access token used is expired and should be refresh, to do that must use the refresh token method

//Ex: VYou.instance().refreshToken()

suspend fun refreshToken(): VYouCredentials

This must be implemented on a network interceptor to provide a seamless user experience, if the refresh token fails, the user must log in again to retrieve a new access token.

# Integration with social libraries

To facilitate integration with Google and Facebook, we have created several artefacts to manage login through each platform.

# Installation (Social)

To use the library, you need to add the Amazon S3 provider as described in the Client instructions.

Then, open the build.gradle file of your module and add the following:

dependencies {
    // Your dependencies
    // Client dependency (required)
    implementation "com.vyou:android-client:$vyou_version"
    // Google dependency
    implementation "com.vyou:android-google:$vyou_version"
    // Facebook dependency
    implementation "com.vyou:android-facebook:$vyou_version"

}

# Getting started (Social)

The use of both libraries is very similar. To start using them, first install each library you want to use through the VYou Builder explained in the getting started section of the VYou client.

# Initialize the client (Social)

Each library has a Builder class that returns a Koin module to be used for client initialisation.

val googleModule = VYouGoogle.Builder(googleClientId).module()
val facebookModule = VYouFacebook.Builder(application, facebookClientId).module()

Each module() must be used in the client builder to use them

val builder = VYou.Builder(clientId, serverUrl) {
    androidContext(applicationContext)
}
builder.addModule(googleModule)
builder.addModule(facebooModule)

Then, we can start using both libraries inside our application through their instance() method. Remember, that if you don't install the modules, the instance() method will throw an exception.

# Sign in (Social)

Both libraries have similar methods to sign in to the VYou platform, but before using them we must configure the activity/fragment depending on each library.

Using Google platform, in the activity where we are going to use the Google integration, we must apply this method before the activity invokes its onStart method.

//Ex: VYouGoogle.instance().registerForActivityResult(activtyResultCaller)
fun registerForActivityResult(activityResultCaller: ActivityResultCaller)

//Ex: Inside onCreate activity method
fun onCreate(savedInstanceBundle: Bundle) {
    super.onCreate()
    VYouGoogle.instance().registerForActivityResult(this)
}

In the case of Facebook, we need to apply onActivityResult() method inside our activity/fragment class method.

//Ex: VYouFacebook.instance().onActivityResult(requestCode, resultCode, data)
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

//Ex: Inside onActivityResult activity method
fun onActivityResult(savedInstanceBundle: Bundle) {
    super.onCreate()
    VYouFacebook.instance().registerForActivityResult(this)
}

After applying these methods, we can use the signIn() method of each library.

//Google
//Ex: VYouGoogle.instance().signIn()
suspend fun signIn(): VYouCredentials

//Facebook
//Ex: VYouFacebook.instance().signIn(activity or fragment)
suspend fun signIn(activity: Activity): VYouCredentials
suspend fun signIn(fragment: Fragment): VYouCredentials

Each method returns a VYouCredentials that you can use as you wish.

# Sign out (Social)

To exit social libraries, we have the same method for each library.

//Ex: VYouGoogle.instance().signOut()
//Ex: VYouFacebook.instance().signOut()
suspend fun signOut()

If you use both platforms in your application, we encourage you to use the signOut() method in the client section when the user wants to sign out and then use these social signOut() methods within addOnSignOut() of the client's constructor class.

val builder = VYou.Builder()
builder.addOnSignOut {
    VYouGoogle.instance().signOut()
    VYouFacebook.instance().signOut()
}

# Integration with payment methods

To enhance your customers' experience, the SDK also provides a solution that uses Stripe to make payments and create subscription methods.

# Installation (Stripe)

To use the library, you need to add the Amazon S3 provider as described in the Client instructions.

Then, open the build.gradle file of your module and add the following:

dependencies {
    // Your dependencies
    // Client dependency (required)
    implementation "com.vyou:android-client:$vyou_version"
    // Stripe dependency
    implementation "com.vyou:android-stripe:$vyou_version"
}

# Getting started (Stripe)

To start using the library, it is necessary to install it through the VYou Builder explained in the section getting started of the VYou client.

# Initialize the client (Stripe)

The library has a Builder class that returns a Koin module to be used to initialise the client.

// publishableKey - Key from Stripe's dashboard
// merchantDisplayName - The name of the merchant that you want to display in the payment sheet.
val stripeModule = VYouStripe.Builder(
    applicationContext,
    publishableKey,
    merchantDisplayName
).module()

Each module() must be used in the client builder to use them

val builder = VYou.Builder(clientId, serverUrl) {
    androidContext(applicationContext)
}
builder.addModule(stripeModule)

Then, we can start using the library inside our application through its instance() method. Remember that if you don't install the module, the instance() method will throw an exception.

# Register (Stripe)

Before creating any payment or subscription, we need to register the activity or fragment that will be used to display the payment sheet.

VYouStripe.instance().register(activity)
// or
VYouStripe.instance().register(fragment)

# Payments (Stripe)

Now, we can create any payment to our users, the SDK provides two ways to do it, for users logged into the platform, or do it anonymously, when you don't need the user's information.

VYouStripe.instance().createPayment(params)
VYouStripe.instance().createAnonymousPayment(params)

VYouPaymentParams is a data class that requires the desired amount to be displayed to the user in cents, so if you want to display 1 euro, you must create a VYouPaymentParams(amount: 100) object.

In case the user cancels the payment or the transaction fails, the SDK will return a VYouError.

# Subscriptions (Stripe)

For subscriptions, the process is similar, the only thing that changes is the params object, which is now a VYouSubscriptionParams(priceId: String). The priceId is the payment interval option related to the subscription (product in Stripe). The SDK through the Client library provides a way to to display all subscriptions related to the tenant. You can see this and related methods in the section

VYouStripe.instance().createSubscription(params)

In case the user cancels the subscription or the operation fails, the SDK will return a VYouError.