Open-source purchase validation and entitlement infrastructure for the OpenIAP ecosystem. Managed by OpenIAP, IAPKit verifies purchases from the App Store, Google Play, Amazon Appstore, and Meta Horizon; maintains subscription and entitlement state; and provides catalog, analytics, and store management workflows.
For verification that must survive a caller disconnect, the optional
POST /v1/purchase/verification-jobs API stores accepted work and exposes its
result through GET /v1/purchase/verification-jobs/{jobId}. Keep the same
API credential and random Idempotency-Key for retries and result reads.
Existing SDK verification stays synchronous. See the
queue integration guide
for lifecycle states, limits and fulfillment requirements.
IAPKit is neutral infrastructure, not a paywall or growth-optimization SaaS. Operational revenue and subscription analytics remain in scope; paywall creation, audience targeting, experimentation, lifecycle marketing, and conversion optimization do not. Commercial products can build those experience layers on top of OpenIAP and IAPKit.
The community-operated instance run by the OpenIAP project lives at kit.openiap.dev. Other domains running this code are independent deployments and are not operated by the OpenIAP project — do not paste production API keys or receipts into instances you don't control.
IAPKit is provided as-is with best-effort support. There is no SLA on the community instance. If you need guaranteed response times, self-host from
packages/kit/(single binary) or contact the maintainers before launch. An organization whose load strains the shared servers may be removed from the shared pool; to continue, it can sponsor through GitHub Sponsors or self-host.
openiap-kit/
├── src/ # React 19 + Vite SPA (dashboard, auth, project UIs)
├── server/ # Hono + Bun server (/v1/* API + /api/v1/* compat) + static SPA serving
├── convex/ # Convex backend (auth, orgs, projects, API keys, receipts)
├── public/ # SPA static assets (favicons, og-image, etc.)
├── Dockerfile # Multi-stage build → single-binary Fly.io image
└── fly.toml # Fly.io deployment config (app = "openiap-kit")
One package, one binary, one Fly.io app.
- Apple StoreKit 2 JWS verification (
@apple/app-store-server-library) - Google Play purchase verification (
googleapis) - Amazon Appstore RVS verification with explicit sandbox opt-in and bounded purchase reconciliation
- Meta Horizon entitlement verification (Graph API)
- Publishable and secret API keys per project with server-enforced scopes and usage telemetry
- Organization + project multi-tenancy via Convex
- Free under fair-use limits — no billing meter; shared hosted capacity is protected by rate, replay, size, and concurrency safeguards and sustained by community sponsorship
- GitHub OAuth via
@convex-dev/auth(email one-time codes closed on 2026-09-30) - OpenAPI spec auto-generated by
hono-openapi - Codex / Claude Code MCP plugin endpoint at
/mcpfor IAPKit project inspection, revenue questions, product management, and store-sync workflows - OpenIAP CLI — browser login, organization and project administration, API keys, store credentials, catalog sync, purchase operations and analytics through
npx @hyodotdev/openiap kit; see the CLI guide - Per-product client payloads for public, app-readable TOML, JSON, or text rules without a separate metadata service
- Read-only order lookup in the dashboard — paste an Apple or Google order ID from a customer receipt to see the live order and, when available, subscription status, using the project's existing store credentials; lookups are proxied live and never stored
git clone https://github.com/hyodotdev/openiap.git
cd openiap
bun install
cd packages/kitRecommended (one terminal):
bun run dev:alldev:all lets convex dev configure the deployment and write its standard
CONVEX_DEPLOYMENT, VITE_CONVEX_URL, and VITE_CONVEX_SITE_URL values to
.env.local before it starts Hono and Vite. On a new checkout or worktree,
complete the interactive Convex prompt in that terminal. Starting all three
processes in parallel before this first configuration can make Hono or the SPA
exit because the Convex URL is not available yet.
Copy individual optional settings from .env.example only after Convex has
created .env.local; do not replace the generated deployment values.
Receipt verification also requires a private service credential shared by the
local Bun server and that selected development Convex deployment. Generate
32 random bytes as 64 lowercase hex characters, store them as
IAPKIT_VERIFICATION_SOURCE_SECRET in ignored .env.local, and set the same
value through the development deployment's environment-variable UI or
convex env set via stdin. Keep it separate from production and customer API
keys. Never prefix it with VITE_, copy it to the example app, or log it.
Missing or mismatched values defer verification instead of granting access.
Git worktrees:
.env.localand.env.productionare intentionally ignored, so Git does not copy them into a new worktree. Provision them from the maintainer's secure local copy before launching IAPKit, and never commit either file. The VS CodeKit: Devlauncher stops with an explicit message when.env.localis missing instead of silently configuring an unrelated anonymous deployment.
GitHub OAuth uses two different URLs in local development:
-
The GitHub OAuth App callback remains
https://<dev-deployment>.convex.site/api/auth/callback/github. -
The Convex dev deployment's
SITE_URLmust match the Vite origin that starts sign-in:bunx convex env set SITE_URL http://localhost:5173
Convex Auth redirects to SITE_URL after GitHub calls the Convex endpoint.
Keep Vite on port 5173; its strict-port configuration now fails visibly instead
of silently switching to 5174 and creating an unreachable OAuth return URL.
After .env.local has been configured, the split-terminal workflow is also
available:
# Terminal A — Convex functions + schema watcher
bun run dev:convex
# Terminal B — Hono API server (http://localhost:3000)
bun run dev:server
# Terminal C — Vite dashboard (http://localhost:5173)
bun run devFor API-only work:
bun run dev:serverThe dev server also exposes the Codex / Claude Code MCP plugin endpoint at
http://localhost:3000/mcp. Use an IAPKit secret admin key, not a mobile
publishable key and not an OpenAI, ChatGPT, Anthropic, or Claude API key:
IAPKIT_API_KEY="openiap-kit_sk_<your-secret-key>" bun run dev:serverbun run build:all # Vite build + Bun compile → ./openiap-kit-server
./openiap-kit-server # serves /v1/*, /api/v1/* + static SPA on :3000Use an IAPKit project secret key from your backend. Create the Stripe
PaymentIntent or initial subscription invoice, then register the checkout
before confirming payment. Set the same orderId, userId, and productId
on PaymentIntent metadata for a one-time purchase or Subscription metadata
for a recurring purchase. Use opaque app user IDs.
- For Apple, send each token to
POST /v1/external-purchase-tokenswith{ profileId, userId, token }and retain the returnedtokenId. Register tokens even if the customer abandons checkout. For Google Alternative Billing Only, forward theexternalTransactionTokenreturned by Play. - Send
POST /v1/external-checkoutswith anIdempotency-Keyheader. Keep the key for retries. A conflicting key or order returns409. - Confirm payment through Stripe. Its signed webhook queues verification.
You can also call
POST /v1/external-checkouts/{checkoutId}/verify. Its202means the request was durably accepted. - Read
GET /v1/external-checkouts/{checkoutId}forpaymentStatus,reportingStatus, andentitlement.active. Subscriptions also includeentitlement.expiresAtin Unix milliseconds. Use the entitlement to gate access while reporting is queued or retrying.
A Google checkout request body looks like this.
{
"orderId": "order_123",
"userId": "user_42",
"productId": "premium_monthly",
"payment": {
"provider": "stripe",
"kind": "invoice",
"reference": "in_example"
},
"price": {
"currency": "EUR",
"netMinor": 800,
"taxMinor": 200,
"regionCode": "DE"
},
"reporting": {
"store": "google",
"profileId": "play-de-test",
"externalTransactionToken": "<Play token>"
}
}For Apple, use { "store": "apple", "profileId": "apple-de-test", "tokenIds": ["<tokenId>"] }
as the reporting value. For a one-time purchase, use kind: "payment_intent"
and a pi_ reference. Prices are integer minor units in the checkout currency.
For a subscription that starts with a free trial, register its first invoice
with netMinor and taxMinor of 0. IAPKit grants access until the trial
ends, reports the free start to the store, and reports the first paid invoice
as a renewal; Apple's days of paid service leave out the trial.
Change the Stripe subscription's plan at once with
proration_behavior: "always_invoice", or at the next renewal with a
subscription schedule phase. In the same update or phase, set the
subscription's metadata orderId and productId to the new order. Register
the invoice that bills the change as a new checkout with changeOf set to the
current checkout's ID, the invoice's total and tax as the price, and a new
store token: the externalTransactionToken Play returns for the change, or
new Apple tokenIds. A downgrade whose credit leaves nothing to bill
registers netMinor and taxMinor of 0.
Register the change within a day of its invoice's payment; you can register it
as soon as Stripe creates the invoice. When IAPKit verifies the invoice, the
new checkout takes over the subscription and the previous checkout's
entitlement ends; refunds of earlier payments still apply but don't restore
it. IAPKit reports the change to the store, and Apple's report references the
subscription's first report. If you register a change later, call
POST /v1/external-checkouts/{checkoutId}/verify for it instead of reporting
its invoice yourself: IAPKit verifies and reports it, and clears the manual
report the invoice left on the previous checkout.
Stripe can pay part or all of an invoice from the customer's credit balance, such as a downgrade's credit. IAPKit reports only what the customer paid then, with tax in proportion, since the credit came from a payment already reported. The days the credit pays for still count as paid service for Apple.
Set IAPKIT_EXTERNAL_CHECKOUTS_CONFIG in the Convex deployment's secret
environment. Each integration binds one project and Stripe account to
sandbox or production. The Stripe key needs read access to the account,
PaymentIntents, charges, invoices, refunds, and disputes. Install the
project’s Apple In-App Purchase key or Play Developer API service account
through the existing IAPKit credential setup.
{
"integrations": [
{
"id": "stripe-test",
"projectId": "<Convex project ID>",
"accountId": "acct_example",
"environment": "sandbox",
"apiKey": "<Stripe test API key>",
"signingSecret": "<Stripe webhook signing secret>"
}
],
"profiles": [
{
"id": "play-de-test",
"integrationId": "stripe-test",
"store": "google",
"appId": "com.example.app",
"regions": ["DE"]
}
]
}Use unique integration and profile IDs and keep their account, app, and
environment bindings stable. Use one Apple profile per project and environment
for unreported-token notifications. For a Google profile that includes India,
set administrativeArea to the applicable ISO 3166-2 subdivision and limit
the profile to that subdivision. Use a Play license tester and test app for
sandbox profiles.
Point a Stripe webhook at /v1/webhooks/stripe/{integrationId} and subscribe
to payment_intent.succeeded, invoice.paid, refund.created,
refund.updated, and charge.dispute.closed. The account can also serve
other sales: IAPKit skips a PaymentIntent with no checkout binding in its
metadata and no registered checkout, and refunds or disputes of unknown
charges wait without calling Stripe. Configure Apple's existing IAPKit App
Store Server Notifications V2 URL to receive unreported-token notifications.
When Apple lists an unused token as unreported, IAPKit sends its report
again.
A successful Stripe capture grants access and queues a store report in the same database transaction. Reports retry with stable IDs. A full refund removes the refunded payment's contribution to access, and a partial refund keeps it active. Partial refunds allocate the pretax amount in proportion to the original charge, with cumulative rounding. A lost dispute counts as a refund of the disputed amount, up to what the customer has not already been refunded, and is reported to the store as a refund. An open or won dispute changes nothing. IAPKit processes the remaining paid subscription periods independently. If the user was erased before IAPKit verified the payment, the payment is still recorded and reported, without access.
The first integration supports direct Stripe accounts, one captured
PaymentIntent per purchase, and single-item subscriptions: initial, recurring
cycle, and plan change invoices paid by a captured Stripe charge, the
customer's credit balance, or nothing, such as a free trial. A later paid
invoice IAPKit can't verify, such as a renewal that also bills prorations or a
plan change not registered within a day, sets
reportingStatus: "action_required", which later payments don't clear; access
lasts until the verified period ends, and the invoice needs a manual store
report unless a late plan change claims it. A refund or dispute of a recorded
payment that IAPKit can't verify, such as one the Stripe key can't read, sets
it too: access and paymentStatus stay as they were, and the refund needs a
manual store report unless a later Stripe event for it is verified. Store
report failures also appear as reportingStatus: "action_required" when a
provider rejects a report permanently or retries expire. Google requires
reporting within 24 hours.
Apple programs requiring manual reports still use the App Store Connect
process.
The hosted service is a shared resource for the OpenIAP ecosystem, and its
running costs are meant to be covered by sponsorship. It is free to use without
a request-based billing meter, but it is not unlimited infrastructure and does
not include dedicated capacity or an SLA. Clients must cache stable reads, avoid
continuous polling, and honor 429 Retry-After and 503 Retry-After responses.
Traffic that looks like abusive automation, denial-of-service activity, or deliberate safeguard evasion may be throttled or blocked to protect other users. These application and proxy controls are defense in depth, not a claim that any public service can be made immune to DDoS attacks.
Capacity planning must use requests, peaks, and store-verification frequency — not DAU alone. For example, 1 million users making one hosted request per day average about 11.6 requests/second, already above the default per-key steady rate of 10 requests/second before launch-time or notification-driven peaks. Verify purchases only after purchase or restore, persist entitlement snapshots, coalesce concurrent refreshes, and revalidate only when the snapshot is stale or the user explicitly refreshes it.
If an organization expects sustained high volume or a meaningful share of the hosted service, contact the maintainers before production launch. If its load strains the shared servers, it may be removed from the shared pool. To keep using the hosted service at that volume, it may be required to sponsor the capacity it uses through GitHub Sponsors; otherwise, it can self-host this MIT-licensed server, which also gives predictable scaling, dedicated resources, and full operational control. Sponsorship does not reserve capacity or create an SLA. The plan is to share the service's costs openly as usage grows.
When an organization sponsors OpenIAP on GitHub, the maintainer links the
sponsorship to it with the $link-sponsor skill, and from then on IAPKit sends
that organization no sponsorship requests. Any tier or amount counts, and the
organization does nothing: the request email asks it to reply with the
sponsoring account. The link shows on the organization's Usage page. When
the sponsorship ends, the maintainer removes the link and the organization is
back on the normal schedule.
A written arrangement outside GitHub Sponsors is still recorded with
internal.sponsorship.internal.markSponsored.
GET /health returns public operational metadata without touching Convex:
{
"ok": true,
"status": "healthy",
"service": "iapkit",
"apiVersion": "v1",
"revision": "a1b2c3d4e5f6",
"instanceId": "7849e073a91568",
"verificationSourceReady": true,
"environment": "production",
"timestamp": "2026-07-30T12:34:56.000Z"
}apiVersion identifies the public HTTP contract rather than the private
workspace package metadata; hosted IAPKit deployments themselves are
revisioned services, not installable semantic-versioned packages. revision
is the first 12 characters of the deployed Git commit. Local builds report
null when no valid revision is injected. The response is
Cache-Control: no-store, remains safe for Fly.io liveness/readiness probes,
and performs no database or store request. instanceId comes from Fly runtime
metadata (otherwise null); verificationSourceReady reports only a valid
local credential format, not a successful Convex handshake.
The server installs SIGTERM and SIGINT handlers that call
Bun.serve().stop() and let in-flight /v1/* and /api/v1/* requests
drain before the process exits. Fly.io sends SIGTERM before stopping a
machine, so deploys don't cut off requests mid-verify.
Receipt verification and publishable-key product and client-payload routes,
plus secret-key subscription account reads and binding, share bounded
in-memory protection before Convex is called. Publishable-key Apple/Google
webhook ingress uses the same guard before dispatching its verification action.
The default axes are per API key (600-request burst, 10 req/sec), per
source IP (600-request burst, 5 req/sec), and per Fly process
(5,000-request burst, 100 req/sec). The /api/v1/* compatibility aliases use
the same middleware.
Payload-inclusive catalog pages also use a weighted limiter: a request costs
one token per requested product, so a 50-payload page costs 50. Responses carry
X-RateLimit-Limit, X-RateLimit-Remaining, and, on a rejection,
X-RateLimit-Scope; the server returns 429 RATE_LIMITED with
Retry-After.
The verify endpoint also has a per-(API key, payload) replay guard for
the exact same receipt: 30-request burst, ~1/min sustained, plus a
5-minute cooldown after the upstream store settles a payload as invalid (a
response with finalVerdict: true; a Google subscription on hold, paused or in
grace can come back, so it gets no cooldown). A burst returns
429 DUPLICATE_PAYLOAD with Retry-After. During the cooldown the same
payload gets the same verdict again without asking the store; only a verdict
IAPKit could not keep, such as a malformed one, returns 429 REPEATED_FAILURE.
Accepted verification work is also capped at 8 concurrent handlers per API
key, 16 per trusted source IP, and 32 per process by default. The key and
source shares make rotating credentials insufficient to monopolize the process
from one network source. When Convex or an upstream store is slow and any axis
is full, the server returns 503 SERVICE_BUSY with Retry-After,
X-Concurrency-Limit, X-Concurrency-Remaining, and X-Concurrency-Scope
instead of retaining an unbounded in-process queue. Tune self-hosted instances
with VERIFY_MAX_IN_FLIGHT, VERIFY_MAX_IN_FLIGHT_PER_KEY, and
VERIFY_MAX_IN_FLIGHT_PER_IP. The source axis trusts only Fly's
fly-client-ip, so a deployment that does not run behind Fly resolves every
caller to one shared unknown source and that axis becomes a second
process-wide cap; raise VERIFY_MAX_IN_FLIGHT_PER_IP to
VERIFY_MAX_IN_FLIGHT to recover the intended global concurrency there. Fly
Proxy separately protects the complete HTTP service at 80 soft / 120 hard
concurrent requests per machine.
Key/IP bucket stores have a 15-minute idle TTL and are bounded (default 10,000 entries) with LRU eviction. An attacker churning random API keys or addresses past the parse-only middleware cannot grow the maps without bound. Rate checks do not write a Convex counter on every request.
The buckets are per-machine. min_machines_running = 1 is a minimum, not
an inventory: running and standby machines each have their own allowance.
Use the actual machine count when estimating the edge ceiling. Convex's
per-project admission bucket is shared across those machines. Deployment
usage limits provide a separate hard brake only when configured; a triggered
limit stops verification. See COST-SAFETY.md.
The revenue cron discovers historical projects once through checkpointed, byte-bounded pages. New store events seed the existing per-project run status in the same transaction. Bootstrap pages schedule their own continuation; the cron starts or resumes failed discovery without accelerating actual rollups. After discovery finishes, cron ticks read that small status table instead of rereading recent signed webhook payloads. The ten-minute rollup cadence, expiry evaluation and late-event catch-up remain unchanged.
Every request that passes the auth-header shape check on
/v1/purchase/verify or its /api/v1/purchase/verify compatibility
alias emits one structured JSON log line to stdout with { corrId, method, path, statusCode, durationMs, apiKeyHash, store, isValid, state }. The hashed API key is the same 16-hex keyed hash the rate
limiter uses, keyed per server process — the plaintext key is never logged.
Those logged responses also carry an X-Correlation-Id header so
customer support tickets can cross-reference logs. Missing or malformed
Authorization headers return before the logger runs.
Receipt-verification request bodies are capped at 32 KB before JSON
parsing. Product-management writes are capped at 64 KB, subscription
user-binding writes at 32 KB, and webhook pushes at 256 KB. jws
(Apple) is bounded at 16 KB, and purchaseToken is bounded at 2 KB for
Google tokens or 16 KB when an Apple JWS is passed to subscription
binding; userId, sku, and productId are bounded at 256 chars where
accepted. Oversized fields return
400 INVALID_INPUT; oversized request bodies return
413 PAYLOAD_TOO_LARGE. Invalid inputs stop before upstream store calls
or Convex mutations.
The 64 KB product-management limit is for the entire HTTP request
before JSON parsing; it is not per-product metadata capacity. A
clientPayload.body is separately limited to 16 KiB of UTF-8, must be
nonblank, and—when its format is JSON or TOML—must pass syntax validation.
A purchase row is deleted 30 days after a store last answered that it does not
know the evidence: a Google token Play cannot find or that belongs to another
package, a receipt Amazon RVS calls invalid, or Meta success: false. The
dashboard's Total and Invalid counts drop with the row. A row is kept
indefinitely once it holds any other verdict, an owner, a Google order ID, or a
subscription, and rows written before the unrecognizedAt field existed are
never pruned. Monthly usage is not lowered; evidence presented again after its
row is gone counts as a new verification.
Apple App Store Server Notifications v2 and Google RTDN are accepted only in the store-to-IAPKit direction. IAPKit deduplicates those deliveries and updates the canonical subscription snapshot. It does not relay raw events, SSE, WebSockets, long polls, APNs, or FCM to shipped apps.
The raw event row exists for bounded operational history and deduplication, then expires under webhook retention. The canonical subscription snapshot remains. Polling reads that current state rather than replaying a cursor, so an app does not have to consume every event in order.
The recommended account-access flow is:
- For a purchase started in the current app session, use the SDK purchase
callback and verification response for the immediate UI update. Bind the
stable purchase token to an opaque, app-scoped
userIdon your authenticated backend with a secret admin key. - Authenticate the user on the developer backend and resolve the opaque IAPKit
userIdfrom that session. Never trust an independently supplied user ID. - Call
GET /v2/subscriptions/status?userId=...orGET /v2/subscriptions/entitlements?userId=...with a secret key kept only on the backend. The v2 response omitspurchaseTokenandoriginalTransactionId. - Return only the access decision or tokenless fields the app needs. Coalesce concurrent reads, scope any backend cache by IAPKit project and authenticated user, and fail closed after its bounded stale window.
- Respect
429 Retry-Afterand use jittered backoff. Do not run a continuous foreground/background polling timer.
Snapshot reads use the (projectId, userId, updatedAt) index, support up to 200
subscription rows per user, and perform no usage or last-access mutation. One
additional indexed row is read only to detect overflow; IAPKit fails closed
instead of returning a partial entitlement set. All account reads and ownership
binding now require a secret admin key, including the legacy v1 routes and
direct Convex calls. Canonical publishable-key account calls receive 403 INSUFFICIENT_SCOPE; shipped helpers use key-in-path account routes and receive 410 LEGACY_ACCOUNT_ROUTE_RETIRED. Migrate those calls to your authenticated backend
and the tokenless v2 reads. Never replace a mobile publishable key with a secret.
Authorized v1 server responses retain their existing fields and use no-store.
A developer-owned backend also owns any optional
APNs/FCM delivery after processing store webhooks.
The v2 reads accept environment=production|sandbox|all. Explicit scopes
exclude unknown historical environments and acknowledge the applied filter as
environmentScope; omission preserves legacy mixed reads. Require the expected
acknowledgement so older servers cannot silently ignore your filter. The
reference backend defaults to production-only access and applies a server-owned
acceptSandbox(userId) allow-list during both confirmation and later reads.
Include authenticated App Review and approved test accounts in that allow-list;
never take the policy from a mobile request. See the
purchase-flow guide.
POST /v2/subscriptions/user-erasure removes an app user ID from IAPKit
subscription and commerce-event rows. Poll the returned job until completion.
The developer backend must separately erase any event copy it already received.
Each iOS or Android catalog row can carry an optional public
clientPayload with { format, body, version, updatedAt }. Payloads are
stored separately from the store-catalog cache: App Store Connect / Play
Console sync never receives or overwrites them, and resetting the local
catalog retains them for the next matching pull. A retained payload is not
app-readable while its matching product is absent or Removed.
Apps can opt into payloads on catalog reads with
GET /v1/products/{apiKey}?platform=IOS&includeClientPayload=true, or fetch
one directly at
GET /v1/products/{apiKey}/{productId}/client-payload?platform=IOS. Valid
Apple/Google verification responses can include the same top-level field
when the request sends includeClientPayload: true; default, invalid,
missing/Draft/Removed-product, missing-payload, Horizon, and Amazon responses omit
it.
Grant access only when isValid and state permit it and the store-verified
productId is present and matches the product the app expected. Never fall
back to a client-supplied product ID when the verified value is missing, and
never use clientPayload contents as entitlement authority.
Every app-facing catalog read is cursor-paginated so a public request never
collects an unbounded catalog. limit defaults to 25 and accepts 1-50.
Continue while hasMore is true by passing the opaque nextCursor back as
cursor. Without payload inclusion the payload table is never queried.
Payload-inclusive reads additionally require platform and perform at most 50
exact indexed payload lookups. If catalog churn invalidates a cursor, IAPKit returns
400 INVALID_CURSOR; restart from the first page without cursor.
Client payloads are retrieved by an app request. They do not send APNs/FCM notifications and must never contain credentials, secrets, or private server-only rules.
Known products should use the direct endpoint instead of downloading the full
catalog on every foreground event. Direct responses carry a project/key-scoped
ETag. If-None-Match can return 304 after reading only body-free metadata,
and responses use Cache-Control: private, no-cache; catalog and secret-admin
responses use private, no-store. React Native IAP and Expo IAP can persist the
payload body, version, and ETag through an AsyncStorage-compatible
clientPayloadCache and revalidate only on an explicit { refresh: true }.
A refresh that fails with a network error, 429, 5xx, or a 2xx body that
is not a payload (a captive portal page) returns the cached copy marked
stale; kitApi.localizedClientPayload returns null instead of throwing so
the app can fall back to built-in copy.
Edits go to a draft that apps never read. Publishing makes the draft the next
version; every publish, rollback, and removal is recorded in an append-only
history of the newest 50 versions per product. Rollback republishes an older
body as a new version. A draft keeps the version it was first saved against;
once a newer version goes live, publish refuses it until the draft is rebased
by saving it with expectedVersion set to the current version. Every
organization member can edit, and history records the author; API keys see a
display name, never an email. The secret-key PUT publishes in one step and is
recorded too.
Draft, publish, history, and rollback routes live under
/v1/products/client-payload/{productId}/ and in the MCP tools.
Payload copy may follow a neutral localization convention
({ schemaVersion, default, locales }) resolved on device by
resolveLocalizedPayload; IAPKit never reads the app's keys. Show prices,
currencies, and trial terms from the store through the SDK, never from a
payload or from the catalog's mirrored priceAmountMicros/currency.
A matching IAPKit catalog row must exist before a payload write. When external
automation creates a product directly in App Store Connect or Play Console,
run POST /v1/products/sync/{ios|android}?direction=pull&dryRun=false with a
secret Bearer key, poll the returned job until it succeeds, and then set the
payload. Alternatively create the IAPKit row through the
secret-authenticated POST /v1/products route. An early payload write returns
PRODUCT_NOT_FOUND.
Mobile apps use openiap-kit_pk_... publishable keys. They may verify purchases
and read public client payloads, but cannot read app-account subscriptions,
bind ownership, change catalog or payload data,
inspect project-wide analytics, or start store sync.
Administrative REST and MCP operations require an openiap-kit_sk_... secret
key stored in a trusted environment. Existing unclassified keys are treated as
publishable so previously shipped app builds fail closed without losing
verification access.
New administrative integrations send the secret only as
Authorization: Bearer openiap-kit_sk_.... Header-authenticated
GET /v1/products is a client-safe catalog read; catalog writes use
POST /v1/products, POST /v1/products/state,
DELETE /v1/products/{productId}, and /v1/products/sync/*; subscription
analytics use /v1/subscriptions/{list|metrics|revenue}. Account operations
require canonical header-authenticated routes. Secret keys in any legacy URL
are rejected with 410 SECRET_API_KEY_IN_URL and must be rotated.
After deploying the scoped-key schema, operators may persist the runtime
fallback classification. Like every migration command in this README, it
follows the deployment-selector rules in
Secret-key storage migration — read those
first and swap --prod for your deployment's selector:
npx convex run --prod migrations:run \
'{"fn":"migrations:classifyLegacyApiKeysAsPublishable"}'Secret keys created before digest-only storage also need the resumable backfill described in the same section.
The migration is idempotent. Authorization already treats an absent keyType
as publishable, so existing app verification remains available before and
during the backfill.
Calls to androidpublisher.purchases.{productsv2, subscriptionsv2} are
wrapped in an exponential-backoff retry (max 3 attempts, base 200 ms,
cap 2 s, full jitter) that fires on HTTP 5xx and Node network errors
(ECONNRESET, ETIMEDOUT, …). 4xx responses — including 404 and 410,
which are deterministic — are not retried. See
convex/purchases/retry.ts.
Horizon entitlements are verified via Meta's Graph API
(verify_entitlement) rather than a signed receipt. Enable the
feature in project settings, provide the App ID + App Secret
from the Meta Developer Dashboard; IAPKit combines them into the
OC|APP_ID|APP_SECRET app access token per request — the client
never sees the secret. Verify calls use
POST /v1/purchase/verify with
{ "store": "horizon", "userId": "...", "sku": "..." }.
See convex/purchases/horizon.ts.
Amazon requests use
{ "store": "amazon", "userId": "...", "receiptId": "...", "sandbox"?: true, "expectedProductId"?: "..." }.
Production verification requires the project's write-only RVS shared secret.
Cloud Sandbox is disabled by default because Amazon accepts any non-empty
secret there; a project operator must explicitly enable Allow Amazon App Tester
/ RVS Cloud Sandbox in project settings. Sandbox calls always use an IAPKit
placeholder and never place the production secret in the sandbox URL.
Handled Amazon responses include environment: "Sandbox" | "Production", and
purchase rows persist the same provenance. expectedProductId is a
caller-scoped guard: a mismatch returns INAUTHENTIC, while the purchase row
keeps the store-verified product and state.
Valid Amazon purchase rows become due for another RVS check 48 hours after the latest authoritative write. This is a scheduling cadence, not a completion guarantee: the bounded worker claims at most 20 due rows per five-minute tick (5,760/day, or 17,280 over Amazon's 72-hour window before failures), with a 12-minute crash-recovery lease. Deployments approaching that active-row ceiling must monitor the due backlog rather than assume every row will complete within 48 or 72 hours. The worker makes one 10-second attempt per row and spaces request starts by 200 ms (at most 5 TPS). Definitive 400/497 and 410 responses update the row; network, timeout, throttling, secret, and response-protocol failures only reschedule the claim and never overwrite a newer authoritative snapshot. The compare-and-set apply mutation also prevents a slow worker from replacing a foreground verification that completed after the claim.
Amazon's cancelDate is treated as the loss-of-access signal. renewalDate is
the next renewal date and is not inferred as expiry when it is in the past.
This reconciler updates the unified purchases table only; it does not create
Amazon subscriptions rows or claim webhook-style subscription semantics.
See convex/purchases/amazon.ts.
The Apple verify path calls AppStoreServerAPIClient.getTransactionInfo
after JWS validation, which returns the transaction's current state
including revocationDate / revocationReason. Revoked or refunded
transactions are mapped to CANCELED in the harmonized state — see
convex/purchases/shared.ts.
The monorepo-root husky hook (.husky/pre-commit) is paths-aware:
when staged changes touch packages/kit/**, packages/mcp-server/**, or
specs/commerce-protocol/** it runs the CI-equivalent install,
lint, format, test, and smoke steps of the verify job in
.github/workflows/deploy-kit.yml (its dependency audit, coverage, Docker, and
Trivy steps stay CI-only) plus the Commerce Protocol suite that ci.yml runs
in test-commerce-protocol:
bun install --frozen-lockfile # catches lockfile drift
bun run --filter @hyodotdev/openiap-kit lint # tsc + eslint
bunx prettier --check src/** server/** convex/** # prettier check
bun run --filter @hyodotdev/openiap-kit test # vitest
bun run --filter @hyodotdev/openiap-commerce-protocol test # spec suite + drift check
bun run --filter @hyodotdev/openiap-kit smoke:server # bun compile + boot probe
bun run --filter @hyodotdev/openiap-mcp-server lint # served at /mcp
bun run --filter @hyodotdev/openiap-mcp-server testThe hook is intentionally CI-equivalent — past pushes failed in CI
for issues that silently passed locally (e.g. tsc inferring
third-party callback types correctly against an incremental
node_modules but failing on CI's fresh install). Running the same
checks on commit avoids the push → red CI → fix-up → push loop.
Cost: ~30-60 s on first run after a clean checkout, ~15-20 s on warm
checkouts. Don't bypass with --no-verify — fix the underlying issue.
smoke:server compiles the Bun binary via build:all and runs
scripts/smoke-server.sh, which boots the
server on port 3100, confirms that the spawned process owns the listener, and
probes /, /v1, /api/v1, /health, static 404 behavior, and a malformed
POST /v1/purchase/verify request that must return 400 without contacting a
store. This catches startup regressions (missing env, bind conflicts, missing
dist/index.html) without mistaking an older process for the binary under
test. The same script runs in CI.
To run ad-hoc:
bun run smoke:server
# or override the port if 3100 is in use
SMOKE_PORT=3200 ./scripts/smoke-server.shflyctl auth login
cd packages/kit
# Provide CONVEX_DEPLOY_KEY, FLY_API_TOKEN and the existing stable
# IAPKIT_VERIFICATION_SOURCE_SECRET through your environment or ignored
# .env.production.local. Analytics settings are optional.
bun run deploy:prodThe script asks the Convex CLI for the canonical URL selected by the deploy
key and checks it against IAPKIT_PRODUCTION_CONVEX_URL in the gitignored
production.env before any remote setting changes. It then provisions the
service credential, deploys Convex functions and Fly, and verifies every
retained Fly machine. Create that file locally from the Convex dashboard's
production deployment:
IAPKIT_PRODUCTION_CONVEX_DEPLOYMENT=<production deployment name>
IAPKIT_PRODUCTION_CONVEX_URL=<its CONVEX_CLOUD_URL>A development deploy key cannot publish a production Fly bundle.
The production deployment uses custom domains: api.openiap.dev for the
Convex API and auth.openiap.dev for HTTP actions, with CONVEX_CLOUD_URL and
CONVEX_SITE_URL overridden to match in the Convex dashboard. The Convex CLI
therefore reports https://api.openiap.dev, and the production GitHub OAuth
App callback is https://auth.openiap.dev/api/auth/callback/github.
Development deployments keep their default convex.cloud and convex.site
URLs.
Change either override only right before a production deploy. Convex Auth
signs tokens with the new CONVEX_SITE_URL at once, but auth.config.ts
accepts the new issuer only after the next convex deploy, so sign-in fails
until that deploy finishes. Keep the old callback in the GitHub OAuth App until
sign-in works on the new domain. To roll back, first make sure the old callback
is registered in the GitHub OAuth App, then clear both overrides, set the
production target back to the default URL, and deploy again.
IAPKIT_VERIFICATION_SOURCE_SECRET is a service-to-service credential, separate
from customer API keys. Use one stable 64-character lowercase hex value in the
GitHub kit-production environment secret KIT_VERIFICATION_SOURCE_SECRET.
Provision it before merging the source guard; deployments validate its format
and checks that both deployment credentials are present before proceeding. The reviewed deployment
script passes it only via stdin to Convex's selected environment and Fly's
staged runtime secret. It never becomes a Docker build argument, SPA variable,
artifact or GITHUB_ENV entry. Manual fallback uses the same script.
This cutover intentionally fails closed. Convex deploys first, so old Fly
instances temporarily return retryable /v1 verification errors until the new
binary starts. Commerce retains its existing REST 502 / GraphQL error envelopes;
replay attempts are refunded. If Fly fails after Convex, repair forward using
the same credential and reviewed guarded code. Do not restore a pre-guard Fly
binary or remove the guard as an availability workaround. Credential rotation
also needs a coordinated deployment and can temporarily defer verification.
The final gate enumerates all retained Fly machines, including stopped ones, and requires each to serve the expected revision in production with the source credential configured. Directed health requests must return the exact machine ID; routing fallback cannot pass. It rechecks machine/configuration IDs after the probes and waits for a stable inventory. A failed or partial rollout fails the deployment; it never triggers an automatic rollback.
Deployments that issued secret API keys before digest-only storage must run the resumable backfill after deploying the dual-read lookup. Running it before that deployment would make migrated keys unreadable to the old code.
npx convex run targets the dev deployment from .env.local unless told
otherwise, and the deploy key sourced by deploy:prod does not survive that
script's shell — so every migration command in this README pins its deployment
with an explicit selector. Pick yours before running anything:
- this project's default Convex Cloud production:
--prod(used by the secret-key commands below); - a non-default Convex Cloud deployment:
--deployment <name-or-reference>; - a true self-hosted backend:
--env-file .env.self-hosted.localholdingCONVEX_SELF_HOSTED_URLandCONVEX_SELF_HOSTED_ADMIN_KEY(used by the self-hosted backfill examples further down). The CLI rejects--prodfor self-hosted deployments, and the.env.*.localname is already gitignored — never pass the admin key on the command line or commit it.
From packages/kit/, start with the read-only status query: the selector
fixes the target, and the query returns the migration's current state there.
Act on that state before anything else — unknown (never run, or an
interrupted run whose worker is gone): inspect the read-only aggregate below,
then start or resume the real run; inProgress:
do not start another run, skip to the watch command; failed or canceled:
read the reported error if any, then re-run the real command — it resumes from
the saved cursor (add "reset":true only to restart from the beginning);
success: it already completed, stop here.
The migration component's dryRun logs examples of changed documents before and
after the change. Do not use it on production secrets or customer records. Inspect
counts with an inline read-only query instead; it cannot write, and the query
below returns only counts. Require partial: false. Otherwise, finish a
paginated read-only audit before starting the migration. Then watch the real
run reach success:
npx convex run --prod --component migrations lib:getStatus \
'{"names":["migrations:hashStoredSecretApiKeys"]}'
npx convex run --prod --inline-query '
const keys = await ctx.db.query("apiKeys").take(1001);
return {
scanned: keys.length,
partial: keys.length > 1000,
secretWithRawStorage: keys.filter(k => k.keyType === "secret" && !!k.key).length,
secretNeedingDigest: keys.filter(k => k.keyType === "secret" && !!k.key && !k.keyHash).length
};'
npx convex run --prod migrations:run \
'{"fn":"migrations:hashStoredSecretApiKeys"}'
npx convex run --prod --component migrations lib:getStatus \
'{"names":["migrations:hashStoredSecretApiKeys"]}' --watchThe real run removes plaintext only after writing its digest and display preview; publishable and already-clean rows are skipped, so restarting is safe.
Self-hosted deployments that never completed the original row-wise purchase stats backfill should run it first (already-completed deployments no-op):
npx convex run --env-file .env.self-hosted.local migrations:run \
'{"fn":"migrations:backfillPurchaseStatsFromPurchases"}'Deployments with purchase history from before the Amazon and Horizon stats
buckets were added should also run the new resumable migration from
packages/kit/:
npx convex run --env-file .env.self-hosted.local migrations:run \
'{"fn":"migrations:backfillPurchaseStatsStoreBuckets"}'It processes one purchase per mutation. An atomic per-purchase sentinel makes partial resumes and resets safe without a project-wide receipt scan, while new purchases are skipped because their store buckets are already counted. The hosted IAPKit audit found no historical Amazon or Horizon purchases, so no hosted migration run was needed or performed.
For deployments that also need to clean up legacy duplicate Google orders, the
required order is: complete backfillPurchaseStatsFromPurchases, complete
backfillPurchaseOrderIds (the cleanup groups rows by the orderId column,
so rows it never populated are invisible to the cleanup), run the cleanup
until done, then run the full-project recomputeAllPurchaseStats last
whenever any non-dry cleanup page reported rowsDeleted > 0. The recompute is
optional only if cleanup is not run or deletes no rows.
The cleanup is not a migration: it is the internal mutation
purchases/cleanup:collapseDuplicatePurchasesByOrderId, and one invocation
processes a single page (default 200 rows). Feed each result's cursor into
the next call until isDone is true — first with "dryRun": true to scope
the damage, then again without it — and sum rowsDeleted across the real
pages:
npx convex run --prod migrations:run \
'{"fn":"migrations:backfillPurchaseOrderIds"}'
npx convex run --prod purchases/cleanup:collapseDuplicatePurchasesByOrderId \
'{"dryRun":true}'
# then: pass the returned cursor until isDone, repeat without dryRunThe Amazon/Horizon backfillPurchaseStatsStoreBuckets
migration is independent of the Google duplicate cleanup, so those two steps
may run in either order after the base backfill. Both must finish before any
required recompute. The recompute does not write per-purchase sentinels, so
running it first would let a later row backfill replay counts.
VITE_* values have to be passed at build time, not just runtime
secrets — Vite inlines them into the SPA bundle at bun run build
time. The deploy script sends the Convex-CLI-verified
VITE_KIT_CONVEX_URL and VITE_KIT_SENTRY_DSN as build args, and sends
VITE_KIT_MIXPANEL_TOKEN as a BuildKit secret only to avoid Docker's
TOKEN-named ARG/ENV warning. Omitting Sentry or Mixpanel is fine; the SPA skips
those integrations.
Server-side runtime secrets (read by the compiled Bun binary at boot)
are set once with flyctl secrets set:
| Secret | Purpose |
|---|---|
CONVEX_URL |
Convex HTTP client endpoint for the Hono server |
SENTRY_DSN |
Server-side Sentry (@sentry/bun) — optional |
SENTRY_SEND_DEFAULT_PII |
true / false (default false) |
RATE_LIMIT_* |
Override bounded key/IP/process rate-limit defaults |
VERIFY_MAX_IN_FLIGHT |
Override concurrent purchase-verification work |
VERIFY_MAX_IN_FLIGHT_PER_KEY |
Override one key's share of verification work |
VERIFY_MAX_IN_FLIGHT_PER_IP |
Override one source IP's share of verification work |
Outbound deliveries created before the eventType column existed are missing
from the operator eventType filter. After the deploy that adds the column, an
operator runs the resumable backfill once; CI never runs it. Use the
deployment selector and status states described under
Secret-key storage migration. Rows that already
carry a type are skipped. Use the same read-only preview policy to avoid logging
delivery documents. The aggregate distinguishes recoverable rows from orphaned
events; report orphan counts rather than editing or deleting those rows:
npx convex run --prod --component migrations lib:getStatus \
'{"names":["migrations:backfillOutboundDeliveryEventTypes"]}'
npx convex run --prod --inline-query '
const rows = await ctx.db.query("outboundDeliveries").take(1001);
let recoverable = 0;
let orphan = 0;
for (const row of rows) {
if (row.eventType !== undefined) continue;
if (await ctx.db.get(row.eventId)) recoverable++;
else orphan++;
}
return { scanned: rows.length, partial: rows.length > 1000, recoverable, orphan };'
npx convex run --prod migrations:run \
'{"fn":"migrations:backfillOutboundDeliveryEventTypes"}'
npx convex run --prod --component migrations lib:getStatus \
'{"names":["migrations:backfillOutboundDeliveryEventTypes"]}' --watchThe hosted service has no paid plans, and the schema no longer has the Stripe
billing data once stored on organizations: 19 fields, from stripeCustomerId
through the stored card details, billing email, and tax ID, plus the
stripeEvents and meteredUsageAccruals tables. Convex rejects this schema
while any row still holds them.
A deployment that predates the removal deletes the data first. Deploy commit
911b1831a, the last one with the three migrations, and run them once there;
CI never runs them. The deletion cannot be undone, so export a Convex snapshot
first, and cancel any subscription still open in Stripe, because the rows hold
the only link between an organization and its Stripe customer. Use the
deployment selector and status states described under
Secret-key storage migration. The aggregate
returns counts only, never billing values:
npx convex run --prod --component migrations lib:getStatus \
'{"names":["migrations:removeLegacyBillingFields","migrations:deleteLegacyStripeEvents","migrations:deleteLegacyMeteredUsageAccruals"]}'
npx convex run --prod --inline-query '
const orgs = await ctx.db.query("organizations").take(10001);
const legacy = (k) => k.startsWith("stripe") || k.startsWith("defaultPaymentMethod") || ["billingEmail", "taxId", "taxIdType"].includes(k);
return {
scanned: orgs.length,
partial: orgs.length > 10000,
withLegacyBilling: orgs.filter((o) => Object.keys(o).some(legacy)).length,
stripeEvents: (await ctx.db.query("stripeEvents").take(1001)).length,
meteredUsageAccruals: (await ctx.db.query("meteredUsageAccruals").take(1001)).length
};'
npx convex run --prod migrations:run \
'{"fn":"migrations:removeLegacyBillingFields"}'
npx convex run --prod migrations:run \
'{"fn":"migrations:deleteLegacyStripeEvents"}'
npx convex run --prod migrations:run \
'{"fn":"migrations:deleteLegacyMeteredUsageAccruals"}'
npx convex run --prod --component migrations lib:getStatus \
'{"names":["migrations:removeLegacyBillingFields","migrations:deleteLegacyStripeEvents","migrations:deleteLegacyMeteredUsageAccruals"]}' --watchRun the aggregate again afterwards: partial must be false and the three
other counts 0. Then continue with
Unused project bucket fields.
Admission buckets live in verificationAdmissionBuckets, and the schema no
longer has the four fields older projects held: verificationAdmissionTokens,
verificationAdmissionRefilledAt, entitlementRecheckTokens, and
entitlementRecheckRefilledAt. Convex rejects this schema while any project
still holds one.
A deployment that predates the removal deletes them first. After the legacy
billing removal above, whose data this commit's schema also rejects, deploy
commit b0e28bebd, the last one with the migration, and run it once there; CI
never runs it. It removes only those four fields and is safe to rerun:
npx convex run --prod migrations:run \
'{"fn":"migrations:removeUnusedProjectBucketFields"}'
npx convex run --prod --component migrations lib:getStatus \
'{"names":["migrations:removeUnusedProjectBucketFields"]}' --watchThen deploy the current release.
Use the locked Convex CLI version. Convex 1.46
fixed an index-change check that incorrectly required deployment:data:view
during deployment. Older CLIs can reject a scoped deploy key before pushing
functions.
.github/workflows/deploy-kit.yml
runs verify, deploys Convex, and then deploys Fly on every push to main that
matches the workflow's push.paths (kit, the MCP server, the Commerce
Protocol, the workflow itself, the security-tool installer, and the workspace
manifests). Required kit-production environment secrets (all KIT_-prefixed to
namespace them away from other monorepo secrets):
Manual workflow dispatches from non-main refs run verification only. Select
main explicitly when a production redeploy is intended.
The production Convex URL is public Vite configuration, so it is not stored in
a GitHub secret. The workflow obtains the canonical URL from the Convex CLI and
requires it to match the IAPKIT_PRODUCTION_CONVEX_URL variable of the
kit-production environment before deploying either surface. Optional VITE_KIT_* integrations are also inlined into the SPA and
must be treated as public configuration even though Actions stores them as
secrets for injection convenience.
| Secret | Real secret? | Purpose |
|---|---|---|
KIT_FLY_API_TOKEN |
✅ yes | flyctl deploy auth — keep private |
KIT_CONVEX_DEPLOY_KEY |
✅ yes | Convex function deploy |
KIT_VERIFICATION_SOURCE_SECRET |
✅ yes | Stable private verification source shared by Convex and Fly runtime |
VITE_KIT_SENTRY_DSN |
Build arg for SPA (optional — SPA skips init if absent) | |
VITE_KIT_MIXPANEL_TOKEN |
BuildKit secret for SPA (optional — analytics opt-in) |
Use a production-scoped Convex deploy key with deployment:deploy and
deployment:env:write. The deployment provisions the shared verification
credential before pushing functions, so a code-deploy-only key cannot complete
it. See Convex role actions
for these permissions.
The workflow checks deployment-credential presence, source-credential format and the canonical Convex target before changing either surface. Missing credentials or a Convex URL mismatch fail before function deployment. Later provider failures can leave a partial rollout, which requires repair forward as described in the cutover procedure. Set the Convex key with:
# Value from Convex dashboard → Settings → Deploy Keys
gh secret set KIT_CONVEX_DEPLOY_KEY --env kit-production --repo hyodotdev/openiapAuth providers (GitHub OAuth, Resend) and Apple root certs live in the
Convex dashboard → Settings → Environment Variables, not in Fly
secrets. See .env.example for the full list.
IAPKit is one of several ways to use the OpenIAP specification:
| Hosted (kit.openiap.dev) | Self-hosted | |
|---|---|---|
| Client libraries (free, MIT) | expo-iap / react-native-iap / flutter_inapp_purchase / kmp-iap / godot-iap | same |
| Native modules (free, MIT) | openiap-apple, openiap-google | same |
| Receipt validation backend | IAPKit — free on shared capacity under fair-use safeguards | Deploy this repo yourself (MIT) |
The specification (openiap.dev) is 100% open source. IAPKit's hosted service is free for every developer under fair-use safeguards; infrastructure is sustained through GitHub Sponsors, OpenCollective, and other community support listed at openiap.dev/sponsors. You can always run this repo on your own infrastructure and pay no IAPKit license fee.
Thank you to Meta, Amazon Developer, and Codemagic for supporting OpenIAP. View sponsorship options.
Claude for Open Source provides the Claude Ultra plan for the maintainer for 6 months.
Codemagic provides infrastructure support for OpenIAP.
We also recognize sponsors and backers through OpenCollective. The original react-native-iap collective now supports the broader OpenIAP ecosystem and is managed separately from the main sponsor program.
Become a sponsor | Become a backer
Supported the project before the OpenIAP sponsor program: Nami for 30 months and Courier for 1 month.
MIT © OpenIAP contributors. See the monorepo root LICENSE.

