Datacove API Developer guides
Mobile · Android

Android integration guide

Everything an Android app needs to talk to the Datacove API: signing users in with a one-time code, keeping their session alive, running workflows, receiving results, and selling credits or a subscription through Google Play.

Base URLhttps://<api-host>/api
Credentialsx-api-key · Bearer JWT
Formatapplication/json
User roleMOBILE_USER / EMAIL_OTP_USER / USER

01Before you start

You need two things from your Datacove tenant administrator before writing any code.

An ANDROID API key

A tenant API key whose type is ANDROID. It identifies your app and is sent as the x-api-key header on the sign-in calls and on file uploads. The OTP routes reject keys of any other type.

The API base URL

Every path in this guide is relative to BASE_URL, which already includes the /api prefix and any path prefix your deployment adds in front of it.

Treat the API key as an app identifier, not a secret

Anything shipped inside an APK can be extracted. The key only unlocks the sign-in endpoints and tenant-scoped public data; everything user-specific requires the user's own token. Keep it out of logs and crash reports, and inject it at build time (for example through BuildConfig) rather than committing it.

CredentialSent asUsed for
API keyx-api-key: <key>Requesting and verifying OTPs, uploading files with /media/v1/upload
Access tokenAuthorization: Bearer <token>Everything the signed-in user does: profile, workflows, reports, purchases. Valid for 30 minutes.
Refresh tokenJSON bodyOnly POST /auth/v1/refresh, to get a new token pair. Valid for 7 days and rotated on every use.
App buildX-App-Build: <versionCode>Every request. Lets the server tell outdated builds to update (see App updates).

02How it fits together

The user never sets a password. They prove they own a phone number or email address with a six-digit code, and the app receives a token pair it keeps refreshing for as long as the user stays signed in.

Request OTP x-api-key Verify OTP → token pair Activate first sign-in only Signed-in app Bearer token · refresh every 30 min Workflows execute Billing verify-purchase Report results Socket.IO push, or poll the report
Sign-in uses the app's API key; everything after it uses the user's access token.

03Sign in

Offer phone, email, Google, or any mix. Phone and email work the same way: request a code, verify it, and activate the account the first time it signs in. Google skips the code. Each phone number or email address maps to one account per tenant, created automatically the first time it is used.

Step 1Request codePOST mobile|email/request-otp
Step 2Verify codePOST mobile|email/verify-otp
Step 3ActivatePOST auth/v1/activate
Step 4Load profileGET users/v1/profile
Rate limits on every sign-in route

3 requests per minute and 10 per hour from one IP address. A 429 means wait; show a countdown rather than retrying in a loop.

Phone number

POST/auth/v1/mobile/request-otp API keySend a code

Creates the account if this number is new, then sends a six-digit code by SMS, or by WhatsApp when the tenant has WhatsApp delivery enabled. The response is identical for new and existing numbers, so it never reveals whether an account exists.

FieldTypeNotes
phoneNumberrequiredstringInternational format, digits only, for example 919876543210. A leading + is accepted and stripped.
nameoptionalstringDisplay name. Used only when the account is new; ignored afterwards.
channeloptional"sms" | "whatsapp"Defaults to sms. Send the same value again on verify.
languageoptionalstringPreferred language for emails and messages, as a two-letter code such as en or hi. Used only when the account is new; defaults to en.
StatusMeaning
200Code sent.
400Invalid number, or WhatsApp was requested but isn't enabled for this tenant.
429Rate limited, or (WhatsApp) a code was sent to this number less than 60 seconds ago.
500WhatsApp refused to send the code. Nothing was sent, so the user can retry straight away.
POST/auth/v1/mobile/verify-otp API keyExchange the code for tokens

Codes expire 10 minutes after they're sent and lock after 5 wrong attempts. A locked or expired code can't be retried; request a new one.

FieldTypeNotes
phoneNumberrequiredstringThe same number used on request.
otprequiredstringExactly six digits.
channeloptional"sms" | "whatsapp"Must match the request.
Response · 200
{
  "accessToken": "eyJhbGciOiJIUzI1NiIs...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIs...",
  "expiresIn": 1800
}
StatusMeaning
401Wrong code.
403Locked after 5 wrong attempts.
404No account for this number. Request a code first.
410Code expired.
Kotlin · Retrofit
interface AuthApi {
    @POST("auth/v1/mobile/request-otp")
    suspend fun requestMobileOtp(@Body body: RequestMobileOtp): Response<Unit>

    @POST("auth/v1/mobile/verify-otp")
    suspend fun verifyMobileOtp(@Body body: VerifyMobileOtp): TokenPair

    @POST("auth/v1/activate")
    suspend fun activate(): TokenPair          // Bearer token added by the interceptor

    @POST("auth/v1/refresh")
    suspend fun refresh(@Body body: RefreshRequest): TokenPair
}

data class RequestMobileOtp(val phoneNumber: String, val name: String? = null, val channel: String = "sms")
data class VerifyMobileOtp(val phoneNumber: String, val otp: String, val channel: String = "sms")
data class RefreshRequest(val refreshToken: String)
data class TokenPair(val accessToken: String, val refreshToken: String, val expiresIn: Int)

// Sign-in routes need the app's API key; everything else carries the user's token.
class ApiKeyInterceptor(private val apiKey: String) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): okhttp3.Response =
        chain.proceed(chain.request().newBuilder().header("x-api-key", apiKey).build())
}

