Skip to content

Ads

Prove to your advertising partners that an impression or a click came from a real person. On Android, your app tells the SDK when an ad is on screen, clicked and gone; for each, the SDK signs the session's current score with the device key into a proof, and your app uploads that proof to DEA's recording service.

The SDK does not request, render or wrap ads. Your ad stack keeps doing that.

Note: Android has no ad session object. It has one proof call, getProof: your app keeps the ad session's id, declares each event itself and uploads each proof as the Upload contract says. See Compared with the Web SDK.

Deprecated: sendProof and record, which signed and uploaded in one call, still work in this release and are removed in a later release. Use getProof and the upload below.

When to use it

  • You sell ad inventory and want to show buyers verified human traffic
  • You want each impression, click and end of an ad signed with the score of the session it happened in

Compared with the Web SDK

The Web SDK's Ads module does more of the work. On Android:

Web Android
ads.session_opened(surface?, adUnit?, options?) (options since 0.26.0) sends the impression and resolves with an AdSession getProof(ProofEvent.AD_IMPRESSION, sessionId = ""), then POST /api/sessions; keep the session_id DEA answers with
ad.click() getProof(ProofEvent.AD_CLICK, sessionId = id), then POST /api/sessions
ad.end() getProof(ProofEvent.AD_ENDED, sessionId = id), then PUT /api/sessions/{id}
A click on the watched element that nothing touched is refused Not checked. A click is signed whenever your app declares one
One click per ad session, and none after end() Not enforced. Your app decides
ads.counts Your app counts what its uploads answered
Proofs are sent in the background; click() and end() return at once getProof blocks while it fetches a challenge, and the upload blocks too: run both off the main thread

Prerequisites

  • The SDK is installed and initialized with your appId and your appKey. See the Quick Start. The appKey is required: on a production appId (one without a test_ or sandbox_ prefix) with no appKey, getProof returns null and lastProofRefusal is app_key_missing, without a request.
  • The device key is registered: call attest() and get PASSED before the first ad. The SDK does not register the key by itself, and DEA accepts a proof only when the key that signed it is registered under the same app. Without a registration the SDK still signs; the proof then claims tier C. It claims B only after a PASSED registration that carried a Play Integrity token and has not expired.
DeaSdk.init(
    this,
    DeaConfig(appId = "YOUR_APP_ID", appKey = "YOUR_APP_KEY"),
)

Usage

Send one ad's events

An ad session takes three proofs, in this order:

  1. The impression, signed with an empty sessionId and uploaded as POST /api/sessions. DEA opens the ad session and answers {"session_id": "<id>"}. Do not leave sessionId out: the default is the capture session's id (sessionInfo.session), which is not an ad session's id.
  2. The click, if there is one, signed with the id DEA answered and uploaded as POST /api/sessions.
  3. The end, signed with the same id and uploaded as PUT /api/sessions/{id}, the update of that ad session.

Pass the same adUnit to all three: it is signed into each proof.

getProof blocks: it fetches a challenge (a single-use nonce) from DEA, then signs. It never uploads. The upload is your app's, and it follows the Upload contract.

Upload contract

Item Rule
Host https://poh-api.dep-protocol.com
ad.impression getProof with sessionId "", then POST /api/sessions. The answer {"session_id": "<id>"} names the ad session
ad.click getProof with sessionId set to the ad session id, then POST /api/sessions
ad.ended getProof with sessionId set to the ad session id, then PUT /api/sessions/{id}, {id} URL-encoded. The path id equals the proof's session_id claim, or DEA answers 400
Headers Content-Type: application/json, Accept: application/json, X-App-Key with the SDK's appKey property. No X-App-ID
Body One JSON object: the app's own unsigned fields first, then h_proof (the SignedProof.proof) and sdk_version, which win over an app field of the same name
sdk_version SDK_VERSION (import ai.dea.sdk.SDK_VERSION)
Timeout 15 s per request
Accepted Any 2xx. An empty body or a body that is not JSON still counts as accepted
Retry Only on no answer (an I/O error or a timeout) or a 5xx
Final Any 4xx, 429 included: no retry
Never retry An error that is neither an HTTP status nor a transport failure, such as an answer that did not parse: DEA took the proof, and the same jti again is a replay
Attempts At most 5 sends in all
Backoff Before retry n (n is 1 after the first failed send): min(2000 * 2^(n-1), 30000) ms, plus a random 0 to 999 ms
Expiry Never send at or after the proof's exp claim (iat plus 90 s): stop and drop the proof
Same proof A retry resends the same h_proof. Each getProof makes a new jti

