Skip to content

Recommended IAP architecture

🔴 Business Side Must-Read for In-App Purchase Design · This chapter presents the recommended architecture for SuperSDK + business backend (F038 v0.3 pass-through) · Evolving IAP from ‘client-side dominant (fragile)’ to ‘server-side dominant (robust)’.

v0.3 Core (Pass-through): provider = two methods { createOrder(payParams)→json, pay(json)→three-state result }. createOrder outputs json which is completely opaque to the SDK transport layer — the SDK routes solely by provider name and passes the JSON transparently to pay, parsing no fields. IAP pay is natively deducted by the SDK’s built-in google_play (host Apple provider self-implemented) via native read json; third-party business logic implements both methods independently. Receipts are guarded by Native PayBridge: submitting receipts + whitelisting stripping three states to H5 (receipts never leave Native).

1. Architecture Comparison: client-driven vs server-driven

Section titled “1. Architecture Comparison: client-driven vs server-driven”

❌ Client-side driven (Fragile · Not recommended for production)

H5 → SDK → payment platform → SDK → H5 receives the purchase credential
↓
H5 POST /verify to the host backend (only notification path)
↓
Host backend verifies, grants entitlement, and acknowledges

Critical Weakness: If the client crashes, experiences network failure, gets killed, or intentionally fails to report after user payment, the business backend will never know what the user purchased, resulting in the user being charged without receiving goods. Additionally, the receipt, handled via H5 business JS, can be tampered with or redirected by malicious H5 code.

✅ Server-Side Driven (Robust · v0.3 Pass-through)

H5 → SDK.pay.purchase({provider, payParams})
└─ json = provider.createOrder(payParams) [host implementation; may create an order on the backend; retains orderToken]
└─ provider.pay(json) [IAP: native provider reads json; third party: host JavaScript]
↓
provider.pay → PayBridge(internal NativePayResult includes credential)
↓
├──→ PayBridge constructs an allowlisted three-state result → H5(finished · no credential)
├──→ PayBridge posts the credential to receiptUrl (idempotent with retries, bypasses H5)
│ └──→ backend independently verifies the signature and grants entitlement idempotently
└──→ platform RTDN / ASSN notifications (authoritative fallback)
↓
H5 polls the host order endpoint with orderToken(success/processing/failed/unknown)

Server = Source of Truth · Receipt PayBridge Direct Delivery + Platform Push · Client-side failures do not affect fulfillment · Receipt never leaves Native.

sequenceDiagram
    participant H5
    participant JS as supersdk.js(pass-through)
    participant Bridge as PayBridge(native validation)
    participant Prov as GooglePayProvider(built-in pay)
    participant BE as host backend
    participant Google as Google Play
    H5->>JS: pay.purchase({provider:'google_play', payParams})
    JS->>JS: json = provider.createOrder(payParams)  [override or identity; host may create the order]
    Note over JS: SDK passes json through without parsing
    JS->>Bridge: appbridge.nativePay('google_play', JSON.stringify(json), cb)
    Bridge->>Prov: payService.pay('google_play', json, cb)
    Prov->>Prov: Reads json.productId (required), accountId and profileId
    Prov->>Google: launchBillingFlow<br/>setObfuscatedAccountId(accountId)<br/>setObfuscatedProfileId(profileId)
    Google-->>Prov: PurchaseResult
    Prov-->>Bridge: NativePayResult { status, orderToken?, credential{purchaseToken,...} }
    alt finished + credential
      Bridge->>BE: POST receiptUrl(credential · idempotency key orderToken||purchaseToken)  [native validation]
      Bridge-->>H5: allowlisted { status:'finished', orderToken? }(no credential)
    else cancelled / error
      Bridge-->>H5: allowlisted three-state response { status, phase?, code? }
    end
    Google->>BE: RTDN(authoritative fallback)
    H5->>BE: Poll order status with orderToken
    BE-->>H5: { status: success/processing/failed/unknown }

iOS Isomorphism: iOS lacks a built-in ApplePayProvider; the host app provider reads the JSON to implement pay, returning the credential to PayBridge together. The receipt is submitted by PayBridge (not by the host app directly). Both platforms share the same receipt path and are testable.