Email

Identical to the phone flow, with an email address instead of a number and no channel choice. Requesting a new code within 60 seconds of the last one returns 429.

POST/auth/v1/email/request-otp
Body
{ "email": "jane@example.com", "name": "Jane Doe", "language": "hi" }
POST/auth/v1/email/verify-otp
Body
{ "email": "jane@example.com", "otp": "123456" }

Google

Sign the user in with Google on the device, then send the ID token Google returns. With Credential Manager (or Google Sign-In), pass the tenant's web OAuth client ID to setServerClientId(). The backend checks every platform's token against that one client ID, so a token issued for the app's own client ID is rejected. There is no code to request and no activate step: a Google account is active from the start.

POST/auth/v1/google-login?country=IN API keyExchange a Google ID token for tokens
FieldTypeNotes
idTokenrequiredstringThe Google ID token, sent in the body.
languageoptionalstringPreferred language for emails and messages, as a two-letter code such as en or hi. Used only when the account is new; defaults to en.
countryquerystringTwo-letter country code. Required the first time an email signs in, when the account is created; ignored afterwards.
StatusMeaning
200{ accessToken, refreshToken, expiresIn }, or a 2FA challenge (see below).
400New account and no country was sent.
401The ID token is invalid or expired, was issued for another client ID, or Google sign-in isn't configured for this tenant.
403The account is disabled.
429Rate limited.
One account per email address

Google and email codes sign in to the same account for the same address, here, in the other mobile app and on the web, with the same wallet, history and plans. An account made with an email code becomes a full account the first time the user signs in with Google. Phone-number accounts are separate, because they are identified by the number.

Two-factor authentication

If the user has turned on two-factor authentication on the web, google-login and email/verify-otp return { "twoFactorRequired": true, "challengeToken": "..." } instead of tokens. Ask for the six-digit code from their authenticator app (or a backup code) and send { challengeToken, code } to POST /auth/v1/2fa/verify with the API key; it returns the usual token pair. The challenge expires after 5 minutes. Accounts without two-factor authentication never see this response.

Activate and load the profile

A brand-new account comes back from verify with status: "CREATED" in its access token. Call activate once to move it to ACTIVE; it returns a fresh token pair that replaces the one you just stored. The call is idempotent, so if you're unsure whether it succeeded (a timeout, a dropped connection), just call it again.

POST/auth/v1/activate Access tokenNo body

Returns the same { accessToken, refreshToken, expiresIn } shape. 400 means the account is in a state that can't be activated from the app.

GET/users/v1/profile Access tokenWho is signed in
Response · 200
{
  "name": "Jane Doe",
  "phone": "919876543210",
  "country": "IN",
  "timezone": "Asia/Kolkata",
  "status": "ACTIVE",
  "language": "hi",
  "wallet": { "WALLET": 25, "TRIAL": 0, "SUBSCRIPTION": 0 }
}

wallet.WALLET is the user's spendable credit balance. A new account can start with a signup bonus the tenant configures per platform (the amount for android applies to accounts created in this app, whichever way they sign in), so don't assume it starts at zero.

To change the name, phone number or preferred language, use PATCH /users/v1/profile. Offer the language your users' messages should arrive in on the sign-up screen (send it as language on the first request-otp or google-login call) and in settings. To let a user delete their own account, see Deleting the account.

Deleting the account

Before an account is deleted, the person confirms who they are again, even though they are signed in, so an unlocked phone or a copied token can't erase it. Deletion is immediate and cannot be undone: the person's details, sessions, reports and files are removed, and a later sign-in with the same email or number starts a new account. Unused credits are lost, and a Google Play subscription is not cancelled: link to Google Play's subscription settings. Say both on the confirmation screen.

GET/users/v2/account/deletion-challenge Access tokenWays to confirm

Returns { "methods": [ { "method": "EMAIL_CODE" }, { "method": "PHONE_CODE", "channels": ["sms", "whatsapp"] } ] }, the proofs this account can give. Offer only these.

MethodWhat the person doesSent with the delete
PASSWORDTypes their password.password
EMAIL_CODEEnters the six-digit code emailed to them.code
PHONE_CODEEnters the six-digit code sent by SMS or WhatsApp.code
GOOGLESigns in with Google again, with the same address. Send the new ID token within 5 minutes.idToken
TWO_FACTOREnters a code from their authenticator app, or a backup code.code
POST/users/v2/account/deletion-challenge Access tokenStart confirming

Send { "method": "PHONE_CODE", "channel": "sms" } (channel only for PHONE_CODE). For a code method, the code goes to the account's own email or phone, at most once a minute. Returns { challengeId, method, channel, sentTo, expiresAt }; sentTo is masked, for example r***@example.com. A challenge lasts 10 minutes and allows 5 wrong answers.

DELETE/users/v2/account Access tokenDelete

Send { challengeId } with password, code or idToken, as in the table above. 204 means the account is gone: clear the stored tokens and return to sign-in. A retry with the same token after the account is gone also answers 204.

StatusMeaning
204Deleted.
400METHOD_NOT_AVAILABLE: offer one of the returned methods instead.
401PROOF_INCORRECT: let the person try again. CHALLENGE_INVALID: start a new challenge.
403CHALLENGE_LOCKED after 5 wrong answers: start a new challenge.
409LEGAL_HOLD: the account can't be deleted right now. Show the message and point to support.
410CHALLENGE_EXPIRED after 10 minutes: start a new challenge.
429A code was sent less than a minute ago, or too many attempts. Five a minute, twenty an hour.
502CODE_NOT_SENT: nothing was sent; try again or offer another method.

