--- title: HarmonyOS SDK description: "CaptchaLa SDK for HarmonyOS NEXT (ArkTS): HAR installation from the dashboard, verification flow, and server-side validation." --- # HarmonyOS SDK ArkTS SDK for **HarmonyOS NEXT (API 12 / HarmonyOS 5.0.0 and later)**, packaged as a single `.har` (`@captchala/captchala`). Current version: **1.2.0**. It gives you the same verification flow as the Android and iOS SDKs: the challenge opens in a dialog over your page, and your backend validates the `passToken` it returns. ::: info HarmonyOS 4.x and earlier run Android apps. Use the [Android SDK](./android) there. ::: ## Install The SDK is **not published on ohpm**. You download the HAR from the dashboard and add it as a local dependency. 1. Sign in to the dashboard and open [**SDK downloads**](https://dash.captcha.la/sdk-downloads?platform=harmony). The same page also offers a HarmonyOS demo project (source) you can open in DevEco Studio. 2. Download the HarmonyOS HAR, e.g. `captchala-1.2.0.har`. 3. Compare its SHA-256 with the value shown on the download page. Don't use the file if they differ. ```bash # macOS / Linux shasum -a 256 captchala-1.2.0.har # Windows (PowerShell) Get-FileHash captchala-1.2.0.har -Algorithm SHA256 ``` 4. Copy the file to `entry/libs/` and add it to `entry/oh-package.json5`: ```json5 // entry/oh-package.json5 { "dependencies": { "@captchala/captchala": "file:./libs/captchala-1.2.0.har" } } ``` 5. Run `ohpm install` in the `entry` directory, or click **Sync Now** in DevEco Studio. ```bash cd entry ohpm install ``` The HAR is an obfuscated release build that exposes only the public API listed below. Its consumer obfuscation rules ship inside the HAR, so your release build needs no extra keep rules. ### Permissions The SDK uses one permission, `ohos.permission.INTERNET`. It never requests or prompts for a runtime permission. Make sure your entry module declares it: ```json5 // entry/src/main/module.json5 { "module": { "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] } } ``` ### Upgrading Download the new HAR, copy it to `entry/libs/`, change the version in the `file:` path in `entry/oh-package.json5`, delete the old `.har`, and run `ohpm install` again. ## Quick start The flow: 1. Your backend issues a one-time `server_token` for the signed-in user (see [Server token](#server-token)). 2. The app passes it to the SDK and opens the CAPTCHA. 3. `onSuccess` returns a `passToken`; the app sends it to your backend. 4. Your backend validates the `passToken` (see [Server-side validation](#server-side-validation)). ```ts import { CaptchalaClient, CaptchalaConfigBuilder, CaptchalaListener, CaptchalaResult, CaptchalaError } from '@captchala/captchala'; @Entry @Component struct Login { private async verify(): Promise { // 1. Fetch a one-shot server_token from YOUR backend // (which calls the CaptchaLa server API with X-App-Key + X-App-Secret). const serverToken: string | null = await fetchServerTokenFromYourBackend(); // 2. Listen for terminal events. const listener: CaptchalaListener = { onReady: (): void => { /* challenge presented */ }, onSuccess: (result: CaptchalaResult): void => { // Send result.passToken to your backend for validation. sendToBackend(result.passToken); }, onFail: (error: CaptchalaError): void => { /* wrong answer, the user may retry */ }, onError: (error: CaptchalaError): void => { /* network / configuration error */ }, onClose: (): void => { /* user dismissed */ }, onExpired: (passToken: string): void => { /* the pass token expired: ask the user to verify again */ } }; // 3. Build the config. const config = new CaptchalaConfigBuilder() .setAppKey('YOUR_APP_KEY') .setAction('login') // login, register, pay, … // .setLang('ja') // optional: default is the device language // .setTheme('light') // optional: 'auto' (default, follows the system) | 'light' | 'dark' .setServerToken(serverToken) .setOnServerTokenExpired(() => fetchServerTokenFromYourBackend()) .build(); // 4. Open the CAPTCHA. The result is delivered through the listener. CaptchalaClient.getClient(this.getUIContext()) .init(config) .setListener(listener) .verify(); } build() { Button('Verify').onClick(() => { this.verify(); }) } } ``` ## Server token {#server-token} Your backend, not the app, mints the `server_token` by calling `/v1/server/challenge/issue` with your `X-App-Key` + `X-App-Secret`. Pass `bind_uid` with your own user ID so the token, and the `passToken` that comes out of it, belong to that user: ```bash POST https://verify.captcha.la/v1/server/challenge/issue X-App-Key: YOUR_APP_KEY X-App-Secret: YOUR_APP_SECRET Content-Type: application/x-www-form-urlencoded action=login&ttl=300&max_uses=1&bind_uid=user_12345 ``` ```json { "code": 0, "data": { "server_token": "sct_xxxxxxxxxxxx", "expires_in": 300, "issued_at": 1713600000 } } ``` Return `data.server_token` (prefix `sct_`) to the app. `action` must match the value passed to `setAction`. With `setOnServerTokenExpired`, the SDK fetches a fresh token and retries on its own when a token is rejected mid-challenge; return `null` to surface the original error instead. Identity binding options (`bind_uid`, `bind_ip`) are set only on your server when the token is issued. The app never sends them. See the [API Reference](../api-reference#server-token) for every parameter, or use the [PHP](./server-php) / [Go](./server-go) server SDK. ## API surface | Symbol | Purpose | | --- | --- | | `CaptchalaClient.getClient(uiContext)` | Singleton entry point, bound to the `UIContext` of your page. | | `CaptchalaConfigBuilder` | Fluent builder for the configuration (see the table below). `build()` returns a `CaptchalaConfig`. | | `init(config)` | Apply the configuration. Returns the client, so calls can be chained. | | `setListener(listener)` | Register a `CaptchalaListener`. Only `onSuccess` is required; `onReady`, `onFail`, `onError`, `onClose` and `onExpired` (see [Token expiry](#token-expiry)) are optional. | | `verify()` | Open the CAPTCHA dialog. The result is delivered through the listener. | | `refresh()` / `cancel()` / `dismiss()` | Reload the current challenge / stop the flow and close the dialog / close the dialog. | | `setServerToken(token)` | Replace the server token: the next ticket request uses it, instead of the configured one or one the provider returned earlier. Safe before or between `verify()` calls; it never starts a verification. An empty token is ignored; `init(config)` goes back to the config's token. | | `getLastError()` | The last `CaptchalaError` of the current or last verification, or `null`. Cleared when `verify()` starts and when it passes. | | `CaptchalaClient.destroy()` | Release the singleton. | | `CaptchalaResult` | `passToken`, `challengeId`, `ttl`, `isOffline`, `isClientOnly`. Send `passToken` to your backend. `ttl` is deprecated since 1.2.0: the server decides the token lifetime and may change it; use `onExpired`. | | `CaptchalaError` | `code`, `message`, `detail`, and the error fields `errorClass`, `retryable`, `retryAfter`, `reason`, `attempt`, `willRetry`. Passed to `onFail` (the user may retry) and `onError` (network, configuration or system error). | ```ts const client = CaptchalaClient.getClient(this.getUIContext()); client.refresh(); // reload the current challenge client.cancel(); // stop the flow and close the dialog client.dismiss(); // close the dialog CaptchalaClient.destroy(); // release the singleton ``` ### Configuration | Setter | Default | Meaning | | --- | --- | --- | | `setAppKey(string)` | required | Your app key from the dashboard. | | `setAction(string)` | `default` | Business action (`login`, `register`, `pay`, …). Must match the action of the `server_token`. | | `setLang(string)` | `''` (auto) | Challenge language, e.g. `en`, `zh-CN`. | | `setTheme(string)` | `auto` | `auto` (follows the system), `light` or `dark`. | | `setCornerRadius(number)` | `12` | Dialog corner radius in vp; `0` = square. The page and its loading skeleton are clipped to it. | | `setTitle(string \| null)` | `null` | No effect on HarmonyOS: the dialog has no title area (the challenge shows its own title). Used by the macOS / desktop window title only. | | `setServerToken(string \| null)` | `null` | The `server_token` issued by your backend. | | `setOnServerTokenExpired(cb)` | `null` | `() => Promise` that fetches a fresh `server_token` from your backend. | | `setTimeout(number)` | `10000` | Request timeout, ms. | | `setEnableVoice(boolean)` | `true` | Offer the audio challenge. | | `setEnableOfflineMode(boolean)` | `false` | Allow the outage fallback. Its results carry `isOffline` / `isClientOnly`. | | `setMaskClosable(boolean)` | `false` | Tapping the backdrop closes the dialog. | | `setAccount(string \| null)` | `null` | Optional account identifier. | | `setRetryCount(number)` | `3` | Attempts. | | `setRetryDelay(number)` | `1000` | Delay between retries, ms. | | `setBypassServers(string[] \| null)` | `null` | Custom offline bypass hosts. | | `setCollectOdid(boolean)` | `true` | Report a hash of the device ODID (see [Privacy](#privacy)). | | `setLoadingStyle(string)` | `'spinner'` | Loading indicator, see [Loading indicator](#loading-indicator). | | `setLoadingColor(string \| null)` | white | Indicator colour, `#RRGGBB` or `#RRGGBBAA`. | | `setLoadingSize(string)` | `'medium'` | `'small'`, `'medium'` or `'large'`. | | `setLoadingDelay(number)` | `300` | Milliseconds before the indicator appears, `0`–`5000`. | | `setDebug(boolean)` | `false` | Verbose logging during development. | ## Behaviour - **Set the server token before `verify()`.** Pass it with `setServerToken()` on the builder before `init(config)`. To use a new token later, call `client.setServerToken(token)` before the next `verify()`, or let `setOnServerTokenExpired` provide it. Calling `init()` again also works. - **Language.** An empty `setLang` (the default) means auto: the app / device language mapped onto the 54 supported languages, English as the fallback. - **`cancel()` reports `onClose` once** when a verification or a dialog was active, and nothing else: no error and no late result. - **One verification at a time.** A `verify()` while a verification is running or the dialog is shown is ignored. You get one result per verification. ## Token expiry {#token-expiry} The pass token from `onSuccess` is valid for a limited time, decided by the server. If your page has not used it by then, the listener's `onExpired(passToken)` is called once, so you can clear the stored token and ask the user to verify again instead of submitting an expired one. Start a new verification with `verify()`. ```ts const listener: CaptchalaListener = { onSuccess: (result: CaptchalaResult): void => { this.passToken = result.passToken; }, onExpired: (passToken: string): void => { this.passToken = ''; this.showVerifyAgain = true; // your button calls client.verify() again } }; ``` `onExpired` is not called after a new `verify()`, `init()` or `destroy()`. Available from 1.2.0. ## Loading indicator {#loading-indicator} While the challenge loads, the SDK shows a small indicator on the dim. It appears only when loading takes longer than `setLoadingDelay` (default 300 ms), and disappears when the challenge is shown. Available from 1.2.0. - `setLoadingStyle`: `'spinner'` (default, spokes), `'ring'` (a turning arc), `'dots'` or `'none'`. With `'none'` nothing is shown: show your own indicator from `verify()` until `onReady`. - `setLoadingColor`: `#RRGGBB` or `#RRGGBBAA`, default white. - `setLoadingSize`: `'small'`, `'medium'` (default) or `'large'`. - `setLoadingDelay`: milliseconds, `0`–`5000`. ```ts const config = new CaptchalaConfigBuilder() .setAppKey('YOUR_APP_KEY') .setLoadingStyle('dots') .setLoadingColor('#3B82F6') .setLoadingSize('small') .setLoadingDelay(500) .build(); ``` ## ArkGuard (code obfuscation) The HAR's consumer rules keep the SDK's public API working in your obfuscated release build. If your app enables **property obfuscation** (`-enable-property-obfuscation`), ArkGuard also renames property names in **your own code**, so reading JSON with dot access (for example `body.server_token` from your backend's response) can break. Read JSON fields with string keys, or keep the names: ```ts const body: Record = JSON.parse(text) as Record; const token = body['server_token'] as string; // string key: not renamed ``` ```text # obfuscation-rules.txt (alternative) -keep-property-name server_token ``` ## Error handling and retries Options (all optional; leaving them out keeps the earlier behaviour): `setRetry`, `setRetryInterval`, `setRetryMax` (connection attempts, same as `setRetryCount`), `setRetryBackoff`, `setOfflineFallback` (same as `setEnableOfflineMode`), `setRefreshExpired`, `setServerTokenProvider` (wins over `setOnServerTokenExpired`, 10 s timeout). Error fields: `CaptchalaError.errorClass` (`config`, `rate_limit`, `blocked`, `subscription`, `server_token`, `business`, `network`, `clock_skew`; the same classes as the web SDK), `retryable`, `retryAfter` (seconds or `null`), `reason`, `attempt` (ticket requests in this verification, 1 = first) and `willRetry` (`true` when the SDK carries on by itself). `client.getLastError()` returns the last error; `client.setServerToken(token)` replaces the server token for the next request. ```ts const config = new CaptchalaConfigBuilder() .setAppKey('YOUR_APP_KEY') .setRetry('auto') // 'legacy' (default) | 'auto' | 'never' .setServerTokenProvider(async (): Promise => fetchServerTokenFromYourBackend()) .setRefreshExpired('auto') .build(); const listener: CaptchalaListener = { onSuccess: (result: CaptchalaResult): void => { /* … */ }, onError: (error: CaptchalaError): void => { if (error.retryAfter !== null) { showWaitHint(error.retryAfter); } // rate limit else if (!error.retryable) { showSupportHint(error.code); } // config, blocked, binding else { showRetryButton(); } // verify() again later } }; ``` - **Offline fallback is fail-closed by default.** `offlineFallback` follows `enableOfflineMode` (`false`): an outage ends in an error, never in an offline or client-only pass. - **Rate limits.** An HTTP 429 answer is reported as an error with class `rate_limit`, `retryable` and `retryAfter` (seconds). It is not retried by default; with `retry` = `auto` the SDK retries once after `retryAfter` when the wait is at most 60 seconds. See [Handling errors and retries](../concepts/handling-errors) for the error classes and the recommended handling. ## Fast first challenge - `setPrewarm(true)` (the default) warms the API connection and the challenge page at `init()`. Call `init()` when the page appears (`aboutToAppear`), not only on tap. - Fetch the server token from your backend when the screen appears, keep it, and use it on tap. Fetch it inline only when it is missing or expired. - Since 1.1.0 the first challenge is shown without an extra request: the page renders from the answer the SDK already received. ## Server-side validation Forward `result.passToken` to your backend and validate it against the CaptchaLa API. Never put `X-App-Secret` in the app. ```bash POST https://verify.captcha.la/v1/validate X-App-Key: YOUR_APP_KEY X-App-Secret: YOUR_APP_SECRET Content-Type: application/json { "pass_token": "", "expected_action": "login" } ``` Accept the request only when `data.valid` is `true` and `data.uid` equals the user you issued the `server_token` for. Tokens are single-use. See the [API Reference](../api-reference) for the full response and error codes. ## Privacy The SDK reads a set of device attributes that need no permission (model, OS version, screen, locale, time zone and similar) and uses them only for verification and fraud prevention. By default it also reports a truncated SHA-256 hash of the device ODID, never the raw value. No OAID, UDID, serial number or account data is collected. To turn the ODID hash off: ```ts const config = new CaptchalaConfigBuilder() .setAppKey('YOUR_APP_KEY') .setCollectOdid(false) // the ODID is never read .build(); ``` If you keep it on, declare a device identifier used for fraud prevention in your privacy policy and AppGallery privacy label. Where the operating system allows it, the SDK reports the device's local network addresses and the hardware (MAC) addresses of its network interfaces, for fraud prevention. They are sent only inside the encrypted request and never written to a log. CaptchaLa keeps them in full for a short period (7 days by default) and afterwards only in truncated form (IPv4 /24, IPv6 /48, MAC vendor prefix). ## Troubleshooting - **`ohpm install` can't find the package** The `file:` path is relative to the `entry` module. Check that the file exists at `entry/libs/` and that the file name in `oh-package.json5` matches it exactly. - **The old version is still used after an upgrade** Delete the old `.har` from `entry/libs/`, update the version in the `file:` path, then run `ohpm install` again (or **Sync Now**). - **SHA-256 doesn't match** Download the HAR again from [**SDK downloads**](https://dash.captcha.la/sdk-downloads?platform=harmony). Don't ship a file whose checksum doesn't match the dashboard. - **`onError` with a `server_token_*` code** Check that the app's `setAction` matches the `action` used when issuing the token, and that `setOnServerTokenExpired` returns a fresh token. - **The device runs HarmonyOS 4.x or earlier** Not supported. These devices run Android apps; use the [Android SDK](./android). ## Requirements - HarmonyOS NEXT, API 12 (HarmonyOS 5.0.0) or later, Stage model - Device types: phone, tablet, 2-in-1 - ABIs: `arm64-v8a`, `x86_64` (emulator) - `ohos.permission.INTERNET`