3. Provider two-method contract (v0.3 pass-through core)

Section titled “3. Provider two-method contract (v0.3 pass-through core)”
  • pay.purchase internal: json = provider.createOrder(payParams) → provider.pay(json) → three states (public interface still has only one entry point: pay.purchase).
  • createOrder: Provider implementation · Produces a JSON opaque to the SDK (the business can call the backend to create an order here · the business generates the orderToken · hold it immediately · no SDK callback required to return to the business). Default = identity (json = payParams).
  • pay: consume JSON · return tri-state (internal includes credential for PayBridge). IAP = SDK built-in native; third-party = business JS self-written (self-checkout + polling).
  • 🔴 SDK does not read any JSON fields · Does not touch productId, accountId, profileId, or orderToken · Only JSON.stringify is used to pass through (JSB universal pipeline nativePay(provider, jsonString, callbackId)).

JSB Universal Pipeline: appbridge.nativePay(provider, jsonString, callbackId) (replaces legacy positional parameters purchaseV2/purchaseV3). A single method supports all built-in IAP providers, with parameters passed as an opaque JSON string.

4. Google Provider Input Key (Documented input for Google Play Provider · Non-SDK transport layer)

Section titled “4. Google Provider Input Key (Documented input for Google Play Provider · Non-SDK transport layer)”

The built-in google_play provider’s pay (SDK native implementation) reads the following keys from the JSON — this is the input contract for the Google provider (anyone overriding createOrder must produce output conforming to this), not the SDK transport layer contract:

JSON keyRequiredBuilt-in pay mappingBackend retrieval
productIdYeslaunchBillingFlow product (missing → phase:'pay' error)-
productTypeNo'inapp' (default) → ProductType.INAPP; 'subs' → ProductType.SUBS-
basePlanIdWhen productType='subs', it isMatch the base plan in the user’s available SubscriptionOfferDetails.base plan of subscriptionsv2
offerIdNoMatch the offer precisely when passing the value; omit it to match the base-plan offer where offerId == null.offer for subscriptionsv2
accountIdNosetObfuscatedAccountId(user identifier)Signature verification API obfuscatedExternalAccountId
profileIdNo · If yes, UUID is required.setObfuscatedProfileId(Order Token)Signature verification API obfuscatedExternalProfileId
  • Field reading and slot mapping are internal responsibilities of provider.pay (within the Native provider, not the SDK transport layer). If the key is empty, no corresponding slot is set.
  • Mandatory Re-verification Before Subscription Purchase: Do not cache or reuse ProductDetails or offerToken; re-query for each purchase and perform an exact match using productId + basePlanId + nullable offerId. If no match is found, return OFFER_UNAVAILABLE without launching the Billing UI; only after a match is found should the latest token be written to BillingFlowParams.ProductDetailsParams.
  • 🔴 orderToken(profileId) must be in UUID format — a cross-platform hard constraint: iOS appAccountToken is mandated by StoreKit to be UUID; although Android obfuscatedProfileId accepts a broader character set (^[A-Za-z0-9_-]{1,64}$), it must also be UUID to ensure cross-platform consistency and avoid cross-platform pitfalls where “Android works but iOS crashes”.
  • 🔴 The built-in google_play provider validates: if the passed profileId (orderToken) is not a UUID → this provider directly returns { status:'error', phase:'pay', code:'INVALID_ORDER_TOKEN' } (the provider validates its own input contract · it does not silently allow it, to prevent Android from succeeding while iOS crashes at StoreKit).
  • iOS Host app provider customizes its pay input key; typically mapping the order ID key to Product.PurchaseOption.appAccountToken = UUID(orderToken) (StoreKit single slot · mandatory UUID · non-UUID will be rejected by StoreKit) · host provider must self-validate and return INVALID_ORDER_TOKEN (phase:pay) · user identity is verified by the backend via order reverse lookup.
  • 🔴 When the business createOrder generates an orderToken, you must use UUID: Recommended crypto.randomUUID() (the backend order creation endpoint signing is the same · see example below).

5. Pay three-state semantics (whitelist · callback to H5)