Disabled accounts. A disabled account can't sign in, so its owner deletes it signed out, with the API key: POST /users/v2/disabled-account/deletion-challenge with { email } or { phoneNumber, channel }, then DELETE /users/v2/disabled-account with { challengeId, code }. The first call answers the same way whether or not a disabled account matches, so show "If an account matches, we've sent a code" either way.

Accounts nobody uses. An account unused for 3 years is deleted the same way, after one warning 30 days before (by email, and by WhatsApp or SMS where the tenant has set it up). Any sign-in, token refresh or run keeps it for another 3 years, and an account with an active plan is never deleted.

The old route. DELETE /users/v1/account still deletes without asking the person to confirm, and answers with Deprecation and Sunset: Sat, 01 May 2027 00:00:00 GMT headers. Move to the v2 routes; v1 is removed once every supported build calls v2.

04Keeping the session alive

Access tokens last 30 minutes. Refresh tokens last 7 days and change every time you use one, so a user who opens the app at least once a week stays signed in indefinitely.

POST/auth/v1/refresh No auth headerRotate the token pair
Body
{ "refreshToken": "eyJhbGciOiJIUzI1NiIs..." }

Returns a new { accessToken, refreshToken, expiresIn }. Always save the new refresh token: the one you sent stops working once the new one is issued.

Rules for a well-behaved client

  • Store tokens securely. Use DataStore or SharedPreferences encrypted with a key from the Android Keystore. Never log them.
  • Refresh proactively. Refresh about a minute before expiresIn elapses, and also when any request returns 401, then retry that request once.
  • Refresh one at a time. If several requests fail at once, they should all wait for a single refresh rather than each starting their own. Two refreshes that arrive within 30 seconds of each other with the same token both succeed and return the same new token. Anything later with an old token is treated as a stolen token and ends the session.
  • Persist before you use. Write the new pair to storage before continuing, so a crash can't leave the app holding a refresh token that's already been replaced.
Kotlin · OkHttp authenticator with single-flight refresh
class TokenAuthenticator(
    private val store: TokenStore,          // encrypted persistence
    private val authApi: AuthApi,           // a separate Retrofit instance without this authenticator
) : Authenticator {
    private val mutex = Mutex()

    override fun authenticate(route: Route?, response: okhttp3.Response): Request? = runBlocking {
        val rejected = response.request.header("Authorization")?.removePrefix("Bearer ")
        val tokens = mutex.withLock {
            val current = store.read() ?: return@withLock null
            // Another request already refreshed while we were waiting: reuse its result.
            if (current.accessToken != rejected) return@withLock current
            try {
                authApi.refresh(RefreshRequest(current.refreshToken)).also { store.write(it) }
            } catch (e: HttpException) {
                if (e.code() == 401) store.clear()   // session is over; send the user to sign-in
                null
            }
        } ?: return@runBlocking null
        response.request.newBuilder().header("Authorization", "Bearer ${tokens.accessToken}").build()
    }
}

When a refresh is rejected

A 401 from refresh, or from any authenticated request, carries a machine-readable code inside error. Use it to tell the user why they were signed out.

401 response
{
  "statusCode": 401,
  "timestamp": "2026-10-02T09:30:00.000Z",
  "path": "/api/auth/v1/refresh",
  "error": {
    "statusCode": 401,
    "error": "Unauthorized",
    "message": "You were signed out because this account signed in on another device.",
    "code": "SESSION_EVICTED"
  }
}
codeWhat happenedSuggested message
SESSION_EVICTEDThe account signed in on more than 5 devices, and this was the oldest session."You were signed out because your account was used on another device."
SESSION_REVOKEDThis session was signed out: logout, "sign out of all devices", signed out from another device's session list, or the account was disabled."You've been signed out."
TOKEN_REUSEDA refresh token that had already been replaced was used again, so the session was ended as a precaution."For your security, please sign in again."
REFRESH_INVALIDThe refresh token is expired (older than 7 days), malformed, or unknown."Your session has expired. Please sign in again."

Devices and signing out

An account can be signed in on up to 5 devices at once. Signing in on a sixth ends the least recently created session. The same endpoints let you build a "signed-in devices" screen:

CallDoes
GET /auth/v1/sessionsLists the user's sessions with createdAt, lastUsedAt, the app type that created it, and current: true on this one.
DELETE /auth/v1/sessions/:sessionIdSigns out one device. Its access token stops working immediately.
GET /auth/v1/logoutSigns out this device.
DELETE /auth/v1/sessionsSigns out every device, including this one.

05Running workflows

A workflow is an AI task with a defined set of inputs. Fetch its definition, render a form from its inputs, then execute it. Each run costs the credits configured for that workflow, deducted from wallet.WALLET.

ListBrowse catalogGET workflows/v1/:page/:size
DescribeGet inputsGET workflows/v1/:id
RunExecutePOST workflows/v1/execute
ResultInline or reportbody · socket · poll

Discover workflows

GET /workflows/v1/:pageNo/:pageSize returns { data, meta }, filtered to what your tenant offers. Optional query parameters: search, category, featured. Then fetch one by its id, for example GET /workflows/v1/wf-sec-001, to get its inputs.