The SDK's appKey property is the key to send: the appKey you passed, the development key on a test_ or sandbox_ account that named none, or null.

Upload a proof

This uploader follows the contract with HttpURLConnection. It blocks; call it off the main thread:

import ai.dea.sdk.DeaSdk
import ai.dea.sdk.SDK_VERSION
import ai.dea.sdk.proof.SignedProof
import android.net.Uri
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import kotlin.random.Random

/** What DEA answered one proof with. */
sealed class Upload {
    /** A 2xx. `body` is the answer as JSON, or null when it was empty or not JSON. */
    data class Accepted(val body: JSONObject?) : Upload()
    /** A 4xx, which is final, or the last 5xx. */
    data class Refused(val status: Int, val body: String) : Upload()
    /** No answer in five sends, the proof expired, or an error that must not be retried. */
    data class Undelivered(val why: String) : Upload()
}

object DeaUpload {
    private const val HOST = "https://poh-api.dep-protocol.com"
    private const val TIMEOUT_MS = 15_000

    /** Uploads one proof. `update` sends it as `PUT /api/sessions/{id}`: pass it for AD_ENDED. */
    fun send(
        signed: SignedProof,
        update: Boolean = false,
        appFields: Map<String, Any?> = emptyMap(),
    ): Upload {
        val appKey = DeaSdk.instance?.appKey ?: return Upload.Undelivered("no appKey")
        // The app's fields first; h_proof and sdk_version are put last, so they win.
        val body = JSONObject(appFields)
            .put("h_proof", signed.proof)
            .put("sdk_version", SDK_VERSION)
            .toString()
            .toByteArray(Charsets.UTF_8)
        // The path id is the proof's own session_id, URL-encoded.
        val path = if (update) "/api/sessions/" + Uri.encode(signed.sessionId) else "/api/sessions"
        val expiresAtMs = (signed.claims?.optLong("exp") ?: 0L) * 1000

        var last: Upload = Upload.Undelivered("not sent")
        for (attempt in 1..5) {
            if (attempt > 1) {
                val n = attempt - 1
                Thread.sleep(minOf(2000L shl (n - 1), 30_000L) + Random.nextLong(1000))
            }
            if (System.currentTimeMillis() >= expiresAtMs) return Upload.Undelivered("proof expired")

            var conn: HttpURLConnection? = null
            try {
                conn = URL(HOST + path).openConnection() as HttpURLConnection
                conn.requestMethod = if (update) "PUT" else "POST"
                // HttpURLConnection has no whole-request limit: connect and read get 15 s each.
                conn.connectTimeout = TIMEOUT_MS
                conn.readTimeout = TIMEOUT_MS
                conn.doOutput = true
                conn.setRequestProperty("Content-Type", "application/json")
                conn.setRequestProperty("Accept", "application/json")
                conn.setRequestProperty("X-App-Key", appKey)
                conn.outputStream.use { it.write(body) }

                val status = conn.responseCode
                val text = runCatching {
                    val stream = if (status < 400) conn.inputStream else conn.errorStream
                    stream?.bufferedReader()?.use { it.readText() }
                }.getOrNull().orEmpty()

                when (status) {
                    in 200..299 -> return Upload.Accepted(runCatching { JSONObject(text) }.getOrNull())
                    in 500..599 -> last = Upload.Refused(status, text) // retried
                    else -> return Upload.Refused(status, text) // a 4xx, 429 included: final
                }
            } catch (noAnswer: IOException) {
                last = Upload.Undelivered("no answer: $noAnswer") // retried, timeouts included
            } catch (other: Exception) {
                return Upload.Undelivered("not retried: $other") // DEA may hold the proof
            } finally {
                conn?.disconnect()
            }
        }
        return last
    }
}

