This is the abridged 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. 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/). # 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. # 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). # 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/). # 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/). # 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. # 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 | # 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. # 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. # 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. # Add the React Native component > The smallest working integration - an Expo app with the component's built-in store - in four steps. 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/). # 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. # 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). # 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/). # 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). # 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/). # 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`. # 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`). # 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. # 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. # 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/). # 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. # 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. # 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. # 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 | # 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 `.postMessage(json)`). `deliverScript(json)` builds the deliver call. Ready-made shims: [iOS](http://sdk.snap4.id/integrate/native-app/ios/#the-shim), [Android](http://sdk.snap4.id/integrate/native-app/android/#the-shim). A shim that arrives a moment late is tolerated: the page waits up to 1.5 s before showing “no bridge”. ## Envelope [Section titled “Envelope”](#envelope) ```json { "v": 1, "id": "", "type": "", "payload": {}, "replyTo": "" } ``` | Field | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `v` | `1` | yes | Envelope version; anything else is refused (`unsupported_protocol`) | | `id` | string | yes | Unique per message (a UUID) | | `type` | string | yes | The message type, below | | `payload` | object | yes | Validated per `type` | | `replyTo` | string | | The `id` being answered: on the host `hello` and `price.result` (both answer the page `hello`) and on `purchase.result` to a request | ## Who checks the purchase (trust mode) [Section titled “Who checks the purchase (trust mode)”](#who-checks-the-purchase-trust-mode) The protocol calls who checks purchases the **trust mode**; the page reports it in its `hello` (`trustMode`): | Your setup | Trust mode | | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Snap4ID checks purchases](http://sdk.snap4.id/set-up-payments/snap4id-checks/) and [You check: our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/) | `verifier`: the page sends the receipt to a verifier URL (Snap4ID’s, or your server’s); the verifier validates it and calls the Partner API `unlock`, signed with the key it holds | | [You check: your own backend](http://sdk.snap4.id/set-up-payments/your-backend/) | `backend`: the host hands the receipt to your backend, which validates it and calls the Partner API `unlock`, signed with your key | ## Versioning [Section titled “Versioning”](#versioning) The protocol version is `"1.0"`, exchanged in `hello`. Same major = compatible; another major ends the session with a fatal `unsupported_protocol`. Minor versions are additive: unknown payload keys are dropped, never rejected, and new error codes may appear (treat an unknown non-fatal code as a log line). ## Messages [Section titled “Messages”](#messages) | Page → host | | Host → page | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------ | ----------------------------------------- | | [`hello`](http://sdk.snap4.id/reference/bridge-protocol/messages/#hello) | always first; names your product | [`hello`](http://sdk.snap4.id/reference/bridge-protocol/messages/#hello-1) | reply to the page `hello` | | [`job.created`](http://sdk.snap4.id/reference/bridge-protocol/messages/#jobcreated) | a new job | [`price.result`](http://sdk.snap4.id/reference/bridge-protocol/messages/#priceresult) | your store price, after your `hello` | | [`purchase.request`](http://sdk.snap4.id/reference/bridge-protocol/messages/#purchaserequest) | sell the photo | [`purchase.result`](http://sdk.snap4.id/reference/bridge-protocol/messages/#purchaseresult) | reply to a request, or unsolicited | | [`job.completed`](http://sdk.snap4.id/reference/bridge-protocol/messages/#jobcompleted) | paid, files ready | [`back`](http://sdk.snap4.id/reference/bridge-protocol/messages/#back) | system back gesture | | [`artifact.save`](http://sdk.snap4.id/reference/bridge-protocol/messages/#artifactsave), [`artifact.share`](http://sdk.snap4.id/reference/bridge-protocol/messages/#artifactshare) | Save / Share tapped | [`consent.changed`](http://sdk.snap4.id/reference/bridge-protocol/messages/#consentchanged) | analytics choice changed | | [`stepChanged`](http://sdk.snap4.id/reference/bridge-protocol/messages/#stepchanged), [`canGoBack`](http://sdk.snap4.id/reference/bridge-protocol/messages/#cangoback), [`close`](http://sdk.snap4.id/reference/bridge-protocol/messages/#close) | navigation | [`error`](http://sdk.snap4.id/reference/bridge-protocol/messages/#error-1) | `invalid_message`, `unsupported_protocol` | | [`error`](http://sdk.snap4.id/reference/bridge-protocol/messages/#error) | a page error | | | ## Shared types [Section titled “Shared types”](#shared-types) * `Money` = `{ amount_minor, currency }`: integer minor units and an ISO 4217 code, for example `{ "amount_minor": 1999, "currency": "PLN" }`. * `Receipt`: `app-store` (StoreKit 2 JWS), `play` (purchase data + signature) or `fake` (tests only), see [receipts](http://sdk.snap4.id/reference/bridge-protocol/messages/#receipts). * `consent` = `{ statistics?, marketing? }`: analytics only when `statistics` is `true`; marketing is never used. ## Package entry points [Section titled “Package entry points”](#package-entry-points) | Entry | Runs in | Contents | | ---------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `@snap4id-sdk/embed-protocol` | anywhere | versions, schemas, `parseWebToHost` / `parseHostToWeb` (never throw), `createWebToHost` / `createHostToWeb`, error codes, receipts, `storeBindingFor`, consent rules, host overrides, `hostShimSource`, `deliverScript` | | `@snap4id-sdk/embed-protocol/page` | browser | `createPageBridge`, the page side of the transport | | `@snap4id-sdk/embed-protocol/node` | Node | Partner API request signing (`signRequest`, `verifyRequest`), webhook signing, test keys | # Bridge messages > Every message of the host bridge protocol: what it means, its fields and a complete example envelope. Each message travels in the [envelope](http://sdk.snap4.id/reference/bridge-protocol/#envelope) `{ v: 1, id, type, payload, replyTo? }`; the tables describe `payload`. Receivers drop unknown payload keys, never reject them. The [React Native component](http://sdk.snap4.id/integrate/react-native/) sends and answers all of these for you; a [native host](http://sdk.snap4.id/integrate/native-app/) handles them itself. The JSON Schemas ship in `@snap4id-sdk/embed-protocol` under `schema/`. ## Page → host [Section titled “Page → host”](#page--host) Sent by the Snap4ID page to your app. ### `hello` [Section titled “hello”](#hello) Always the first message. The page says who it is and which trust mode Snap4ID has on file for you; answer with the [host `hello`](#hello-1) within the handshake time, or the page shows `handshake_timeout`. Page → hostAlways firstAnswer: host `hello` | Field | Type | Required | Description | | -------------------- | --------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `protocolVersion` | string (protocol version) | yes | The page’s protocol version (`1.0`). Same major ⇒ compatible. | | `page` | object | yes | What the page was opened for. | | `page.partnerId` | string (non-empty) | yes | Your partner id, from the URL. | | `page.jobId` | string (job id) | | Set when the page was opened to resume a job (`/embed/{partnerId}/job/{jobId}`). | | `trustMode` | `"verifier"` \| `"backend"` | | `verifier` (the page has the receipt checked: Snap4ID, or your verifier server) or `backend` (your own backend checks and unlocks). Check it matches your app; absent when your configuration is unavailable (then `embed_unavailable` follows). | | `productIds` | object | | The product the page sells: your in-app purchase item, one store product id per store, as you gave them to Snap4ID at onboarding. Look up the price of the id for your store and answer with [`price.result`](#priceresult) after your `hello`. Absent when your configuration is unavailable. | | `productIds.ios` | string (non-empty) | | Your App Store product id. | | `productIds.android` | string (non-empty) | | Your Google Play product id. | * JSON ```json { "v": 1, "id": "a3c5e1f0-4d2b-4c8e-9f1a-2b3c4d5e6f70", "type": "hello", "payload": { "protocolVersion": "1.0", "page": { "partnerId": "your-partner-id" }, "trustMode": "verifier", "productIds": { "ios": "pl.example.app.idphoto", "android": "pl.example.app.idphoto" } } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'hello') { const { protocolVersion, trustMode, productIds } = parsed.message.payload; if (!isCompatibleProtocol(protocolVersion)) return closeWith('unsupported_protocol'); if (trustMode && trustMode !== myTrustMode) return fail('trust_mode_mismatch'); replyHello(parsed.message.id); // see host hello: answer at once if (productIds) replyPrice(parsed.message.id, productIds.ios); // see price.result: after the hello } ``` ### `job.created` [Section titled “job.created”](#jobcreated) A new job exists. Store its id if you want to reopen the job later (`/embed/{partnerId}/job/{jobId}`). Page → hostNo reply | Field | Type | Required | Description | | ------- | --------------- | -------- | ----------------- | | `jobId` | string (job id) | yes | The new job’s id. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000002", "type": "job.created", "payload": { "jobId": "eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42" } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'job.created') { await myJobs.add(parsed.message.payload.jobId); } ``` ### `purchase.request` [Section titled “purchase.request”](#purchaserequest) The user pressed the order button. Buy `productId` in the store **bound to `paymentRef`** and answer with one [`purchase.result`](#purchaseresult) carrying `replyTo` = this message’s `id`. One request per `paymentRef`. Page → hostAnswer: `purchase.result` | Field | Type | Required | Description | | ---------------------------------- | -------------------- | -------- | ------------------------------------------------------------------------ | | `jobId` | string (job id) | yes | The job being paid. | | `productId` | string (non-empty) | yes | The store product to buy (one of the product ids Snap4ID holds for you). | | `paymentRef` | string (payment ref) | yes | Fresh per request. Binds the store purchase to this job. | | `storeBinding` | object | yes | What to put into the store purchase; both fields equal `paymentRef`. | | `storeBinding.appAccountToken` | string (payment ref) | yes | App Store: pass as the purchase option `appAccountToken`. | | `storeBinding.obfuscatedProfileId` | string (payment ref) | yes | Google Play: pass as `obfuscatedProfileId` in the billing flow params. | * JSON ```json { "v": 1, "id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f", "type": "purchase.request", "payload": { "jobId": "eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42", "productId": "pl.example.app.idphoto", "paymentRef": "3b241101-e2bb-4255-8caf-4136c566a962", "storeBinding": { "appAccountToken": "3b241101-e2bb-4255-8caf-4136c566a962", "obfuscatedProfileId": "3b241101-e2bb-4255-8caf-4136c566a962" } } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'purchase.request') { const { jobId, productId, paymentRef, storeBinding } = parsed.message.payload; const outcome = await store.buy(productId, { appAccountToken: storeBinding.appAccountToken }); reply('purchase.result', { jobId, paymentRef, ...outcome }, { replyTo: parsed.message.id }); } ``` A receipt that is not bound to the `paymentRef` is refused (`binding_mismatch`). Keep the purchase **unfinished** until the job is unlocked: see [payments and trust](http://sdk.snap4.id/how-it-works/payments-and-trust/). ### `job.completed` [Section titled “job.completed”](#jobcompleted) The job is paid and every file has a link. Sent once per page load and again whenever a paid job is reopened, so store it **idempotently by `jobId`** and copy the files: links expire with the job. Page → hostAt least onceUnlock evidence | Field | Type | Required | Description | | ----------------------- | --------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `jobId` | string (job id) | yes | The paid job. | | `orderCode` | string (non-empty) | yes | Six-character order code; shown to the user and quoted to support. | | `artifacts` | array of object (≥ 1) | yes | Every deliverable file, whatever the done screen shows. Using them: [receiving the files](http://sdk.snap4.id/how-it-works/receiving-files/). | | `artifacts[].code` | string (non-empty) | yes | Stable artifact code (for example the main photo, the print sheet, the transparent PNG). | | `artifacts[].title` | string | yes | Title in the session locale. | | `artifacts[].mimeType` | string (non-empty) | yes | `image/jpeg`, `image/png` or `application/pdf`. | | `artifacts[].filename` | string (file name) | yes | A safe file name to save under. | | `artifacts[].url` | string (URL) | yes | Time-limited signed HTTPS download URL, usually on `storage.googleapis.com`. Treat it as opaque: do not parse or rewrite it, do not assume a host. | | `artifacts[].expiresAt` | string (date-time) | yes | When the link (and the job) expires: 30 days after creation. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000004", "type": "job.completed", "payload": { "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" } ] } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'job.completed') { const { jobId, artifacts } = parsed.message.payload; if (!(await delivered.has(jobId))) { await copyFiles(artifacts); // keep the files, not the links await delivered.add(jobId); } await finishPurchaseFor(jobId); // verifier trust: this is the unlock evidence } ``` ### `artifact.save` [Section titled “artifact.save”](#artifactsave) The user tapped Save on a file. Sent only when your host `hello` granted `capabilities.save`. Page → hostNeeds `capabilities.save` | Field | Type | Required | Description | | ------- | ------------------ | -------- | ----------------------------------------- | | `jobId` | string (job id) | yes | The job. | | `code` | string (non-empty) | yes | The artifact `code` from `job.completed`. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000005", "type": "artifact.save", "payload": { "jobId": "eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42", "code": "photo-main" } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'artifact.save') { await saveToPhotos(parsed.message.payload.jobId, parsed.message.payload.code); } ``` ### `artifact.share` [Section titled “artifact.share”](#artifactshare) The user tapped Share on a file. Sent only when your host `hello` granted `capabilities.share`. Page → hostNeeds `capabilities.share` | Field | Type | Required | Description | | ------- | ------------------ | -------- | ----------------------------------------- | | `jobId` | string (job id) | yes | The job. | | `code` | string (non-empty) | yes | The artifact `code` from `job.completed`. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000006", "type": "artifact.share", "payload": { "jobId": "eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42", "code": "photo-main" } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'artifact.share') { await openShareSheet(parsed.message.payload.jobId, parsed.message.payload.code); } ``` ### `stepChanged` [Section titled “stepChanged”](#stepchanged) The flow moved to another step. Show `title` in your own header (the page has no chrome of its own). Page → hostNo reply | Field | Type | Required | Description | | ------- | -------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------- | | `step` | `"capture"` \| `"processing"` \| `"payment"` \| `"done"` | yes | The current step. | | `title` | string | | A title for your header, in the session locale (overridable for `capture` and `done`). | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000007", "type": "stepChanged", "payload": { "step": "payment", "title": "Zamówienie" } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'stepChanged') { header.setTitle(parsed.message.payload.title ?? defaultTitle); } ``` ### `canGoBack` [Section titled “canGoBack”](#cangoback) Whether the page can go back. While `true`, send [`back`](#back) on the system back gesture instead of closing. Page → hostNo reply | Field | Type | Required | Description | | ----------- | ------- | -------- | ---------------------------------- | | `canGoBack` | boolean | yes | The page has a step to go back to. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000008", "type": "canGoBack", "payload": { "canGoBack": true } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'canGoBack') { pageCanGoBack = parsed.message.payload.canGoBack; } ``` ### `close` [Section titled “close”](#close) The user is done (“Back” on the done screen, or the end of done screen `none`). Close the flow screen. Page → hostNo reply No fields: the payload is `{}`. * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000009", "type": "close", "payload": {} } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'close') { navigation.goBack(); } ``` ### `error` [Section titled “error”](#error) Something went wrong in the page. A fatal code ends the session; close the flow. Codes and actions: [error codes](http://sdk.snap4.id/reference/errors/). Page → hostNo reply | Field | Type | Required | Description | | ------------ | -------------------- | -------- | ------------------------------------------------------------------------- | | `code` | string (error code) | yes | One of the [bridge error codes](http://sdk.snap4.id/reference/errors/#bridge-error-message). | | `fatal` | boolean | yes | Fixed per code. `true` ends the session. | | `message` | string | | For logs only; never show it to the user. | | `paymentRef` | string (payment ref) | | Only with `duplicate_purchase`: the purchase to refund. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000010", "type": "error", "payload": { "code": "duplicate_purchase", "fatal": false, "paymentRef": "3b241101-e2bb-4255-8caf-4136c566a962" } } ``` * TypeScript ```ts import { parseWebToHost } from '@snap4id-sdk/embed-protocol'; const parsed = parseWebToHost(JSON.parse(raw)); // never throws if (parsed.ok && parsed.message.type === 'error') { const { code, fatal, paymentRef } = parsed.message.payload; if (code === 'duplicate_purchase') await refunds.record(paymentRef); if (fatal) closeFlow(); } ``` ## Host → page [Section titled “Host → page”](#host--page) Sent by your app to the page (the React Native component sends them for you). ### `hello` [Section titled “hello”](#hello-1) Your answer to the page `hello`, with `replyTo` = the page hello’s `id`. Tells the page what your app is and can do, the user’s consent, and optional cosmetic overrides. Host → pageReply to page `hello` | Field | Type | Required | Description | | -------------------- | ---------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- | | `protocolVersion` | string (protocol version) | yes | Your protocol version: `1.0`. | | `platform` | `"ios"` \| `"android"` \| `"test"` | yes | `ios` or `android`; `test` only with a fake store (accepted only by test deployments). | | `appVersion` | string (non-empty) | yes | Your app version, for support. | | `consent` | object | | The user’s analytics consent. Absent ⇒ analytics off. | | `consent.statistics` | boolean | | `true` only if the user allowed statistics in your app. | | `consent.marketing` | boolean | | Ignored: Snap4ID never uses marketing in embedded pages. | | `capabilities` | object | | What the done screen may offer. Absent ⇒ both `false`. | | `capabilities.save` | boolean | yes | Show Save buttons (you handle `artifact.save`). | | `capabilities.share` | boolean | yes | Show Share buttons (you handle `artifact.share`). | | `doneScreen` | `"all"` \| `"photo"` \| `"none"` | | Override the done screen: `all` files, the `photo` only, or `none` (you show the files). | | `theme` | map | | Theme token → value overrides, see [theme](http://sdk.snap4.id/customize/theme/). A wrong shape is ignored. | | `copy` | map | | Text overrides: copy id → `{ locale: text }`. Ids and limits: [texts](http://sdk.snap4.id/customize/texts/). Invalid entries are dropped one by one. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000021", "type": "hello", "payload": { "protocolVersion": "1.0", "platform": "ios", "appVersion": "4.2.0", "consent": { "statistics": true }, "capabilities": { "save": true, "share": true } }, "replyTo": "a3c5e1f0-4d2b-4c8e-9f1a-2b3c4d5e6f70" } ``` * TypeScript ```ts import { createHostToWeb, deliverScript } from '@snap4id-sdk/embed-protocol'; const message = createHostToWeb( 'hello', { protocolVersion: '1.0', platform: 'ios', appVersion: '4.2.0', consent: { statistics: userAllowedStatistics }, capabilities: { save: true, share: true }, }, { replyTo: pageHello.id }, ); webView.evaluateJavaScript(deliverScript(JSON.stringify(message))); // your WebView's "run script" call ``` ### `price.result` [Section titled “price.result”](#priceresult) The store price of the product the page named in its `hello` (`productIds`), for your store, so the page can show it on its order button. Send it after your `hello`, with `replyTo` = the page hello’s `id`: never hold the `hello` for the store. No price (no id for your store, the store does not know it, a store error) ⇒ send `products: {}`; the page then shows no price. Host → pageReply to page `hello`, after your `hello` | Field | Type | Required | Description | | -------------------------- | ------------------ | -------- | ---------------------------------------------------------------------------------------------------- | | `products` | map | yes | The price, keyed by the product id you looked up (the one for your store); empty when you have none. | | `products.*.amount_minor` | integer (≥ 0) | yes | Price in minor units (grosze). | | `products.*.currency` | string (currency) | yes | ISO 4217 code, upper case. | | `products.*.display_price` | string (non-empty) | yes | The store’s localized price string, shown as is. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000025", "type": "price.result", "payload": { "products": { "pl.example.app.idphoto": { "amount_minor": 1999, "currency": "PLN", "display_price": "19,99 zł" } } }, "replyTo": "a3c5e1f0-4d2b-4c8e-9f1a-2b3c4d5e6f70" } ``` * TypeScript ```ts import { createHostToWeb, deliverScript } from '@snap4id-sdk/embed-protocol'; const productId = pageHello.payload.productIds?.ios; // your store's id const product = productId ? await store.product(productId) : undefined; // your store's lookup const message = createHostToWeb( 'price.result', { products: product ? { [productId]: { display_price: product.displayPrice, amount_minor: product.priceMinor, currency: product.currency } } : {}, }, { replyTo: pageHello.id }, ); webView.evaluateJavaScript(deliverScript(JSON.stringify(message))); // your WebView's "run script" call ``` ### `purchase.result` [Section titled “purchase.result”](#purchaseresult) The outcome of a `purchase.request` (`replyTo` = its `id`). Without `replyTo` it is an **unsolicited** result for the open job: a purchase that resolved later, such as an approved “Ask to Buy”. Host → pageReply to `purchase.request`, or unsolicited | Field | Type | Required | Description | | -------------------- | ----------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `jobId` | string (job id) | yes | The job from the request. | | `paymentRef` | string (payment ref) | yes | The `paymentRef` from the request. | | `status` | `"succeeded"` \| `"cancelled"` \| `"failed"` \| `"pending"` \| `"busy"` | yes | `succeeded` (bought), `pending` (waiting for approval), `cancelled` (by the user), `failed` (see `reason`), `busy` (another purchase is in progress). | | `receipt` | object, `kind` one of `"fake"`, `"app-store"`, `"play"` | | Trust mode `verifier`: the store receipt, required with `succeeded`. Trust mode `backend`: omit it; send `succeeded` only after your backend unlocked the job. | | `reason` | string | | Why it failed, for logs. | | `price` | object | | The store price you charged, if known (Google Play receipts carry no price). | | `price.amount_minor` | integer (≥ 0) | yes | Minor units. | | `price.currency` | string (currency) | yes | ISO 4217, upper case. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000022", "type": "purchase.result", "payload": { "jobId": "eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42", "paymentRef": "3b241101-e2bb-4255-8caf-4136c566a962", "status": "succeeded", "receipt": { "kind": "app-store", "jws": "eyJhbGciOiJFUzI1NiJ9.eyJ0cmFuc2FjdGlvbklkIjoiMjAwMDAwMDAwMSJ9.c2ln" }, "price": { "amount_minor": 1999, "currency": "PLN" } }, "replyTo": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f" } ``` * TypeScript ```ts import { createHostToWeb, deliverScript } from '@snap4id-sdk/embed-protocol'; const message = createHostToWeb( 'purchase.result', { jobId, paymentRef, status: 'succeeded', receipt: { kind: 'app-store', jws: transaction.jwsRepresentation } }, { replyTo: request.id }, ); webView.evaluateJavaScript(deliverScript(JSON.stringify(message))); // your WebView's "run script" call ``` ### `back` [Section titled “back”](#back) The user made the system back gesture while the page reported `canGoBack: true`. Host → pageNo reply No fields: the payload is `{}`. * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000023", "type": "back", "payload": {} } ``` * TypeScript ```ts import { createHostToWeb, deliverScript } from '@snap4id-sdk/embed-protocol'; const message = createHostToWeb('back', {}); webView.evaluateJavaScript(deliverScript(JSON.stringify(message))); // your WebView's "run script" call ``` ### `consent.changed` [Section titled “consent.changed”](#consentchanged) The user changed their analytics choice in your app during the session. Host → pageNo reply | Field | Type | Required | Description | | -------------------- | ------- | -------- | ------------------------------------------- | | `consent` | object | yes | The new consent. | | `consent.statistics` | boolean | | `true` only if the user allowed statistics. | | `consent.marketing` | boolean | | Ignored. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000024", "type": "consent.changed", "payload": { "consent": { "statistics": false } } } ``` * TypeScript ```ts import { createHostToWeb, deliverScript } from '@snap4id-sdk/embed-protocol'; const message = createHostToWeb('consent.changed', { consent: { statistics: false } }); webView.evaluateJavaScript(deliverScript(JSON.stringify(message))); // your WebView's "run script" call ``` ### `error` [Section titled “error”](#error-1) Your host tells the page about a protocol problem. Only two codes may be sent this way. Host → pageNo reply | Field | Type | Required | Description | | --------- | ------------------- | -------- | ---------------------------------------------------------------------------------------------------- | | `code` | string (error code) | yes | `invalid_message` (a page message failed validation and expected a reply) or `unsupported_protocol`. | | `fatal` | boolean | yes | `true` for `unsupported_protocol`, `false` for `invalid_message`. | | `message` | string | | For logs only. | * JSON ```json { "v": 1, "id": "0b8f5c2e-7a41-4d3b-9e6c-000000000025", "type": "error", "payload": { "code": "invalid_message", "fatal": false }, "replyTo": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f" } ``` * TypeScript ```ts import { createHostToWeb, deliverScript } from '@snap4id-sdk/embed-protocol'; const message = createHostToWeb('error', { code: 'invalid_message', fatal: false }, { replyTo: bad.id }); webView.evaluateJavaScript(deliverScript(JSON.stringify(message))); // your WebView's "run script" call ``` ## Receipts [Section titled “Receipts”](#receipts) The `receipt` of a successful `purchase.result`, discriminated on `kind`. ### `app-store` [Section titled “app-store”](#app-store) StoreKit 2: the signed transaction (`VerificationResult.jwsRepresentation`). | Field | Type | Required | Description | | ------ | -------------------- | -------- | ----------------------------------------------------------- | | `kind` | `"app-store"` | yes | Always `app-store`. | | `jws` | string (compact JWS) | yes | The compact JWS of the transaction, as StoreKit returns it. | ```json { "kind": "app-store", "jws": "eyJhbGciOiJFUzI1NiJ9.eyJ0cmFuc2FjdGlvbklkIjoiMjAwMDAwMDAwMSJ9.c2ln" } ``` ### `play` [Section titled “play”](#play) Google Play Billing: the purchase data and its signature, unchanged. | Field | Type | Required | Description | | -------------- | ------------------ | -------- | ------------------------------------------ | | `kind` | `"play"` | yes | Always `play`. | | `originalJson` | string (non-empty) | yes | `Purchase.getOriginalJson()`, as returned. | | `signature` | string (base64) | yes | `Purchase.getSignature()`, base64. | ```json { "kind": "play", "originalJson": "{\"orderId\":\"GPA.1234-5678-9012-34567\",\"productId\":\"pl.example.app.idphoto\",\"obfuscatedProfileId\":\"3b241101-e2bb-4255-8caf-4136c566a962\"}", "signature": "bXlzaWduYXR1cmU=" } ``` ### `fake` [Section titled “fake”](#fake) From the SDK’s fake store, for tests. Refused by production; accepted only by test deployments. | Field | Type | Required | Description | | --------------- | ------------------ | -------- | ------------------------------------------- | | `kind` | `"fake"` | yes | Always `fake`. | | `testOnly` | `true` | yes | Always `true`. | | `transactionId` | string (non-empty) | yes | Fake transaction id. | | `productId` | string (non-empty) | yes | The product bought. | | `accountToken` | string (non-empty) | yes | The `paymentRef` the purchase was bound to. | | `purchasedAt` | string (non-empty) | yes | When it was “bought”. | ```json { "kind": "fake", "testOnly": true, "transactionId": "fake-0001", "productId": "pl.example.app.idphoto", "accountToken": "3b241101-e2bb-4255-8caf-4136c566a962", "purchasedAt": "2026-11-24T12:00:00.000Z" } ``` ## Formats [Section titled “Formats”](#formats) Named string formats used in the tables above. | Format | Rule | Example | | ---------------- | ------------------------------------------------------------ | ----------------------------------------- | | job id | An optional two-letter zone, a dash, then a lower-case UUID. | `eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42` | | payment ref | Lower-case UUID version 4. | `3b241101-e2bb-4255-8caf-4136c566a962` | | protocol version | `major.minor`. | `1.0` | | file name | Letters, digits, `_`, `.` and `-`; not only dots. | `snap4id-photo.jpg` | | currency | ISO 4217, upper case. | `PLN` | | compact JWS | Three base64url parts joined by dots. | `eyJh.eyJ0.c2ln` | | base64 | Standard base64 with padding. | `bXlzaWduYXR1cmU=` | # Component API > The public API of @snap4id-sdk/app-embed - createSnap4IdClient, the client, Snap4IdFlow, Snap4IdResume, the config plugin and the testing entry. Entry points: `@snap4id-sdk/app-embed` (React Native), `@snap4id-sdk/app-embed/dev` (a ready-made fake store for simulators; development builds only), `@snap4id-sdk/app-embed/testing` (fakes for unit tests; never in a release app), and the Expo config plugin `@snap4id-sdk/app-embed`. Protocol types are re-exported from `@snap4id-sdk/embed-protocol`. Guides: [quickstart](http://sdk.snap4.id/integrate/react-native/) and [component details](http://sdk.snap4.id/integrate/react-native/details/). ## `createSnap4IdClient(config, overrides?)` [Section titled “createSnap4IdClient(config, overrides?)”](#createsnap4idclientconfig-overrides) Creates the client: once per app process. Throws `ConfigurationError` (`configuration_invalid`) for an invalid config. | Parameter | Type | Required | Description | | ------------------- | ----------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `partnerId` | `string` | yes | Your partner id from onboarding | | `purchases` | `'built-in'` \| `AppPurchases` | yes | The built-in store (`expo-iap`), or [your own store code](http://sdk.snap4.id/integrate/react-native/own-store/) | | `onCompleted` | `(completion) => Promise \| void` | yes | Files of a paid job; at least once per job until it resolves | | `onError` | `(error: ComponentError) => void` | | `{ code, fatal, message?, paymentRef?, jobId?, transactionId? }`, see [error codes](http://sdk.snap4.id/reference/errors/#component-onerror) | | `onVerifyPurchase` | `(receipt, { jobId, paymentRef, price? }) => Promise` | | Present ⇒ your backend checks receipts ([your backend](http://sdk.snap4.id/set-up-payments/your-backend/)); bounded at 15 s | | `onBridgeMessage` | `(entry) => void` | | Redacted bridge traffic, for logs | | `namespace` | `string` | | Per signed-in user; default `'default'` | | `theme`, `copy` | `HostTheme`, `HostCopy` | | [Theme](http://sdk.snap4.id/customize/theme/) and [text](http://sdk.snap4.id/customize/texts/) overrides | | `origin` | `string` | | Default `https://snap4.id`; leave unset in release builds | | `trustedOrigins` | `string[]` | | Extra exact HTTPS origins (pre-production Snap4ID only) | | `allowLocalOrigins` | `boolean` | | **Test builds only.** Lets a release build load `http://127.0.0.1[:port]` / `http://10.0.2.2[:port]` (a local Snap4ID or the [fake page](http://sdk.snap4.id/test/fake-store/#the-fake-snap4id-page)); default `false`. Development builds allow local origins without it | | `storage` | `JsonStore` | | Default: `FileJsonStorage`, JSON files via `expo-file-system` | | `devHooks` | `DevHooks` | | From `./testing`; ignored outside development builds | `AppPurchases` = `{ onPurchaseRequest, onConfirmPurchase, getUnfinishedPurchases?, getPendingPurchases?, getPrice? }`. `overrides.builtInStore` replaces the store behind `'built-in'` (the fake store in development builds, from `createDevFakeStore()` in `@snap4id-sdk/app-embed/dev`; see [fake store](http://sdk.snap4.id/test/fake-store/#simulator-runs-with-the-fake-store)). * Snap4ID checks ```ts import { createSnap4IdClient } from '@snap4id-sdk/app-embed'; export const snap4id = createSnap4IdClient({ partnerId: 'your-partner-id', purchases: 'built-in', onCompleted: (completion) => snap4id.downloadArtifacts(completion), onError: (error) => log.warn(error.code), }); ``` * Your own backend ```ts import { AlreadyPaidError, createSnap4IdClient } from '@snap4id-sdk/app-embed'; export const snap4id = createSnap4IdClient({ partnerId: 'your-partner-id', purchases: 'built-in', onVerifyPurchase: async (receipt, { jobId, paymentRef, price }) => { const res = await api.post('/snap4id/purchases', { jobId, paymentRef, receipt, price }); if (res.status === 409) throw new AlreadyPaidError(); if (!res.ok) throw new Error(`verify failed: ${res.status}`); }, onCompleted: (completion) => snap4id.downloadArtifacts(completion), }); ``` ### 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. `AppPurchases.getPrice(productId)` (your own store code): `Promise`, `ProductPrice` = `{ display_price, amount_minor, currency }`. ## The client [Section titled “The client”](#the-client) | Member | Returns | Description | | --------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `start()` | `Promise` | Store listeners + recovery; once per app start | | `stop()` | `void` | Detach the listeners | | `recover()` | `Promise` | Run recovery again | | `purchaseUpdated(purchase)` | `Promise` | Your own store code: a purchase that resolved later (approved “Ask to Buy”) | | `downloadArtifacts(completion)` | `Promise` | Copy a completion’s files into app storage; rejects until all are stored | | `files` | object | `save(jobId, code)`, `share(jobId, code)`: a job’s stored file (else a temporary copy of its link) | | `downloads` | object | Files stored by `downloadArtifacts`: `list()` and `forJob(jobId)` return `Promise`; `subscribe(listener)` calls `listener(files)` with the full, updated `DownloadedFile[]` after every change and returns an unsubscribe function. `DownloadedFile` = `{ jobId, code, title, mimeType, filename, localUri, bytes }` | | `resumeQueue.subscribe(listener)` | unsubscribe function | Job ids the component wants reopened | | `jobs()`, `deleteJob(jobId)` | | The component’s job records | `recover(config)` (a separate export) runs start-up recovery headless, for a background task before any UI. ## `` [Section titled “\”](#snap4idflow) The full-screen flow. Render it under your own header. | Prop | Type | Required | Description | | ----------------- | --------------------------------------------------- | -------- | ----------------------------------------------------------------------------------- | | `client` | `Snap4IdClient` | yes | The client | | `onClose` | `({ reason: 'page' \| 'fatal' \| 'back' }) => void` | yes | Close the screen | | `jobId` | `string` | | Reopen a job; omit for a new one | | `consent` | `{ statistics?: boolean }` | | Absent ⇒ analytics off; marketing never | | `onStateChange` | `({ jobId?, step?, title?, canGoBack }) => void` | | Header title and step | | `doneScreen` | `'all' \| 'photo' \| 'none'` | | Default from your partner configuration, see [done screen](http://sdk.snap4.id/customize/done-screen/) | | `capabilities` | `{ save?: boolean; share?: boolean }` | | Default: both, where supported | | `theme`, `copy` | `HostTheme`, `HostCopy` | | Win over the client config per key / id | | `style`, `testID` | | | | ```tsx // statisticsConsent: your app's own analytics consent (boolean | undefined); undefined ⇒ analytics off. navigation.setOptions({ title })} onClose={() => navigation.goBack()} /> ``` ## `` [Section titled “\”](#snap4idresume) Hidden WebViews that reopen queued jobs one at a time, so paid jobs are delivered after a kill. Mount once near the root. | Prop | Type | Required | Description | | ----------- | ---------------------- | -------- | -------------------------------------------------- | | `client` | `Snap4IdClient` | yes | The client | | `jobIds` | `string[]` | | Jobs to reopen; default: the client’s resume queue | | `onSettled` | `(jobId, end) => void` | | A reopened job’s hidden session ended, with why | ## The completion [Section titled “The completion”](#the-completion) What `onCompleted` and `downloadArtifacts` receive. | Field | Type | Description | | ------------- | ----------------------------------------------------- | -------------------------------------------------- | | `jobId` | `string` | The paid job | | `orderCode` | `string` | Six characters, for the user and support | | `artifacts[]` | `{ code, title, mimeType, filename, url, expiresAt }` | Every file; `url` expires at `expiresAt` (30 days) | ## Config plugin [Section titled “Config plugin”](#config-plugin) ```ts plugins: [['@snap4id-sdk/app-embed', { cameraPermission, photosPermission, savePhotosPermission }], 'expo-iap']; ``` | Option | Writes | | ---------------------- | ------------------------------------------------------------------- | | `cameraPermission` | iOS `NSCameraUsageDescription`; Android `android.permission.CAMERA` | | `photosPermission` | iOS `NSPhotoLibraryUsageDescription` | | `savePhotosPermission` | iOS `NSPhotoLibraryAddUsageDescription` | The Android media permissions (`READ_MEDIA_IMAGES`, `READ_MEDIA_VIDEO`, `READ_MEDIA_AUDIO`, `READ_MEDIA_VISUAL_USER_SELECTED`, and the legacy storage ones) come from `expo-media-library`’s own config plugin, not from this one. The component only saves photos: to request images only, configure that plugin too, e.g. `['expo-media-library', { granularPermissions: ['photo'] }]`, and check what Google Play’s photo and video permissions policy asks of your app. Peer dependencies (what `npx expo install` picks for Expo SDK 58): `expo` ^58, `react-native` ^0.88, `react` ^19.3, `react-native-webview` ^14, `expo-iap` ^6.4 (optional: only for `purchases: 'built-in'`), `expo-file-system`, `expo-media-library`, `expo-sharing`, `expo-constants` (all ^58). Development builds also need `expo-dev-client`. ## `./dev` [Section titled “./dev”](#dev) Development builds only (import it behind `__DEV__`). | Export | Description | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `createDevFakeStore(options?)` | A `FakeStore` with a native “Test purchase” alert (Buy / Pending / Fail / Cancel) and file storage. Options: `dialog`, `store`, `blocksRebuyUntilFinished` (default: `true` on Android, like Play) | | `alertPurchaseDialog` | That alert, as a `FakePurchaseDialog` | | `FakeStore` | `new FakeStore(dialog, store, clock?, newId?, options?)`: `dialog` = `{ choose(request): Promise<'succeed' \| 'pending' \| 'fail' \| 'cancel'> }`, `store` = a `JsonStore` (e.g. `new FileJsonStorage()` from the main entry) | ## `./testing` [Section titled “./testing”](#testing) `FakeStore`, `MemoryJsonStore`, `MemoryFileStore`, `RecordingMedia`, `RecordingSender`, `ManualClock`, `ScriptedDialog`, `FakeHostBackend`, `OneShotDevHooks`, `createTestClient`. See [fake store](http://sdk.snap4.id/test/fake-store/). # Error codes > Every error code a partner integration can see (bridge, component, purchase verifier, Partner API) and what to do. Four places report a code. Your app sees the first two (`onError` of the React Native component, or `error` messages on a native bridge); your backend sees the last two. A **fatal** code ends the session. ## Bridge `error` message [Section titled “Bridge error message”](#bridge-error-message) Payload `{ code, fatal, message?, paymentRef? }`, in either direction. `fatal` is fixed per code; `message` is for logs only; `paymentRef` comes only with `duplicate_purchase`. On a fatal code the component calls `onClose({ reason: 'fatal' })`. | Code | Fatal | Sent by | Meaning | What to do | | ----------------------- | ------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `embed_unavailable` | **yes** | page | Your partner embed configuration is missing, disabled or invalid (unknown partner id, unsupported locale or document). Sent right after the page `hello`, which then has no `trustMode`. | Check the partner id; ask Snap4ID to enable embedding for it. | | `handshake_timeout` | **yes** | page | The host never answered the page `hello`. | The bridge shim was not injected at document start, or page messages are not forwarded to your code. | | `unsupported_protocol` | **yes** | page, host | The envelope `v` is not 1, or the other side speaks another protocol major version. | Update the SDK (or your native host) to the current protocol. | | `job_not_found` | **yes** | page | A resumed job id is unknown or belongs to another partner. | Drop the job from your list. | | `processing_failed` | no | page | The photo could not be processed. | Nothing to do: the user can start again in the page, and nothing was charged. | | `unlock_rejected` | no | page | The purchase was refused for good (invalid receipt, wrong product or environment, transaction already used). | Do not deliver; check your store setup and the store details Snap4ID holds for you. | | `duplicate_purchase` | no | page | The job was already paid with another transaction. Carries `paymentRef`. | **Refund** this purchase. The component reports it to `onError` with `jobId` and `transactionId`. | | `artifacts_unavailable` | no | page | The files were still not ready 30 s after payment. | Nothing to do: the page keeps waiting and delivers when they are. | | `maintenance` | no | page | Snap4ID is temporarily in maintenance. | Ask the user to try again later. | | `invalid_message` | no | page, host | Reply to a message that failed validation and expected an answer. | A bug in the sender: log it with the message type. | Codes are additive: a new code is a minor protocol version. Treat an unknown non-fatal code as a log line. ## Component `onError` [Section titled “Component onError”](#component-onerror) `@snap4id-sdk/app-embed` reports the bridge codes above plus its own (never sent over the bridge). `onError` gets `{ code, fatal, message?, paymentRef?, jobId?, transactionId? }`. | Code | Fatal | Meaning | What to do | | -------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `trust_mode_mismatch` | **yes** | `onVerifyPurchase` is set (your own backend checks) but your configuration has the page check purchases (Snap4ID or your verifier server), or the reverse (the page reports its trust mode in `hello`). | Make the app match your setup: [choose your setup](http://sdk.snap4.id/choose-your-setup/). | | `origin_rejected` | **yes** | The flow was asked to open a URL outside the origin policy. | Leave `origin` unset in release builds; in development use `127.0.0.1`, `10.0.2.2` or a LAN address. | | `configuration_invalid` | **yes** | The client config is invalid; the message names the field. | Fix the config. | | `save_failed` | no | Saving a file failed (permission, storage). | Show your own message. | | `share_failed` | no | Sharing a file failed. | Show your own message. | | `purchase_callback_failed` | no | Your `onPurchaseRequest`, `onConfirmPurchase` or `onVerifyPurchase` threw. | Fix the callback. A thrown purchase request counts as failed; the other two are retried. | | `orphan_purchase` | no | An unfinished store purchase with no record in the component (for example, app data was cleared). It is left unfinished. | Check it in your store console; refund it if no job was delivered for it. | | `storage_corrupt` | no | One of the component’s records was unreadable and set aside. | Report it to Snap4ID support with the job id. | | `price_unavailable` | no | The page asked for the store price of your product and the component has none (`message` names the product id and platform): no id for this store, the store does not know it, or a store error. The page shows no price; the purchase still works. | Check the product id you gave Snap4ID for this store matches your store product (and that it is active / in your StoreKit file); with your own store code, implement `getPrice`. | ## Purchase verifier [Section titled “Purchase verifier”](#purchase-verifier) Snap4ID’s verifier (and our [ready-made verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/)) answers `{ "error": { "code" } }`. The page reports a final refusal as `unlock_rejected` and `already_paid` as `duplicate_purchase`; retried answers are retried by the page. | Code | HTTP | Retried | Meaning | | -------------------------- | ---- | ------- | -------------------------------------------------------------------------------------------------------- | | `invalid_receipt` | 400 | no | Signature, certificate chain, app, purchase state, or a test receipt where none is accepted. | | `binding_mismatch` | 400 | no | The receipt is not bound to `payment_ref`, or the job is not yours. | | `unknown_product` | 400 | no | The product id is not among the products Snap4ID holds for you. | | `environment_not_allowed` | 400 | no | The store environment is refused here (for example, sandbox in production without an App Review window). | | `payment_ref_mismatch` | 400 | no | The payment ref was not issued for this job. | | `invalid_request` | 400 | no | The request body is malformed. | | `unknown_partner` | 400 | no | No configuration for this partner id. | | `app_check_failed` | 401 | no | The page could not prove it is the genuine Snap4ID page. | | `origin_not_allowed` | 403 | no | The request came from an origin that is not allowed. | | `not_found` | 404 | no | Unknown path. | | `method_not_allowed` | 405 | no | Wrong HTTP method for the path. | | `transaction_already_used` | 409 | no | The transaction already unlocked another job. Do not deliver for it. | | `already_paid` | 409 | no | The job was paid by another transaction: the page reports `duplicate_purchase`. Refund this one. | | `job_not_payable` | 409 | no | The job is not waiting for a store payment. | | `request_too_large` | 413 | no | The body is over 64 KiB. | | `internal_error` | 500 | yes | Configuration or key unreadable on the verifier side. | | `unlock_failed` | 502 | yes | Snap4ID could not be reached to unlock the job. | ## Partner API [Section titled “Partner API”](#partner-api) Answers `{ "error": { "code" } }`. `@snap4id-sdk/partner-api` throws one typed error per code (`isPartnerApiError(e, code)`), with `error.requestId` for support; the rows marked *client* are raised by the client itself. | Code | HTTP | What to do | | -------------------------- | -------- | ------------------------------------------------------------------------------------------- | | `invalid_request` | 400 | Fix the request body (the client validates it before sending). | | `payment_ref_mismatch` | 400 | The payment ref was not issued for this job: send the ref from the same `purchase.request`. | | `unknown_product` | 400 | Tell Snap4ID about the new product id (keep retired ones listed for 30 days). | | `environment_not_allowed` | 400 | Wrong store environment for this deployment, or `platform` and `environment` disagree. | | `unauthorized` | 401 | Key id, key, partner id or clock skew (over 5 minutes). Never retried. | | `not_found` | 404 | Wrong job id, or not your job. | | `transaction_already_used` | 409 | The transaction unlocked another job: do not deliver for it. | | `already_paid` | 409 | The job was paid by another transaction: **refund** this purchase. | | `job_not_payable` | 409 | The job does not wait for a store payment: do not charge. | | `server_error` | *client* | Snap4ID answered `5XX` after the client’s retries: keep the purchase and retry later. | | `timeout` | *client* | No answer in time after retries: keep the purchase and retry later. | | `network` | *client* | Snap4ID unreachable after retries: keep the purchase and retry later. | | `aborted` | *client* | Your `AbortSignal` cancelled the call. | | `invalid_response` | *client* | The answer did not match the contract: report it with `requestId`. | | `unexpected_response` | *client* | A status / code pair outside the contract: report it with `requestId`. | | `invalid_argument` | *client* | The client was called with invalid arguments (checked before sending). | # Purchase verifier > The verifier HTTP API the page calls, the partner configuration and key formats, and the library exports. The receipt checks of Snap4ID’s verifier, published as `@snap4id-sdk/purchase-verifier`: as a library for [your own backend](http://sdk.snap4.id/set-up-payments/your-backend/) and as the ready-made [verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/). Snap4ID’s verifier runs at `https://snap4.id/verifier`. The page calls the HTTP API itself; you call it only when testing your own verifier server. ## HTTP API [Section titled “HTTP API”](#http-api) | Method | Path | | | ------ | --------------------------------------------- | -------------------------------------------------------------- | | `POST` | `/v1/receipts` (also `/verifier/v1/receipts`) | verify and unlock | | `GET` | `/v1/health` (also `/verifier/v1/health`) | `200 { "status": "ok", "deployment": "production" \| "test" }` | ### `POST /v1/receipts` [Section titled “POST /v1/receipts”](#post-v1receipts) Called by the page with `Content-Type: application/json` and an `X-Firebase-AppCheck` token; at most 64 KiB. | Field | Type | Required | Description | | ------------- | ---------------- | -------- | ---------------------------------------------------- | | `partner_id` | string | yes | Your partner id | | `job_id` | string (job id) | yes | The job being paid | | `payment_ref` | string (UUID v4) | yes | The `paymentRef` of the `purchase.request` | | `receipt` | `Receipt` | yes | `app-store`, `play` (or `fake` on a test deployment) | | `price` | `Money` | | The host-reported store price (Google Play) | ```json { "partner_id": "your-partner-id", "job_id": "eu-6f1c2b9e-3d4a-4b8f-9c2e-1a7d5e3f0b42", "payment_ref": "3b241101-e2bb-4255-8caf-4136c566a962", "receipt": { "kind": "app-store", "jws": "eyJ…" }, "price": { "amount_minor": 1999, "currency": "PLN" } } ``` Success `200 { "status": "paid" }` (also for a repeat of the same transaction). Errors `{ "error": { "code" } }` (all codes also in [error codes](http://sdk.snap4.id/reference/errors/#purchase-verifier)): | Status | Code | Meaning | | ------ | ------------------------------------ | -------------------------------------------------------------------------- | | 400 | `invalid_receipt` | signature, chain, app, state, or a test receipt refused | | 400 | `binding_mismatch` | receipt not bound to `payment_ref`, or the job is not this partner’s | | 400 | `unknown_product` | product not in the partner configuration | | 400 | `environment_not_allowed` | environment refused in this deployment | | 400 | `payment_ref_mismatch` | ref not issued for this job | | 400 | `invalid_request`, `unknown_partner` | bad body; no configuration for the partner | | 401 | `app_check_failed` | missing / invalid App Check token (or your auth hook refused) | | 403 | `origin_not_allowed` | `Origin` not in the allow-list | | 409 | `transaction_already_used` | the transaction unlocked another job | | 409 | `already_paid` | paid by another transaction: the page reports `duplicate_purchase`; refund | | 409 | `job_not_payable` | job not waiting for a store payment | | 413 | `request_too_large` | body over 64 KiB | | 500 | `internal_error` | configuration or key unreadable; retried | | 502 | `unlock_failed` | Snap4ID unreachable; retried | Checks run in order: origin → path / method → authentication → size → body → partner configuration → receipt → unlock key → unlock. CORS: exact allowed origins, `POST, GET`, headers `content-type, x-firebase-appcheck`, no credentials. ## Partner configuration [Section titled “Partner configuration”](#partner-configuration) Your store details in one JSON document: `.config.json` on a verifier server, `config` for `verifyReceipt` on your backend. When Snap4ID checks purchases, Snap4ID writes it from [what you send](http://sdk.snap4.id/set-up-payments/snap4id-checks/#what-you-send-us). ```json { "partner_id": "your-partner-id", "apps": { "ios": { "bundle_id": "pl.example.app", "product_ids": ["pl.example.app.idphoto"] }, "android": { "package_name": "pl.example.app", "product_ids": ["pl.example.app.idphoto"], "play_public_key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA…" } }, "allowed_environments": ["production"], "sandbox_in_prod_until": "2026-12-15T00:00:00Z" } ``` | Field | Rule | | ------------------------------------------------- | ------------------------------------------------------------------------------------------- | | `partner_id` | `^[a-z0-9][a-z0-9-]{1,31}$` | | `apps` | `ios` and / or `android`, at least one | | `apps.ios.bundle_id`, `apps.android.package_name` | reverse-DNS app id | | `apps.*.product_ids` | non-empty, unique; keep retired ids for 30 days | | `apps.android.play_public_key` | base64 RSA public key from the Play Console | | `allowed_environments` | of `production`, `sandbox`, `xcode`, `test`; production deployments refuse `xcode` / `test` | | `sandbox_in_prod_until` | optional ISO 8601 date-time; sandbox accepted in production until then | Every object is strict: unknown fields make the configuration invalid. JSON Schemas ship in the package under `schema/`. Key record `.key.json`: `{ "key_id": "", "private_key_pem": "" }`. ## Library [Section titled “Library”](#library) | Export | Purpose | | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `verifyReceipt(input, options)` | offline check: `{ ok: true, purchase }` or `{ ok: false, code }` | | `choosePrice(storePrice, hostPrice)` | the price fields of an unlock (signed store price wins) | | `verifyAndUnlock(request, deps)` | configuration lookup, `verifyReceipt`, price, Partner API unlock, answer mapping | | `createReceiptHandler(deps)` | framework-neutral HTTP handler (paths, CORS, auth hook, size limit, logging) | | `createMemoryConfigSource`, `createFileConfigSource`, `withCache` | configuration sources | | `parseRuntimeConfig(env)` | deployment policy; refuses an unsafe production setup | | `PartnerConfigSchema`, `UnlockKeyRecordSchema`, `VerificationRequestSchema` | the formats | # Test App Store purchases > StoreKit configuration files in Xcode, sandbox Apple accounts and TestFlight, and the sandbox window for production and App Review. Simulators cannot buy from the real App Store (sandbox, TestFlight): check those purchases and kill-after-pay on a phone. Xcode’s StoreKit testing (below) also works on a simulator. | Stage | How | Receipt environment | Accepted by | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------- | ----------------------------------------------- | | Local, no account | an Xcode **StoreKit configuration** (`.storekit` file) with your consumable product; run from Xcode | `xcode` | the fake Snap4ID page and test deployments only | | Sandbox | a **sandbox Apple account** (App Store Connect → Users and Access → Sandbox) signed in under Settings → App Store on the phone | `sandbox` | production while a sandbox window is open | | TestFlight | a TestFlight build; testers buy with sandbox receipts | `sandbox` | production while a sandbox window is open | ## StoreKit in Xcode [Section titled “StoreKit in Xcode”](#storekit-in-xcode) A **StoreKit configuration file** (`.storekit`) declares products locally (id, type, price, localized names). When Xcode launches your app with that file selected in the scheme, StoreKit serves those products from the file instead of the App Store: purchases show the real system purchase sheet, need no Apple account and no App Store Connect product, and work on a simulator. Each transaction is signed by a local Xcode certificate and carries the receipt environment `xcode`; the sheet’s confirmation reads **\[Environment: Xcode]**. 1. File → New → File → StoreKit Configuration File; add a **consumable** product with your product id and price. 2. Product → Scheme → Edit Scheme → Run → Options → StoreKit Configuration: select the file. 3. Run the app **from Xcode** (Product → Run). Only a launch from Xcode applies the file; an app started otherwise (from the home screen, `xcrun simctl launch`, or a command-line run such as `npx expo run:ios`) talks to the real store. 4. Buy in the app: the purchase sheet appears and ends in “\[Environment: Xcode]”. Debug → StoreKit → Manage Transactions lists the transactions, which is how you check a purchase stays unfinished until the unlock. Expo and React Native: `expo prebuild` regenerates the Xcode project and its scheme, so a file selected by hand is lost on the next prebuild. Add it to the scheme with a small config plugin, development builds only. The SDK’s partner-app example has one, a StoreKit file and a script that prepares the run ([`examples/partner-app/README.md`](https://github.com/lradomski10m/snap4id-sdk/blob/main/examples/partner-app/README.md), “Real purchase sheet”). Xcode receipts are refused by production (`environment_not_allowed`), so use this against the [fake Snap4ID page](http://sdk.snap4.id/test/fake-store/#the-fake-snap4id-page) (its partners sell `dev.snap4id.test.photo`: use that product id in the StoreKit file) or a test deployment. ## Sandbox against production [Section titled “Sandbox against production”](#sandbox-against-production) Production accepts `sandbox` receipts only while your **sandbox window** is open: ask Snap4ID for one, with an end date, for your own testing and for **App Review** (which buys with sandbox receipts against production). It expires by itself. When Snap4ID checks purchases, Snap4ID opens it; when you check, it is `allowed_environments` / `sandbox_in_prod_until` in your own configuration. Check: buy, kill the app right after paying, reopen it: the photo still arrives and the transaction is finished only then. # Test without a store account > Unit tests with in-memory fakes, then simulator runs with the fake store against the SDK's fake Snap4ID page. Test in layers: unit tests with in-memory fakes, simulator runs against the SDK’s fake Snap4ID page with a fake store, then the real store sandboxes on phones ([App Store](http://sdk.snap4.id/test/app-store/), [Google Play](http://sdk.snap4.id/test/google-play/)). ## Unit tests: `@snap4id-sdk/app-embed/testing` [Section titled “Unit tests: @snap4id-sdk/app-embed/testing”](#unit-tests-snap4id-sdkapp-embedtesting) Never import it in production code. | Export | Use | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `createTestClient(overrides)` | a client with in-memory ports | | `FakeStore` | a purchase port: `new FakeStore(dialog, store)`; the dialog answers `succeed`, `cancel`, `fail` or `pending`; `approvePending()` approves every pending purchase; receipts are `kind: 'fake'`, `testOnly: true` | | `ScriptedDialog` | a `FakeStore` dialog your test scripts | | `MemoryJsonStore`, `MemoryFileStore`, `RecordingMedia`, `ManualClock` | storage, files, media library and time you control | | `RecordingSender` | records what the host sends to the page | | `FakeHostBackend` | a backend stand-in for backend-trust tests | | `OneShotDevHooks` | simulate a kill at a chosen point (`config.devHooks`, honoured only in development builds) | ## Simulator runs with the fake store [Section titled “Simulator runs with the fake store”](#simulator-runs-with-the-fake-store) In a development build, replace the device store with the fake store: a “Test purchase” alert with Buy / Pending / Fail / Cancel, no store account needed. The host `hello` then says `platform: 'test'`, and only a test deployment or the [fake Snap4ID page](#the-fake-snap4id-page) accepts its receipts (`kind: 'fake'`); production refuses them. Keep it in one file you delete before release, and load it only under `__DEV__` (with `require`, so a release bundle never contains it). The `EXPO_PUBLIC_*` variables below are **your app’s own** build settings (the component reads no environment variables): name them as you like. ```ts // src/dev-only.ts: DEVELOPMENT ONLY, delete before release. import { createDevFakeStore } from '@snap4id-sdk/app-embed/dev'; /** `createSnap4IdClient` overrides for simulator runs; empty unless EXPO_PUBLIC_SNAP4ID_TEST_STORE=1. */ export function devOverrides() { if (process.env.EXPO_PUBLIC_SNAP4ID_TEST_STORE !== '1') return {}; return { builtInStore: createDevFakeStore() }; } /** A local Snap4ID origin (the fake page) from your build settings, else none (production). */ export const devOrigin = process.env.EXPO_PUBLIC_SNAP4ID_ORIGIN || undefined; ``` The client of [quickstart step 2](http://sdk.snap4.id/integrate/react-native/#2-one-client-per-app-process), with the two dev additions (the dev-only `require` and the second argument): src/snap4id.ts ```ts import { createSnap4IdClient } from '@snap4id-sdk/app-embed'; // eslint-disable-next-line @typescript-eslint/no-require-imports -- require keeps the file out of release bundles const dev: typeof import('./dev-only') | null = __DEV__ ? require('./dev-only') : null; export const snap4id = createSnap4IdClient( { partnerId: process.env.EXPO_PUBLIC_SNAP4ID_PARTNER_ID ?? 'your-partner-id', ...(dev?.devOrigin ? { origin: dev.devOrigin } : {}), 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); }, onError: (error) => console.warn(error.code, error.message), }, dev?.devOverrides() ?? {}, ); ``` Metro inlines `EXPO_PUBLIC_*` values when it bundles, not when the native app is built: start Metro (`npx expo start` or `npx expo run:ios`) with the same variables, or the fake store and the local origin are silently off. The fake store sells whatever product the page requests (the fake page’s partners name `dev.snap4id.test.photo`) and prices every product at `$4.99`, so the page shows a price on its order button without any store setup (`createDevFakeStore({ price: null })`: no prices). `createDevFakeStore()` keeps its transactions in a file (they survive a restart, like StoreKit’s unfinished purchases) and follows the device store’s rebuy rule (on Android a bought product stays owned until it is finished). For your own dialog or storage: `createDevFakeStore({ dialog, store })`, or `new FakeStore(dialog, store)` from `./testing` ([component API](http://sdk.snap4.id/reference/component-api/#dev)). Native hosts test the same way: send `platform: 'test'` and a [`fake` receipt](http://sdk.snap4.id/reference/bridge-protocol/messages/#fake) from a debug build, against the fake page below. ## The fake Snap4ID page [Section titled “The fake Snap4ID page”](#the-fake-snap4id-page) The SDK repository ships a fake Snap4ID page in `tools/fake-snap4id-page/`: a small local server (`:8090`) that speaks the bridge protocol and the Partner API like Snap4ID, without processing or payments, and accepts the fake store’s receipts. In a checkout of the SDK repository (Node 22 or later): ```sh npm ci npm run fake-page # http://127.0.0.1:8090; FAKE_SNAP4ID_HOST=0.0.0.0 for a phone on the same network ``` `/embed/{partnerId}` starts a job, `/embed/{partnerId}/job/{jobId}` resumes one; `?auto=1` runs create, process and purchase by itself. Two partners are built in: | Partner id | Who checks purchases | | --------------- | ------------------------------------------------------------------------------------------------------------------------ | | `test-verifier` | the page’s verifier stand-in (as when [Snap4ID checks purchases](http://sdk.snap4.id/set-up-payments/snap4id-checks/)) | | `test-backend` | your own backend, through the page’s Partner API; it also sends signed `job.paid` webhooks to `FAKE_SNAP4ID_WEBHOOK_URL` | Both sell the product `dev.snap4id.test.photo`. Point a development build at it with `origin: 'http://127.0.0.1:8090'` (Android emulator: `http://10.0.2.2:8090`; a phone: your computer’s LAN address). Development builds allow these `http` origins; a release build allows only the loopback and emulator ones, and only with `allowLocalOrigins: true` in the client config (never in a build you ship). With the two files above: ```sh EXPO_PUBLIC_SNAP4ID_ORIGIN=http://127.0.0.1:8090 \ EXPO_PUBLIC_SNAP4ID_PARTNER_ID=test-verifier \ EXPO_PUBLIC_SNAP4ID_TEST_STORE=1 \ npx expo run:ios ``` On the fake page, a run is: **Create job** → **Process** → **Request purchase** → **Buy** (the “Test purchase” alert) → **Complete** → **Back to app**; the files then appear in `client.downloads` (the fake page delivers three: the photo, the print sheet as JPG and as PDF; Snap4ID’s real list depends on the document). The page is taller than a phone screen: **Back to app** is below the fold after **Complete** (UI tests: scroll to it, e.g. Maestro `scrollUntilVisible`). Kill the app right after **Buy** and start it again: the photo still arrives (recovery). A development build may show the system “Open in …?” prompt and the Expo developer menu over your app, on the first launch and again after a relaunch (as in the recovery check): dismiss both (UI tests: tap them away after every launch). Every control of the page has a stable id for UI tests (Maestro, Detox, XCUITest); the list, the environment variables and the endpoints are in `tools/fake-snap4id-page/README.md`. A complete app that runs against this page, with a Maestro UI test of the whole flow, is the SDK’s [`examples/partner-app`](https://github.com/lradomski10m/snap4id-sdk/tree/main/examples/partner-app): its README ([`examples/partner-app/README.md`](https://github.com/lradomski10m/snap4id-sdk/blob/main/examples/partner-app/README.md)) has the commands. # Test Google Play purchases > Internal testing tracks, license testers and test accounts for Play Billing purchases against Snap4ID. Play Billing needs a build installed from Google Play (a testing track) and a Google account the Play Console treats as a tester. Emulators with the Play Store work for flows; check kill-after-pay on a phone. ## Set up [Section titled “Set up”](#set-up) 1. **Product.** Play Console → Monetize → In-app products: a consumable with your product id, activated. 2. **Track.** Upload a release build (an `.aab` signed with your upload key) to **internal testing** and add your testers’ accounts to the track; testers install it from the opt-in link. Expo: `expo prebuild`, then `./gradlew :app:bundleRelease` in `android/`; the SDK’s [`examples/partner-app/README.md`](https://github.com/lradomski10m/snap4id-sdk/blob/main/examples/partner-app/README.md) (“Google Play internal testing”) shows the full commands. 3. **License testers.** Settings → License testing: add the same accounts. Their purchases use test payment methods (“Test card, always approves”, “…declines”, “Slow test card” for a pending purchase) and are never charged. 4. **Licensing key.** Monetization setup → Licensing: the base64 RSA public key; Snap4ID (when it checks purchases) or your backend needs it to check receipts. ## Environment [Section titled “Environment”](#environment) License-tester purchases are `sandbox` receipts. Production accepts them only while your **sandbox window** is open (ask Snap4ID; with your backend it is your own `allowed_environments` / `sandbox_in_prod_until`). A purchase in the wrong environment fails with `environment_not_allowed`. ## What to check [Section titled “What to check”](#what-to-check) * The purchase is made with `obfuscatedProfileId` = the page’s `paymentRef` (else `binding_mismatch`). * “Slow test card” gives a pending purchase: it must survive an app restart and unlock when it completes. * Kill the app right after paying and reopen it: the photo arrives, and the purchase is consumed only then. # Test your backend > Signed fixtures for webhook receivers and Partner API calls, test receipts, and the fake Snap4ID page's backend mode. For when you check purchases: in [your own backend](http://sdk.snap4.id/set-up-payments/your-backend/) (or on [our verifier server](http://sdk.snap4.id/set-up-payments/our-verifier-server/)). * **Webhook receiver.** `@snap4id-sdk/embed-protocol/node` has the webhook signing helpers and test keys; sign a fixture body and check your receiver accepts it, rejects a tampered body with `401`, and answers a repeated `event_id` with `2xx` and no side effect. * **Signing vectors.** The SDK repository’s `contracts/` holds signing test vectors for Partner API requests and webhooks: run them against any signing code of your own. * **Receipts.** `verifyReceipt` with `policy: { deployment: 'test', acceptTestReceipts: true }` accepts the fake store’s receipts, so your endpoint can be tested end to end without a store. Production code keeps `deployment: 'production', acceptTestReceipts: false`. * **End to end.** The SDK’s [fake Snap4ID page](http://sdk.snap4.id/test/fake-store/#the-fake-snap4id-page) with partner `test-backend`: your app sends receipts to your backend, your backend unlocks through the page’s Partner API (base URL `http://127.0.0.1:8090`, signed with the test partner key the page writes to `.local/test-keys/partner.ed25519.private.pem` in the SDK checkout, key id in `.local/test-keys/key-ids.json`), and the page sends signed `job.paid` webhooks to `FAKE_SNAP4ID_WEBHOOK_URL`. The SDK’s [`examples/partner-backend`](https://github.com/lradomski10m/snap4id-sdk/tree/main/examples/partner-backend) runs this way out of the box (its README). Cases worth a test: unlock success, a repeated unlock (idempotent, same answer), `already_paid` recorded as a refund, a retryable failure that keeps the purchase pending, and recovery unlocking it later. # Try it now, no account > Run the SDK's example app on your machine, in the iOS simulator or Android emulator, against a fake Snap4ID page with a fake store - no Snap4ID or store account, no purchases. The SDK’s example app runs **on your machine**: a development build in the iOS simulator or the Android emulator (not Expo Go, not a download from a store). It opens a fake Snap4ID page that runs next to it and buys with a fake store: no Snap4ID account, no store account, no real purchase. You need git, Node 22 or later, and Xcode with a simulator (macOS) or Android Studio with an emulator. ## 1. Start the fake Snap4ID page [Section titled “1. Start the fake Snap4ID page”](#1-start-the-fake-snap4id-page) ```sh git clone https://github.com/lradomski10m/snap4id-sdk.git cd snap4id-sdk npm ci npm run fake-page # http://127.0.0.1:8090; leave it running ``` ## 2. Run the example app [Section titled “2. Run the example app”](#2-run-the-example-app) In a second terminal, from the same checkout: ```sh cd examples/partner-app APP_VARIANT=development \ EXPO_PUBLIC_SNAP4ID_ORIGIN=http://127.0.0.1:8090 \ EXPO_PUBLIC_SNAP4ID_PARTNER_ID=test-verifier \ EXPO_PUBLIC_SNAP4ID_TEST_STORE=1 \ npx expo run:ios ``` Android emulator: `EXPO_PUBLIC_SNAP4ID_ORIGIN=http://10.0.2.2:8090` and `npx expo run:android`. The first build takes several minutes. A phone on the same network works too, with a development build installed from your computer (`npx expo run:android --device`, or `npx expo run:ios --device` with your Apple signing team): start the page with `FAKE_SNAP4ID_HOST=0.0.0.0 npm run fake-page` and use your computer’s LAN address as the origin: `http://:8090`. ## 3. Buy a photo [Section titled “3. Buy a photo”](#3-buy-a-photo) Tap **Get your photo**. On the fake page: **Create job** → **Process** → **Request purchase**, choose **Buy** in the “Test purchase” alert, then **Complete** and **Back to app** (scroll down to it). The order is in **My photos** with its files. Kill the app right after **Buy** and start it again: the photo still arrives (recovery). More (your own store code, your own backend with partner `test-backend`, a Maestro UI test): the example’s [README](https://github.com/lradomski10m/snap4id-sdk/blob/main/examples/partner-app/README.md). The same setup in your own app: [fake store](http://sdk.snap4.id/test/fake-store/).