Build the form from inputs

An inputs array
[
  {
    "key": "url",
    "label": "Website address",
    "type": "text",
    "placeholder": "https://example.com",
    "validation": { "required": true }
  },
  {
    "key": "document",
    "label": "Document",
    "type": "file",
    "fileOptions": { "accept": ".pdf,.docx", "maxSizeMb": 10, "multiple": false }
  }
]
FieldUse
keyThe property name to send inside input.
typetext, text-area, number, date, time, location, dropdown, select, file, object, array.
optionsChoices for dropdown and select.
fileOptionsAllowed formats (accept), size limit in MB (maxSizeMb), and whether several files are allowed. The server enforces all three, so read them from here rather than hardcoding them.
validationRules such as required. The server enforces them too.
POST/workflows/v1/execute Access tokenJSON or multipart
FieldTypeNotes
idrequiredstringThe workflow id, for example wf-sec-001.
inputrequiredobjectOne property per input key.
countryoptionalstringISO country code, for workflows whose output varies by country.

Text-only inputs: send JSON. File inputs: send multipart/form-data with id (and country, if used) as plain text fields, every non-file workflow input in one text field named input as a JSON string (send {} if there are none), and each file as a part named after its input key. A missing, empty, unreadable or oversized file, or one whose content isn't an accepted format, is rejected with 400 before anything runs (see file errors).

Kotlin · JSON and multipart
interface WorkflowApi {
    @POST("workflows/v1/execute")
    suspend fun execute(@Body body: ExecuteRequest): JsonObject

    @Multipart
    @POST("workflows/v1/execute")
    suspend fun executeWithFiles(
        @Part("id") id: RequestBody,                 // plain text
        @Part("input") input: RequestBody,           // JSON string of the non-file inputs
        @Part files: List<MultipartBody.Part>,       // one part per file input, named by key
    ): JsonObject
}

data class ExecuteRequest(val id: String, val input: Map<String, Any?>)

// Text input
val result = workflowApi.execute(ExecuteRequest("wf-sec-001", mapOf("url" to "https://example.com")))

// File input: "document" is the input's key
val text = "text/plain".toMediaType()
val filePart = MultipartBody.Part.createFormData(
    "document", "contract.pdf", file.asRequestBody("application/pdf".toMediaType()),
)
val started = workflowApi.executeWithFiles(
    id = "wf-sec-008".toRequestBody(text),
    input = "{}".toRequestBody(text),            // no non-file inputs on this workflow
    files = listOf(filePart),
)

Running workflows with v2

POST/workflows/v2/execute Access tokenmultipart only

Same callers, credits, responses and errors as POST /workflows/v1/execute; only the request differs. New builds should use v2: v1 is deprecated and will be removed once every client has moved.

Form fieldNotes
workflowIdrequiredThe workflow id, for example wf-sec-001 (v1 called it id).
input.<key>One field per workflow input, named after its key. Numbers as decimal text, object and array inputs as JSON text, everything else as text.
input.<key> (file)A file input is the file itself, as a file part with the same name. Repeat the part for inputs that accept several files. Text in a file input (a link, an S3 address, an id) is refused with FILE_INPUT_NOT_A_FILE.
country, name, email, couponCodeoptionalAs in v1.
callAsyncoptionaltrue for sk_ and mk_ keys only. In v2 it is a form field, not a query parameter.

Files are stored privately, exactly as sent: send the original file, without compressing or converting it. A run that doesn't start keeps no files. Other 400 codes: UNKNOWN_FIELD (a field that is neither a run field nor an input of this workflow) and INVALID_JSON. A JSON body gets 415. 403 UPLOADS_NOT_ENABLED means the tenant can't accept files yet. 429 FILE_LIMIT_REACHED means the user or the app has sent too many files for now: wait the number of seconds in the Retry-After header (also error.retryAfterSeconds) and tell the user, rather than retrying. Don't set Content-Type yourself; let the HTTP client add the multipart boundary.

Kotlin · v2
interface WorkflowApiV2 {
    @Multipart
    @POST("workflows/v2/execute")
    suspend fun execute(@Part parts: List<MultipartBody.Part>): JsonObject
}

val parts = listOf(
    MultipartBody.Part.createFormData("workflowId", "wf-sec-008"),
    MultipartBody.Part.createFormData("input.question", "Is this clause fair?"),
    MultipartBody.Part.createFormData(            // the original file, not a resized copy
        "input.document", "contract.pdf",
        file.asRequestBody("application/pdf".toMediaType()),
    ),
)
val started = workflowApiV2.execute(parts)

Two kinds of response

Instant result

Chat and analysis workflows answer in the same request. The 201 body is the result itself.

Report

Longer workflows start a run and return straight away with { "success": true, "eventId": "…", "message": "…" }. Keep the eventId and collect the result as shown in the next section. Reports can take several minutes.

Each workflow always responds the same way, so a client can simply check for eventId in the response.

06Getting report results

Use the realtime channel to be told the moment a report is ready, and keep polling as a fallback. Both use the eventId from execute.

Realtime (recommended) →

Mint a ticket, connect with Socket.IO, join the run's room, and receive workflow_status_update when it finishes. The Realtime guide has a complete Kotlin example.

Polling

Call GET /workflows/reports/v1/:eventId every 5 seconds. A run can take up to 20 minutes, so keep polling at least that long before giving up.