A retry resends the same body, so the same h_proof. Do not call getProof again to retry: that signs a new proof with a new jti.

One ad, from impression to end

This class signs and uploads one ad's three proofs in a coroutine, one after the other:

import ai.dea.sdk.DeaSdk
import ai.dea.sdk.attest.Verdict
import ai.dea.sdk.proof.ProofEvent
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/** DEA's proofs for one ad. Create one for each ad you show. */
class AdProofs(
    private val scope: CoroutineScope,
    private val adUnit: String,
    private val userId: String? = null, // your app user id, signed as appScopedUid
) {
    private val lock = Mutex() // the impression, the click and the end go up in this order
    @Volatile private var adSessionId: String? = null
    @Volatile private var clickSent = false

    /** The ad is on screen. */
    fun shown() = queued {
        val dea = DeaSdk.instance ?: return@queued
        if (dea.attest().verdict != Verdict.PASSED) return@queued

        // An empty session id: DEA opens the ad session and answers with its id.
        val proof = dea.getProof(ProofEvent.AD_IMPRESSION, sessionId = "", adUnit = adUnit, appScopedUid = userId)
        if (proof == null) {
            Log.w("MyApp", "Impression not signed: ${dea.lastProofRefusal}")
            return@queued
        }
        when (val answer = DeaUpload.send(proof)) {
            is Upload.Accepted ->
                adSessionId = answer.body?.optString("session_id")?.takeIf { it.isNotEmpty() }
            else -> Log.w("MyApp", "Impression not recorded: $answer")
        }
    }

    /** The user clicked the ad. */
    fun clicked() = queued {
        val id = adSessionId ?: return@queued // no ad session, or the ad has ended
        if (clickSent) return@queued // one click per ad session
        clickSent = true

        val dea = DeaSdk.instance ?: return@queued
        val proof = dea.getProof(ProofEvent.AD_CLICK, sessionId = id, adUnit = adUnit, appScopedUid = userId)
        if (proof == null) {
            Log.w("MyApp", "Click not signed: ${dea.lastProofRefusal}")
            return@queued
        }
        val answer = DeaUpload.send(proof)
        if (answer !is Upload.Accepted) Log.w("MyApp", "Click not recorded: $answer")
    }

    /** The ad is gone: removed or replaced. */
    fun ended() = queued {
        val id = adSessionId ?: return@queued
        adSessionId = null

        val dea = DeaSdk.instance ?: return@queued
        val proof = dea.getProof(ProofEvent.AD_ENDED, sessionId = id, adUnit = adUnit, appScopedUid = userId)
        if (proof == null) {
            Log.w("MyApp", "End not signed: ${dea.lastProofRefusal}")
            return@queued
        }
        val answer = DeaUpload.send(proof, update = true) // PUT /api/sessions/{id}
        if (answer !is Upload.Accepted) Log.w("MyApp", "End not recorded: $answer")
    }

    private fun queued(block: suspend () -> Unit) {
        scope.launch(Dispatchers.IO) { lock.withLock { block() } }
    }
}

Call shown() when the ad is on screen, clicked() when it is clicked, and ended() when it is removed or replaced — from your ad SDK's callbacks, for example. Pass a scope that outlives the screen, such as one your Application holds: an ad often ends as its screen closes, and a scope cancelled with the screen would never upload the end. The next ad is a new AdProofs.

A click or an end before DEA has answered the impression has no ad session id to be signed with, so this class sends nothing for it, as the Web SDK does. lastProofRefusal is read right after the null, before anything else signs: the next getProof, from any thread, overwrites it.

