Skip to main content

Requirements

  • minSdkVersion: 21 (Android 5.0)
  • targetSdkVersion: 34 (Android 14)
  • Kotlin version: 1.8.22 or higher
  • Java compatibility: Java 8

Installation

To install Nemu SDK in your application built with Kotlin, it is mandatory to add the SDK dependency in your build.gradle.kts (or .gradle) file. Additionally, add dependencies to retrieve the origin from your app installations on Google Play.
repositories {
    mavenCentral()
}

dependencies {
    implementation("com.nemu:nemu-kotlin-sdk:1.0.0")
    /* Dependencies for origin recovery through app installation */

    // Google Play
    implementation ("com.android.installreferrer:installreferrer:2.2")
}
After installation, initialize our SDK in the global onCreate of your application, providing the Nemu pixel ID and your Nemu SDK key as arguments.
Note: For security measures, we recommend that your Nemu SDK key be stored as an environment variable.
As a suggestion, you can use a Gradle plugin (like dotenv-gradle) to load a .env with content like:
SDK_TOKEN=<SDK_TOKEN>
PIXEL_ID=<PIXEL_ID>
And use in build.gradle.kts:
val sdkToken = System.getenv("SDK_TOKEN") ?: "default"
val pixelId = System.getenv("PIXEL_ID") ?: "default"
buildConfigField("String", "SDK_TOKEN", "\"$sdkToken\"")
buildConfigField("String", "PIXEL_ID", "\"$pixelId\"")
Example of SDK initialization in the entry file of a mobile application.
import android.app.Application
import com.nemu.NemuTrackingLib
// ...
class MyApp: Application() {
    override fun onCreate() {
        super.onCreate()
        // ...
     // Using environment variables
NemuTrackingLib.getInstance().init(BuildConfig.PIXEL_ID, BuildConfig.SDK_TOKEN, this)
        // ...
    }
    // ...
}
After these steps, the installation of our SDK will be complete in your Kotlin application.

Registering UID to the SDK session

For total security and integrity of your application user data, all UIDs registered by our SDK are encrypted before being stored on our servers.
During the application login process, add a call to the setUserId() method, passing as an argument the defined UID of the user who just completed the login process. See this example:
import com.nemu.NemuTrackingLib

fun AuthUserUseCase(email: String, password: String) {
    loginUser(
        email = email,
        password =password,
        onSuccess = { userId ->
            NemuTrackingLib.getInstance().setUserId(userId)

            Log.d("NemuTracking", "User registred: $userId")
        },
        onError = {
            Log.e("NemuTracking", "Error to login app: $userId")
        }
    )
}
An important point is that we must ensure that users who were already logged in before the SDK installation are also tracked after the update. To do this, you can insert the UID at the moment it becomes available in your application, such as in the Application’s onCreate() or right after loading the saved user (e.g., after sessionManager.loadUser()).
class MyApp: Application() {
override fun onCreate() {
        super.onCreate()

    // Check if user is logged in
        val userId = UserSessionManager.getCurrentUserId()
        if (userId != null) {
            NemuTrackingLib.getInstance().setUserId(userId)
        }
}
}

Retrieving UTMs when sending sale event to Nemu API

The getLastSessionHistory() method returns an object containing the UTMs from the user’s last session. Use this object when sending the sale information to the Nemu API. See the example below:
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
import com.nemu.NemuTrackingLib

fun sendPurchaseWithUtms() {
    val session = NemuTrackingLib.getInstance().getLastSessionHistory()

    val payload = JSONObject().apply {
        put("transactionId", "123")
        put("netValue", 10)
        put("status", "paid")
        put("utm_campaign", session?.utmCampaign ?: JSONObject.NULL)
        put("utm_content", session?.utmContent ?: JSONObject.NULL)
        put("utm_medium", session?.utmMedium ?: JSONObject.NULL)
        put("utm_source", session?.utmSource ?: JSONObject.NULL)
        put("utm_term", session?.utmTerm ?: JSONObject.NULL)
    }

    val client = OkHttpClient()
    val requestBody = payload.toString().toRequestBody("application/json".toMediaType())

    // Request to Nemu API - POST - CREATE ORDER
    val request = Request.Builder()
        .url("https://developers.nemu.com.br/api/v1")
        .post(requestBody)
        .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            println("Error sending request: ${e.message}")
        }

        override fun onResponse(call: Call, response: Response) {
            println("API response: ${response.code}")
        }
    })
}

Testing the SDK and ensuring everything is right

To test the complete flow and ensure your integration is working correctly, you can execute the simple steps below:

1. Initialize the SDK in DEBUG mode

To view logs generated by the SDK itself, you can enable it by passing the optional argument isDebugMode as true to the SDK initialization method where it is being called.
NemuTrackingLib.getInstance().init(BuildConfig.PIXEL_ID, BuildConfig.SDK_TOKEN, this, true) // Last argument refers to debugMode
If your application is not yet configured to receive deep links, click here to learn how to configure them. In your emulation tool, access a link that redirects to your app with a set of UTMs, example:
https://myapp.com?utm_source=nemu&utm_medium=medium-test&utm_campaign=campaign-test&utm_content=content-test

3. Access your application and check if the SDK was initialized correctly through the logs

After the app runs, check your application logs. If everything is configured correctly, we will see the 3 logs below:
2025-05-22 14:55:02 [DEBUG] [NemuTracking] application has been successfully connected with Nemu services

2025-05-22 14:55:03 [DEBUG] [NemuTracking] Reading of UTM parameters via deeplink successfully performed - {"utm_source": "nemu","utm_medium": "medium-test","utm_campaign": "campaign-test","utm_content": "content-test"}

2025-05-22 14:55:04 [DEBUG] [NemuTracking] UID registered by the application - { "userId": "example@email.com" }

A quick explanation about each log:

  1. Connection to Nemu: Shows that Nemu’s SDK was able to correctly connect to Nemu servers through valid pixel ID and SDK token
  2. UTM Extraction: Displays that the SDK was able to receive and correctly store the UTMs defined in the DeepLink
  3. UID Registered: Informs that the SDK was able to assign the UID passed to the current access

4. Check if UTMs are being correctly retrieved when calling the getLastSessionHistory() method

As a final step, check if when calling the getLastSessionHistory() method UTMs are being correctly retrieved. With debug mode enabled, you will be able to see the returned object in the logs, but you can complementarily add logs in the section where the method is being executed for validations:
fun sendPurchaseWithUtms() {
    val session = NemuTrackingLib.getInstance().getLastSessionHistory()

    println("utmSource: ${session?.utmSource}")
    println("utmCampaign: ${session?.utmCampaign}")
    println("utmMedium: ${session?.utmMedium}")
    println("utmContent: ${session?.utmContent}")
    println("utmTerm: ${session?.utmTern}")
    // more code here...
}
In debug mode, when calling this method, the following log will be returned:
2025-05-22 14:55:04 [DEBUG] [NemuTracking] Last session history retrieved - {"utm_source": "nemu","utm_medium": "medium-test","utm_campaign": "campaign-test","utm_content": "content-test||nemu_xiI85afzrP"}
Note: Note that at the end of utm_content the string "||nemu_xiI85afzrP" is automatically inserted. This string represents Nemu’s internal session identifier and should be sent as part of utm_content when sending sales to the Nemu API.