GET /workflows/reports/v1/:eventIdMeaning
200 { "status": "GENERATING" }Still running.
200 (report body)Finished. The body is the report.
404The run failed, or the report doesn't exist. These look the same on purpose. Credits are refunded on failure.
410 REPORT_DELETEDThe report was deleted by its owner or with their account. Its content is gone for good, for everyone it was shared with too. Show "This report has been deleted" and stop polling.

A user's past runs are listed by GET /workflows/reports/v1/history/:page/:limit. The list includes runs the same account made on the web or in the other app; add ?source=android to show only this app's runs. Each item carries its source. The credit history, GET /credits/v1/history/:page/:limit, takes the same filter.

Opening files sent with a run

Files sent with a v2 run are private. List a run's files with the route below, then ask the backend for a link each time the user opens one; the link is signed, works for 10 minutes, and points at the product's own file domain (for example files.legalaware.ai). Don't store links or put them in logs: anyone holding one can open the file until it expires.

GET/workflows/reports/v1/:reportId/files Access tokenthe files of one run

Returns { "data": [...] }, one item per file sent with the run: uploadId, inputKey, fileName, mimeType, sizeBytes, blocked (true when the file was found to contain malware) and linkRoute, the link route below for that file. The check, the password query parameter and the errors are the report's own. Files from runs started before the v2 run route are not listed.

GET/media/v2/files/:uploadId/link Access tokensigned link, 10 minutes

Returns { "url", "expiresAt" }. The same account that may read the run's report may open its files, with the report's password query parameter if it has one. Images, video, audio and PDF open in place; other files download.

StatusMeaning
200Open url right away, in a browser view or the system viewer.
401The report is password-protected and the password is missing or wrong.
403 FILE_BLOCKEDThe file was found to contain malware. Nobody can open it; tell the user it was blocked.
404No such file for this account: unknown, deleted with its report, or someone else's.
409 FILE_LINKS_NOT_ENABLEDThe product has no file domain yet.
GET/media/v2/files/:pageNo/:pageSize Access tokenthe user's own files

The files the user sent, newest first, as { "data": [...], "meta": { "total", "page", "limit", "totalPages" } }. Each item has uploadId, reportId, workflowId, inputKey, fileName, mimeType, sizeBytes and createdAt. A file goes when its report or the account is deleted; there is no separate delete.

Kotlin
interface FilesApi {
    @GET("media/v2/files/{uploadId}/link")
    suspend fun link(
        @Path("uploadId") uploadId: String,
        @Query("password") password: String? = null,
    ): FileLink                                   // { url, expiresAt }
}

// Ask for a fresh link each time; never cache it.
val link = filesApi.link(uploadId)
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link.url)))

07Google Play billing

Apps can sell two kinds of product through Play Billing. Your tenant administrator creates both in the Datacove catalog, using the same product ids you set up in the Play Console.

Credit packages

One-time, consumable products such as "500 credits". A verified purchase adds the package's credits to wallet.WALLET. Users can buy them again and again.

Plan (service entitlement)

A subscription (monthly or annual) or a one-year prepaid plan that unlocks specific workflows. The tenant decides which plans are on sale. A subscription's free trial is part of the plan in the Play Console; a server trial, if any, is for one-year plans only.

Trial and entitlement

Workflows covered by a plan are available while the user has an active trial or an active plan. Without either, executing one returns 403 with code: "ENTITLEMENT_INACTIVE". A run that is allowed is charged the workflow's own credit price like any other run; a workflow included in a plan is normally free, and every other workflow uses credits as usual. The account is what holds the plan, so it follows the user to every device they sign in on, whichever Google account paid. Read the state at launch, when the app returns to the foreground, and after every purchase:

GET/payment/v1/mobile/entitlement Access tokenTrial, plan and paywall in one read
Response · 200
{
  "trial": { "status": "active", "startedAt": "2026-10-01T08:00:00.000Z", "expiresAt": "2026-10-08T08:00:00.000Z" },
  "trialOffer": { "available": true, "durationDays": 7 },
  "entitlement": { "status": "none" },
  "plans": [
    {
      "productId": "650f1c2e9b1d4a0012ab34cd",
      "platformProductId": "plan_one_year",
      "displayName": "1 Year Protection",
      "interval": "one_time_year",
      "gatedWorkflowId": "wf-sec-001"
    }
  ],
  "canExecuteGatedWorkflow": true,
  "serverTime": "2026-10-02T09:30:00.000Z"
}
  • trial.status: not_started, active or expired.
  • trialOffer.available: whether this app offers the server trial (with durationDays when it does). Show a "start free trial" action only when it's true and trial.status is not_started. It is false unless the tenant sets a trial length for this app, which is the usual setup when the subscriptions carry Play's own free trial.
  • plans: the plans on sale in this app, oldest first. Query them with queryProductDetailsAsync using each platformProductId, and build the paywall from what Play returns. interval is monthly, annual or one_time_year.
  • entitlement.status: none if the user has no current plan; otherwise active, in_grace_period or cancelled, with productId, platform and currentPeriodEnd. cancelled means auto-renew is off; the plan still works until currentPeriodEnd.
  • entitlement.inFreeTrial: true while a subscription is in Play's own free trial. Play decides when it ends and charges; the plan gives access throughout, so you only need this to word the UI (for example, "Free trial until date").
  • entitlement.platform is google_play for a Play plan, or reviewer when the account was unlocked with the reviewer login (then there is no productId or currentPeriodEnd). Treat any other value as a label.
  • Use canExecuteGatedWorkflow to decide whether to show the paywall. Compare dates against serverTime, never the device clock.