Section titled “5. Pay three-state semantics (whitelist · callback to H5)”
statusMeaningDoes it contain a receipt?H5 Handling
finishedPlatform has accepted · Process ended normally ≠ Payment successful❌ Not includedUse orderToken to query the business order for the definitive truth; Google PENDING / ITEM_ALREADY_OWNED also fall into this state.
cancelledUser cancelled❌Silent
errorFailed · with phase(create/pay)+ code❌create=createOrder failed, did not launch; can retry; pay=platform billing error (IAP=SDK mapping / third-party=custom business logic)

🔴 Closed Whitelist: The object sent to the H5 contains only { status, phase?, code?, message?, orderToken? }, explicitly constructed by the Native PayBridge (without directly forwarding internal provider results). Credentials (purchaseToken/signature/originalJson) never reach the H5. orderToken is the sole business key returned to the H5 (for order lookup).

6. Direct receipt delivery through PayBridge

Section titled “6. Direct receipt delivery through PayBridge”

🔴 The credential flow never passes through H5 business JS and never exits via Native business callbacks: provider.pay returns a NativePayResult containing the credential to PayBridge. When finished is true and a credential exists, PayBridge POSTs the credential to the receipt endpoint (receiptUrl) configured during host app initialization. Subsequently, a three-state whitelist is constructed and sent to H5. H5 cannot set receiptUrl at runtime to prevent malicious H5 from redirecting the credential.

Receipt Endpoint Configuration (host-only · H5 cannot be set):

  • Android: SDKPayService.Builder.setReceiptEndpoint(absoluteUrl) (configured when the host builds PayService)
  • iOS: Initialize SDKPayService with the receiptEndpoint parameter.

ReceiptPayload schema (constructed by PayBridge):

{ "purchaseToken": "...", "originalJson": "...", "signature": "...",
"productId": "...", "provider": "google_play", "platform": "android", "orderToken": "..." }

Delivery Contract:

  • Idempotency key = orderToken if present; otherwise fallback to purchaseToken (globally unique). Endpoint must be idempotent.
  • timeout defaults to 10s · retry uses exponential backoff (default ≤3 times)
  • With identity headers X-Aid / X-Device-Id / X-SDK-Version
  • HTTP 2xx indicates acceptance. Delivery failure does not block the three-state callback (SLogger.e logs the error, with fallback handled by RTDN/order inquiry).
  • The backend must independently re-verify signatures with Google/Apple (do not trust the SDK claim).
  • RTDN / ASSN as authoritative secondary confirmation and fallback: PayBridge receipt delivery failure or delay triggers self-healing; backend signature verification API retrieves obfuscatedExternalAccountId/ProfileId (Android) / appAccountToken (iOS).

7. 🔴 Host App Provider Checklist (iOS · Required Reading)

Section titled “7. 🔴 Host App Provider Checklist (iOS · Required Reading)”

The SDK does not include ApplePayProvider (following the F035/F036 boundary). iOS payments are implemented by the host app. In v0.3, the host app’s Apple PayProvider must:

  • Implement providerName (custom name, e.g., "app_store"). H5 must use this name returned by getProviders() to call purchase/registerProvider (the SDK has no built-in Apple provider name).
  • Implement pay(json): self-read custom JSON keys (SDK does not modify fields) · Launch StoreKit
  • 🔴 Map the order identifier key to Product.PurchaseOption.appAccountToken = UUID(orderToken) (StoreKit single slot · Mandatory UUID)
  • 🔴 Self-verify that orderToken is a UUID — Non-UUID values will be rejected by StoreKit (UUID(uuidString:) returns nil / throws error). The host provider must validate first and return { phase:'pay', code:'INVALID_ORDER_TOKEN' } (same code as built-in google_play · cross-platform consistency · prevent crash in StoreKit).
  • User ID iOS No Independent Slot · Not Mapped (User identity is looked up via orderToken on the backend)
  • 🔴 Return the credential (e.g., purchaseToken, JWS) to PayBridge (do not self-inject receipt; PayBridge guards and delivers) · success but credential is nil → return as error
  • Log exceptions using equivalent logs (aligned with Android SLogger.e); do not swallow exceptions.

