The SDK provides in-app payment bridging capabilities. H5 calls it via SuperSDK.pay.*.
🔴 F038 Disruptive Change (Second after F036): pay.purchase returns a PayResult3State three-state object instead of the PurchaseResult receipt object from F036. Unified to the provider.createOrder → provider.pay → three-state callback contract; receipts no longer pass through H5 business JS (directly sent from SDK Native PayBridge to the backend receipt endpoint). Live H5 must be upgraded accordingly (no compatibility period, no alias). See the F038 Migration Guide below.
🔴 SDK is a pass-through (v0.3 design principle): provider = two methods{ createOrder(payParams)→json, pay(json)→three-state result }. The json produced by createOrder is completely opaque to the SDK — the SDK does not parse any of its fields (productId / accountId / profileId / orderToken are untouched), but instead routes based on provider and passes json transparently to pay. Field semantics are self-consistently guaranteed by the provider implementation (createOrder output ↔ pay consumption).
Business Prerequisites (Must Read):
This capability assumes that the business party already has a server-side IAP architecture:
Order creation / receipt verification (verify) / acknowledge / consume / order query: all implemented by the business backend (calling Google Play Developer API + App Store Server API). The SDK does not provide these.
The SDK is responsible only for: ① routing by provider name and transparently passing the opaque JSON generated by createOrder to pay; ② built-in native deduction via google_play or the host app’s Apple provider; ③ direct delivery of the receipt from the Native PayBridge to the backend receipt endpoint (the receipt never leaves Native); ④ three-state callback whitelist; ⑤ detection capabilities; ⑥ client-side restore (optional).
⚠️ Apple Guideline 3.1.1 Compliance Reminder: Subscription / Non-Consumable In-App Purchases must provide a “Restore Purchases” button. The SDK supports pay.restorePurchases (returns NOT_SUPPORTED if the provider does not implement it; the business layer should fallback to the backend /api/pay/my-purchases). Failure to implement this will result in rejection during review.
Query the subscription offers that the current account can purchase right now on Google Play. Data is sourced exclusively from SubscriptionOfferDetails returned by the client-side queryProductDetailsAsync(ProductType.SUBS) call; the SDK does not query the full catalog in Play Console, does not read Settings, does not merge business copy, and does not handle UI sorting.
// The offerId for the standard base plan is explicitly set to null.
// offerToken is never exposed to H5.
console.log(offers[0]);
// {
// productId: 'matrixvplan01',
// basePlanId: 'weekly01',
// offerId: null,
// offerTags: [],
// title: 'Go VPN',
// description: '...',
// pricingPhases: [{
// formattedPrice: 'US$2.69',
// currencyCode: 'USD',
// priceAmountMicros: 2690000,
// billingPeriod: 'P1W',
// billingCycleCount: 0,
// recurrenceMode: 1
// }]
// }
Parameter
Type
Required
Description
options.provider
string
No
Single provider can be omitted; Google’s built-in name is google_play.
options.productIds
string[]
Yes
Subscribe to a non-empty product ID list
Returns Promise<SubscriptionOffer[]>. Multiple current eligible offers may be returned for the same base plan. Promotions not returned by Play for the current account will not be concatenated by the SDK. Supported on Android; iOS explicitly returns NOT_SUPPORTED.
Query errors will reject: PRODUCT_NOT_FOUND (no products returned in the request), BILLING_UNAVAILABLE (Billing service unavailable), QUERY_FAILED (other query failures), SDK_TOO_OLD (Native does not yet support this JSB), or NOT_IN_APP.
Single payment entry. Internally aggregates the provider.createOrder → provider.pay sequence (the public interface remains this single entry only; no new createAndPay is added).
Execute orchestration (v0.3 pass-throughline):
Validate payConfig (the SDK checks that payConfig/payParams are objects and leaves business fields untouched)
→ json = provider.createOrder(payParams) [implemented by the provider; defaults to passing payParams through]
provider: 'google_play', // 🔴 Built-in Google provider name (not 'google') · Refer to the result returned by getProviders() · A single provider can be omitted
payParams: { // createOrder input parameters · consumed by your createOrder · not parsed by the SDK
productId: 'sku_premium',
userId: currentUser.id
}
});
// result is a three-state object PayResult3State (not a receipt).
switch (result.status) {
case'finished': // Platform has accepted ≠ Payment successful · Check order status via business system to determine the truth · Do not deliver in the client app
pay: async (json) => { // Required (inline) · Self-checkout + polling · Returns three states
// `json` is the object produced by your `createOrder` call (the `orderToken` is generated by you, held locally, and does not require the SDK to return it).
Payment method name (auto-selected for single Provider, required for multiple Providers) · Subject to getProviders()
payParams
object
Yes
createOrder input parameters · Any object (The SDK only validates that it is an object; fields are consumed by your createOrder implementation; the SDK does not parse them)
createOrder
function
No
inline mode · (payParams) => Promise<json> · 🔴 Only compatible with inline pay; passing createOrder without pay constitutes misuse → reject with INVALID_PARAMS. If you need to override createOrder while pay uses the built-in native implementation, please register via registerProvider (not inline). By default, json = payParams (identity passed through).
pay
function
No
inline mode · (json) => Promise<PayResult3State> · if present, use inline JS provider; otherwise, use built-in native IAP
🔴 Remove onOrderCreated / checkout / queryStatus / pollInterval / maxPolls / onProgress from v0.2: In the v0.3 pass-through, these are implemented by the provider itself (third parties handle checkout and polling within their own pay; the orderToken is generated by the business’s createOrder, held locally, and no SDK callback is needed to return it to the business).
Input Contract (Cannot Start → Reject):
Only “Cannot Start” rejects with INVALID_PARAMS, NOT_IN_APP, SDK_TOO_OLD, PURCHASE_IN_PROGRESS, PROVIDER_REQUIRED, or NO_PROVIDER. All terminal states of an already initiated flow (create/pay failure, cancellation, or completion) must resolve to three states.
No input provided.
Behavior
pay.purchase(undefined/null/'x')
reject INVALID_PARAMS · err.detail: “payConfig must be object”
pay.purchase({}) or payParams is not an object
reject INVALID_PARAMS · err.detail: “payParams must be object”
Pass createOrder but do not pass pay (inline createOrder has no corresponding pay).
reject INVALID_PARAMS · err.detail: “inline createOrder requires an inline pay function; register a createOrder-only override via registerProvider instead” (no longer silently discard createOrder)
Native path but not in the client environment
reject NOT_IN_APP
Native path but the old SDK lacks appbridge.nativePay.
reject SDK_TOO_OLD (explicit upgrade, no silent fallback for old purchase)
Multiple Providers without passing provider
reject PROVIDER_REQUIRED
No provider
reject NO_PROVIDER
An inline request is initiated while another is already in progress.
reject PURCHASE_IN_PROGRESS
🔴 v0.3 No longer validates productId: The SDK does not touch business fields. Missing productId or type errors are handled by the provider itself (if the built-in google_play pay cannot read productId → return phase:'pay' error).
Return value: Promise<PayResult3State> — Unified three-state object (IAP and third-party paths return consistent structures, constructed by the Native PayBridge whitelist):
Field
Type
Required
Description
status
enum
Yes
finished / cancelled / error
phase
enum
when an error occurs
create (failure in the createOrder phase · captured within the JSSDK · pay not invoked) / pay (platform billing error in the pay phase)
provider returns the association key from its internal pay result (unique business key · for H5 order query)
🔴 Closed Whitelist (Receipts Never Reach Native): The object sent to H5 contains only the fields in the table above, explicitly constructed by the Native PayBridge — never pass through the provider’s internal results as-is. Receipts such as purchaseToken, signature, and originalJsonnever reach the H5 (the PayBridge submits the receipt to the endpoint).
🔴 finished ≠ Payment Success: Semantics indicate “Client process completed normally · Check order status”. Google PENDING (Cash/Parent Ask-to-Buy/Slow Payment) and iOS equivalent pending state mapping to finished; Google ITEM_ALREADY_OWNED also maps to finished (Check order status · Backend reconciliation and re-issuance) rather than error. H5 always determines success/pending/failure based on business order check results · No delivery/unlocking occurs on the client side (see below Business Order Check Four States ]).
Detect the list of payment methods supported by the host app (merge JS-registered + Native-registered).
constproviders=await SuperSDK.pay.getProviders();
// For example: ['google_play', 'alipay'] ← The actual value is subject to the return of this method.
🔴 The provider name is determined by the return value of pay.getProviders() · Do not hardcode it. The built-in Google provider’s registration name is 'google_play' (hardcoded in GooglePayProvider.getProviderName() · not'google'). iOS has no built-in payment provider; the provider name for Apple is customized when the host app implements ApplePayProvider. It is recommended to call getProviders() first to obtain the return value and then pass it to purchase / registerProvider, avoiding PROVIDER_NOT_FOUND errors caused by incorrect hardcoded names. The example below uses the literal 'google_play' for clarity; production code should use the return value from getProviders().
Register a payment Provider. Starting from v0.3, the provider consists of two methods{ createOrder?, pay? } (at least one is required). Routing is determined by the existence of pay:
Form A · Third-party Payment (Alipay / WeChat / Stripe, etc., non-IAP): Has pay (optionally with createOrder). pay handles checkout + polling · Returns three states.
SuperSDK.pay.registerProvider('alipay', {
createOrder: async (payParams) => { // Optional · Output JSON opaque to the SDK (your pay consumption)
Form B · IAP createOrder override (Built-in Google = 'google_play' / Host Apple provider name see getProviders()): Only createOrder (no pay). pay uses the SDK’s built-in native deduction (appbridge.nativePay). Used to let IAP’s createOrder produce the JSON you agreed upon (for the built-in native pay to read).
🔴 The registration name must exactly match the built-in/host app provider name (the built-in Google provider is 'google_play', not'google'). Otherwise, purchase will return PROVIDER_NOT_FOUND. It is recommended to use the return value of (await SuperSDK.pay.getProviders()) as the name instead of hardcoding it.
// The business fetches the order creation endpoint to create an order · Returns the pay input JSON for the built-in google_play provider (see "google provider input keys" below).
// no pay → SDK internally uses Google Play native pay to consume the JSON above (SDK does not parse; internal provider.pay reads it directly).
});
🔴 orderToken must be a UUID (same value as profileId / iOS appAccountToken): If generated purely on the frontend, use crypto.randomUUID(); if issued by the backend, the backend order creation endpoint must return a UUID. If not a UUID, the built-in google_play / iOS host provider returns { phase:'pay', code:'INVALID_ORDER_TOKEN' }.
// Example of frontend generating orderToken (when no backend order creation is involved)
createOrder: async (payParams) => ({
productId: payParams.productId,
profileId: crypto.randomUUID() // 🔴 UUID · Universal for both Android (obfuscatedProfileId) and iOS (appAccountToken)
})
provider field:
Field
Form
Description
createOrder
A Optional / B Required
(payParams) => Promise<json> · Returns a json object opaque to the SDK · Default = identity(json=payParams)
pay
A Required / B None
(json) => Promise<PayResult3State> · If it exists = third-party JS pay; if it does not exist = built-in native IAP pay
🔴 Provider Contract (v0.3 Dummy Pipeline): pay.purchase internally executes json = createOrder(payParams) → pay(json). The SDK does not parse any fields in the json (productId, accountId, profileId, orderToken are all untouched). Consistency is guaranteed by the provider implementation (the createOrder output ↔ pay consumption).
Google Provider Input Key (Documented · Non-SDK Transport Layer): Built-in google_play pay self-read JSON: productId (required), productType (optional, default 'inapp' or 'subs'), basePlanId (required for subs), offerId (optional for subs), accountId (optional → obfuscatedAccountId), profileId (optional → obfuscatedProfileId). Subscriptions match basePlanId + offerId precisely from the user-available SubscriptionOfferDetails returned by Google; if offerId is not provided, it matches the offer of the base plan itself, without silently falling back to other offers. No match returns OFFER_UNAVAILABLE. This is the Google Provider’s input contract (anyone overriding createOrder must generate this accordingly) · not the SDK transport layer contract. Host app Apple provider customizes its pay input key.
Pure IAP without overriding createOrder: The provider has neither registered createOrder nor payConfig, and lacks createOrder → The SDK uses identity(json=payParams), meaning payParams is directly used as input for the built-in pay (note that payParams must include the Google provider input key).
🔵 F038 No Change to Contract: restorePurchases still returns F036’s PurchaseResult[] (client-side StoreKit/BillingClient receipt restoration). This is a different path from purchase’s “three-state + direct receipt delivery” (restore is client-side receipt restoration, bypassing direct receipt delivery). Unification is reserved for a future Feature (known inconsistency).
Google Subscription Constraints: The restore method of the built-in google_play provider queries only ProductType.SUBS and does not return one-time products.
try {
// The provider name is determined by the return value of getProviders(): the built-in Google provider is 'google_play'; the iOS Apple provider name is registered by the host app.
constpurchases=await SuperSDK.pay.restorePurchases({ provider: 'apple'/* Host app registration name · subject to getProviders() */ });
Optional with a single Provider; required with multiple Providers.
Return value: Promise<Object[]> — an array of purchase records, where each element has the same structure as the Native IAP return object of pay.purchase (containing orderId / productId / purchaseToken / purchaseTime / purchaseState / isAcknowledged / signature / originalJson / provider / raw). Returns an empty array [] if no recoverable purchases exist.
error three-state code(result.status==='error' · with phase):
code
phase
Meaning
Suggested handling
CREATE_FAILED
create
createOrder reject/throw (caught within JSSDK · pay not called)
Retry Prompt (Not Launched · Safe to Retry)
INVALID_JSON
create
The JSON output from createOrder cannot be JSON serialized (IAP path).
Check the output object of createOrder
INVALID_PARAMS
pay
Built-in google_play missing productId / subscription missing basePlanId / productType is not inapp/subs
Fix Google provider input key
INVALID_ORDER_TOKEN
pay
provider input contract validation: orderToken(profileId / appAccountToken) non-UUID format (both built-in google_play and iOS host provider will return this code)
createOrder generates the orderToken using crypto.randomUUID() (the backend order creation endpoint does the same).
PRODUCT_NOT_FOUND
pay
Re-check after purchase failed to find the selected subscription item.
Refresh eligible offer list
OFFER_UNAVAILABLE
pay
No matching basePlanId + offerId found in the user’s available subscription offers returned by google_play.
Refresh product configuration, verify user eligibility, and check Play Console base plan/offer.
BILLING_UNAVAILABLE
pay
Google Billing service is unavailable during subscription query or purchase.
🔴 Note: cancelled is not in the error column (it is a separate status==='cancelled'); PENDING / ITEM_ALREADY_OWNED are also not errors (classified under finished · check order · see Architecture section below). The specific code for phase:'pay' is returned by provider.pay (IAP = SDK built-in mapping; third-party = business-defined), and the SDK does not converge the enumeration (pass-through).
finished ≠ payment success. The SDK does not provide an order query API (decoupled from payment channels). The H5 uses orderToken to poll the business’s own order query interface to determine the actual result. The business order query interface is agreed to return four states:
status
Meaning
H5 Handling
success
Backend signature verified + delivery completed
Unlock / Prompt Success
processing
Processing (SDK receipt not received / RTDN not received / retrying)
const { status } =awaitfetch('/api/pay/order-status?orderToken='+ orderToken).then(r=> r.json());
if (status ==='success'|| status ==='failed') return status;
awaitnewPromise(r=>setTimeout(r, interval));
}
return'unknown'; // Upper limit not yet determined · Rely on backend RTDN/ASSN for fallback
}
The receipt has been directly forwarded by the SDK Native (PayBridge) to the backend receipt endpoint, with independent signature verification and fulfillment performed by the backend. Even if the frontend process is killed, RTDN/ASSN fallback mechanisms ensure the order ultimately reaches a success state (see Receipt Forwarding Contract PayBridge Gatekeeper).
// 🔴 Receipts bypass H5:purchaseToken/signature and are sent directly from the SDK Native (PayBridge) to the backend receipt endpoint. H5 no longer POSTs to /verify.
🔴 Breaking Change (Second after F036): pay.purchase now returns a PayResult3State three-state object instead of a PurchaseResultreceipt; the receipt is no longer passed via H5. The JSB signature changes from positional parameters to the generic nativePay(provider, jsonString, callbackId). Host app H5 must be upgraded in tandem (no alias, no compatibility period). restorePurchases remains unchanged (still F036 PurchaseResult[]).
F036 writing
F038 Post-behavior
Migration Path
const r = await pay.purchase(...) r.purchaseToken / r.orderId / r.signature
r no longer contains receipt (three-state object)
Remove the “read receipt + POST /verify” logic; instead, read r.status (finished/cancelled/error).
if (r.purchaseState===0) ... (receipt verification success)
r.purchaseState does not exist
Change to r.status==='finished' → Use orderToken to query the order to determine the truth.
try/catch catch CANCELLED
Cancel no longer reject
Switch to the r.status==='cancelled' branch
try/catch to handle payment failure
Payment phase failure no longer rejects (falls into the three-state error).
Change to r.status==='error' + r.phase/r.code; reject only includes “Cannot Start” (INVALID_PARAMS/NOT_IN_APP/SDK_TOO_OLD/PURCHASE_IN_PROGRESS/PROVIDER_REQUIRED/NO_PROVIDER).
H5 POST /api/pay/verify (receipt)
Receipts do not go through H5.
Delete; The receipt is directly sent by the SDK Native (PayBridge) to the host app’s configured receipt endpoint. H5 is changed to polling the business order inquiry interface.
(None) Order association is not required.
—
Register createOrder override · Output Google provider input key (orderToken → profileId); orderToken is generated by your own createOrder · Held locally · No SDK callback required
🔴 No compatibility baggage: F038 directly changes the three-state return. No PurchaseResult legacy return alias is provided, and no compatibility period is retained. CHANGELOG marks this as a BREAKING CHANGE.