POST/payment/v1/mobile/trial/start Access tokenIdempotent

Starts the user's one server free trial, whose length the tenant sets for this app. This is separate from a subscription's Play free trial, which needs no call. Calling it again returns the existing trial unchanged, including an expired one, so it's safe to call whenever you're unsure. Send an empty body {}.

Call it only when trialOffer.available is true. Otherwise an account with no trial yet gets 403 with code: "TRIAL_NOT_OFFERED". A trial the user already started, on any device, keeps counting.

If an older version of your app tracked the trial on the device, send that record once as legacyTrial: { startedAt, expiresAt } on the user's first call. The server clamps it to the tenant's trial length, and ignores it if the account already has a trial.

GET/payment/v1/mobile/offer API keyBefore sign-in

Onboarding and a paywall shown before sign-in can't call entitlement, which needs a session. Call this one at launch with the app's x-api-key and no access token. It returns the same trialOffer and plans as entitlement for this app, and nothing about any account.

Response · 200
{
  "trialOffer": { "available": false },
  "plans": [
    {
      "productId": "650f1c2e9b1d4a0012ab34cd",
      "platformProductId": "plan_one_year",
      "displayName": "1 Year Protection",
      "interval": "one_time_year",
      "gatedWorkflowId": "wf-sec-001"
    }
  ],
  "serverTime": "2026-10-02T09:30:00.000Z"
}

trialOffer says whether the app offers a trial, not whether this user can still start one. After sign-in, entitlement is the source of truth. The response may be cached for five minutes. A key that isn't an Android or iOS app key gets 403.

Purchases

  1. Launch the purchase with Play Billing, setting setObfuscatedAccountId() to the user's Datacove user id (the userId claim in the access token). This is recommended rather than required: it ties the purchase to the user inside Google's own records.
  2. Confirm it with the backend as soon as Play Billing reports PURCHASED: call verify-purchase with the purchase token and product id.
  3. Don't acknowledge it yourself. The backend acknowledges every purchase it verifies. For a credit package, call consumeAsync after a 200 so the user can buy the same package again. Leave subscriptions alone.
  4. Recover unfinished purchases. On every launch, call queryPurchasesAsync and send any purchase you haven't confirmed yet through verify-purchase. Verifying the same purchase twice is safe; it is only ever granted once.
POST/payment/v1/mobile/verify-purchase Access tokenGrant a purchase
FieldTypeNotes
platformrequired"google_play"The store the purchase came from.
platformProductIdrequiredstringThe Play product id. The server looks it up in the tenant's catalog to decide what was bought.
purchaseTokenrequiredstringPurchase.getPurchaseToken().
transferToCurrentAccountoptionalbooleanOnly on the retry after the user agreed to move a plan to this account. See Moving a plan.
Credit package · 200
{ "kind": "credit_package", "creditsGranted": 500 }
Plan · 200
{
  "kind": "service_entitlement",
  "entitlementStatus": "active",
  "currentPeriodEnd": "2026-11-02T09:30:00.000Z"
}

A plan response also has "transferred": true when the call moved the plan from another account.

StatusMeaning
400Missing purchase token, the purchase isn't complete yet (for example, pending payment), or it belongs to a different app.
404The product id isn't in the tenant's catalog.
409PURCHASE_LINKED_TO_ANOTHER_ACCOUNT: this plan belongs to a different account. If error.canTransfer is true, offer to move it (see Moving a plan). Otherwise ask the user to sign in with that account.
Kotlin · Play Billing
// 1. Launch, tagging the purchase with the Datacove user id
val params = BillingFlowParams.newBuilder()
    .setProductDetailsParamsList(listOf(productParams))
    .setObfuscatedAccountId(datacoveUserId)
    .build()
billingClient.launchBillingFlow(activity, params)

// 2-3. Confirm each completed purchase with the backend
override fun onPurchasesUpdated(result: BillingResult, purchases: MutableList<Purchase>?) {
    purchases.orEmpty()
        .filter { it.purchaseState == Purchase.PurchaseState.PURCHASED }
        .forEach { purchase -> scope.launch { confirm(purchase) } }
}

suspend fun confirm(purchase: Purchase) {
    val productId = purchase.products.first()
    val granted = paymentApi.verifyPurchase(
        VerifyPurchase(platform = "google_play", platformProductId = productId, purchaseToken = purchase.purchaseToken),
    )
    if (granted.kind == "credit_package") {
        // Consume so the same package can be bought again. The server has already acknowledged it.
        billingClient.consumePurchase(ConsumeParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build())
    }
    refreshWalletAndEntitlement()
}

// 4. On launch, retry anything that never reached the backend
billingClient.queryPurchasesAsync(QueryPurchasesParams.newBuilder().setProductType(ProductType.INAPP).build()) { _, list ->
    list.filter { it.purchaseState == Purchase.PurchaseState.PURCHASED }.forEach { scope.launch { confirm(it) } }
}
Renewals, cancellations and refunds

You don't need to report these. Google notifies the backend directly, and the plan's status updates on its own. Re-read GET /payment/v1/mobile/entitlement when the app returns to the foreground.

Moving a plan to another account