Reference: Android built-in Google provider name = "google_play" (GooglePayProvider.getProviderName()); iOS host app Apple provider name is custom-defined. Both H5 sides rely on getProviders() for the result.

8. Tasks for the backend system (checklist)

Section titled “8. Tasks for the backend system (checklist)”

The business backend must implement the following endpoints (this feature defines only the contract, not the backend implementation):

EndpointWho callsInput parametersOutput parameters
Create single endpointprovider.createOrder(business JS fetch)payParams{ orderToken(🔴 UUID required on both platforms), ...host-defined JSON fields }
Receipt endpoint (receiptUrl)PayBridge(host app initialization configuration)ReceiptPayloadHTTP 2xx = Accepted
Query order endpointH5 (orderToken polling)orderToken{ status: success/processing/failed/unknown }

Android Google Play:

  • 🔴 Create order endpoint issues UUID orderToken (non-UUID → built-in google_play provider returns INVALID_ORDER_TOKEN · and iOS rejects the same orderToken via StoreKit)
  • Integrate the PayBridge receipt endpoint · Use a Service Account to call androidpublisher.purchases.{products|subscriptions}.get for independent signature verification.
  • Read obfuscatedExternalAccountId (corresponding to accountId), obfuscatedExternalProfileId (corresponding to orderToken), and orderId from the response.
  • Play Console configure RTDN topic (Cloud Pub/Sub) fallback · idempotent fulfillment + acknowledge (3-day ack window)

iOS Apple:

  • Create single order endpoint issues UUID orderToken
  • Integrate the PayBridge receipt endpoint · Independently verify signatures by calling /inApps/v1/transactions/{transactionId} via the App Store Server API.
  • Read appAccountToken (corresponding to orderToken) and transactionId from the response. Use orderToken to reverse-lookup the user’s order.
  • Configure ASSN V2 endpoint fallback · idempotent fulfillment · notify client Transaction.finish()

📚 Official Documentation: Google Play RTDN · Google Play Developer API · App Store Server Notifications V2 · App Store Server API

Q: Why does the SDK not parse parameters? A: v0.3 Pass-through Principle. Hard-coding the semantics of productId/accountId/profileId/orderToken into the SDK’s transport layer makes the SDK increasingly complex and difficult to adapt to new payment methods. Instead, the provider implementation (createOrder production ↔ pay consumption) achieves self-consistency, while the SDK only handles routing and JSON passthrough.

Q: How does orderToken return to H5 to query the order? A: It is generated by your createOrder · held immediately (no SDK callback required to return it). provider.pay will also inject it into NativePayResult, and PayBridge transparently passes it to the three-state orderToken field via the whitelist.

Q: How to pass the business accountId in iOS? A: StoreKit’s appAccountToken carries the orderToken (order dimension). Starting from Native SDK 1.0.0.67-SNAPSHOT, the host provider can optionally fill in accountId in PayCredential, which PayBridge then includes in the business receipt POST body; the built-in Android google_play provider carries this field back from the purchase parameters. This field does not alter StoreKit parameters or the project identity header X-Aid; if not filled, the backend can still reverse-query the user identity via orderToken.

Q: Must orderToken be a UUID? (Cross-platform minefield) A: 🔴 Yes. iOS appAccountToken is forced to be a UUID by StoreKit. Although Android obfuscatedProfileId accepts a broader character set, using a non-UUID value (e.g., order_123) creates a cross-platform pitfall where the flow works on Android but crashes on iOS within StoreKit. Therefore, a unified UUID requirement is enforced: both the built-in google_play and the iOS host provider will validate this; if the check fails, the response is { phase:'pay', code:'INVALID_ORDER_TOKEN' }. The business createOrder function must generate orderToken using crypto.randomUUID() (the backend order creation endpoint also issues UUIDs).

Q: Why check the order status if it’s already finished? A: finished only indicates the end of the client-side flow (including Google PENDING / ITEM_ALREADY_OWNED). The truth lies with the backend (signature verification + RTDN/ASSN). Client-side fulfillment can be forged or replayed.

Q: Does a failed POST of the receipt lead to order loss? A: No. A failed delivery does not block the three states; backend RTDN/ASSN fallbacks will eventually succeed; H5 order check transitions from processing to success.