Note: On Android the SDK does not check a click against the user's touches. Your app declares the click, and the SDK signs it whether or not anything touched the ad.

Nothing is signed until the session is sufficient: until it has as many actions as the model asks for, 8 with the built-in model (see Evidence). Before that, getProof returns null with lastProofRefusal not_scored, so an impression declared then is not recorded, and the SDK does not keep it to sign later. When an impression has to be recorded, check that getClassification().result is not INSUFFICIENT first.

Find out why a proof was not accepted

Two steps can fail: signing and the upload.

When getProof returns null, read lastProofRefusal right after it. It is null before the first getProof and after a signed one, and holds the reason after a null:

lastProofRefusal Why
no_core dispose() was called, or no core is loaded. Check coreFault
app_key_missing A production appId without appKey. Refused on the device, without a request
no_key The device has no key to sign with: Android below 6.0, or the Keystore refused
automated Automation detection stopped the SDK, on every account and build. reset() or a new start lifts the stop. See stopped
not_scored The session is not sufficient yet (core code -33): fewer actions than the model asks for, 8 with the built-in model. Sign the impression again once getClassification().result is no longer INSUFFICIENT, if the ad is still on screen
core_not_initialised The core refused: code -1
core_bad_argument The core refused: code -2
claims_invalid The core refused the claims: code -30, or a code outside this list
claim_reserved The core refused the claims: code -31
claim_missing The core refused the claims: code -32
proof_too_large The core refused: code -34
core_panic The core failed: code -99
key_sign_failed The device key did not sign
claim_score_missing The composed claims lack h_score, h_ts or h_wc
answer_mismatch The composed claims name another session, event or key
claim_model_version_invalid The composed h_mv is not a whole number at or above 0

When a proof was signed, the upload's own outcome says the rest:

Upload outcome Why
2xx DEA accepted the proof. After an impression, an answer without a session_id (or one that is empty or not JSON) still counts as accepted, but no ad session opened: send no click and no end
4xx, 429 included Final, not retried. For example the device key is not registered (call attest() first), appKey is not the app the device key is registered under, or, for an end, the path id is not the proof's session_id (400)
5xx Retried; after five sends, the last answer
No answer: an I/O error or a timeout Retried; DEA could not be reached in five sends
The proof expired The retries ran up to the proof's exp, 90 seconds after it was signed. The proof is dropped
Another error, such as an answer that did not parse Not retried: DEA may hold the proof, and the same jti again is a replay

Read the classification before you request an ad

getProof does not read the classification: once the session is sufficient, every ad your app declares is signed, whatever the score, and the score inside the proof is what tells DEA how human the session was. To decide whether to request an ad at all, read the classification first and act on it in your own ad stack — see Human Scoring.

App user id

Pass your app's id for the user as appScopedUid to each getProof of one ad: the impression, the click and the end. The SDK signs it into the proof, and DEA stores it on the ad session. Leave it out and no id is sent. The AdProofs class above takes it as userId.

val proof = dea.getProof(ProofEvent.AD_IMPRESSION, sessionId = "", adUnit = adUnit, appScopedUid = userId)

Use an id that does not identify the person, of 1 to 128 characters, and the same one you pass to AI Data Tasks. See App user ids.

API

Member Returns Description
getProof(event, sessionId, attestation, adUnit, appScopedUid) SignedProof? Signs one ad event without uploading it; null when nothing was signed. Blocking: fetches a challenge first
lastProofRefusal String? Why the last getProof returned null; null before the first getProof and after a signed one
appKey String? The key to send as X-App-Key
sendProof(...) RecordOutcome Deprecated, removed in a later release. Use getProof and your own upload
record(...) Boolean Deprecated, removed in a later release. Use getProof and your own upload

ProofEvent: AD_IMPRESSION, AD_CLICK, AD_ENDED.

SignedProof.proof is the compact JWS to send as h_proof; SignedProof.sessionId is the signed session_id, and SignedProof.claims the decoded claim set, exp included. See the API Reference for every parameter and for SignedProof.