An account is a phone number or email; a plan is paid for by a Google account. When someone signs in with a new number on a phone whose Google account already has an active plan on their old account, verify-purchase answers 409 PURCHASE_LINKED_TO_ANOTHER_ACCOUNT, with error.linkedPlanEndsAt saying when the plan on the other account ends.

  1. If error.canTransfer is true, ask the user, for example: "Your Google Play account already has a plan on another account, active until date. Move it to this account? The other account will lose it."
  2. If they agree, call verify-purchase again with the same purchase token and "transferToCurrentAccount": true. A 200 with "transferred": true means the plan is now on this account.
  3. If they decline, send nothing more. The plan and its remaining time stay on the other account.

canTransfer is false when the plan has ended or belongs to another workspace; don't offer the move then. The server moves a plan without asking when the old account was deleted or shares this account's phone number or email. A move takes the plan's remaining time with it, and renewals and refunds follow the plan to its new account.

Buying again while the plan is on another account

The one-year plan is a prepaid plan, so Google Play lets the same Google account buy it again while it's active: it adds a year as a top-up. If the user declined the move and buys on this account, this account gets exactly the year just bought, starting now, and the other account keeps its remaining time until linkedPlanEndsAt. The currentPeriodEnd that verify-purchase and GET /payment/v1/mobile/entitlement return is this account's own end date, which can be earlier than the date Google Play shows for the whole subscription. Before opening the purchase, tell the user, for example: "This Google Play account already has a plan on another account, active until date. Buying here adds a year to this account; the other account keeps its time."

Reviewer login

Google Play reviewers need the paid feature without paying. They sign in like anyone else (email code), and the paywall offers a Reviewer login next to the payment options: a username and password the tenant administrator sets for this app and gives to Google in the Play Console under App content → App access. Never put a reviewer credential in the app itself.

POST/mobile-apps/v1/reviewer-unlock Access tokenSkip payment
Request
{ "username": "play-reviewer", "password": "••••••••" }
Response · 200
{
  "accessToken": "eyJhbGciOi...",
  "refreshToken": "eyJhbGciOi...",
  "expiresIn": 1800,
  "canExecuteGatedWorkflow": true
}
  • On 200 the account is activated and can run the plan's workflows. Save the new tokens exactly as after POST /auth/v1/activate, then re-read GET /payment/v1/mobile/entitlement (it reports platform: "reviewer").
  • 401 with code: "REVIEWER_LOGIN_INVALID" covers a wrong username or password and a login that isn't set up or is turned off. Show one message, for example "Those reviewer details aren't right." Limited to 5 tries a minute and 10 an hour.
  • Access lasts until the administrator revokes it, which also signs the user out. After signing in again the user sees the paywall.

Store setup

Done once per app by whoever administers the tenant, before purchases can be verified.

  1. In Google Cloud, enable the Google Play Android Developer API, create a service account, and download its JSON key.
  2. In the Play Console under Setup → API access, link that project and grant the service account View financial data and Manage orders and subscriptions.
  3. Create a Pub/Sub topic, grant google-play-developer-notifications@system.gserviceaccount.com the Publisher role on it, and select it under Monetization setup → Real-time developer notifications.
  4. Add a push subscription to that topic that delivers to https://<api-host>/webhooks/google-play (webhooks live outside the /api prefix; include any deployment path prefix). Enable authentication on it so the backend can verify that the messages come from Google.
  5. Save the credentials with PATCH /tenants/v1/:id/google-play-config: packageName, serviceAccountEmail, serviceAccountPrivateKey and pubSubTopic.
  6. Create the catalog: credit packages through /pricing-config (provider google_play, with iapCreditPackages) and plans through /service-entitlement-products (with platformProductIds.googlePlay). Each product id must match the Play Console exactly.
  7. Set free trials on subscriptions in the Play Console, as offers on each base plan. For a server trial on a one-year plan, use PATCH /tenants/v1/:id/trial-config: android.durationDays sets its length, and 0 (the default) means no server trial. Don't offer both on one app.
  8. Set the reviewer login with PUT /mobile-apps/v1/reviewer-logins/:apiKeyId (the Android key's id), and enter the same username and password in the Play Console under App content → App access. GET /mobile-apps/v1/overview shows what each app still needs.

08App updates

The tenant can set the oldest build of your app that may keep using the API. When it raises that minimum, older builds get a notice period (24 hours unless the tenant chooses otherwise) in which they keep working and are told to update. After the deadline the API refuses them until the user updates.

  1. Send X-App-Build on every request, signed in or not: your versionCode (BuildConfig.VERSION_CODE), a whole number such as 59. Without it the server can't tell which build is calling.
  2. Check at launch, before sign-in, with GET /mobile-apps/v1/version-policy.
  3. Read the update headers on every response, and handle 426.
GET/mobile-apps/v1/version-policy API keyIs this build supported?

Send the app's x-api-key and X-App-Build. It is never blocked, even for an outdated build.

Response · 200
{
  "status": "update_required",
  "build": 58,
  "minVersionCode": 59,
  "latestVersionCode": 60,
  "enforceAt": "2026-11-02T10:00:00.000Z",
  "storeUrl": "https://play.google.com/store/apps/details?id=com.example.app",
  "message": "This update keeps your protection working.",
  "serverTime": "2026-11-01T10:00:00.000Z"
}
statusWhat to show
okNothing.
update_availableA dismissible "New version available" prompt, using Play's flexible in-app update. Never block.
update_requiredA banner with the deadline, for example "Update by 2 Nov, 3:30 PM to keep using the app", and an Update button using Play's flexible in-app update. Count down from serverTime to enforceAt, never from the device clock. The app keeps working until then.
update_blockedA full-screen "Update required" with message and Play's immediate in-app update. Don't sign the user out.

On every other response

ResponseMeaning
X-App-Update: availableA newer build exists. Offer it; never block.
X-App-Update: required
X-App-Update-Deadline: <ISO 8601>
X-App-Min-Build: <number>
This build must update before the deadline. The request itself succeeded. Show the deadline banner.
426error.code: "APP_UPDATE_REQUIRED", with error.minVersionCode, error.enforceAt, error.storeUrl and error.message. The deadline has passed: show the blocking update screen. Don't retry and don't sign the user out.

These calls keep working for an outdated build, so the user can always sign out, delete their account or update: the version check, POST /auth/v1/refresh, GET /auth/v1/logout, DELETE /auth/v1/sessions, the account deletion routes (v1 and v2) and the reviewer login.

Kotlin · OkHttp
// Send the build number on every request
class AppBuildInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(
            chain.request().newBuilder()
                .header("X-App-Build", BuildConfig.VERSION_CODE.toString())
                .build(),
        )
        when (response.header("X-App-Update")) {
            "required" -> updateNotice.showDeadline(response.header("X-App-Update-Deadline"))
            "available" -> updateNotice.offerUpdate()
        }
        if (response.code == 426) updateNotice.block()   // error.code == "APP_UPDATE_REQUIRED"
        return response
    }
}
Ship this before you need it

