This is the full developer documentation for Snap4ID partner SDK
# What is Snap4ID embedding?
> Put Snap4ID ID-photo capture, processing and delivery inside your mobile app, paid through your app store.
Start here
* **Try it now, no account:** [run the example app](http://sdk.snap4.id/try-it/) on your machine (iOS simulator or Android emulator) against a fake Snap4ID page and a fake store. No purchases.
* **Go live:** [get your partner id](http://sdk.snap4.id/go-live/onboarding/) from Snap4ID, then integrate against `https://snap4.id`.
* **Using an AI coding agent?** [Install the Snap4ID skills](http://sdk.snap4.id/reference/agent-context/#install-the-skills).
Snap4ID turns a selfie into a compliant ID or passport photo (Polish documents first: `pl` locale, PLN prices). With embedding, the whole Snap4ID flow runs **inside your app**: your app shows the Snap4ID page in a WebView, the user pays you through the App Store or Google Play, and the finished files come back to your app.
## How it works
[Section titled “How it works”](#how-it-works)
Three parts work together: a **WebView** in your app shows the Snap4ID page, a small **bridge** carries messages between the page and your app, and your app runs the **store purchase** when the page asks for one. The purchase is then checked by a server, never by the app, and the job is unlocked.
```
flowchart LR
subgraph phone[User's phone]
subgraph app[Your app]
H[Host code]
W[WebView: Snap4ID page]
H <-->|bridge messages| W
end
end
S[(App Store / Google Play)]
SV[Snap4ID]
V{{Purchase check: Snap4ID or you}}
W <-->|HTTPS| SV
H <-->|purchase + receipt| S
H -.->|receipt| V
V -->|unlock the job| SV
```
1. **Capture.** Your app opens `https://snap4.id/embed/{partnerId}`. The page takes or picks a photo and processes it.
2. **Pay.** The page asks your app to sell the photo. Your app runs the store purchase, bound to the page’s payment reference.
3. **Unlock.** A server checks the store receipt and unlocks the job: Snap4ID checks it, or you do (on our verifier server or in your own backend).
4. **Deliver.** The page sends the files to your app, which copies them. Your backend can also get a signed webhook. See [receiving the files](http://sdk.snap4.id/how-it-works/receiving-files/).
“Host code” is either our **React Native component**, which does all of the above for you, or your own code in any native app (iOS, Android, Flutter) speaking the bridge protocol. See [choose your setup](http://sdk.snap4.id/choose-your-setup/).
## Who does what
[Section titled “Who does what”](#who-does-what)
| Part | Does |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| **Your app** | Opens the page full screen, answers the bridge, runs the store purchase, keeps the files |
| **Snap4ID page** | The user interface: capture, preview, order button, done screen. Has no chrome of its own |
| **Snap4ID** | Processes the photo, holds the job for 30 days, signs the file links |
| **Store** | Charges the user. **You are the merchant of record**: the store pays you; refunds and terms are yours |
| **Purchase check** | Snap4ID (with your store details), or you: our verifier server, or your own backend through the [Partner API](http://sdk.snap4.id/reference/partner-api/) |
## Packages
[Section titled “Packages”](#packages)
| Package | Runs in | For |
| -------------------------------- | ----------------------- | -------------------------------------------------------------------------- |
| `@snap4id-sdk/app-embed` | React Native / Expo app | ``: WebView, bridge, store, recovery, delivery |
| `@snap4id-sdk/embed-protocol` | anywhere | the bridge contract: types, JSON Schemas, the transport shim |
| `@snap4id-sdk/partner-api` | your Node backend | signed Partner API client, `job.paid` webhook verifier |
| `@snap4id-sdk/purchase-verifier` | your Node backend | App Store / Google Play receipt verification, a ready-made verifier server |
All SDK source code (packages, examples and these docs) is in the public GitHub repository [lradomski10m/snap4id-sdk](https://github.com/lradomski10m/snap4id-sdk).
New to the words used here? See the [glossary](http://sdk.snap4.id/overview/glossary/). Using a coding agent? Point it at [`/llms.txt`](http://sdk.snap4.id/llms.txt) and the [agent context](http://sdk.snap4.id/reference/agent-context/).
Next step
[Choose your setup](http://sdk.snap4.id/choose-your-setup/): how your app hosts the page, and who checks the purchase.
# Choose your setup
> Two decisions - how your app hosts the page, and who checks the store purchase - and where each combination is documented.
Every integration makes two independent choices. You can change either later; the page stays the same.
## 1. How your app hosts the page
[Section titled “1. How your app hosts the page”](#1-how-your-app-hosts-the-page)
| | React Native component | Any native app |
| ------------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| **For** | React Native / Expo apps | Swift / UIKit / SwiftUI, Kotlin / Java, Flutter, other WebView stacks |
| **You write** | a client config and one screen | the host side of the bridge: WebView setup, message handling, store code |
| **Bridge, recovery, delivery** | done by `@snap4id-sdk/app-embed` | your code, following the [bridge protocol](http://sdk.snap4.id/reference/bridge-protocol/) |
| **Store purchase** | built in (`expo-iap`), or [your own store code](http://sdk.snap4.id/integrate/react-native/own-store/) | StoreKit 2 / Play Billing in your app |
| **Start** | [React Native component](http://sdk.snap4.id/integrate/react-native/) | [Any native app](http://sdk.snap4.id/integrate/native-app/) |
## 2. Who checks the purchase?
[Section titled “2. Who checks the purchase?”](#2-who-checks-the-purchase)
Before Snap4ID releases the files, someone checks the store receipt and unlocks the job. That check always runs on a **server**, never in your app: an app can be modified, so a check there proves nothing.
### Snap4ID checks purchases, or you do?
[Section titled “Snap4ID checks purchases, or you do?”](#snap4id-checks-purchases-or-you-do)
| | Snap4ID checks purchases | You check |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **How** | the page sends the receipt to Snap4ID, which validates it and unlocks the job | a server of yours validates the receipt, then asks Snap4ID to unlock the job with a request signed with your key |
| **Snap4ID needs** | your store specifics: iOS bundle id, Android package, product ids, Play licensing public key, accepted environments. You send them at onboarding; Snap4ID configures them and holds the signing key | an Ed25519 public key (and your product ids) |
| **You run** | nothing | a server: see below |
| **Choose it when** | you have no backend, or don’t need purchases server-side | policy requires checks on your infrastructure, or your backend must own the purchase record |
| **Set up** | [Snap4ID checks purchases](http://sdk.snap4.id/set-up-payments/snap4id-checks/) | one of the two ways below |
### You check: our ready-made server, or your own backend code?
[Section titled “You check: our ready-made server, or your own backend code?”](#you-check-our-ready-made-server-or-your-own-backend-code)
| | Our verifier server | Your own backend |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| **How** | you deploy our ready-made verifier server (configuration only); the Snap4ID page sends the receipt to it, it validates it and sends Snap4ID a signed unlock request | your app sends the receipt to your server, which checks it (optionally with our verifier library) and calls our unlock API |
| **You write** | no code: environment variables and two configuration files | an endpoint behind your user authentication |
| **Your app** | the same as when Snap4ID checks | hands the receipt to your server (`onVerifyPurchase`) |
| **Set up** | [You check: our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/) | [You check: your own backend](http://sdk.snap4.id/set-up-payments/your-backend/) |
Snap4ID records your choice in your partner configuration, and your app must match it (the React Native component reports `trust_mode_mismatch` otherwise).
## Pick a combination
[Section titled “Pick a combination”](#pick-a-combination)
| Your app | Snap4ID checks | You check: our verifier server | You check: your own backend |
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| **React Native** | the least code. [Quickstart](http://sdk.snap4.id/integrate/react-native/) → [Snap4ID checks](http://sdk.snap4.id/set-up-payments/snap4id-checks/) | [Quickstart](http://sdk.snap4.id/integrate/react-native/) → [our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/) | [Quickstart](http://sdk.snap4.id/integrate/react-native/) + `onVerifyPurchase` → [your own backend](http://sdk.snap4.id/set-up-payments/your-backend/) |
| **Native (iOS / Android / Flutter)** | your app hands the receipt to the page. [Native host](http://sdk.snap4.id/integrate/native-app/) → [Snap4ID checks](http://sdk.snap4.id/set-up-payments/snap4id-checks/) | the same, the page sends it to your server. [Native host](http://sdk.snap4.id/integrate/native-app/) → [our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/) | your app sends the receipt to your server. [Native host](http://sdk.snap4.id/integrate/native-app/) → [your own backend](http://sdk.snap4.id/set-up-payments/your-backend/) |
Not sure? Let Snap4ID check purchases first: switching later changes only who checks the receipt.
Next step
Read [how the flow works](http://sdk.snap4.id/how-it-works/flow/), or go straight to the [React Native component](http://sdk.snap4.id/integrate/react-native/) or [any native app](http://sdk.snap4.id/integrate/native-app/).
# Delivery and recovery
> How files reach your app at least once, what happens after a kill, and what you must make idempotent.
A paid photo must never be lost, even if the app is killed between the payment and the delivery. The protocol is built for at-least-once delivery; your host keeps a small record per job and purchase and finishes interrupted work on the next start. The React Native component does this for you; a native host follows the same rules.
## Guarantees
[Section titled “Guarantees”](#guarantees)
* **Delivery at least once.** `job.completed` is sent once per page load of a paid job, and again whenever the job is reopened (`/embed/{partnerId}/job/{jobId}`). Store it idempotently by `jobId`. The component calls `onCompleted` until it resolves, and once more if the app dies between “resolved” and its own record.
* **Purchases finish only after the unlock**, and only for the job they unlocked.
* **Recovery at every start.** Unfinished store purchases are adopted and unlocked; paid jobs not yet delivered are reopened in a hidden WebView so the page sends `job.completed` again. The user does nothing.
## Copy, don’t link
[Section titled “Copy, don’t link”](#copy-dont-link)
File links are signed and live as long as the job: **30 days**. Copy the files you keep. A link that expired while the job still exists is fixed by reopening the job, which sends fresh `job.completed` data. Your backend can also copy the files with the Partner API `getJob`.
## Kill scenarios
[Section titled “Kill scenarios”](#kill-scenarios)
| Killed while… | Next start |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| the store sheet was open | an approved purchase is found among the store’s unfinished purchases and unlocked; a pending one stays pending (up to 24 h) |
| after paying, before the unlock | the purchase is still unfinished: unlocked again (idempotent) |
| after the unlock, before delivery | the job is reopened in the background and delivered |
| while storing the files | delivery runs again for the same job |
## Duplicates
[Section titled “Duplicates”](#duplicates)
A second purchase for an already paid job is reported as `duplicate_purchase` **before** it is finished, so a kill can repeat the report but never lose it. Refund each reported transaction once.
## Several users on one device
[Section titled “Several users on one device”](#several-users-on-one-device)
Keep jobs and purchases per signed-in user (the component: one `namespace` per user).
Next step
[Privacy and consent](http://sdk.snap4.id/how-it-works/privacy-and-consent/).
# The flow, step by step
> From opening the page to the files in your app - every bridge message in order, whoever checks the purchase.
This is what happens on the wire whichever way you host the page. The React Native component performs every host step for you; a native host implements them (see [any native app](http://sdk.snap4.id/integrate/native-app/)).
```
sequenceDiagram
autonumber
participant P as Snap4ID page
participant H as Your app (host)
participant S as Store
participant R as Purchase check
participant SV as Snap4ID
H->>P: open https://snap4.id/embed/{partnerId} (shim injected first)
P->>H: hello (trustMode, productIds)
H-->>P: hello reply (platform, consent)
H-->>P: price.result (store price of the product)
P->>SV: upload + process photo
P->>H: job.created
P->>H: purchase.request (productId, paymentRef)
H->>S: buy, bound to paymentRef
S-->>H: purchase + receipt (left unfinished)
H->>R: receipt (via the page, or to your backend)
R->>SV: verify and unlock the job
H-->>P: purchase.result
SV-->>P: job paid, links signed
P->>H: job.completed (orderCode, files)
H->>S: finish the purchase
H->>H: copy the files
P->>H: close
```
## 1. Open the page
[Section titled “1. Open the page”](#1-open-the-page)
Your app loads `https://snap4.id/embed/{partnerId}` (or `/embed/{partnerId}/job/{jobId}` to reopen a job) full screen. Before any of the page’s scripts run, it injects the **shim**, which defines the bridge. Only `https://snap4.id` is ever loaded in a release build.
## 2. Handshake
[Section titled “2. Handshake”](#2-handshake)
The page sends `hello` saying who checks your purchases and naming your product (the store product id per store you gave Snap4ID at onboarding); your app answers at once with its own `hello`: platform, app version, the user’s analytics consent, what the done screen may offer (Save / Share), and optional theme and text overrides. No answer within the handshake time ⇒ `handshake_timeout`. Then your app looks up the product’s price in its store and sends it (`price.result`) for the order button.
## 3. Capture and process
[Section titled “3. Capture and process”](#3-capture-and-process)
The user takes or picks a photo inside the page (your app grants camera and file-chooser access). The page sends `job.created` with the job id, processes the photo and shows the preview and the price. Navigation goes through the bridge: `stepChanged` titles your header, `canGoBack` tells you whether the system back gesture should go to the page (`back`) or close the flow.
## 4. Purchase
[Section titled “4. Purchase”](#4-purchase)
The user presses the order button: `purchase.request { jobId, productId, paymentRef, storeBinding }`. Your app buys the consumable product with the store binding (App Store `appAccountToken`, Google Play `obfuscatedProfileId`), so the receipt names the job’s payment ref. It keeps the purchase **unfinished** for now.
## 5. Check the receipt and unlock
[Section titled “5. Check the receipt and unlock”](#5-check-the-receipt-and-unlock)
* **Snap4ID checks, or our verifier server:** your app answers `purchase.result { status: 'succeeded', receipt }`; the page posts the receipt to Snap4ID’s verifier, which checks it and unlocks the job.
* **Your own backend:** your app sends the receipt to your backend, which checks it and calls the Partner API `unlock`; then your app answers `purchase.result { status: 'succeeded' }` without a receipt.
Details, prices and refunds: [payments and trust](http://sdk.snap4.id/how-it-works/payments-and-trust/).
## 6. Deliver
[Section titled “6. Deliver”](#6-deliver)
Once paid and every file has a link, the page sends `job.completed { jobId, orderCode, artifacts }`. That is your signal to **finish the store purchase** (when the page had the receipt checked) and to **copy the files**. Your backend can also receive the signed `job.paid` webhook. The done screen then shows the files (or hands over to your UI) and sends `close`.
What the files are and how to store, show and share them: [receiving the files](http://sdk.snap4.id/how-it-works/receiving-files/). If the app is killed anywhere in between, the next start picks up: see [delivery and recovery](http://sdk.snap4.id/how-it-works/delivery-and-recovery/).
Next step
[Payments and trust](http://sdk.snap4.id/how-it-works/payments-and-trust/): who checks the receipt and why the purchase stays unfinished.
# Payments and trust
> How a store purchase becomes a paid job - the payment-ref binding, who checks the purchase, confirm-after-unlock, prices, duplicates and sandbox.
The user pays **you** in your app through the App Store or Google Play; you are the merchant of record. Snap4ID releases the files only after the purchase is proven: the **unlock**.
## The binding
[Section titled “The binding”](#the-binding)
Every `purchase.request` carries a fresh `paymentRef` (UUID v4). Your app passes it into the store purchase, App Store `appAccountToken` or Google Play `obfuscatedProfileId` (both equal `storeBinding` in the request). The store signs it into the receipt, so the receipt proves which job it paid for. A receipt not bound to the ref is refused (`binding_mismatch`).
## Who checks the purchase
[Section titled “Who checks the purchase”](#who-checks-the-purchase)
Whichever option you choose, a **server** does the same two steps. It is **never done in the app**: an app can be modified, and a check inside it would prove nothing.
1. **Validate the receipt**, offline, against your store details. App Store: the StoreKit JWS chains to Apple’s root certificate, and names your bundle id, one of your products, `appAccountToken` = the payment ref, and is not revoked. Google Play: `originalJson` verifies with your Play licensing public key, and names your package, one of your products, `obfuscatedProfileId` = the payment ref, a completed purchase. In both, the store environment must be one you accept.
2. **Ask Snap4ID to unlock the job**: `POST /api/v1/partner/jobs/{jobId}/unlock`, naming the payment ref, product, transaction id and environment (plus the price; the receipt is attached for audit only), **signed with an Ed25519 key registered for your partner id**. Snap4ID does not check the receipt again: the signature is what it trusts.
| | Snap4ID checks | You check: our verifier server | You check: your own backend |
| -------------------- | ------------------------------------------------------------ | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| Receives the receipt | Snap4ID’s verifier, from the page | your verifier server, from the page | your backend, from your app |
| Validates it with | the store details you sent Snap4ID | the store details in your server’s configuration | your code; our [verifier library](http://sdk.snap4.id/reference/purchase-verifier/) does the checks |
| Calls unlock | Snap4ID’s verifier | your verifier server | your backend |
| Signs that call with | a key Snap4ID holds for your partner id | your Ed25519 key (on your server; public half registered with Snap4ID) | your Ed25519 key (in your secret manager; public half registered with Snap4ID) |
| Snap4ID configures | your store details and product ids | your product ids, your public key, your server’s URL | your product ids, your public key |
| Your code | none | none: configuration only | an endpoint |
| Set up | [Snap4ID checks purchases](http://sdk.snap4.id/set-up-payments/snap4id-checks/) | [our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/) | [your own backend](http://sdk.snap4.id/set-up-payments/your-backend/) |
On every unlock, whoever calls, Snap4ID checks the signature (an active key of your partner), that the job is yours, that the payment ref was issued for this job, that the product is one of yours, that the environment is allowed and matches the platform, that the transaction never unlocked another job, and that the job is not already paid (`already_paid`: refund that purchase).
Your choice is part of your partner configuration at Snap4ID. The page reports it in `hello`; the React Native component compares it with your app (`onVerifyPurchase` present ⇒ your own backend) and fails with `trust_mode_mismatch` if they differ.
## Confirm after unlock
[Section titled “Confirm after unlock”](#confirm-after-unlock)
A consumable store purchase that is finished before the job is unlocked can be lost: if the app is killed in between, the store no longer returns it and nobody can prove the payment. So the purchase stays **unfinished** until the unlock is known:
* Snap4ID or your verifier server checks: when `job.completed` arrives for the job;
* your own backend checks: when your backend answered that it unlocked the job.
Then finish (acknowledge / consume) it, once. Libraries that finish purchases on their own (RevenueCat by default) break this: use observer mode, or the component’s built-in store.
## Prices
[Section titled “Prices”](#prices)
The page shows the store’s localized price for the product on its order button. The product is your in-app purchase item; Snap4ID has its id per store from your onboarding, so the page names it and your app only looks up its price in the store (`price.result`). On iOS the verifier reads the charged price from the signed transaction; Google Play receipts carry no price, so the host reports the store price it knows (`purchase.result.price`).
## Duplicates and refunds
[Section titled “Duplicates and refunds”](#duplicates-and-refunds)
If a job is already paid and another purchase arrives for it (for example an “Ask to Buy” approved after the user bought again), the unlock answers `already_paid`. The extra purchase is finished so the store stops returning it, and reported as `duplicate_purchase` (with `paymentRef`, plus `jobId` / `transactionId` when your app bought it). **Refund it.** A transaction that already unlocked another job is refused (`transaction_already_used`).
## Store environments
[Section titled “Store environments”](#store-environments)
Production accepts `production` receipts only. For App Review, which buys with sandbox receipts against production, Snap4ID can accept `sandbox` until a date you agree; it expires by itself. Xcode StoreKit-configuration receipts and the SDK’s fake receipts are never accepted in production. See [test](http://sdk.snap4.id/test/app-store/).
Next step
[Receiving the files](http://sdk.snap4.id/how-it-works/receiving-files/): what your app gets after payment and how to keep it.
# Privacy and consent
> What the embedded page collects, how analytics consent travels from your app, and what your terms must cover.
## Analytics consent comes from your app
[Section titled “Analytics consent comes from your app”](#analytics-consent-comes-from-your-app)
The embedded page shows no cookie banner and no consent dialog of its own. It runs Snap4ID analytics only when **your app** says the user allowed statistics:
* your host `hello` carries `consent: { statistics: true }` only from the user’s real choice in your app;
* absent or `false` ⇒ analytics stay off;
* if the user changes their choice during the session, send `consent.changed`;
* marketing is never used in embedded pages, whatever you send.
With the React Native component: ``, updated when your consent state changes.
## Terms and privacy policy
[Section titled “Terms and privacy policy”](#terms-and-privacy-policy)
Snap4ID shows no terms of its own in the embedded page: the user accepts **your** terms in your app. They must cover Snap4ID processing the user’s photo and the store purchase. Your privacy policy names Snap4ID as the service that processes the photo.
## What stays where
[Section titled “What stays where”](#what-stays-where)
* The photo and the job live at Snap4ID for **30 days**, then are deleted with their file links.
* Receipts go only to the receipt check (Snap4ID’s verifier, or your backend); the bridge log the component exposes (`onBridgeMessage`) is redacted: no receipts, no store secrets, no signed link query strings. Keep bridge logs out of persistent storage in release builds.
* Your Partner API private key stays on your backend. Nothing secret is ever in the app.
Next step
Integrate: the [React Native component](http://sdk.snap4.id/integrate/react-native/) or [any native app](http://sdk.snap4.id/integrate/native-app/).
# Receiving the files
> What your app gets after payment, when, and for how long - job.completed, onCompleted and the download helper, the Partner API and the job.paid webhook - and how to store, show, save and share the files.
After the user paid, Snap4ID delivers **every** file of the order to your app, whatever the done screen shows. The files are not kept for you: the links in a delivery expire with the job after **30 days**, so your app (or your backend) downloads and stores them.
## Delivery paths
[Section titled “Delivery paths”](#delivery-paths)
```
flowchart LR
SV[Snap4ID]
subgraph phone[User's phone]
P[Snap4ID page]
H[Your app]
F[(Your app storage)]
P -->|"job.completed (bridge)"| H
H -->|download each url| F
end
B[Your backend]
ST[(Your server storage)]
SV -->|paid, links signed| P
SV -.->|"job.paid webhook (optional)"| B
B -->|"Partner API GET job"| SV
B -->|download each url| ST
```
* **In the app (always):** the page sends `job.completed` over the bridge; your app downloads each file.
* **On your backend (optional):** a signed `job.paid` webhook tells you a job was paid; your backend reads the job’s files with the Partner API `getJob` and downloads them. Use it when files must reach your servers too, or to recover a delivery the app never completed.
## What the app gets: `job.completed`
[Section titled “What the app gets: job.completed”](#what-the-app-gets-jobcompleted)
Sent once the job is paid **and** every file has a link, never with a partial set.
| Field | Type | Meaning |
| ----------------------- | --------- | ----------------------------------------------------------------------------------------- |
| `jobId` | string | the paid job |
| `orderCode` | string | six characters, shown to the user and quoted to support |
| `artifacts[]` | array | every deliverable file of the order |
| `artifacts[].code` | string | the file’s artifact code (stable per document; use it as a key) |
| `artifacts[].title` | string | a title in the session language, for your UI |
| `artifacts[].mimeType` | string | `image/jpeg`, `image/png` or `application/pdf` |
| `artifacts[].filename` | string | a safe file name to save under (letters, digits, `_ . -`) |
| `artifacts[].url` | string | time-limited signed download URL, usually on `storage.googleapis.com`; opaque (see below) |
| `artifacts[].expiresAt` | date-time | when the link stops working: the job’s expiry, 30 days after it was created |
```json
{
"jobId": "eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42",
"orderCode": "7K3M9Q",
"artifacts": [
{
"code": "photo-main",
"title": "Zdjęcie do dowodu",
"mimeType": "image/jpeg",
"filename": "snap4id-photo.jpg",
"url": "https://storage.googleapis.com/example-bucket/…/photo.jpg?GoogleAccessId=…&Expires=…&Signature=…",
"expiresAt": "2026-12-24T12:00:00.000Z"
}
]
}
```
About `url`: it is a time-limited **signed download URL**, today a Google Cloud Storage link on `storage.googleapis.com` (its query string carries the signature). Treat it as opaque: don’t parse, rewrite or shorten it, and don’t assume a host, which may change. Plain HTTPS works on iOS (App Transport Security) and Android without extra configuration; if your app, network security configuration, proxy or backend firewall allow-lists hosts, allow `storage.googleapis.com`. The file is deleted at `expiresAt` (the job’s expiry), whatever the link says.
Full schema: [`job.completed`](http://sdk.snap4.id/reference/bridge-protocol/messages/#jobcompleted).
## Which files
[Section titled “Which files”](#which-files)
The files are the **deliverables** of the document the user ordered, as defined in Snap4ID’s document metadata. For an ID or passport photo they are typically:
| File | Type |
| --------------------------------------- | ---- |
| the main photo | JPG |
| a print sheet with several copies | JPG |
| the same print sheet | PDF |
| the photo with a transparent background | PNG |
Previews and thumbnails are never delivered. The set and the codes can differ per document and may grow, so don’t hard-code a fixed list: iterate `artifacts`, key by `code`, and use `mimeType` and `title` for display.
## Guarantees
[Section titled “Guarantees”](#guarantees)
* **At least once, not exactly once.** `job.completed` is sent on every page load of a paid job, and again when the job is reopened (`/embed/{partnerId}/job/{jobId}`). Store the delivery idempotently by `jobId` (and `code`).
* **Survives a kill.** If the app dies before the files are stored, the next start delivers them again: the React Native component reopens paid, undelivered jobs in a hidden WebView (`client.start()` + ``); a native host does the same by reopening the job’s URL. See [delivery and recovery](http://sdk.snap4.id/how-it-works/delivery-and-recovery/).
* **Links live 30 days** (`expiresAt`), then the job and its files are deleted. Copy the files, don’t keep links.
## React Native: the component’s download helper
[Section titled “React Native: the component’s download helper”](#react-native-the-components-download-helper)
The component never downloads by itself. Call the helper from `onCompleted`: it copies every file into `snap4id//jobs//` in the app’s documents directory, records them, skips files already stored, and **rejects until every file is stored**, so the component calls `onCompleted` again (an expired link also makes it reopen the job for fresh data).
src/snap4id.ts
```ts
export const snap4id = createSnap4IdClient({
partnerId: 'your-partner-id',
purchases: 'built-in',
onCompleted: (completion) => snap4id.downloadArtifacts(completion), // idempotent by jobId
});
```
The stored files are in `client.downloads`: `list()` and `forJob(jobId)` return a promise of the stored files; `subscribe(listener)` calls `listener(files)` with the full, updated list after every change and returns an unsubscribe function. Each file is `{ jobId, code, title, mimeType, filename, localUri, bytes }`.
```tsx
// A list that follows new deliveries.
const [files, setFiles] = useState([]);
useEffect(() => {
void snap4id.downloads.list().then(setFiles);
return snap4id.downloads.subscribe(setFiles);
}, []);
```
```tsx
// Show a job's main photo, and save or share any file.
const files = await snap4id.downloads.forJob(jobId);
const photo = files.find((f) => f.mimeType === 'image/jpeg');
;
await snap4id.files.save(jobId, photo.code); // to the photo library
await snap4id.files.share(jobId, photo.code); // the system share sheet
```
`client.files` uses the stored copy, or a temporary copy of the job’s last link when none was stored. Failures throw; inside the flow the component reports them as `save_failed` / `share_failed`. A complete “My photos” screen is in the SDK repository: [`examples/partner-app/src/photos.ts`](https://github.com/lradomski10m/snap4id-sdk/blob/main/examples/partner-app/src/photos.ts).
## Any native app: download from the URLs
[Section titled “Any native app: download from the URLs”](#any-native-app-download-from-the-urls)
On `job.completed`, download each `url` to your app’s storage under its `filename`, record it, then mark the job delivered. Do it again for a job whose files are not all stored yet.
```swift
// iOS
func store(_ completion: JobCompleted) async throws {
let dir = URL.documentsDirectory.appending(path: "snap4id/\(completion.jobId)")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
for artifact in completion.artifacts {
let target = dir.appending(path: artifact.filename)
if FileManager.default.fileExists(atPath: target.path) { continue } // idempotent
let (temp, response) = try await URLSession.shared.download(from: URL(string: artifact.url)!)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw DeliveryError.link }
try FileManager.default.moveItem(at: temp, to: target)
}
try markDelivered(completion.jobId)
}
```
```kotlin
// Android (OkHttp)
fun store(completion: JobCompleted) {
val dir = File(context.filesDir, "snap4id/${completion.jobId}").apply { mkdirs() }
for (artifact in completion.artifacts) {
val target = File(dir, artifact.filename)
if (target.exists()) continue // idempotent
http.newCall(Request.Builder().url(artifact.url).build()).execute().use { response ->
check(response.isSuccessful) { "download failed: ${response.code}" }
response.body!!.byteStream().use { input -> target.outputStream().use { input.copyTo(it) } }
}
}
markDelivered(completion.jobId)
}
```
Show images with your image view; save to the photo library (iOS `PHPhotoLibrary`, Android `MediaStore`) or share (`UIActivityViewController`, `Intent.ACTION_SEND` with a `FileProvider` URI). When the page sends `artifact.save` / `artifact.share`, do the same for that `code` ([done screen](http://sdk.snap4.id/customize/done-screen/)).
## On your backend: Partner API and webhook
[Section titled “On your backend: Partner API and webhook”](#on-your-backend-partner-api-and-webhook)
* `job.paid` webhook: `{ event_id, type, job_id, payment_ref, order_code, paid_at }`, with no files. Verify it, then read the job ([webhooks](http://sdk.snap4.id/set-up-payments/webhooks/)).
* `GET /api/v1/partner/jobs/{jobId}` (`snap4id.getJob(jobId)`): once `paid` is `true`, `artifacts` lists each file as `{ code, title, mime_type, filename, url, expires_at }`, in the same order as in the app. The links are the job’s own signed download URLs (the same on every call, the same kind as in the app), valid until `expires_at`.
```ts
const job = await snap4id.getJob(jobId);
if (job.paid) for (const file of job.artifacts ?? []) await copyToStorage(file.url, file.filename);
```
The backend file names include the order code, for example `snap4id-7K3M9Q-.jpg`, so they don’t collide across jobs in one bucket.
## When something goes wrong
[Section titled “When something goes wrong”](#when-something-goes-wrong)
| Situation | What to do |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| a download fails (network) | keep what is stored and retry the rest; the component’s helper does this and rejects, so `onCompleted` runs again |
| a link answers `403` / `410` before `expiresAt` | reopen the job (`/embed/{partnerId}/job/{jobId}`) for a fresh `job.completed`; the component does this itself |
| files not ready 30 s after payment | the page sends `artifacts_unavailable` (not fatal) and keeps waiting; nothing to do |
| the app was killed before storing | the next start delivers again (recovery) |
| more than 30 days passed | the job and its files are gone; nothing can be recovered, so store files when they arrive |
Next step
[Delivery and recovery](http://sdk.snap4.id/how-it-works/delivery-and-recovery/): the guarantees in detail, kill by kill.
# Host the page in any native app
> What a native host (iOS, Android, Flutter or any WebView stack) does to embed Snap4ID - the bridge contract as a checklist.
Without React Native, your app implements the host side of the bridge itself. It is a small, well-defined job: a WebView, a script injected at document start, a message handler, and your store code. The contract is the [bridge protocol](http://sdk.snap4.id/reference/bridge-protocol/); field-level details are in [bridge messages](http://sdk.snap4.id/reference/bridge-protocol/messages/). Platform walk-throughs: [iOS](http://sdk.snap4.id/integrate/native-app/ios/) and [Android](http://sdk.snap4.id/integrate/native-app/android/).
TypeScript hosts can use `@snap4id-sdk/embed-protocol` directly (`parseWebToHost`, `createHostToWeb`, `hostShimSource`, `deliverScript`). Other languages use the JSON Schemas it ships under `schema/` and the shim text on the platform pages.
## What your host does
[Section titled “What your host does”](#what-your-host-does)
1. **Load only Snap4ID.** Open `https://snap4.id/embed/{partnerId}` (or `/embed/{partnerId}/job/{jobId}` to reopen a job) full screen. Allow main-frame navigation and accept messages from `https://snap4.id` only; open other links outside the WebView or not at all.
2. **Inject the shim at document start.** A short script, before any page script, defines `window.Snap4IdHost`. Its only stack-specific part is the line that posts to your native code (`webkit.messageHandlers…` on iOS, your JavaScript object on Android). If your WebView injects it a moment late, the page waits up to 1.5 s.
3. **Receive messages.** Each page message arrives as one JSON string: `{ v: 1, id, type, payload, replyTo? }`. Validate it; answer an invalid one that expected a reply with `error { code: 'invalid_message' }`.
4. **Send messages** by running the shim’s deliver function with the JSON string: `window.__snap4idHostDeliver(json)`. The shim queues messages until the page is ready.
5. **Answer `hello`** at once with your `hello` (`replyTo` = the page hello’s `id`): `protocolVersion: '1.0'`, `platform`, `appVersion`, the user’s `consent`, `capabilities`. Check the page’s `trustMode` matches your setup. Then **send the price**: the page’s `hello` names your product per store (`productIds`, the ids you gave Snap4ID at onboarding; your app configures none). Look up the id for your store and answer `price.result { products }` (`replyTo` = the page hello’s `id`; `products: {}` when your store has no price), which the page shows on its order button. Never hold your `hello` for the store.
6. **Sell on `purchase.request`.** Buy the consumable `productId` bound to the `paymentRef` (StoreKit `appAccountToken`, Play `obfuscatedProfileId`) and keep the purchase **unfinished**. Then, by who checks purchases:
* *Snap4ID or our verifier server:* answer `purchase.result { status: 'succeeded', receipt }`; the page has the receipt checked;
* *your own backend:* send the receipt to your backend; after it unlocked the job, answer `purchase.result { status: 'succeeded' }` without a receipt (on failure: `failed` with a `reason`). Cancelled, pending and failed purchases answer `cancelled`, `pending`, `failed`.
7. **Finish after the unlock.** The page had the receipt checked: when `job.completed` arrives for the job. Your own backend: when it answered success. A `duplicate_purchase` error names a purchase to finish **and refund**.
8. **Deliver.** Store `job.completed` idempotently by `jobId` and copy the files (links expire after 30 days): [receiving the files](http://sdk.snap4.id/how-it-works/receiving-files/#any-native-app-download-from-the-urls). Handle `artifact.save` / `artifact.share` if you granted them.
9. **Navigate.** Show `stepChanged.title` in your header; while the page reported `canGoBack: true`, the system back gesture sends `back`; close on `close` and on a fatal `error`.
10. **Grant camera and files.** Camera permission for `https://snap4.id` and a file chooser for the photo library.
11. **Recover at every start.** Unlock purchases the store still holds unfinished (resend an unsolicited `purchase.result` when a pending one resolves while the page is open), and reopen paid jobs you have not delivered: the page sends `job.completed` again.
Rules 6–11 are the ones that protect a paid photo; see [payments and trust](http://sdk.snap4.id/how-it-works/payments-and-trust/) and [delivery and recovery](http://sdk.snap4.id/how-it-works/delivery-and-recovery/).
## Flutter and other stacks
[Section titled “Flutter and other stacks”](#flutter-and-other-stacks)
Use a WebView that can inject a user script at **document start** and expose a JavaScript channel to native code (for Flutter, for example, `flutter_inappwebview`). Build the shim with that channel’s post call as the stack-specific line, and deliver messages by evaluating `window.__snap4idHostDeliver(json)`. Everything else in the list above is the same.
Next step
Walk through [iOS](http://sdk.snap4.id/integrate/native-app/ios/) or [Android](http://sdk.snap4.id/integrate/native-app/android/), then [set up payments](http://sdk.snap4.id/set-up-payments/snap4id-checks/).
# Android (WebView + Play Billing)
> A native Android host for the Snap4ID page - document-start shim, the web message listener, delivery, Play Billing purchase and consuming.
A sketch of the host side in Kotlin with AndroidX WebKit (`androidx.webkit`) and Play Billing: every piece the [host contract](http://sdk.snap4.id/integrate/native-app/) asks for. Message shapes: [bridge messages](http://sdk.snap4.id/reference/bridge-protocol/messages/).
## The shim
[Section titled “The shim”](#the-shim)
Ship this script with your app (generated from `@snap4id-sdk/embed-protocol`; refresh it on a new protocol major). It posts page messages to the `snap4idHost` object that `addWebMessageListener` injects.
snap4id-shim.js
```js
(function () {
if (window.Snap4IdHost) return;
var queue = [];
var isReady = false;
function deliver(json) {
var bridge = window.Snap4IdBridge;
if (bridge && typeof bridge.receive === 'function') bridge.receive(json);
else queue.push(json);
}
window.Snap4IdHost = {
postMessage: function (json) { snap4idHost.postMessage(json); },
ready: function () {
isReady = true;
var pending = queue;
queue = [];
pending.forEach(deliver);
}
};
window.__snap4idHostDeliver = function (json) {
if (!isReady) { queue.push(json); return; }
deliver(json);
};
})();
true;
```
## WebView and bridge
[Section titled “WebView and bridge”](#webview-and-bridge)
```kotlin
private val snap4id = setOf("https://snap4.id")
fun setUp(webView: WebView, shim: String) {
webView.settings.javaScriptEnabled = true
webView.settings.domStorageEnabled = true
webView.settings.mediaPlaybackRequiresUserGesture = false
// Page → host, from the Snap4ID main frame only.
WebViewCompat.addWebMessageListener(webView, "snap4idHost", snap4id) { _, message, origin, isMainFrame, _ ->
if (isMainFrame && origin.toString() == "https://snap4.id") message.data?.let(::handle)
}
// The shim before the page's first script (else the page waits up to 1.5 s for a late one).
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
WebViewCompat.addDocumentStartJavaScript(webView, shim, snap4id)
}
webView.webViewClient = object : WebViewClientCompat() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean =
request.isForMainFrame && !(request.url.scheme == "https" && request.url.host == "snap4.id")
}
webView.webChromeClient = object : WebChromeClient() {
override fun onPermissionRequest(request: PermissionRequest) { // CAMERA granted to the app first
if (request.origin.host == "snap4.id") request.grant(arrayOf(PermissionRequest.RESOURCE_VIDEO_CAPTURE))
else request.deny()
}
override fun onShowFileChooser(view: WebView, callback: ValueCallback>,
params: FileChooserParams): Boolean = launchPicker(callback, params)
}
webView.loadUrl("https://snap4.id/embed/your-partner-id")
}
// Host → page: hand the JSON string to the shim's deliver function (main thread).
fun send(webView: WebView, json: String) {
webView.evaluateJavascript("window.__snap4idHostDeliver && window.__snap4idHostDeliver(${JSONObject.quote(json)});", null)
}
```
On the system back gesture: send `back` while the page reported `canGoBack: true`, else close the screen.
## Answer `hello`
[Section titled “Answer hello”](#answer-hello)
Reply at once with `replyTo` = the page hello’s `id` and `platform: "android"`. Then send `price.result` (also `replyTo` = the page hello’s `id`) with the price of the product the page named for Google Play (`payload.productIds.android`), from Play (`queryProductDetailsAsync`, `oneTimePurchaseOfferDetails`: `formattedPrice` → `display_price`; `amount_minor` = `priceAmountMicros / 10_000` for two-decimal currencies; `priceCurrencyCode`); no product ⇒ `"products": {}`.
## Buy on `purchase.request`
[Section titled “Buy on purchase.request”](#buy-on-purchaserequest)
```kotlin
fun buy(activity: Activity, details: ProductDetails, paymentRef: String) {
val params = BillingFlowParams.newBuilder()
.setProductDetailsParamsList(listOf(
BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(details).build()))
.setObfuscatedProfileId(paymentRef) // = storeBinding.obfuscatedProfileId
.build()
billingClient.launchBillingFlow(activity, params)
}
// PurchasesUpdatedListener: do NOT consume yet. Record the purchase for recovery first.
fun resultFor(purchase: Purchase): JSONObject = when (purchase.purchaseState) {
Purchase.PurchaseState.PURCHASED -> JSONObject()
.put("status", "succeeded")
.put("receipt", JSONObject().put("kind", "play")
.put("originalJson", purchase.originalJson).put("signature", purchase.signature))
Purchase.PurchaseState.PENDING -> JSONObject().put("status", "pending")
else -> JSONObject().put("status", "failed").put("reason", "unspecified")
}
```
Answer `purchase.result` with `jobId`, `paymentRef`, this outcome and the store `price` (`{ amount_minor, currency }`: Play receipts carry no price), `replyTo` = the request’s `id`. `USER_CANCELED` answers `cancelled`. With **your backend** checking receipts, send `originalJson` + `signature` to your backend first and answer `succeeded` without `receipt` once it unlocked the job.
## Consume after the unlock
[Section titled “Consume after the unlock”](#consume-after-the-unlock)
```kotlin
suspend fun finishPurchase(purchase: Purchase) {
billingClient.consumePurchase(ConsumeParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build())
}
```
Consume when `job.completed` arrives for the job (the page had the receipt checked) or when your own backend confirmed the unlock, and for a `duplicate_purchase` (then refund it). At every app start, `queryPurchasesAsync` (`INAPP`) lists what is still unconsumed: unlock it (a pending purchase approved later becomes an unsolicited `purchase.result` while the page is open), and reopen `/embed/{partnerId}/job/{jobId}` for paid jobs you have not delivered.
Next step
[Set up payments](http://sdk.snap4.id/set-up-payments/snap4id-checks/), then [test with Play internal testing](http://sdk.snap4.id/test/google-play/).
# iOS (WKWebView + StoreKit 2)
> A native iOS host for the Snap4ID page - shim injection, the message handler, delivery, StoreKit 2 purchase and finishing.
A sketch of the host side in Swift: every piece the [host contract](http://sdk.snap4.id/integrate/native-app/) asks for, without your app’s structure around it. Message shapes: [bridge messages](http://sdk.snap4.id/reference/bridge-protocol/messages/).
## The shim
[Section titled “The shim”](#the-shim)
Ship this script with your app (it is generated from `@snap4id-sdk/embed-protocol`; refresh it when you update to a new protocol major). It posts page messages to the `snap4idHost` script message handler.
snap4id-shim.js
```js
(function () {
if (window.Snap4IdHost) return;
var queue = [];
var isReady = false;
function deliver(json) {
var bridge = window.Snap4IdBridge;
if (bridge && typeof bridge.receive === 'function') bridge.receive(json);
else queue.push(json);
}
window.Snap4IdHost = {
postMessage: function (json) { window.webkit.messageHandlers.snap4idHost.postMessage(json); },
ready: function () {
isReady = true;
var pending = queue;
queue = [];
pending.forEach(deliver);
}
};
window.__snap4idHostDeliver = function (json) {
if (!isReady) { queue.push(json); return; }
deliver(json);
};
})();
true;
```
## WebView and bridge
[Section titled “WebView and bridge”](#webview-and-bridge)
```swift
import WebKit
final class Snap4IdHostController: NSObject, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate {
let webView: WKWebView
private let handlerName = "snap4idHost"
init(shim: String) {
let content = WKUserContentController()
content.addUserScript(WKUserScript(source: shim, injectionTime: .atDocumentStart, forMainFrameOnly: true))
let config = WKWebViewConfiguration()
config.userContentController = content
config.allowsInlineMediaPlayback = true
webView = WKWebView(frame: .zero, configuration: config)
super.init()
content.add(self, name: handlerName) // weak-wrap in production to avoid a retain cycle
webView.navigationDelegate = self
webView.uiDelegate = self
}
func open(partnerId: String) {
webView.load(URLRequest(url: URL(string: "https://snap4.id/embed/\(partnerId)")!))
}
// Page → host: one JSON string per message, from the Snap4ID main frame only.
func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
let origin = message.frameInfo.securityOrigin
guard message.frameInfo.isMainFrame, origin.protocol == "https", origin.host == "snap4.id",
let json = message.body as? String else { return }
handle(json) // parse { v, id, type, payload, replyTo? }, validate, dispatch on type
}
// Host → page: hand the JSON string to the shim's deliver function.
func send(_ json: String) {
let literal = String(data: try! JSONEncoder().encode(json), encoding: .utf8)! // a JS string literal
webView.evaluateJavaScript("window.__snap4idHostDeliver && window.__snap4idHostDeliver(\(literal));")
}
// Only Snap4ID in the main frame; other links open outside (or not at all).
func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard action.targetFrame?.isMainFrame == true else { return decisionHandler(.allow) }
let url = action.request.url
decisionHandler(url?.scheme == "https" && url?.host == "snap4.id" ? .allow : .cancel)
}
// Camera for the capture step (NSCameraUsageDescription in Info.plist).
func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin,
initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType,
decisionHandler: @escaping (WKPermissionDecision) -> Void) {
decisionHandler(origin.host == "snap4.id" ? .grant : .deny)
}
}
```
The photo-library picker of `` needs `NSPhotoLibraryUsageDescription`; saving to Photos needs `NSPhotoLibraryAddUsageDescription`.
## Answer `hello`
[Section titled “Answer hello”](#answer-hello)
Reply at once with `replyTo` = the page hello’s `id`:
```json
{ "v": 1, "id": "", "type": "hello", "replyTo": "",
"payload": { "protocolVersion": "1.0", "platform": "ios", "appVersion": "4.2.0",
"consent": { "statistics": true }, "capabilities": { "save": true, "share": true } } }
```
Then send the price of the product the page named for the App Store (`payload.productIds.ios`), also with `replyTo` = the page hello’s `id`. It comes from StoreKit (`Product.products(for: [id])`: `displayPrice`; `amount_minor` from `price` in minor units, `currency` from `priceFormatStyle.currencyCode`); no product ⇒ `"products": {}`:
```json
{ "v": 1, "id": "", "type": "price.result", "replyTo": "",
"payload": { "products": { "pl.example.app.idphoto": { "amount_minor": 1999, "currency": "PLN", "display_price": "19,99 zł" } } } }
```
## Buy on `purchase.request`
[Section titled “Buy on purchase.request”](#buy-on-purchaserequest)
```swift
import StoreKit
func buy(productId: String, appAccountToken: String) async throws -> [String: Any] {
guard let product = try await Product.products(for: [productId]).first,
let token = UUID(uuidString: appAccountToken) else { return ["status": "failed", "reason": "no_product"] }
switch try await product.purchase(options: [.appAccountToken(token)]) {
case .success(let verification):
// Do NOT finish yet. Record (paymentRef, transaction id) for recovery first.
return ["status": "succeeded", "receipt": ["kind": "app-store", "jws": verification.jwsRepresentation]]
case .pending:
return ["status": "pending"]
case .userCancelled:
return ["status": "cancelled"]
@unknown default:
return ["status": "failed", "reason": "unknown"]
}
}
```
Answer `purchase.result` with `jobId`, `paymentRef` and this outcome, `replyTo` = the request’s `id`. With **your backend** checking receipts, send the `jws` to your backend first and answer `succeeded` without `receipt` once it unlocked the job.
## Finish after the unlock
[Section titled “Finish after the unlock”](#finish-after-the-unlock)
```swift
func finishPurchase(appAccountToken: UUID) async {
for await result in Transaction.unfinished {
if case .verified(let transaction) = result, transaction.appAccountToken == appAccountToken {
await transaction.finish()
}
}
}
```
Call it when `job.completed` arrives for the job (the page had the receipt checked) or when your own backend confirmed the unlock, and for a `duplicate_purchase` (then refund it). At every app start, walk `Transaction.unfinished` and listen to `Transaction.updates`: unlock what is still unfinished (an approved “Ask to Buy” becomes an unsolicited `purchase.result` while the page is open), and reopen `/embed/{partnerId}/job/{jobId}` for paid jobs you have not delivered.
Next step
[Set up payments](http://sdk.snap4.id/set-up-payments/snap4id-checks/), then [test with StoreKit in Xcode](http://sdk.snap4.id/test/app-store/).
# Add the React Native component
> The smallest working integration - an Expo app with the component's built-in store - in four steps.
Start here
* **Try it now, no account:** [run the example app](http://sdk.snap4.id/try-it/) on your machine (iOS simulator or Android emulator) against a fake Snap4ID page and a fake store. No purchases.
* **Go live:** [get your partner id](http://sdk.snap4.id/go-live/onboarding/) from Snap4ID; this page then connects your app to `https://snap4.id`.
* **Using an AI coding agent?** [Install the Snap4ID skills](http://sdk.snap4.id/reference/agent-context/#install-the-skills).
With React Native, `@snap4id-sdk/app-embed` is the whole host side: it opens the page, injects the bridge before the page’s scripts, answers every message, runs the store purchase, finishes it after the unlock, delivers the files and recovers after a kill. You write a client config and one screen.
All SDK source code (packages, examples and these docs) is in the public GitHub repository [lradomski10m/snap4id-sdk](https://github.com/lradomski10m/snap4id-sdk).
## Before you start
[Section titled “Before you start”](#before-you-start)
* Your **partner id** from [Snap4ID onboarding](http://sdk.snap4.id/go-live/onboarding/), and one **consumable** in-app purchase product in each store whose id you gave Snap4ID at onboarding (your app does not configure it: the page names it and shows its store price).
* An Expo app (SDK 58, React Native 0.88) with a **development build** (`expo-dev-client`): the component has native code, so Expo Go does not work.
* The snippets use **Expo Router** with the layout of the default `npx create-expo-app` template (SDK 58): routes in `src/app/`, the client in `src/snap4id.ts`. The template’s root layout is a tab bar with demo screens: replace it with the Stack of step 3 and `src/app/index.tsx` with your own home screen, then delete the template’s demo files (`src/app/explore.tsx`, `src/components/`, `src/hooks/`, `src/constants/`, `src/global.css`): nothing uses them any more, and some of them fail `tsc` and `npx expo lint`. Or keep your tabs and add `flow` as a full-screen route of the root Stack. Routes in `app/` instead (older templates)? Import the client from `'../src/snap4id'`. Another navigator works the same way: start the client and mount `` in your root component, and render `` on a full-screen screen of your own, below an opaque header.
* Decided who checks purchases ([choose your setup](http://sdk.snap4.id/choose-your-setup/)). This page lets Snap4ID check them; for your own backend you add one callback (step 2).
## 1. Install
[Section titled “1. Install”](#1-install)
```sh
npx expo install expo-dev-client react-native-webview expo-iap expo-file-system expo-media-library expo-sharing expo-constants
npm install @snap4id-sdk/app-embed
```
Add the component’s config plugin to the `plugins` of `app.json` (`npx expo install` has already added `expo-iap` and some of the others there; keep them):
```json
{
"expo": {
"plugins": ["@snap4id-sdk/app-embed", "expo-iap"]
}
}
```
(In an `app.config.ts`, the same list: `plugins: ['@snap4id-sdk/app-embed', 'expo-iap']`.) The config plugin writes the camera and photo-library usage texts and the Android camera permission. `expo-media-library` adds broader Android media permissions of its own: to trim them before a Play release, see [config plugin](http://sdk.snap4.id/reference/component-api/#config-plugin). Rebuild the app.
## 2. One client per app process
[Section titled “2. One client per app process”](#2-one-client-per-app-process)
src/snap4id.ts
```ts
import { createSnap4IdClient } from '@snap4id-sdk/app-embed';
export const snap4id = createSnap4IdClient({
partnerId: 'your-partner-id',
purchases: 'built-in',
onCompleted: async (completion) => {
// Called at least once per paid job until it resolves: key your work by completion.jobId.
await snap4id.downloadArtifacts(completion); // copies the files into your app's storage
},
onError: (error) => console.warn(error.code, error.message),
// Your backend checks receipts? Add onVerifyPurchase: see Set up payments → Your backend.
});
```
## 3. Start it and mount the resumer
[Section titled “3. Start it and mount the resumer”](#3-start-it-and-mount-the-resumer)
```tsx
// src/app/_layout.tsx (replaces the template's tab layout)
import { Snap4IdResume } from '@snap4id-sdk/app-embed';
import { Stack } from 'expo-router';
import { useEffect } from 'react';
import { snap4id } from '../snap4id';
export default function Layout() {
useEffect(() => {
void snap4id.start(); // recovery: unfinished purchases, paid jobs not yet delivered
}, []);
return (
<>
{/* An opaque header: the flow's WebView must start below it (a transparent header covers the page). */}
>
);
}
```
## 4. The flow screen
[Section titled “4. The flow screen”](#4-the-flow-screen)
src/app/flow.tsx
```tsx
import { Snap4IdFlow } from '@snap4id-sdk/app-embed';
import { useNavigation } from 'expo-router';
import { snap4id } from '../snap4id';
// Your app's own analytics consent for Snap4ID's page; undefined ⇒ analytics stay off.
const statisticsConsent: boolean | undefined = undefined;
export default function Flow() {
const navigation = useNavigation();
return (
navigation.setOptions({ title })}
onClose={() => navigation.goBack()}
/>
);
}
```
Render it full screen under your own, opaque header (or, without a header, inside a safe-area view): the page has no chrome of its own. Open it from your home screen with `router.push('/flow')`. To reopen a job, pass `jobId`.
What `onCompleted` receives and how to show, save and share the stored files: [receiving the files](http://sdk.snap4.id/how-it-works/receiving-files/#react-native-the-components-download-helper).
## Try it
[Section titled “Try it”](#try-it)
Run it on a simulator against the SDK’s fake Snap4ID page with the fake store, no Snap4ID or store account needed: [fake store](http://sdk.snap4.id/test/fake-store/) (two small dev-only additions to `src/snap4id.ts`, then `npm run fake-page` in the SDK checkout). A complete, copyable app is in the SDK repository under [`examples/partner-app`](https://github.com/lradomski10m/snap4id-sdk/tree/main/examples/partner-app): [try it now](http://sdk.snap4.id/try-it/).
Already have store code (or RevenueCat)? Use [your own store code](http://sdk.snap4.id/integrate/react-native/own-store/) instead of `'built-in'`. All options: [component details](http://sdk.snap4.id/integrate/react-native/details/) and the [component API](http://sdk.snap4.id/reference/component-api/).
Next step
Set up payments: [Snap4ID checks purchases](http://sdk.snap4.id/set-up-payments/snap4id-checks/) (what you send Snap4ID), [our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/) or [your own backend](http://sdk.snap4.id/set-up-payments/your-backend/).
# Component details
> The client fields that matter, the origin policy, Android specifics, files, users and headless recovery.
## The client
[Section titled “The client”](#the-client)
`createSnap4IdClient(config)` once per app process; it throws `ConfigurationError` (`configuration_invalid`) for a bad config. The fields that shape your integration (all fields: [component API](http://sdk.snap4.id/reference/component-api/)):
| Field | Meaning |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `partnerId` | from onboarding |
| `purchases` | `'built-in'`, or [your own store code](http://sdk.snap4.id/integrate/react-native/own-store/) |
| `onVerifyPurchase` | present ⇒ your own backend checks purchases ([your own backend](http://sdk.snap4.id/set-up-payments/your-backend/)); absent ⇒ the page has them checked (Snap4ID, or [our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/)) |
| `onCompleted(completion)` | at least once per paid job until it resolves |
| `onError(error)` | typed errors: [error codes](http://sdk.snap4.id/reference/errors/#component-onerror) |
| `namespace` | one per signed-in user, so each keeps their own jobs and purchases |
| `theme`, `copy` | optional [theme](http://sdk.snap4.id/customize/theme/) and [text](http://sdk.snap4.id/customize/texts/) overrides |
| `origin` | default `https://snap4.id`; leave it unset in release builds |
Call `client.start()` at every app start: it attaches the store listeners and runs recovery. For a background task before any UI, `await recover(config)` does the same headless.
## The product and its price
[Section titled “The product and its price”](#the-product-and-its-price)
The product is the in-app purchase item you create in your store (App Store Connect, Google Play Console). You give its id to Snap4ID at onboarding, one per store; your app configures nothing. The page names the product and asks the component for its store price, which it shows on its order button:
1. The page’s `hello` carries your ids from your partner configuration: `{ "ios": "pl.example.app.idphoto", "android": "pl.example.app.idphoto" }`.
2. The component answers the `hello` at once, then looks up the price of the id for its store (the built-in store through `expo-iap`; [your own store code](http://sdk.snap4.id/integrate/react-native/own-store/) through `getPrice`) and sends it to the page ([`price.result`](http://sdk.snap4.id/reference/bridge-protocol/messages/#priceresult)):
```json
{ "products": { "pl.example.app.idphoto": { "amount_minor": 1999, "currency": "PLN", "display_price": "19,99 zł" } } }
```
No price (an id missing for this store, a product the store does not know, a store error) ⇒ the page shows the order button without a price, and `onError` gets the non-fatal `price_unavailable` naming the id.
## The flow screen
[Section titled “The flow screen”](#the-flow-screen)
* `onStateChange` reports the step (`capture`, `processing`, `payment`, `done`) and a title for your header.
* Android back goes to the page while it can go back, then `onClose({ reason: 'back' })`.
* `` (once, near the root) reopens queued jobs in hidden WebViews one at a time.
* Done screen and Save / Share: [done screen](http://sdk.snap4.id/customize/done-screen/).
## Origin policy
[Section titled “Origin policy”](#origin-policy)
The flow opens only `https://snap4.id` in release builds (plus exact HTTPS origins in `trustedOrigins`, only for a pre-production Snap4ID you were given). Development builds also allow `http://127.0.0.1:`, `http://10.0.2.2:` (Android emulator) and private LAN addresses, so a phone can reach your dev machine. A **test** release build (e.g. for StoreKit or Play testing against the [fake page](http://sdk.snap4.id/test/fake-store/#the-fake-snap4id-page)) can load `http://127.0.0.1:` and `http://10.0.2.2:` with `allowLocalOrigins: true`, never public `http` or LAN hosts; never set it in a build you ship. Anything else fails with `origin_rejected`. Messages and navigation are accepted from the allowed origin only. Do not wrap the page in iframes of your own: the origin check sees the main frame only.
## Android
[Section titled “Android”](#android)
The bridge must exist before the page’s first script. The package ships a small native module (autolinked; rebuild after installing) that registers it with AndroidX WebKit `addDocumentStartJavaScript`. On a WebView without `DOCUMENT_START_SCRIPT` the page still connects: it waits up to 1.5 s for a late bridge. The component also handles camera capture, the Android file chooser and a lost WebView process (it reloads the job).
## Files
[Section titled “Files”](#files)
`onCompleted` receives `{ jobId, orderCode, artifacts }`, each artifact `{ code, title, mimeType, filename, url, expiresAt }` (for example the main photo, a print sheet image and PDF, a transparent PNG: the list depends on the document). `client.downloadArtifacts(completion)` copies them into your app’s storage and rejects until every file is stored, so the component calls `onCompleted` again. `client.files` saves or shares a stored file (else a temporary copy of the link); `client.downloads` lists the stored files. Details and examples: [receiving the files](http://sdk.snap4.id/how-it-works/receiving-files/).
## Logs
[Section titled “Logs”](#logs)
`onBridgeMessage` receives the redacted bridge traffic (no receipts, store secrets or signed link query strings). The component writes no bridge traffic to storage; keep `persistBridgeLog` for development.
Next step
Set up payments: [Snap4ID checks purchases](http://sdk.snap4.id/set-up-payments/snap4id-checks/), [our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/) or [your own backend](http://sdk.snap4.id/set-up-payments/your-backend/).
# Use your own store code
> Run the store purchase with your app's own store code and keep confirm-after-unlock and recovery working.
The built-in store (`purchases: 'built-in'`) runs `expo-iap` for you. If your app already has store code, pass an object instead and the component calls it:
```ts
createSnap4IdClient({
partnerId: 'your-partner-id',
purchases: {
onPurchaseRequest, // buy, bound to the page's paymentRef
onConfirmPurchase, // finish the purchase, after the unlock only
getUnfinishedPurchases, // recovery after a kill
getPendingPurchases, // "Ask to Buy" / Play PENDING waiting for approval
getPrice, // the store price of the product the page names
},
onCompleted,
});
```
The page shows the store price of your product on its order button. It names the product (the id you gave Snap4ID for this store) and the component asks your `getPrice(productId)`: resolve `{ display_price, amount_minor, currency }` from your store, or `null` when it has no price (the page then shows none; `onError` gets the non-fatal `price_unavailable`). Without `getPrice` the page shows no price.
```ts
async getPrice(productId) {
const [product] = await fetchProducts({ skus: [productId], type: 'in-app' });
if (!product) return null;
return { display_price: product.displayPrice, amount_minor: toMinorUnits(product.price, product.currency), currency: product.currency };
},
```
## `onPurchaseRequest({ jobId, productId, paymentRef, storeBinding })`
[Section titled “onPurchaseRequest({ jobId, productId, paymentRef, storeBinding })”](#onpurchaserequest-jobid-productid-paymentref-storebinding-)
Buy `productId` with `storeBinding.appAccountToken` (App Store) or `storeBinding.obfuscatedProfileId` (Google Play). Answer:
| Answer | When |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `{ status: 'succeeded', transactionId, receipt, price? }` | bought; `receipt` is `{ kind: 'app-store', jws }` or `{ kind: 'play', originalJson, signature }`; `price` = the store price (`{ amount_minor, currency }`) if you know it |
| `{ status: 'pending', transactionId }` | waiting for approval |
| `{ status: 'cancelled' }` | the user cancelled |
| `{ status: 'failed', reason }` | the store failed |
A throw counts as `failed` and is reported to `onError` as `purchase_callback_failed`.
## `onConfirmPurchase(receipt, { jobId, paymentRef, transactionId })`
[Section titled “onConfirmPurchase(receipt, { jobId, paymentRef, transactionId })”](#onconfirmpurchasereceipt--jobid-paymentref-transactionid-)
Finish (acknowledge / consume) the purchase here and **nowhere else**. It is called only after Snap4ID unlocked the job, and again after every start until it resolves: make it idempotent.
## Recovery
[Section titled “Recovery”](#recovery)
* `getUnfinishedPurchases()` lists purchases your store still holds unfinished. Without it, a purchase made right before a kill cannot be recovered.
* `getPendingPurchases()` lists purchases awaiting approval. Without it, an attempt killed while the store sheet was open is kept `pending` for up to 24 h (it may still be approved; buying again could charge twice).
* `client.purchaseUpdated(purchase)` reports a purchase that resolved later (an approved “Ask to Buy”); it follows the normal unlock path.
## RevenueCat and other purchase libraries
[Section titled “RevenueCat and other purchase libraries”](#revenuecat-and-other-purchase-libraries)
Confirm-after-unlock needs the transaction to stay unfinished until `onConfirmPurchase`. Libraries that finish transactions on their own (RevenueCat by default) break that: run RevenueCat in **observer mode**, or use the built-in store. A working `expo-iap` implementation is in the SDK repository: [`examples/partner-app/src/app-purchases.ts`](https://github.com/lradomski10m/snap4id-sdk/blob/main/examples/partner-app/src/app-purchases.ts).
Next step
[Component details](http://sdk.snap4.id/integrate/react-native/details/): origin policy, Android, files and users.
# You check: our verifier server
> You check purchases by deploying our ready-made verifier server - configuration only, no code; the Snap4ID page sends the receipts to it.
You check purchases on your own infrastructure without writing code: deploy our ready-made verifier server and configure it. It runs exactly the checks Snap4ID’s own verifier runs, with your store details and your key. The Snap4ID page sends each receipt to your server. Your server validates it, then sends Snap4ID an unlock request for the job’s payment ref, signed with your Ed25519 key: that signature, not the receipt, is what Snap4ID trusts. If you would rather check receipts inside your existing backend, see [You check: your own backend](http://sdk.snap4.id/set-up-payments/your-backend/).
| | Snap4ID checks purchases | You check: our verifier server |
| -------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------ |
| Where the page sends the receipt | `https://snap4.id/verifier` | `https:///verifier` |
| Your store details | sent to Snap4ID | configuration files on your server |
| Signs the unlock request | the verifier, with a key Snap4ID holds for your partner id | your server, with your Ed25519 key (public half registered with Snap4ID) |
| Page authentication | App Check (Snap4ID) | App Check against Snap4ID’s project, or your own hook |
Your app is set up exactly as when Snap4ID checks (no `onVerifyPurchase`; a native host sends the receipt in `purchase.result`): only the address the page sends it to changes. The receipt is still never checked in the app.
## Run it
[Section titled “Run it”](#run-it)
The server is in the SDK repository under [`examples/purchase-verifier-self-host`](https://github.com/lradomski10m/snap4id-sdk/tree/main/examples/purchase-verifier-self-host) (`package.json`, `server.mjs`, `Dockerfile`), built on `createReceiptHandler` from `@snap4id-sdk/purchase-verifier`. Node 22:
```sh
npm install # @snap4id-sdk/purchase-verifier and firebase-admin from npm
export PURCHASE_VERIFIER_PARTNERS_DIR=/secrets/partners
export PURCHASE_VERIFIER_API_BASE_URL=https://snap4.id
export PURCHASE_VERIFIER_ALLOWED_ORIGINS=https://snap4.id
export PURCHASE_VERIFIER_APP_CHECK_PROJECT_ID=
node server.mjs # PORT, default 8080
curl -s localhost:8080/v1/health # {"status":"ok","deployment":"production"}
```
On a container platform: build the `Dockerfile`, mount the partner directory from your secret store at `/secrets/partners`, allow unauthenticated invocation (the verifier authenticates the page itself), terminate TLS in front. `PURCHASE_VERIFIER_DEPLOYMENT=production` is the default; `test` (with `PURCHASE_VERIFIER_ACCEPT_TEST_RECEIPTS=true`) also accepts fake receipts and is for development only.
## Configuration files
[Section titled “Configuration files”](#configuration-files)
Per partner id in `PURCHASE_VERIFIER_PARTNERS_DIR`: `.config.json` (your store details, [format](http://sdk.snap4.id/reference/purchase-verifier/#partner-configuration)) and `.key.json` (`{ "key_id", "private_key_pem" }`, mode `0600`). Files are re-read about once a minute, and immediately after Snap4ID rejects the key, so rotation needs no restart.
* Keep **retired product ids** for 30 days: a retry of an already unlocked purchase is verified first.
* **Sandbox in production** is refused unless `sandbox_in_prod_until` is a future date (App Review); `xcode` and `test` are always refused in production.
## The unlock key
[Section titled “The unlock key”](#the-unlock-key)
```sh
openssl genpkey -algorithm ed25519 -out verifier.pem
openssl pkey -in verifier.pem -pubout -out verifier.pub.pem
```
Send `verifier.pub.pem` to Snap4ID; you get a `key_id`. The private key never leaves your host and is never logged.
## CORS and authentication
[Section titled “CORS and authentication”](#cors-and-authentication)
* `PURCHASE_VERIFIER_ALLOWED_ORIGINS` lists the page origins exactly; no wildcard, no credentials.
* The default authentication verifies the `X-Firebase-AppCheck` token against Snap4ID’s project (application default credentials). For your own scheme, `createSelfHostedServer(env, { authenticate })`: the hook gets `{ method, path, headers }` and returns `{ ok: true }` or `{ ok: false, code: 'app_check_failed' }`.
## Point Snap4ID at it
[Section titled “Point Snap4ID at it”](#point-snap4id-at-it)
Tell Snap4ID your server’s public URL; your partner configuration’s verifier URL becomes `https:///verifier` (the server answers both `/v1/…` and `/verifier/v1/…`). Check with a test purchase: the job unlocks. HTTP API: [purchase verifier reference](http://sdk.snap4.id/reference/purchase-verifier/).
Next step
[Test your setup](http://sdk.snap4.id/test/your-backend/).
# Snap4ID checks purchases
> Let Snap4ID check your store purchases - what Snap4ID needs to know about your store, what you send at onboarding, and what Snap4ID configures and holds for you.
When Snap4ID checks purchases you run no server. Your app hands the store receipt to the page; the page posts it to Snap4ID’s verifier (`https://snap4.id/verifier`), which checks it and unlocks the job.
This **requires Snap4ID to know your store specifics**: a receipt only proves something when it is checked against your app and your products. You send them once at onboarding and Snap4ID configures them. After a receipt passes, the verifier asks Snap4ID to unlock the job with a request signed by a key Snap4ID holds for your partner id.
## What you send us
[Section titled “What you send us”](#what-you-send-us)
| Item | Example | Where you find it |
| ------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------ |
| iOS bundle id | `pl.example.app` | Xcode target / App Store Connect |
| Android package name | `pl.example.app` | `applicationId` / Play Console |
| Product ids | `pl.example.app.idphoto` (one consumable per price, per store) | App Store Connect / Play Console in-app products |
| Play licensing public key | `MIIBIjANBgkqh…` (base64 RSA) | Play Console → Monetization setup → Licensing |
| Accepted environments | `production`; a `sandbox` window for App Review or your own testing (until a date) | your release plan |
| Platforms | iOS, Android, or both | |
Send only these public identifiers: no store secrets, no App Store Connect keys, no service-account files. Retired product ids stay listed for 30 days so retries of old purchases still verify.
## What Snap4ID does
[Section titled “What Snap4ID does”](#what-snap4id-does)
* Records these details in your partner configuration and sets it to “Snap4ID checks purchases”.
* **Holds the verifier’s signing key** for the unlock: you never see or manage a key with this option.
* Authenticates the page to the verifier itself (App Check): nothing for your app to configure.
* Opens and closes sandbox windows on request (they expire by themselves).
## What your app does
[Section titled “What your app does”](#what-your-app-does)
* **React Native:** nothing extra. Leave `onVerifyPurchase` out of the client config.
* **Native host:** answer `purchase.result { status: 'succeeded', receipt }` and finish the purchase when `job.completed` arrives ([host contract](http://sdk.snap4.id/integrate/native-app/)).
Either way the receipt is checked on Snap4ID’s server, never in your app.
Want the same check on your own infrastructure? [You check: our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/).
## When it refuses
[Section titled “When it refuses”](#when-it-refuses)
| Code | Usual cause |
| ------------------------- | ---------------------------------------------------------------------------------------- |
| `binding_mismatch` | the purchase was not made with `appAccountToken` / `obfuscatedProfileId` = `paymentRef` |
| `unknown_product` | a product id Snap4ID does not have: send the new id |
| `environment_not_allowed` | a sandbox purchase against production with no sandbox window, or an Xcode / fake receipt |
| `invalid_receipt` | wrong bundle id / package name, wrong Play key, or a revoked purchase |
The page reports a final refusal as `unlock_rejected`; all codes: [error codes](http://sdk.snap4.id/reference/errors/#purchase-verifier).
Next step
[Customize the page](http://sdk.snap4.id/customize/theme/), then [test](http://sdk.snap4.id/test/fake-store/).
# Receive the job.paid webhook
> Get the signed job.paid event on your backend, verify it on the raw body and dedupe it.
When a job of yours is paid, Snap4ID can `POST` a signed `job.paid` event to your webhook URL (set at onboarding). It is optional, and useful whoever checks purchases: to record payments server-side and copy files from your backend.
```json
{
"event_id": "3b494732-257b-5290-bd93-33a64be78a6f",
"type": "job.paid",
"job_id": "eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42",
"payment_ref": "3b241101-e2bb-4255-8caf-4136c566a962",
"order_code": "7K3M9Q",
"paid_at": "2026-11-24T12:00:00.000Z"
}
```
## Receive it
[Section titled “Receive it”](#receive-it)
```ts
import express from 'express';
// The RAW body: never let a JSON body parser touch this route (a re-serialised body does not verify).
app.post('/webhooks/snap4id', express.raw({ type: '*/*' }), async (req, res) => {
const result = await snap4id.verifyWebhook({ headers: req.headers, rawBody: req.body });
if (!result.ok) {
res.status(result.reason === 'keys_unavailable' ? 503 : 401).end(); // never 410 here
return;
}
if (await alreadyProcessed(result.event.event_id)) {
res.status(200).json({ duplicate: true });
return;
}
await markPaid(result.event.job_id, result.event.payment_ref);
await rememberProcessed(result.event.event_id);
res.status(200).end();
// then, e.g., snap4id.getJob(jobId) and copy the files
});
```
Without a client: `createWebhookVerifier({ keysUrl: 'https://snap4.id/api/v1/partner/webhook-keys' })`.
## Rules
[Section titled “Rules”](#rules)
| Result | Answer | Why |
| -------------------------------------- | --------------------------------- | ------------------------------------------ |
| verified, new `event_id` | process, then `2xx` | delivered |
| verified, `event_id` already processed | `2xx`, do nothing | retries carry the same body and `event_id` |
| `keys_unavailable` | `503` | Snap4ID retries |
| any other failure | `401` (or `400`), **never `410`** | `410` drops a genuine event for good |
| you deliberately stop this event | `410` | the only way to stop retries |
* Delivery is **at least once**, retried with backoff for **72 hours** after `paid_at`, each attempt with a fresh timestamp and signature but the same body. The 5-minute signature window is not a replay guard; `event_id` dedupe is (it is the UUID v5 of the job id).
* Verification order: headers present, key id known, `|now − x-timestamp| ≤ 5 min`, Ed25519 signature over `key_id\ntimestamp\nsha256(raw body)`, then a valid event. Keys are cached for an hour; an unknown key id refetches once (rotation), at most once a minute.
* Never act on the body of a failed verification. A failing webhook never affects the job or the app’s delivery.
* To stop deliveries when you offboard, ask Snap4ID to disable your webhook.
Wire contract: [Partner API](http://sdk.snap4.id/reference/partner-api/).
Next step
[Test your backend](http://sdk.snap4.id/test/your-backend/) with signed fixtures.
# You check: your own backend
> You check purchases in your own backend - your app sends the receipt to your server, which checks it (optionally with our verifier library) and calls our unlock API.
You check purchases in your own backend, next to your user accounts and purchase records. Your app sends the receipt to your server; your server validates it against your store details and then asks Snap4ID to unlock the job with a call to our unlock API (Partner API) signed with your Ed25519 key. Snap4ID never sees the receipt before your backend accepts it. Our verifier library, `@snap4id-sdk/purchase-verifier`, runs the same checks as Snap4ID’s verifier, so you don’t write receipt cryptography yourself. The receipt is still never checked in the app.
No backend code wanted, only checks on your infrastructure? [You check: our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/).
## 1. Keys and onboarding
[Section titled “1. Keys and onboarding”](#1-keys-and-onboarding)
1. Generate an Ed25519 key pair; keep the private key in your secret manager.
```sh
openssl genpkey -algorithm ed25519 -out partner.pem
openssl pkey -in partner.pem -pubout -out partner.pub.pem
```
2. Send `partner.pub.pem` (the public half only) and your product ids to Snap4ID; you get a **key id** back.
3. Optionally give Snap4ID a webhook URL for `job.paid` ([webhooks](http://sdk.snap4.id/set-up-payments/webhooks/)).
4. Snap4ID sets your partner configuration to “you check: your own backend”.
Rotate by registering a new key, switching to it, then asking Snap4ID to revoke the old one.
## 2. The app side
[Section titled “2. The app side”](#2-the-app-side)
React Native: add `onVerifyPurchase`; its presence tells the component that your backend checks purchases.
```ts
createSnap4IdClient({
partnerId: 'your-partner-id',
purchases: 'built-in', // or your own store code
onVerifyPurchase: async (receipt, { jobId, paymentRef, price }) => {
const res = await fetch('https://api.example.pl/snap4id/purchases', {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${await userToken()}` },
body: JSON.stringify({ jobId, paymentRef, receipt, price }),
});
if (res.status === 409 && (await res.json()).error === 'already_paid') throw new AlreadyPaidError();
if (!res.ok) throw new Error(`verify failed: ${res.status}`);
},
onCompleted,
});
```
Resolve once the job is unlocked; reject otherwise (the purchase stays unfinished and is verified again later). A rejection with `code: 'already_paid'` (`AlreadyPaidError` from `@snap4id-sdk/app-embed`, or the Partner API client’s error) makes the component report `duplicate_purchase` and finish the purchase. The call is bounded at 15 s.
Native host: the same request from your store code, then `purchase.result { status: 'succeeded' }` without a receipt ([host contract](http://sdk.snap4.id/integrate/native-app/)).
## 3. The backend side
[Section titled “3. The backend side”](#3-the-backend-side)
```ts
import { createPartnerClient, isPartnerApiError } from '@snap4id-sdk/partner-api';
import { choosePrice, verifyReceipt } from '@snap4id-sdk/purchase-verifier';
const snap4id = createPartnerClient({
baseUrl: 'https://snap4.id',
partnerId: 'your-partner-id',
keyId: process.env.SNAP4ID_KEY_ID!,
privateKey: process.env.SNAP4ID_PARTNER_KEY_PEM!, // PKCS#8 PEM, checked at start-up
});
export async function handlePurchase({ jobId, paymentRef, receipt, price }) {
// 1. Your user authentication: is this your user, and may they buy for this job?
// 2. Store the purchase as pending (recovery), then verify offline: store signature, your app and product,
// the binding to paymentRef, the environment.
const verified = await verifyReceipt(
{ receipt, payment_ref: paymentRef },
{ config: partnerConfig, policy: { deployment: 'production', acceptTestReceipts: false } },
);
if (!verified.ok) return { status: 400, error: verified.code };
const { purchase } = verified;
// 3. Unlock (idempotent per job + transaction; a repeat of a success answers 200 again).
try {
const { order_code } = await snap4id.unlock(jobId, {
payment_ref: paymentRef,
platform: purchase.platform,
product_id: purchase.productId,
transaction_id: purchase.transactionId,
environment: purchase.environment,
...choosePrice(purchase.storePrice, price), // the signed store price wins over the app's
});
return { status: 200, orderCode: order_code };
} catch (e) {
if (isPartnerApiError(e, 'already_paid')) return { status: 409, error: 'already_paid' }; // refund this purchase
throw e; // retryable codes: keep the purchase and retry later
}
}
```
`partnerConfig` holds your store details (bundle id / package name, product ids, Play licensing public key, accepted environments) in the [partner configuration format](http://sdk.snap4.id/reference/purchase-verifier/#partner-configuration); validate it at start-up with `PartnerConfigSchema`. A complete backend with a state file, recovery and the webhook is in the SDK repository: [`examples/partner-backend`](https://github.com/lradomski10m/snap4id-sdk/tree/main/examples/partner-backend).
## Errors to handle
[Section titled “Errors to handle”](#errors-to-handle)
| Partner API `code` | What to do |
| --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `already_paid` (409) | the job was paid by another transaction: **refund** this purchase |
| `transaction_already_used` (409) | the transaction unlocked another job: do not deliver for it |
| `job_not_payable` (409) | the job does not wait for a store payment: do not charge |
| `payment_ref_mismatch`, `unknown_product`, `environment_not_allowed`, `invalid_request` (400) | fix the input or ask Snap4ID to update your configuration |
| `not_found` (404) | wrong job id for your partner |
| `unauthorized` (401) | key id, key, partner id or clock; never retried |
| `server_error`, `timeout`, `network` | retries exhausted: keep the purchase and retry later |
Quote `error.requestId` to Snap4ID support. All codes: [error codes](http://sdk.snap4.id/reference/errors/#partner-api); wire contract: [Partner API](http://sdk.snap4.id/reference/partner-api/).
## Recovery
[Section titled “Recovery”](#recovery)
Store the purchase before you unlock. Run a periodic job that unlocks pending purchases again (`already_paid` becomes a refund) and uses `getJob(jobId)` to copy the files of paid jobs until `expires_at`.
Next step
[Receive the `job.paid` webhook](http://sdk.snap4.id/set-up-payments/webhooks/) (optional), then [test your backend](http://sdk.snap4.id/test/your-backend/).
# Done screen and Save / Share
> Choose what the page shows after payment - all files, the photo only, or nothing - and whether it offers Save and Share.
After payment the page always sends **every** file to your app (`job.completed`). The done screen only decides what the user sees next.
| `doneScreen` | The user sees | Then |
| ----------------- | ------------------------------------------------------- | ------------------------------------------------------------------ |
| `all` | every file in a carousel, Save / Share per file, “Back” | `close` when the user taps “Back” |
| `photo` (default) | the main photo with Save / Share, “Back” | `close` on “Back” |
| `none` | a short “Returning to the app” state | `close` right after `job.completed`: show the files in your own UI |
The default comes from your partner configuration; your app can override it per session: React Native ``, native host `hello.doneScreen`.
## Save and Share
[Section titled “Save and Share”](#save-and-share)
Save and Share buttons appear only for what your app grants in `hello.capabilities`; the page then sends `artifact.save` / `artifact.share` with the file’s `code` and your app does the work (photo library, share sheet).
* React Native: `` (default: both, where the device supports them); the component saves and shares through `client.files`.
* Native host: `capabilities: { save, share }` in `hello` (absent ⇒ both off), then handle the two messages.
Save needs the photo-library add permission (iOS `NSPhotoLibraryAddUsageDescription`; the Expo config plugin’s `savePhotosPermission`).
Next step
[Test](http://sdk.snap4.id/test/fake-store/) your integration.
# Replace texts
> Override a short list of page texts per locale - titles, the order button, the Back button and the returning screen.
A few texts can carry your wording, per locale. They travel in the host `hello` (`copy`: copy id → `{ locale: text }`).
```tsx
// React Native: per app and per flow; the flow wins per id.
createSnap4IdClient({
// …
copy: { 'payment.order': { pl: 'Kup w aplikacji', 'en-us': 'Buy in the app' } },
});
;
```
## Copy ids
[Section titled “Copy ids”](#copy-ids)
| Id | Max characters | Where |
| ------------------------------------------ | -------------- | ------------------------------------------------------- |
| `capture.title` | 60 | step title of `capture` (reported to your header) |
| `done.title` | 60 | step title of `done` |
| `payment.order` | 40 | the button that opens your store purchase |
| `backToApp` | 40 | the done screen’s back button (default “Back” / “Wróć”) |
| `returning.title`, `returning.message` | 80, 240 | the returning screen (done screen `none`) |
| `unavailable.title`, `unavailable.message` | 80, 240 | shown when your partner configuration is unavailable |
## Rules
[Section titled “Rules”](#rules)
Values are plain text, one line, rendered as text (no HTML, Markdown or placeholders), at most 16 locales per id, lowercase locale keys (`pl`, `en-us`). The page uses the value of its session locale (exact, then the language alone), else its own text, never another language. Invalid entries are dropped one by one (the component warns in development builds).
Not overridable: error and purchase-state texts (support relies on them), the no-bridge screen and the document’s title on the capture card.
Next step
[Done screen and Save / Share](http://sdk.snap4.id/customize/done-screen/).
# Match your brand
> Restyle the embedded page with theme tokens - colours, font and corner radius - per app or per flow.
The page starts from the theme in your partner configuration (set by Snap4ID at onboarding). Your app can adjust it per session; the values travel in the host `hello` (`theme`) and are cosmetic: a wrong value is dropped, never a broken session.
```tsx
// React Native: per app (client config) and per flow (prop); the flow wins per key.
createSnap4IdClient({
// …
theme: { 'color.accent.primary': '#a855f7', 'color.cta.primary': '#a855f7' },
});
;
```
Native host: put the same object in your `hello` payload as `theme`. Precedence per key: flow prop → client config → partner configuration → Snap4ID default. The theme is read when the flow opens.
## Tokens
[Section titled “Tokens”](#tokens)
| Token | Default | Format |
| ---------------------- | ------------- | -------------------------------------------------------------- |
| `base` | `dark` | only `dark` (the page is dark-themed) |
| `color.accent.primary` | `#3b82f6` | `#rrggbb` (also drives the pressed and soft accent unless set) |
| `color.accent.soft` | `#60a5fa` | `#rrggbb` |
| `color.text.onAccent` | `#ffffff` | `#rrggbb` |
| `color.cta.primary` | `#ffffff` | `#rrggbb` (main buttons) |
| `color.cta.onPrimary` | `#0f172a` | `#rrggbb` |
| `color.bg.primary` | `#020617` | `#rrggbb` (page background) |
| `color.bg.secondary` | `#1e293b` | `#rrggbb` |
| `color.bg.surface` | `#1e293b` | `#rrggbb` (also drives controls unless set) |
| `color.bg.card` | `#0f172a` | `#rrggbb` |
| `color.text.primary` | `#f8fafc` | `#rrggbb` |
| `color.text.secondary` | `#e2e8f0` | `#rrggbb` |
| `color.text.muted` | `#94a3b8` | `#rrggbb` |
| `color.border.primary` | `#334155` | `#rrggbb` |
| `font.sans` | `google-sans` | `google-sans` or `system` |
| `radius.scale` | `1` | `0` to `2`, up to two decimals |
## Validation
[Section titled “Validation”](#validation)
At most 32 keys; backgrounds must stay dark and text light; text pairs need a contrast of at least 4.5:1, accents and controls 3:1. Unknown keys are dropped; an invalid theme is ignored as a whole (the configuration theme stays). If your app’s keys pass on their own but break a contrast pair together with the configuration theme, the page keeps the configuration theme.
Next step
[Replace texts](http://sdk.snap4.id/customize/texts/).
# Onboarding and launch checklist
> Everything from your first call with Snap4ID to a release build in the stores, in order.
## Onboarding with Snap4ID
[Section titled “Onboarding with Snap4ID”](#onboarding-with-snap4id)
How to start, what you send and what you get back: [get your partner id](http://sdk.snap4.id/go-live/onboarding/).
| # | You | Snap4ID |
| - | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| 1 | Sign the partner agreement; say which documents and locales you need | creates your **partner id** and partner configuration (locale, document, default theme, done screen) |
| 2 | Choose [who checks purchases](http://sdk.snap4.id/choose-your-setup/) | records it in your configuration |
| 3 | Create one **consumable** product per price in each store | |
| 4 | Snap4ID checks: send your [store details](http://sdk.snap4.id/set-up-payments/snap4id-checks/#what-you-send-us). You check: send your Ed25519 **public** key and product ids | configures them; returns a key id (backend) |
| 5 | Optional: a webhook URL for `job.paid` | enables delivery to it |
| 6 | Ask for a sandbox window for testing | opens it until the date you agree |
## Native configuration
[Section titled “Native configuration”](#native-configuration)
| # | Item | Why |
| -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| 7 | Camera, photo-library and add-to-photos usage texts (in Polish for a Polish app). React Native: config plugin options `cameraPermission`, `photosPermission`, `savePhotosPermission`; Android `CAMERA` permission | the capture and Save steps |
| 8 | In-app purchase capability; each store’s product id given to Snap4ID at onboarding (the app configures none; your own store code implements `getPrice`) | the page names the product and shows its store’s localized price (e.g. `19,99 zł`) |
| 9 | No development networking in release builds (plain HTTP, WebView remote debugging) | release builds load only `https://snap4.id` |
| 10 | No fake store in production code (`@snap4id-sdk/app-embed/testing`, `platform: 'test'`) | fake receipts are refused by production anyway |
## App behaviour
[Section titled “App behaviour”](#app-behaviour)
| # | Item | Why |
| -- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| 11 | One host per app process (per signed-in user); recovery at every app start (`client.start()` + ``) | a paid photo survives a kill |
| 12 | The flow full screen; title from the page’s step titles, close on `close` | the page has no chrome of its own; Android back goes to the page first |
| 13 | Analytics consent from your user’s real choice, updated when it changes | analytics run only on `statistics: true` |
| 14 | No iframes of your own around the page | the origin check sees the main frame only |
| 15 | Purchases finished only after the unlock; RevenueCat and similar in observer mode | a purchase finished early is lost on a kill |
| 16 | Who checks purchases: the app matches your configuration | else `trust_mode_mismatch` |
| 17 | File delivery idempotent by `jobId`; files copied ([receiving the files](http://sdk.snap4.id/how-it-works/receiving-files/)) | delivered at least once; links expire after **30 days** |
| 18 | A refund process for every `duplicate_purchase` / `already_paid` | the job was already paid with another transaction |
| 19 | Backend: key in your secret manager; webhook verified on the raw body, deduped on `event_id` | see [webhooks](http://sdk.snap4.id/set-up-payments/webhooks/) |
| 20 | Bridge logs out of persistent storage in release builds | they are redacted, but still per-user data |
## Store review
[Section titled “Store review”](#store-review)
* App Review buys with sandbox receipts against production: keep a sandbox window open until shortly after the expected approval, then let it expire.
* Your terms and privacy policy cover Snap4ID: [privacy and consent](http://sdk.snap4.id/how-it-works/privacy-and-consent/).
Next step
[Who does what after launch](http://sdk.snap4.id/go-live/responsibilities/).
# Get your partner id
> What you send Snap4ID to go live, and what you get back.
Your app runs against `https://snap4.id` with a **partner id** from Snap4ID. To get one, write to ****. Onboarding starts with the partner agreement.
## What you send
[Section titled “What you send”](#what-you-send)
* The documents and locales you need.
* Your iOS bundle id and / or Android package name.
* Your product ids: one **consumable** in-app product per price, in each store.
* [Who checks purchases](http://sdk.snap4.id/choose-your-setup/). Snap4ID checks: also your Play licensing public key and the accepted environments ([details](http://sdk.snap4.id/set-up-payments/snap4id-checks/#what-you-send-us)). You check: your Ed25519 **public** key ([our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/), [your own backend](http://sdk.snap4.id/set-up-payments/your-backend/)).
* Optional: a webhook URL for `job.paid`.
Send only public identifiers: never a private key, a store secret or a service-account file.
## What you get back
[Section titled “What you get back”](#what-you-get-back)
* Your **partner id**: the client’s `partnerId`, part of the page URL `https://snap4.id/embed/{partnerId}`.
* Your partner configuration: locale, document, default theme, done screen, who checks purchases.
* You check: a **key id** for your public key.
* On request: a sandbox window for store testing, until a date you agree.
Next step
The [launch checklist](http://sdk.snap4.id/go-live/checklist/).
# Who does what after launch
> What Snap4ID runs and answers for, and what stays with you as the merchant of record - refunds, support, terms and keys.
| Area | Snap4ID | You |
| ----------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| **Page and processing** | runs the page, processes photos, keeps jobs and files for 30 days | keep the SDK current; copy the files you keep |
| **Purchase check** | when Snap4ID checks: checks receipts with your store details, holds its signing key | when you check (our verifier server or your own backend): checks receipts, holds your Ed25519 key, calls the Partner API |
| **Store details** | applies changes you send (new or retired products, a new app, the Play key) | tell Snap4ID before you ship a new product id; keep retired ids listed 30 days |
| **Payments** | never charges your users; releases files on the unlock | merchant of record: the store pays you |
| **Refunds** | | yours. App Store: the user asks Apple; Google Play: Play Console or the Play Developer API. Always refund `duplicate_purchase` |
| **User support** | second line: answers you with the order code | first line to your users |
| **Terms and privacy** | processes photos as your processor | your terms cover Snap4ID and the purchase; your privacy policy names Snap4ID |
| **Sandbox windows** | opens and closes them on request | ask before App Review and testing against production |
| **Webhooks** | delivers `job.paid` at least once for 72 hours | verify, dedupe, answer fast; ask to disable it when you offboard |
| **Keys** | revokes a key on request | rotate: register the new key, switch, ask Snap4ID to revoke the old one |
## Contacting support
[Section titled “Contacting support”](#contacting-support)
Send the **order code** (6 characters, on the done screen and in `job.completed`), the job id, the `paymentRef` and, for Partner API calls, the `requestId` of the error. Never send receipts, keys or full signed links.
Next step
Keep the [troubleshooting guide](http://sdk.snap4.id/help/troubleshooting/) and the [FAQ](http://sdk.snap4.id/help/faq/) at hand.
# FAQ
> Short answers to the questions partners ask most.
## Do I need React Native?
[Section titled “Do I need React Native?”](#do-i-need-react-native)
No. The React Native component is one way to host the page; any native app (iOS, Android, Flutter) can implement the [bridge protocol](http://sdk.snap4.id/reference/bridge-protocol/) directly: see [any native app](http://sdk.snap4.id/integrate/native-app/).
## Do I need a backend?
[Section titled “Do I need a backend?”](#do-i-need-a-backend)
No. When [Snap4ID checks purchases](http://sdk.snap4.id/set-up-payments/snap4id-checks/) you send Snap4ID your store details once and run no server. A backend is needed only if you choose to check receipts yourself.
## Can my app verify the receipt itself?
[Section titled “Can my app verify the receipt itself?”](#can-my-app-verify-the-receipt-itself)
No. Receipts are checked on a server (Snap4ID’s or yours), never in the app: an app can be modified, so a check there would prove nothing.
## Who is the seller?
[Section titled “Who is the seller?”](#who-is-the-seller)
You are the merchant of record: the user buys in your app, the store pays you, and refunds are yours.
## Why must the purchase stay unfinished until the unlock?
[Section titled “Why must the purchase stay unfinished until the unlock?”](#why-must-the-purchase-stay-unfinished-until-the-unlock)
If the app is killed between finishing the purchase and the unlock, the store no longer returns the purchase and the payment can’t be proven. Unfinished, it is found again on the next start and unlocked.
## Can I use RevenueCat?
[Section titled “Can I use RevenueCat?”](#can-i-use-revenuecat)
Yes, in **observer mode** (it must not finish transactions on its own), with [your own store code](http://sdk.snap4.id/integrate/react-native/own-store/).
## What does the user see after paying?
[Section titled “What does the user see after paying?”](#what-does-the-user-see-after-paying)
Your choice of [done screen](http://sdk.snap4.id/customize/done-screen/): all files, the photo only, or nothing (your own UI shows the files). Your app always receives every file.
## How long are the files available?
[Section titled “How long are the files available?”](#how-long-are-the-files-available)
30 days. Copy them; the links expire with the job.
## Can I change the look and wording?
[Section titled “Can I change the look and wording?”](#can-i-change-the-look-and-wording)
Yes, within limits: [theme tokens](http://sdk.snap4.id/customize/theme/) and a short list of [texts](http://sdk.snap4.id/customize/texts/).
## Does the page show cookie banners or its own terms?
[Section titled “Does the page show cookie banners or its own terms?”](#does-the-page-show-cookie-banners-or-its-own-terms)
No. Analytics follow the consent your app passes; your terms cover Snap4ID. See [privacy and consent](http://sdk.snap4.id/how-it-works/privacy-and-consent/).
## How do I test without paying?
[Section titled “How do I test without paying?”](#how-do-i-test-without-paying)
The [fake store](http://sdk.snap4.id/test/fake-store/) with the SDK’s [fake Snap4ID page](http://sdk.snap4.id/test/fake-store/#the-fake-snap4id-page), StoreKit configuration files in [Xcode](http://sdk.snap4.id/test/app-store/), and [Play license testers](http://sdk.snap4.id/test/google-play/).
# Troubleshooting
> The usual causes of a stuck flow, a purchase that does not unlock and missing files, and what to send to support.
Every code with its meaning and fix is in [error codes](http://sdk.snap4.id/reference/errors/). This page goes by symptom.
## The flow stays on a spinner
[Section titled “The flow stays on a spinner”](#the-flow-stays-on-a-spinner)
* **“Open this in the app” / no bridge**: the page found no host bridge. It was opened outside your host, the shim was not injected (React Native: rebuild after installing the package; Expo Go is not supported), or a native host posts to the wrong handler name.
* **`handshake_timeout`**: the host did not answer `hello`. Native hosts: check page messages reach your code and you reply with `replyTo` = the page hello’s `id`.
* **`embed_unavailable`**: wrong partner id, or embedding not enabled for it yet.
* **`origin_rejected`** (component): a URL outside the origin policy; leave `origin` unset in release builds.
## The purchase does not unlock
[Section titled “The purchase does not unlock”](#the-purchase-does-not-unlock)
| Symptom | Likely cause |
| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `unlock_rejected` / `binding_mismatch` | the purchase is not bound to the page’s `paymentRef` (App Store `appAccountToken`, Play `obfuscatedProfileId`) |
| `unknown_product` | the product id is not in your partner configuration (tell Snap4ID about new products; keep retired ones 30 days) |
| `environment_not_allowed` | a sandbox purchase against production without a sandbox window, or an Xcode / fake receipt in production |
| `invalid_receipt` | wrong app (bundle id / package name), wrong Play licensing key, or a revoked purchase |
| `trust_mode_mismatch` | the app checks purchases in your own backend (`onVerifyPurchase`) but your configuration says Snap4ID or your verifier server checks them, or the reverse |
| backend: nothing happens | `onVerifyPurchase` never resolves (15 s bound ⇒ `backend: timeout`), or your backend gets `401 unauthorized` (key id, key, clock) |
| the purchase was consumed but the job is unpaid | something finished the purchase before the unlock (RevenueCat auto-finish); use observer mode |
## Files missing
[Section titled “Files missing”](#files-missing)
* `artifacts_unavailable`: files not ready 30 s after payment; the page keeps waiting.
* Paid but nothing arrived: recovery must run at every start (component: `client.start()` and `` mounted), and your delivery handler must succeed (it is retried until it does).
* Links stop working after 30 days: copy files when they arrive.
## Contacting support
[Section titled “Contacting support”](#contacting-support)
Send the **order code**, the job id, the `paymentRef` and, for Partner API calls, the `requestId` of the error. Never send receipts, keys or full signed links.
Next step
[FAQ](http://sdk.snap4.id/help/faq/).
# Glossary
> The words these docs use, in one place.
| Term | Meaning |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Host app** | Your mobile app, which hosts the Snap4ID page in a WebView |
| **Page** | The Snap4ID web page at `https://snap4.id/embed/{partnerId}`: capture, preview, order, done screen |
| **Bridge** | The message channel between the page and your app: JSON envelopes over the WebView’s script messaging. Contract: the [bridge protocol](http://sdk.snap4.id/reference/bridge-protocol/) |
| **Shim** | A small script your app injects before the page’s scripts; it defines the bridge globals |
| **Component** | `@snap4id-sdk/app-embed`, the React Native implementation of the host side |
| **Partner id** | Your id at Snap4ID, from onboarding; part of the page URL |
| **Job** | One photo order. Its id looks like `eu-6f1c2b9e-…`; it lives for 30 days |
| **Order code** | Six characters (for example `7K3M9Q`) shown to the user and quoted to support |
| **Payment ref** | A fresh UUID per purchase request; bound into the store purchase so the receipt proves which job it paid |
| **Store binding** | Where the payment ref goes in the purchase: App Store `appAccountToken`, Google Play `obfuscatedProfileId` |
| **Receipt** | The store’s signed proof of a purchase: a StoreKit 2 JWS, or Play’s purchase data and signature |
| **Unlock** | Marking a job paid after its receipt was checked; only then are the files released |
| **Purchase check** | Who checks receipts and unlocks: Snap4ID, or you (our verifier server, or your own backend). The protocol calls it the trust mode, see the [bridge protocol](http://sdk.snap4.id/reference/bridge-protocol/#who-checks-the-purchase-trust-mode) |
| **Verifier** | The service that checks a receipt against your store details and unlocks the job: Snap4ID’s, or our ready-made verifier server run by you |
| **Verifier library** | `@snap4id-sdk/purchase-verifier`: the same checks, for your own backend (or as the ready-made server) |
| **Partner API** | Signed server-to-server API: unlock a job, read a job, webhook keys |
| **Finish / consume** | Telling the store a consumable purchase is done. Only after the unlock, or a killed app loses it |
| **Artifact** | One delivered file: the main photo, the print sheet (JPG and PDF), a transparent PNG |
| **Done screen** | The last page step: all files, the photo only, or none (your app shows the files) |
| **Merchant of record** | The seller the store pays and the user buys from: you |
Next step
[Choose your setup](http://sdk.snap4.id/choose-your-setup/).
# Agent context
> Files that let your coding agent (Claude Code, Codex, Antigravity, Cursor and others) integrate Snap4ID correctly, and how to install them in each agent.
These docs are published in forms a coding agent can load:
| File | What |
| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`/llms.txt`](http://sdk.snap4.id/llms.txt) | index of every page, with the key rules up front |
| [`/llms-full.txt`](http://sdk.snap4.id/llms-full.txt) | all pages in one Markdown file |
| [`/llms-small.txt`](http://sdk.snap4.id/llms-small.txt) | the same, condensed |
| [`/agent-context/AGENTS.md`](http://sdk.snap4.id/agent-context/AGENTS.md) | drop-in instructions for your repository |
| [`/agent-context/CLAUDE.md`](http://sdk.snap4.id/agent-context/CLAUDE.md) | for Claude Code: imports `AGENTS.md` |
| `/agent-context/skills//SKILL.md` | task skills: [try the example locally, then go live](http://sdk.snap4.id/agent-context/skills/snap4id-try-example/SKILL.md), [integrate the embed](http://sdk.snap4.id/agent-context/skills/snap4id-integrate-embed/SKILL.md), [verify receipts in your backend](http://sdk.snap4.id/agent-context/skills/snap4id-verify-receipts-backend/SKILL.md), [debug a stuck purchase](http://sdk.snap4.id/agent-context/skills/snap4id-debug-stuck-purchase/SKILL.md) |
The same files are the `agent-context/` folder of the SDK repository, [github.com/lradomski10m/snap4id-sdk](https://github.com/lradomski10m/snap4id-sdk). They describe only the public SDK and hold no keys or partner data. Update them when you update the SDK.
## Install the skills
[Section titled “Install the skills”](#install-the-skills)
Your agent needs the rules (`AGENTS.md`) and the skills (`skills//`). Fetch the folder once, then run the commands for your agent from your project’s root:
```sh
S4="$(mktemp -d)/snap4id-sdk"
git clone --depth 1 --filter=blob:none --sparse https://github.com/lradomski10m/snap4id-sdk.git "$S4"
git -C "$S4" sparse-checkout set agent-context
```
Codex, Antigravity and Cursor all read project skills from `.agents/skills/`, so one copy there serves all three.
### Claude Code
[Section titled “Claude Code”](#claude-code)
Install the skills as a plugin from the SDK repository (add `--scope project` to the second command to record it in the project’s `.claude/settings.json`; each teammate still runs both commands once):
```sh
claude plugin marketplace add lradomski10m/snap4id-sdk
claude plugin install snap4id@snap4id-sdk
```
In a session, the same is `/plugin marketplace add lradomski10m/snap4id-sdk` and `/plugin install snap4id@snap4id-sdk`. Plugin skills are namespaced, for example `/snap4id:snap4id-integrate-embed`. To copy the skills instead, use `.claude/skills/` (this project) or `~/.claude/skills/` (all your projects):
```sh
mkdir -p .claude/skills && cp -R "$S4/agent-context/skills/." .claude/skills/
```
The rules are not part of the plugin. Claude Code reads `CLAUDE.md` and falls back to `AGENTS.md` only when there is no `CLAUDE.md`, so copy the file and import it with the line `@AGENTS.snap4id.md` in your `CLAUDE.md`:
```sh
cp "$S4/agent-context/AGENTS.md" AGENTS.snap4id.md
```
Check: `/skills` lists the four skills (`/reload-skills` picks up a newly copied one).
### Codex
[Section titled “Codex”](#codex)
Codex reads skills from `.agents/skills/` in every folder from the working directory up to the repository root, and from `~/.agents/skills/` for all your projects. It reads `AGENTS.md` but has no import, so append the rules:
```sh
mkdir -p .agents/skills && cp -R "$S4/agent-context/skills/." .agents/skills/
cat "$S4/agent-context/AGENTS.md" >> AGENTS.md
```
Check: `/skills` lists them, or type `$` to pick one. Restart Codex if one is missing (it reads `AGENTS.md` once per run).
### Antigravity
[Section titled “Antigravity”](#antigravity)
Antigravity reads workspace skills from `.agents/skills/` and global ones from `~/.gemini/config/skills/`, and reads `AGENTS.md` in the workspace as a rule:
```sh
mkdir -p .agents/skills && cp -R "$S4/agent-context/skills/." .agents/skills/
cat "$S4/agent-context/AGENTS.md" >> AGENTS.md
```
Check: the Customizations menu of the agent panel lists the skills; `/snap4id-integrate-embed` runs one.
### Cursor
[Section titled “Cursor”](#cursor)
Cursor reads skills from `.agents/skills/` or `.cursor/skills/` (this project) and `~/.agents/skills/` or `~/.cursor/skills/` (all projects); it also loads `.claude/skills/`, so skills copied for Claude Code work too. It reads `AGENTS.md` at the project root:
```sh
mkdir -p .agents/skills && cp -R "$S4/agent-context/skills/." .agents/skills/
cat "$S4/agent-context/AGENTS.md" >> AGENTS.md
```
Check: Customize → Skills lists them; type `/` in Agent chat to run one.
### Other agents
[Section titled “Other agents”](#other-agents)
Confirm in your agent’s documentation where it reads instructions and skills. The files can also be downloaded from these docs:
```sh
mkdir -p .agents/skills
curl -fsSL https:///agent-context/AGENTS.md -o AGENTS.snap4id.md
for s in snap4id-try-example snap4id-integrate-embed snap4id-verify-receipts-backend snap4id-debug-stuck-purchase; do
mkdir -p ".agents/skills/$s" && curl -fsSL "https:///agent-context/skills/$s/SKILL.md" -o ".agents/skills/$s/SKILL.md"
done
```
Then reference `AGENTS.snap4id.md` from your own instructions file, or append it there.
# Bridge protocol
> The host bridge protocol 1.0 between the Snap4ID page and your app - transport, envelope, versioning, message overview and package entry points.
The Snap4ID page and your app talk over the WebView in JSON envelopes. `@snap4id-sdk/embed-protocol` declares every message once (TypeScript types, Zod validators, JSON Schemas); the React Native component implements the host side, and a [native host](http://sdk.snap4.id/integrate/native-app/) implements it from the same contract. Every field: [bridge messages](http://sdk.snap4.id/reference/bridge-protocol/messages/). Every code: [error codes](http://sdk.snap4.id/reference/errors/).
## Transport
[Section titled “Transport”](#transport)
| Direction | How |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| page → host | the page calls `window.Snap4IdHost.postMessage(json)`, defined by the **shim** your host injects at document start; the shim forwards the string to your native code |
| host → page | your host evaluates `window.__snap4idHostDeliver(json)`; the shim queues messages until the page calls `Snap4IdHost.ready()` |
`hostShimSource(postExpression)` builds the shim; only the post expression differs per stack (React Native `window.ReactNativeWebView.postMessage(json)`, iOS `webkit.messageHandlers..postMessage(json)`, Android `