A build only gets the friendly notice if it sends X-App-Build and handles the headers and 426. Builds from before that can only be stopped outright. Add this to the next release, so every later release can be enforced gracefully.

09Errors

Every error uses the same envelope. Branch on the HTTP status first, then on error.code when it's present.

Error envelope
{
  "statusCode": 403,
  "timestamp": "2026-10-02T09:30:00.000Z",
  "path": "/api/workflows/v1/execute",
  "error": {
    "code": "ENTITLEMENT_INACTIVE",
    "message": "Your trial has ended and no active subscription was found for this service."
  }
}
StatusWhereMeaning and what to do
400AnyA field failed validation. error.message lists the problems. A file problem has an error.code from the table below. On execute it can also mean the workflow rejected the input: error.message is The workflow could not process this input, with error.detail (a short reason) or error.fields ([{ field, issue }]) when available. Ask the user to change the input; retrying the same input fails again.
413executePAYLOAD_TOO_LARGE: the upload is over the server's size ceiling. Show error.message.
401Any authenticated callToken expired or session ended. Refresh once; if that fails, use error.code to explain and return to sign-in.
403executeInsufficient credit balance: offer a credit package. ENTITLEMENT_INACTIVE: show the plan paywall.
404execute, reportsUnknown or unavailable workflow, or a failed or missing report.
409executeThe same workflow with identical input is still running from a moment ago. Wait for it instead of retrying. Only returned for workflows that cost credits and for report workflows.
401reviewer-unlockREVIEWER_LOGIN_INVALID: the reviewer details are wrong or not set up. Stay on the paywall; don't sign out.
429Sign-in, refresh, reviewer-unlockRate limited. Back off.
426Any app callAPP_UPDATE_REQUIRED: this build is no longer supported. Show the blocking update screen (see App updates). Don't retry or sign out.
502executeThe workflow service failed or couldn't be reached (Workflow service unavailable. Try again later.). Safe to retry with backoff.
5xxAnyTemporary. Retry with backoff.

File errors on execute are 400. Show error.message as-is; {label} is the input's own label and the limits come from its fileOptions.

error.codeerror.message
FILE_REQUIRED{label} is required
FILE_EMPTYThe selected file is empty
FILE_TYPE_NOT_ALLOWED{label} must be one of: .mp4, .webm, .mov, .avi (the input's accepted formats)
FILE_UNREADABLEThe selected file is corrupt or could not be read
FILE_TOO_LARGE{label} exceeds the maximum size of 100MB (the input's maxSizeMb)
FILE_COUNT_EXCEEDED{label} does not accept multiple files

10Launch checklist

  1. The ANDROID API key is injected at build time and never logged.
  2. Tokens are stored encrypted, and every refresh saves the new pair before it's used.
  3. Refresh is single-flight, and 401 handling reads error.code to show the right sign-out message.
  4. File inputs read fileOptions from the workflow instead of hardcoding limits, execute uses multipart, and file errors show error.message as-is.
  5. Report runs use the realtime channel with a polling fallback that keeps going for at least 20 minutes.
  6. Purchases set setObfuscatedAccountId, are confirmed with verify-purchase, credit packages are consumed after a 200, and unfinished purchases are retried on launch.
  7. The paywall is driven by canExecuteGatedWorkflow, plans and trialOffer from the server, and serverTime, not the device clock.
  8. 409 PURCHASE_LINKED_TO_ANOTHER_ACCOUNT with canTransfer: true offers to move the plan, and only retries with transferToCurrentAccount after the user agrees.
  9. Every request sends X-App-Build; the app checks GET /mobile-apps/v1/version-policy at launch and handles X-App-Update headers and 426 APP_UPDATE_REQUIRED.
  10. The paywall's reviewer login calls reviewer-unlock, and the app contains no reviewer credential of its own.