# SuperSDK User Guide SuperSDK is a JavaScript SDK designed for front-end business development, providing the capability to interact with native apps. ## Quick start ### Integrate SDK ```html ``` After integration, the SDK will automatically mount to `window.SuperSDK`. ### Environment Detection ```javascript if (SuperSDK.isInApp()) { // Run within the app } else { // Run in the browser } ``` ## Browser fallback SuperSDK supports running in non-App environments (such as browsers), providing reasonable fallback behavior to allow frontend projects to run and debug in browsers. ### initFallback(config) Initialize the fallback configuration in a non-end environment. The configuration will first be validated; valid calls from within the app (with appbridge) will be ignored. ```javascript SuperSDK.initFallback({ baseUrls: ['https://api.supersdk.com/superapi'], // Server address list (used for reportEvent reporting; business path appended to baseUrl) baseUrl: 'https://api.supersdk.com/superapi', // Supports legacy fields; used when `baseUrls` is not provided; `/superapi` can be omitted. spid: 'ab12cd34', // Replace with the real spid (8 lowercase alphanumeric characters) issued by the console. environment: 'staging', // Optional, default is prod; 1 to 10 lowercase alphanumeric characters appName: 'MyApp', // App Name appIcon: '', // App Icon Base64 (Optional) deviceId: '', // Device ID (optional; auto-generated if not provided) }); ``` **Behavioral Rules**: - `config` must be a plain object; `spid` must match `^[a-z0-9]{8}$`; `environment` defaults to `prod` if omitted, and if explicitly provided, must match `^[a-z0-9]{1,10}$`. - The legacy `aid` field is incompatible; do not trim or convert case. Invalid input immediately throws an error without modifying any active configurations. - In-app (with appbridge) also executes the above validation first; if valid, the fallback configuration is ignored, and all APIs follow the original in-app logic. - Can be called multiple times, using merge semantics (only the fields passed in this call are updated; fields not passed retain their previous values). - `baseUrls` takes precedence over `baseUrl`; if not configured, the default is `['https://api.supersdk.com/superapi']`; the legacy `baseUrl` field is compatible and automatically appends `/superapi`. - The request will prioritize using the last successful baseUrl; if the HTTP status is not 2xx or a network error occurs, it will switch to the next baseUrl among the remaining candidates in random order. - When `initFallback` is not called, the environment configuration class API returns default empty values (without rejecting). **deviceId Explanation**: - Automatically generate a UUID and store it in `localStorage` (key: `supersdk_device_id`) if not provided, maintaining consistency across sessions. - Clear method: `localStorage.removeItem('supersdk_device_id')` - In privacy mode, localStorage may be restricted, causing deviceId to degrade to in-memory storage (different for each session). ### isFallbackMode() Check if the current state is in downgrade mode. ```javascript if (SuperSDK.isFallbackMode()) { // Non-end environment and initFallback has been called // Available for conditional rendering (e.g., hiding feature buttons that are not supported). } ``` Return `true` if the environment is not an end environment (no appbridge) and `initFallback` has been called. ### API downgrade behavior | Category | API | Degradation behavior | Need to call initFallback | |------|-----|----------|:-----------------:| | **Page Navigation** | `openPage` / `openExternal` / `openWithBrowser` / `openBrowser` | `window.open(url, '_blank')` | No | | | `closePage` | `window.close()` or `history.back()` | No | | **UI Feedback** | `showToast(msg)` | `console.log('[SuperSDK Toast]:', msg)` | No | | | `share(content)` | `console.log('[SuperSDK Share]:', content)` | No | | **Environment Configuration** | `getEnv()` | resolve `{ os:'web', spid, environment, appName, deviceId, ... }` | No (more fields are returned via configuration) | | | `setAPIEnvironment(env)` / `getAPIEnvironment()` | Switch project environment during web fallback execution; native host controls set reject, get passes through native values. | set is (initFallback must be called first) | | | `getAppName()` / `getAppIcon()` | resolve configuration value or `""` | No | | | Settings Series | resolve `{}` or `null` | No | | **Event Tracking** | `reportEvent(name, params)` | `fetch` POST to `{baseUrl}/v2/reportEvent`; body includes `basic_data.host_spid/env`, and header includes `X-Aid=` and `X-Super-API-ENV`. | Yes (requires baseUrl/baseUrls + spid) | | **User Feedback** | `submitFeedback(params)` | `fetch` POST to `{baseUrl}/v2/feedback`; body includes `spid/env/platform=web`, header includes `X-Aid=` and `X-Super-API-ENV`; business rejection (`INVALID_REQUEST`/`NOT_FOUND`) does not switch lines. | Yes (requires baseUrl/baseUrls + spid) | | **Event Listener** | `subscribe` / `onForeground` / `onBackground` etc. | Normal registration (but will not receive Native push notifications) | No | | **Push** | `push.getStatus()` | resolve `{ supported: false }` | No | | | `push.requestPermission()` / `push.setTags()` / `push.setUserId()` | reject `Error('NOT_SUPPORTED')` (do not throw synchronous exceptions) | No | | | `push.onMessage()` / `push.onOpened()` | Normal registration (but will not receive Native push notifications) | No | | **No Downgrade** | `callHostMethod` / `requestShortUrl` / `downloadWithCache` / file operations / ZIP / attribution / payment / nativeBlock, etc. | reject, error message `"Not in app environment..."` | - | --- ## API reference ### API overview | Category | Method | Description | asynchronous | |------|------|------|:----:| | **Fallback Configuration** | `initFallback(config)` | Initialize non-end environment degradation configuration | - | | | `isFallbackMode()` | Check if in downgrade mode | - | | **Environment and Configuration** | `isInApp()` | Check if running within the app | - | | | `getEnv()` | Obtain runtime environment information (version, device, offline package, etc.) | ✓ | | | `setAPIEnvironment(env)` | Configure project environment (web fallback mode enabled; in-app reject) | ✓ | | | `getAPIEnvironment()` | Get the current project environment (native value passed through within the app) | ✓ | | | `getAppName()` | Get host app name | ✓ | | | `getAppIcon()` | Get host app icon (Base64) | ✓ | | | `getHostSettings(configName?)` | Get host app cloud control configuration | ✓ | | | `getHostSettingsByKey(key, configName?)` | Get host configuration by key | ✓ | | **Host Methods** | `callHostMethod(name, params)` | Call host app custom method | ✓ | | | `reportEvent(name, params)` | Report tracking events | ✓ | | | `addEventCommonParam(key, value)` | Set common parameters for event tracking | - | | | `submitFeedback(params)` | Submit user feedback (viewable in the console under "Business Operations → User Feedback") | ✓ | | | `openBrowser(url, title)` | Open browser page | - | | | `showToast(message)` | Display Toast notification | - | | | `setStatusBarDarkMode(isDark)` | Set status bar dark/light mode | - | | | `showKeyboard(selector)` | Invoke soft keyboard (Android empty implementation) | - | | **Page Navigation** | `openPage(url, options)` | Open URL in a new page | - | | | `closePage()` | Close current page | - | | | `openExternal(url)` | Open URL via system (App Store, phone, etc.) | - | | | `openWithBrowser(url)` | Open URL in system browser | - | | **Safe Area** | `getSafeArea()` | Get safe area (status bar/navigation bar height) | - | | **Share** | `share(content)` | Call system share | - | | | `requestShortUrl(url, baseUrl?)` | Generate short links from long links | ✓ | | | `requestShortUrlWithHtml(html, baseUrl?)` | Generate short links for HTML content (direct rendering) | ✓ | | **Lifecycle** | `onForeground(callback)` | Listen to the foreground event | - | | | `onBackground(callback)` | Listen to the event of entering the background | - | | **WebView Communication** | `publish(key, data, targetId)` | Send messages to other WebViews | - | | | `subscribe(key, callback)` | Listen to broadcast messages | - | | **Back Button** | `onBackPressed(callback)` | Listen for back button (interceptable) | - | | | `offBackPressed()` | Cancel back key listener | - | | **File Download** | `downloadFile(options)` | Download file (supports progress callback) | ✓ | | | `downloadWithCache(fileUrl, fileMd5, cacheTts, fileCacheKey?)` | Download and cache the file; if the cache is hit, directly return the local path. | ✓ | | **File Operations** | `fileExists(path)` | Check if the file exists | ✓ | | | `getFileMd5(path)` | Get file MD5 | ✓ | | | `deleteFile(path)` | Delete file or directory | ✓ | | | `moveFile(src, dest)` | Move/Rename file | ✓ | | | `createDir(path)` | Create directory | ✓ | | | `listDir(path)` | List directory contents | ✓ | | | `readFile(path)` | Read text file | ✓ | | | `writeFile(path, content)` | Write to a text file | ✓ | | **ZIP** | `unzipFile(zipPath, destPath)` | Extract the ZIP file | ✓ | | | `zipDir(sourcePath, zipPath)` | Compress the directory into a ZIP file. | ✓ | | **Login** | `getAuthProviders()` | Get the list of supported third-party login methods | ✓ | | | `requestLogin(options)` | Trigger third-party login | ✓ | | **Payment**
`SuperSDK.pay.*` | `pay.purchase(payConfig)` | Initiate Purchase (Single Entry · Aggregate createOrder→pay · Return Three States) | ✓ | | | `pay.getProviders()` | Detect the list of payment methods supported by the host app | ✓ | | | `pay.registerProvider(name, provider)` | Register Provider (Web Checkout / Native IAP override) | - | | | `pay.restorePurchases(options)` | Client restore purchase (F036 PurchaseResult[] · provider optional implementation) | ✓ | | **Push**
`SuperSDK.push.*` | `push.getStatus()` | Push status snapshot (`supported / permission / registered / lastError / lastOpened`) | ✓ | | | `push.requestPermission()` | Request notification permission (Android 13+ system dialog) | ✓ | | | `push.setTags(tags)` | Set device tags (`null` / `[]` = clear) | ✓ | | | `push.setUserId(userId)` | Set business user ID (`null` / `''` = clear) | ✓ | | | `push.onMessage(callback)` | Listen for push notifications received in the foreground (`push.message`) | - | | | `push.onOpened(callback)` | Listen to push click events (`push.opened`) | - | | **Experiment**
`SuperSDK.experiment.*` | `experiment.ready(options?)` | Wait for the first experiment result of this session (resolve even on timeout). | ✓ | | | `experiment.get(key, options?)` | Synchronously read experiment groups; the first read freezes the group, and exposure is reported by default. | - | | | `experiment.expose(key)` | Report exposure for experiments read with `expose:false`. | - | | | `experiment.getAll()` | For diagnostics: all results (not frozen, not exposed) | - | | | `experiment.refresh()` | Manual pull | ✓ | | | `experiment.setAttributes(map)` | Set custom audience attributes `attr.*` and re-fetch. | - | | **Attribution** | `getAttribution(onlyFirst)` | Get attribution data | ✓ | | **Native Block** | `nativeBlock.init()` | Initialization, scanning static `` | - | | | `nativeBlock.create(options)` | Dynamically create native components | ✓ | | | `nativeBlock.destroy(blockId)` | Destroy the specified component | - | | | `nativeBlock.destroyAll()` | Destroy all components | - | | | `nativeBlock.updatePositions()` | Manually update component location | - | | **Response Code** | `getSuEncCapabilities()` | Query the suenc codec supported by this client | - | | | `decodeSuEnc(encodedData, codec)` | Decode the suenc response body | - | --- ### Environment and configuration #### getEnv() Get current runtime environment information. ```javascript const env = await SuperSDK.getEnv(); console.log(env); // { // webviewId: "a1b2c3d4", // versionName: "1.0.0", // versionCode: 1010203, // channel: "local_test", // spid: "ab12cd34", // Replace with the real spid issued by the console // environment: "prod", // deviceId: "xxx-xxx-xxx", // platform: "android", // osVersion: "14", // deviceModel: "Pixel 8", // wappVersion: "1.0.0", // Current WApp (offline package) version; non-offline package pages are "" // wappBuildTime: 1740198896 // Offline package build time (second-level timestamp), 0 for non-offline package pages // } ``` #### setAPIEnvironment(environment) / getAPIEnvironment() The project environment corresponds to the env in the top bar of the console (e.g., `prod` / `staging`), which determines the environment for pulling settings and reporting analytics. ```javascript // Web fallback mode: Switch project environment at runtime (initFallback must be called first). await SuperSDK.setAPIEnvironment('staging'); // After switching, the env parameter in the getHostSettings request and the reportEvent // Both basic_data.env and the X-Super-API-ENV header use the new value; // Settings request cache is isolated by environment; switching back to the old environment restores the original cache. // Read the current project environment (Promise; resolve "prod" when the web is uninitialized) const env = await SuperSDK.getAPIEnvironment(); ``` **Rules:** - Value must be 1–10 lowercase letters or digits (`^[a-z0-9]{1,10}$`). Invalid values are rejected with `INVALID_ARGUMENT` and the state remains unchanged. If `initFallback` has not been called in the web environment, `set` is rejected with `NOT_INITIALIZED`. - Before switching, it will attempt to flush pending tracking events in the old environment, then update the value. - **In-app (App Internal)**: `setAPIEnvironment` always rejects `UNSUPPORTED` — the in-app environment is controlled by the native host app via `SuperSDK.setAPIEnvironment` (Android) / `SuperSDKManager.setAPIEnvironment` (iOS); `getAPIEnvironment` passes through the current native value via `getEnv`. - The `environment` field of `initFallback(config)` remains the initial environment for web mode. #### getAppName() Get the host app name. ```javascript const appName = await SuperSDK.getAppName(); // "MyApp" ``` #### getAppIcon() Get the host app icon (Base64 format). ```javascript const iconBase64 = await SuperSDK.getAppIcon(); // "data:image/png;base64,iVBOR..." // Can be directly used in ``` #### getHostSettings(configName?) Retrieve host app configuration information. `configName` is the configuration name; if not provided, the request sent to the client will not include the `configName` parameter. ```javascript const hostSettings = await SuperSDK.getHostSettings(); const featureSettings = await SuperSDK.getHostSettings('feature_flags'); // { code: 'SUCCESS', msg: '', data: { ... } } is consistent with the server-side settings response format. ``` **Parameter**: `configName` (string, optional) — Configuration name; if not provided, the request will not include the `configName` parameter. **Return value**: `Promise` — the host app's cloud control response object. On success, it returns `{ code, msg, data }`, where `data` contains the configuration content. In non-end environments, it resolves to an empty object `{}` and never rejects. #### getHostSettingsByKey(key, configName?) Retrieve host-specific configuration by key. ```javascript const config = await SuperSDK.getHostSettingsByKey('feature_flags'); const config = await SuperSDK.getHostSettingsByKey('enabled', 'feature_flags'); ``` **Parameter**: `key` (string) — The key of the configuration item. **Parameter**: `configName` (string, optional) — Configuration name; if not provided, the request will not include the `configName` parameter. **Return value**: `Promise<*>` — the host app configuration value corresponding to this key; the client-side first checks the response root object, and if not found, falls back to checking `data[key]`. In non-client environments, it resolves to `null`. --- ### Host methods #### callHostMethod(methodName, params) Call custom methods of the host app to implement business extensions. ```javascript const result = await SuperSDK.callHostMethod('getUserInfo', { id: '123' }); console.log(result); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | methodName | string | Method Name | | params | object | Parameter Object | > **Note:** This method has **no timeout limit**; the Promise will wait indefinitely for the host app to return a result. If timeout control is required, implement it at the business layer. > > The host app must implement the `HostMethodService` interface to register custom methods. #### reportEvent(eventName, params) Report events to the SDK's built-in analytics (implemented via `SReporter`). ```javascript await SuperSDK.reportEvent('page_view', { page: 'home', duration: 1200 }); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | eventName | string | Event Name | | params | object | Event Parameters (Optional) | #### openBrowser(url, title) Open browser page (SDK built-in implementation; Android uses the system browser, iOS uses SFSafariViewController). ```javascript SuperSDK.openBrowser('https://example.com', 'Example page'); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | url | string | URL to open | | title | string | Page Title | #### showToast(message) Display Toast notification (SDK built-in implementation; Android uses system Toast, iOS uses custom overlay). ```javascript SuperSDK.showToast('Success'); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | message | string | Message Content | > `reportEvent`, `showToast`, and `openBrowser` are all built-in SDK implementations and do not require additional handling by the host app. #### addEventCommonParam(key, value) Set common tracking parameters. After setting, all subsequent `reportEvent` reports from this WebView will automatically include the common parameters (commonly used to uniformly inject context such as page source or AB experiment group). ```javascript SuperSDK.addEventCommonParam('source', 'home_banner'); SuperSDK.addEventCommonParam('ab_group', 'B'); // All subsequent reportEvent calls will include source and ab_group. ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | key | string | Common Parameter Keys | | value | string | Common parameter values (non-strings are converted to strings, `null`/`undefined` are converted to empty strings) | > Synchronous method, **no return value**. In non-end environments (without appbridge), it is a no-op and throws no errors. #### submitFeedback(params) Submit a user feedback. In the client environment, Native completes `spid / env / device_id / platform / app_version / sdk_version / os_version / device_model` via JSB and reports to `POST /superapi/v2/feedback`. In non-client environments (where `baseUrl(s)` + `spid` are provided via `init`/`initFallback`), JSSDK directly performs `fetch`. The server records the submission time and user IP. The console allows viewing, searching, and marking the processing status under "Business Operations → User Feedback" by project and environment. ```javascript const { feedbackId } = await SuperSDK.submitFeedback({ scene: 'settings', // Required · Feedback Scenario subScene: 'about', // Optional · Sub-scenario title: 'Crash opening Settings', // Required content: 'The app consistently crashes about one second after opening Settings, Pixel 8 / Android 14', // Required userId: 'u_123456', // Optional · Business User ID (SDK does not maintain user identity; caller must pass it per request) extra: { page: 'settings', build: 42 } // Optional · Additional Information }); ``` **Parameter Description:** | Parameter | Type | Required | Description | |------|------|:----:|------| | scene | string | ✓ | Feedback scenario, ≤64 characters | | subScene | string | | Sub-scenario, ≤64 characters | | title | string | ✓ | Title, ≤200 characters | | content | string | ✓ | Feedback content, ≤5000 characters | | userId | string | | Business user ID, ≤128 characters; if not provided, the console user_id is empty. | | extra | object | | Additional information, JSON object, serialized size ≤4KB | **Return value:** `Promise<{ feedbackId: number }>` — Server-side feedback record ID. **Error:** | Scenario | In-app (JSB) | web | |------|------------|-----| | Invalid parameter (length/type) | reject `Error('INVALID_PARAMS')`, with `err.detail` containing the reason | `SuperSDKError` `INVALID_ARGUMENT` | | Not initialized | - | `NOT_INITIALIZED` | | Server-side business rejection | Field rejected by server → reject `Error('INVALID_ARGUMENT')`; project/environment does not exist → reject `Error('BRIDGE_ERROR')` (Native normalizes code via JSB registry, `err.detail` contains sanitized message). | `INVALID_ARGUMENT`, `err.nativeCode` is the server-side code (`INVALID_REQUEST` / `NOT_FOUND` …) | | Trigger rate limiting (10 requests per minute per IP · 600 requests per minute per project) | reject `Error('RATE_LIMITED')` | `RATE_LIMITED` | | Network/Timeout | reject `Error('NETWORK_ERROR' / 'TIMEOUT')` | `NETWORK_ERROR` / `TIMEOUT` / `UNAVAILABLE` (automatic rotation of baseUrls) | | Native version is outdated (no such JSB). | reject `Error('SDK_TOO_OLD')` | - | > Field length is determined by server-side validation (JSSDK local validation is merely a mirror of the same rule); all strings will be trimmed. The submission is **not idempotent**; do not retry the same content repeatedly on the business side. #### setStatusBarDarkMode(isDark) Set status bar dark/light mode. ```javascript // Dark background page: Status bar icons are displayed in white. SuperSDK.setStatusBarDarkMode(true); // Light background page: Status bar icons are displayed in black. SuperSDK.setStatusBarDarkMode(false); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | isDark | boolean | `true`=dark background (status bar icons are white); `false`=light background (icons are black) | > Synchronous method, **no return value**. In non-end environments, it is a no-op and throws no errors. #### showKeyboard(selector) Invoke the soft keyboard. ```javascript SuperSDK.showKeyboard('#search-input'); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | selector | string | CSS selector for the target input box (optional, iOS only) | > Synchronous method, **no return value**. In non-end environments, it is a no-op and throws no errors. > > **Platform Differences**: Android uses an **empty implementation** (calling JS `focus()` on the input box within WebView automatically triggers the keyboard, so this method is unnecessary); iOS forwards the call to Native for handling. #### onJSBridgeReady (internal interface) > ⚠️ **Internal API, do not call from business code**. `onJSBridgeReady` is a ready notification automatically invoked by the SDK when the script loads, used to flush messages buffered by the Native side before the JSBridge becomes ready. Business code should not and does not need to call this method. --- ### Navigation #### openPage(url, options) Open the URL in a new full-screen WebView page. ```javascript // Open new page SuperSDK.openPage('https://example.com'); // With configuration (currently, no features are configured in config) SuperSDK.openPage('https://example.com', {}); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | url | string | URL to open | | options | object | Configuration object (no available configurations currently, reserved for extension) | > **Note:** The opened page is a full-screen WebView without any native title bar obstruction. The page can be closed by calling `closePage()`. #### closePage() Close the current page. ```javascript SuperSDK.closePage(); ``` > Note: Calling this method in a TAB page has no effect. #### openExternal(url) Open URL using system method (jump to external app). ```javascript // Open App Store SuperSDK.openExternal('market://details?id=com.example.app'); // Make a phone call SuperSDK.openExternal('tel:10086'); // Send email SuperSDK.openExternal('mailto:test@example.com'); ``` #### openWithBrowser(url) Open the URL using the system browser. ```javascript SuperSDK.openWithBrowser('https://www.google.com'); ``` --- ### Safe area #### getSafeArea() Obtain safe area information (parsed from UserAgent) to adapt to devices such as notched screens and full-screen displays. ```javascript const safeArea = SuperSDK.getSafeArea(); console.log(safeArea); // { top: 88, bottom: 34 } // top: Status bar height (physical pixels) // bottom: Navigation bar height (physical pixels) ``` **Return Value:** | Parameter | Type | Description | |------|------|------| | top | number | Status bar safe area height (physical pixels) | | bottom | number | Navigation bar safe area height (physical pixels) | > Note: This method is synchronous and returns the result directly. The safe area information is injected by the client via the UserAgent (`SafeAreaTop/xx SafeAreaBottom/xx`). Correct values can only be obtained after the client calls `setSafeArea` or `fitSystemWindows`. --- ### Sharing #### share(content) Call the system share function. ```javascript SuperSDK.share('Text to share'); ``` #### requestShortUrl(url, baseUrl?) Generate short links. Convert long URLs into short links for easier sharing. ```javascript // Use default prefix const shortUrl = await SuperSDK.requestShortUrl('https://example.com/very/long/path?param=value'); console.log(shortUrl); // "https://s.supersdk.com/AbCd12" // Use custom prefix const shortUrl2 = await SuperSDK.requestShortUrl('https://example.com/very/long/path', 'https://s.a.com/'); console.log(shortUrl2); // "https://s.a.com/AbCd12" ``` **Parameter Description:** | Parameter | Type | Required | Description | |------|------|------|------| | url | string | Yes | Original long link | | baseUrl | string | No | Custom short link prefix, e.g., `https://s.a.com/`. If not provided, the default value is used. | **Return value:** `Promise` - Short link string **Features:** - Identical URLs called repeatedly return the same short link (idempotent). - Short links are permanently valid. - Timeout duration 10 seconds **Error Handling:** ```javascript try { const shortUrl = await SuperSDK.requestShortUrl('https://example.com/page'); // Use short links } catch (error) { console.error('Could not create short link:', error.message); // Possible errors: URL is required, network exception, appbridge not available } ``` #### requestShortUrlWithHtml(html, baseUrl?) Generate short links from HTML content. When accessing the generated short link, the HTML page is rendered directly without a 302 redirect. Suitable for scenarios such as generating dynamic share pages and activity posters. ```javascript // Use default prefix const shortUrl = await SuperSDK.requestShortUrlWithHtml('

Hello World

'); console.log(shortUrl); // "https://s.supersdk.com/XyZ789" // Use custom prefix const shortUrl2 = await SuperSDK.requestShortUrlWithHtml('

Campaign page

', 'https://s.a.com/'); console.log(shortUrl2); // "https://s.a.com/XyZ789" ``` **Parameter Description:** | Parameter | Type | Required | Description | |------|------|------|------| | html | string | Yes | HTML content (full document or fragment) | | baseUrl | string | No | Custom short link prefix, e.g., `https://s.a.com/`. If not provided, the default value is used. | **Return value:** `Promise` - Short link string **Features:** - Each call generates a new short link (idempotency deduplication is not performed). - Short links are permanently valid. - HTML content size limit 1MB - Timeout duration 10 seconds **Error Handling:** ```javascript try { const shortUrl = await SuperSDK.requestShortUrlWithHtml('

Campaign page

Campaign details...

'); // Use short link sharing } catch (error) { console.error('Could not create short link:', error.message); // Possible errors: HTML content is required, content exceeds size limit, network exception } ``` --- ### Lifecycle events #### onForeground(callback) Listen for the page entering the foreground event. ```javascript const unsubscribe = SuperSDK.onForeground((data) => { console.log('Entered foreground', data.triggerFrom); // triggerFrom: 'window' | 'view' | 'activity' }); // Cancel listener unsubscribe(); ``` **triggerFrom Description:** | Value | Description | |------|------| | window | Window visibility change (e.g., switching back from another app) | | view | View visibility changes (e.g., tab switching) | | activity | Activity lifecycle change (onResume) | #### onBackground(callback) Listen for the page entering the background event. ```javascript const unsubscribe = SuperSDK.onBackground((data) => { console.log('Entered background', data.triggerFrom); }); ``` --- ### WebView communication #### publish(eventKey, data, targetWebviewId) Send messages to other WebViews. ```javascript // Broadcast to all WebViews SuperSDK.publish('user_login', { userId: '123' }); // Send to specified WebView SuperSDK.publish('refresh_data', { type: 'order' }, 'a1b2c3d4'); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | eventKey | string | Event Identifier | | data | object | Message Data | | targetWebviewId | string | Target WebView ID, omit or pass '*' to broadcast to all | #### subscribe(eventKey, callback) Listen for broadcast messages from other WebViews or clients. ```javascript const unsubscribe = SuperSDK.subscribe('user_login', (data) => { console.log('Message received:', data); }); // Cancel listener unsubscribe(); ``` > **Note:** `subscribe` can receive `publish` messages from other WebViews, as well as broadcasts sent by the client via `sendBroadcast` / `broadcastToAll`. #### Client Broadcast (Native → Frontend) The host app can send broadcast messages to WebView via SDK API, and the frontend uses `subscribe` to receive them. **Client-side invocation method:** ```java // Android - Send broadcast to the current WebView pageView.sendBroadcast("login_changed", "{\"isLogin\":true}"); // Android - Broadcast to all WebViews SuperSDK.broadcastToAll("config_updated", "{\"key\":\"value\"}"); ``` ```swift // iOS - Send broadcast to the current WebView pageView.sendBroadcast(eventKey: "login_changed", jsonData: "{\"isLogin\":true}") // iOS - Broadcast to all WebViews SuperSDK.broadcastToAll(eventKey: "config_updated", jsonData: "{\"key\":\"value\"}") ``` **Front-end reception method:** ```javascript // Listen to client broadcasts (using subscribe, same as communication with WebView) SuperSDK.subscribe('login_changed', (data) => { console.log('Sign-in state changed:', data); // data = { isLogin: true } }); SuperSDK.subscribe('config_updated', (data) => { console.log('Configuration updated:', data); }); ``` > **Note:** If a broadcast is sent before the JSBridge is ready, the message will be buffered and automatically delivered once the JSBridge is ready. --- ### Back button handling #### onBackPressed(callback) Listen for the user pressing the back key event and optionally intercept it. Only one listener is active at a time; later registrations override earlier ones. ```javascript SuperSDK.onBackPressed(() => { if (hasUnsavedData) { showConfirmDialog(); return true; // Return true: intercept and return, the page does not close. } return false; // Return false: do not intercept, execute the default return logic }); ``` **Callback Return Value Description:** | Return value | Behavior | |--------|------| | `true` | Intercept the back key, keep the page on the current screen, and do not execute the default back logic. | | `false` | Do not intercept; execute the default return logic (go back if there is history, otherwise close the page). | | `undefined` (no return value) | Equivalent to `false`, do not intercept. | **Use Case Examples:** ```javascript // Scenario 1: Confirm before leaving the page SuperSDK.onBackPressed(() => { if (formModified) { const confirmed = confirm('Leave without saving your changes?'); if (!confirmed) { return true; // User chooses to stay, intercept return } } return false; // Allow return }); // Scenario 2: Custom return logic (e.g., closing the popup) SuperSDK.onBackPressed(() => { if (isModalOpen) { closeModal(); return true; // Close the pop-up and intercept the back action. } return false; // No pop-up, normal return }); ``` #### offBackPressed() Cancel the back button listener and restore the default back behavior. ```javascript SuperSDK.offBackPressed(); ``` > **Important Notes:** > 1. The callback must **synchronously return** the result; asynchronous operations (async/await) are not supported. > 2. When the callback execution exceeds the timeout (>300ms), the Native SDK automatically executes the default return logic to prevent freezing. > 3. Both the Android physical back button and gesture back will trigger. > 4. On iOS, currently only the navigation bar back button triggers; the swipe-back gesture is not yet supported for interception. --- ### File downloads #### downloadFile(options) Download files to local storage. ```javascript const cancel = SuperSDK.downloadFile({ url: 'https://example.com/file.zip', savePath: 'downloads/file.zip', headers: { 'Authorization': 'Bearer token123' }, onStart: () => { console.log('Download started'); }, onProgress: ({ progress, downloadedBytes, totalBytes }) => { console.log(`Download progress: ${progress}%`); }, onSuccess: ({ filePath, downloadedBytes, totalBytes }) => { console.log('Download complete:', filePath); }, onFail: ({ error }) => { console.error('Download failed:', error); } }); // Cancel Download cancel(); ``` **Parameter Description:** | Parameter | Type | Required | Description | |------|------|------|------| | url | string | Yes | File download link | | savePath | string | Yes | Save path (relative to the SDK file storage directory) | | headers | object | No | Request Header | | onStart | function | No | Download callback | | onProgress | function | No | Progress callback, triggered approximately every 300ms. | | onSuccess | function | No | success callback | | onFail | function | No | Failure callback | **onProgress callback parameters:** | Parameter | Type | Description | |------|------|------| | progress | number | Download progress 0-100 | | downloadedBytes | number | Bytes Downloaded | | totalBytes | number | Total file size in bytes | **onSuccess callback parameters:** | Parameter | Type | Description | |------|------|------| | filePath | string | Absolute file path | | downloadedBytes | number | Bytes Downloaded | | totalBytes | number | Total file size in bytes | **onFail callback parameters:** | Parameter | Type | Description | |------|------|------| | error | string | Error Message | #### downloadWithCache(fileUrl, fileMd5, cacheTts, fileCacheKey) Download the file and write it to the SDK cache directory. If the cache is hit, do not re-download; directly return the local file path. ```javascript const result = await SuperSDK.downloadWithCache( 'https://example.com/assets/file.zip?token=abc', 'd41d8cd98f00b204e9800998ecf8427e', 86400, 'asset-file-v1' ); console.log(result); // { filePath: '/path/to/download_cache/xxx.zip', cacheHit: true, cacheKey: 'asset-file-v1' } ``` **Parameter Description:** | Parameter | Type | Required | Description | |------|------|------|------| | fileUrl | string | Yes | File download link | | fileMd5 | string | No | File MD5; skip MD5 verification if empty. | | cacheTts | number | No | Cache validity period, in seconds; when `<= 0`, force re-download. | | fileCacheKey | string | No | Custom cache key; if empty or not provided, use `fileUrl` without the query string. | **Caching Rules:** - The cache key prioritizes the non-empty `fileCacheKey`; otherwise, it uses the `fileUrl` without the query string. - Native converts the cache key into a secure filename and does not directly concatenate the URL to the file path. - When `fileMd5` is not empty, the cached file and the newly downloaded file are verified. If the MD5 of the newly downloaded file does not match, the operation fails and the old cache is not overwritten. **Return Value:** | Parameter | Type | Description | |------|------|------| | filePath | string | Absolute path of the local cache file | | cacheHit | boolean | Whether cache was hit | | cacheKey | string | The actual original cache key used this time | --- ### File operations > All paths are relative paths relative to the SDK file storage directory. #### fileExists(path) Check if the file or directory exists. ```javascript const info = await SuperSDK.fileExists('downloads/file.zip'); console.log(info); // { exists: true, isFile: true, isDirectory: false } ``` **Return Value:** | Parameter | Type | Description | |------|------|------| | exists | boolean | Does it exist? | | isFile | boolean | Is it a file? | | isDirectory | boolean | Is it a directory? | #### getFileMd5(path) Get the MD5 value of the file. ```javascript const { md5 } = await SuperSDK.getFileMd5('downloads/file.zip'); console.log('MD5:', md5); ``` #### deleteFile(path) Delete files or directories (recursive deletion). ```javascript await SuperSDK.deleteFile('downloads/old_file.zip'); ``` #### moveFile(srcPath, destPath) Move or rename files. ```javascript await SuperSDK.moveFile('downloads/temp.zip', 'cache/final.zip'); ``` #### createDir(path) Create directory (supports recursive creation). ```javascript await SuperSDK.createDir('data/cache/images'); ``` > If the directory already exists, no error will be reported. #### listDir(path) List directory contents. ```javascript const { files } = await SuperSDK.listDir('downloads'); files.forEach(file => { console.log(file.name, file.isFile ? 'file' : 'directory', file.size); }); ``` **Return value files array elements:** | Parameter | Type | Description | |------|------|------| | name | string | File name | | isFile | boolean | Is it a file? | | isDirectory | boolean | Is it a directory? | | size | number | File size (bytes) | | lastModified | number | Last modified time (timestamp) | #### readFile(path) Read the text file content. ```javascript const { content } = await SuperSDK.readFile('config/settings.json'); const settings = JSON.parse(content); ``` #### writeFile(path, content) Write text file content. ```javascript const settings = { theme: 'dark', lang: 'zh' }; await SuperSDK.writeFile('config/settings.json', JSON.stringify(settings)); ``` --- ### ZIP compression and extraction #### unzipFile(zipPath, destPath) Extract the ZIP file to the specified directory. ```javascript await SuperSDK.unzipFile('downloads/archive.zip', 'extracted/'); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | zipPath | string | ZIP file path | | destPath | string | Extract to target directory | > **Security Limit**: ZIP files containing malicious path entries (e.g., `../`) will fail to extract and will not write outside the target directory. #### zipDir(sourcePath, zipPath) Compress the directory into a ZIP file. ```javascript await SuperSDK.zipDir('data/logs/', 'backup/logs.zip'); ``` **Parameter Description:** | Parameter | Type | Description | |------|------|------| | sourcePath | string | Directory path to be compressed | | zipPath | string | Generated ZIP file path | > Note: Compression and decompression operations may take a long time, with a timeout of 60 seconds. --- ### Login The SDK provides third-party login bridging capabilities. H5 triggers native third-party login (e.g., Google, Apple) via the SDK. After obtaining the third-party credentials, the application calls its backend to exchange them for a token. #### getAuthProviders() Obtain the list of third-party login methods supported by the host app. ```javascript const providers = await SuperSDK.getAuthProviders(); // ['google', 'apple'] ``` **Return value:** `string[]` — Array of Provider names #### requestLogin(options) Trigger third-party login via the specified method. ```javascript try { const credential = await SuperSDK.requestLogin({ provider: 'google' }); console.log(credential.provider); // 'google' console.log(credential.token); // Primary Receipt (Google ID Token / Apple Identity Token) console.log(credential.authorizationCode); // Authorization Code console.log(credential.email); // User email console.log(credential.displayName); // username // After obtaining the receipt, the H5 independently calls the backend to exchange for the business token. const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(credential) }); const { token } = await res.json(); } catch (e) { if (e.message === 'CANCELLED') { // User cancels, no error dialog shown. } else { console.error('Sign-in failed:', e.message); } } ``` **Parameters:** | Parameter | Type | Required | Description | |------|------|------|------| | options.provider | string | Yes | Login method name (obtained from getAuthProviders) | **Return value:** `ThirdPartyCredential` | Field | Type | Description | |------|------|------| | provider | string | Login method name (always present) | | token | string | Main receipt (Google=ID Token, Apple=Identity Token) | | authorizationCode | string | Authorization Code (for some Providers) | | email | string | User email | | displayName | string | User Display Name | | photoUrl | string | User avatar URL | | raw | object | Provider raw data | > Different providers return different fields; only `provider` is guaranteed to exist. **Error Code:** | code | Meaning | Suggested handling | |------|------|---------| | CANCELLED | User cancels login | Silent processing, no error prompt displayed. | | PROVIDER_NOT_FOUND | Unregistered Provider | Check the return value of getAuthProviders | | NOT_IMPLEMENTED | Host app has not implemented LoginService | Contact the host app developer | | ERROR | Other errors | Display error message | --- ### Payments (SuperSDK.pay namespace) 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 ](#f038-migration-guide-migrate-from-f036-purchaseresult-to-three-state) 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). - For the detailed architecture, see the [IAP Recommended Architecture](#recommended-iap-architecture) section below (v0.3 has been rewritten). ⚠️ **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. #### pay.querySubscriptionOffers(options) 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. ```javascript const offers = await SuperSDK.pay.querySubscriptionOffers({ provider: 'google_play', productIds: ['matrixvplan01'] }); // 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`. 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`. #### pay.purchase(payConfig) 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.pay(json) [IAP: native provider reads json; third party: host JavaScript] → Return one of three states in PayResult3State { status: finished | cancelled | error } ``` ```javascript // IAP (provider registration createOrder-only override · pay uses SDK's built-in native · see registerProvider) const result = await SuperSDK.pay.purchase({ 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 pollBusinessOrder(result.orderToken); break; case 'cancelled': // User cancelled break; case 'error': // Failure · result.phase('create'|'pay') + result.code console.error(result.phase, result.code, result.message); break; } ``` **Third-party Payment Inline Mode** (no `registerProvider` required · one-time use · both methods are inline): ```javascript const result = await SuperSDK.pay.purchase({ payParams: { productId: pkg.id, userId: uid }, createOrder: async (payParams) => { // Optional · Output JSON opaque to the SDK (your pay is consumed by you) const res = await myApi.createOrder(payParams); return { prepayId: res.prepay_id, orderToken: res.order_token }; }, 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). const { payUrl } = await myApi.checkout(json.prepayId); window.open(payUrl, '_blank'); const status = await pollChannel(json.orderToken); // Business self-implemented polling if (status === 'completed') return { status: 'finished', orderToken: json.orderToken }; if (status === 'cancelled') return { status: 'cancelled' }; return { status: 'error', phase: 'pay', code: status, orderToken: json.orderToken }; } }); ``` **payConfig parameter**: | Parameter | Type | Required | Description | |---|---|---|---| | provider | string | No | 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` · 🔴 **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` · 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` — **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) | | code | string | when an error occurs | Platform error code mapping (e.g., `BILLING_UNAVAILABLE` / `CREATE_FAILED`) | | message | string | No | Debug information (non-sensitive) | | orderToken | string | No | 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 `originalJson` **never 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 ](#business-query-status-after-finished)]). #### pay.getProviders() Detect the list of payment methods supported by the host app (merge JS-registered + Native-registered). ```javascript const providers = 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()`. #### pay.registerProvider(name, provider) 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. ```javascript SuperSDK.pay.registerProvider('alipay', { createOrder: async (payParams) => { // Optional · Output JSON opaque to the SDK (your pay consumption) const res = await myApi.createOrder(payParams); return { prepayId: res.prepay_id, orderToken: res.order_token }; }, pay: async (json) => { // Required (Third-party) · Launch channel independently + Polling · Return PayResult3State const { payUrl } = await myApi.checkout(json.prepayId); window.open(payUrl, '_blank'); const status = await pollChannel(json.orderToken); // Business self-implementation if (status === 'completed') return { status: 'finished', orderToken: json.orderToken }; if (status === 'cancelled') return { status: 'cancelled' }; return { status: 'error', phase: 'pay', code: status, orderToken: json.orderToken }; } }); ``` **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. ```javascript const [googleName] = (await SuperSDK.pay.getProviders()) .filter(n => n === 'google_play'); // Use the actual internal name · Do not hardcode SuperSDK.pay.registerProvider(googleName /* 'google_play' */, { createOrder: async (payParams) => { // 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). const res = await myApi.createOrder(payParams); // 🔴 Backend order creation endpoint issues UUID orderToken return { productId: payParams.productId, // Required productType: payParams.productType ?? 'inapp', // "inapp" (default) or "subs" basePlanId: payParams.basePlanId, // Required when productType='subs' offerId: payParams.offerId, // Subscription discount is optional; if omitted, purchase the base plan. accountId: payParams.accountId, // Optional → obfuscatedAccountId (user ID) profileId: res.order_token // Optional → obfuscatedProfileId (order ID) · 🔴 Required UUID }; } // 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' }`. > > ```javascript > // 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` · Returns a `json` object opaque to the SDK · Default = `identity(json=payParams)` | | pay | A Required / B None | `(json) => Promise` · 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). #### pay.restorePurchases(options) Client restore purchase · Call Native PayService.restorePurchases · **provider implementation is optional**. > 🔵 **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. ```javascript 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. const purchases = await SuperSDK.pay.restorePurchases({ provider: 'apple' /* Host app registration name · subject to getProviders() */ }); // purchases: [{ orderId, purchaseToken, productId, purchaseState }] } catch (e) { if (e.message === 'NOT_SUPPORTED') { // provider did not implement restore · fallback business backend const res = await fetch('/api/pay/my-purchases?userId=' + userId); const purchases = await res.json(); } else if (e.message === 'PROVIDER_NOT_FOUND') { // Invalid provider name } } ``` | Parameter | Type | Required | Description | |---|---|---|---| | options.provider | string | No | Optional with a single Provider; required with multiple Providers. | **Return value**: `Promise` — 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 Codes > F038 `pay.purchase` failures are categorized into two types: **reject code** (payment initiation failed · `e.message`) and **error three-state code** (payment phase failed after initiation · `result.code` + `result.phase`). **reject code (Unable to start · `pay.purchase` thrown)**: | code | Meaning | Suggested handling | |------|------|---------| | INVALID_PARAMS | Invalid input parameters (payConfig/payParams are not objects) · err.detail contains specific field information | Check the passed-in parameters | | NOT_IN_APP | Native path but not in the client environment | Check isInApp() | | SDK_TOO_OLD | The legacy SDK lacks `appbridge.nativePay` (F038 unified payment requires SDK upgrade). | Upgrade host app SDK | | PROVIDER_REQUIRED | Not specified when multiple Providers are used | Pass the provider parameter | | NO_PROVIDER | No provider is available. | Hint: Host app has not implemented payment. | | PURCHASE_IN_PROGRESS | An inline purchase is in progress. | Wait for the current purchase to complete. | **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. | Retry later | | QUERY_FAILED | pay | Subscription purchase query failed (not Billing unavailable) | Retry later and keep the original selection | | PURCHASE_FAILED | pay | Subscription Billing UI launch or purchase callback failed | Display error and allow retry | | FAILED / EXPIRED / CANCELLED... | pay | The custom return code (business-defined) from the third-party provider's pay | Process according to business semantics | | BILLING_UNAVAILABLE / SERVICE_UNAVAILABLE / DEVELOPER_ERROR / ITEM_UNAVAILABLE / NO_ACTIVITY / ERROR ... | pay | Built-in IAP provider.pay platform billing error (mapped from BillingResponseCode / StoreKit Error) | Display error message | > 🔴 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). #### Business query status (after finished) `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) | Continue polling (custom interval/limit) | | `failed` | Backend verification failed (signature verification failed / refund / platform rejection) | Display the error | | `unknown` | Undetermined (super polling limit not yet determined) | Background fallback (RTDN/ASSN will eventually be implemented) · No delivery on the client side | ```javascript async function pollBusinessOrder(orderToken, maxPolls = 6, interval = 2000) { for (let i = 0; i < maxPolls; i++) { const { status } = await fetch('/api/pay/order-status?orderToken=' + orderToken).then(r => r.json()); if (status === 'success' || status === 'failed') return status; await new Promise(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](#6-direct-receipt-delivery-through-paybridge)). #### Complete payment flow example (v0.3) ```javascript let PAY_PROVIDER; // Actual provider name · from getProviders() · not hardcoded async function init() { // 1. Detection capability (provider name is determined by this return value; built-in Google is 'google_play') const providers = await SuperSDK.pay.getProviders(); if (providers.length === 0) return; PAY_PROVIDER = providers[0]; // Or select by business logic, e.g., `providers.find(n => n === 'google_play')` // 2. Register createOrder override for IAP provider (optional · enables createOrder to produce Google provider input keys) SuperSDK.pay.registerProvider(PAY_PROVIDER, { createOrder: async (payParams) => { const res = await fetch('/api/pay/create-order', { // Create order (backend issues UUID orderToken · you hold it on the spot) method: 'POST', body: JSON.stringify(payParams) }).then(r => r.json()); // ⬇️ Google Provider input key; for subscriptions, productType='subs' + basePlanId are required, offerId is optional. return { productId: payParams.productId, productType: payParams.productType ?? 'inapp', basePlanId: payParams.basePlanId, offerId: payParams.offerId, accountId: res.accountId, profileId: res.orderToken // 🔴 UUID }; } }); } async function buyProduct(productId, userId) { // 3. Initiate Purchase (SDK internal `createOrder` → `pay` · Returns three states) const result = await SuperSDK.pay.purchase({ provider: PAY_PROVIDER, // 🔴 Use the return value of `getProviders()` · Do not hardcode 'google' (internally it is 'google_play') payParams: { productId, userId } // Any object · Consumed by your `createOrder` · Not parsed by the SDK }); // 4. Three-state branching switch (result.status) { case 'finished': // ≠ Success · Check order (orderToken is returned internally by the provider) const orderStatus = await pollBusinessOrder(result.orderToken); if (orderStatus === 'success') unlockEntitlement(); else if (orderStatus === 'failed') showFailed(); else showPending(); // processing / unknown break; case 'cancelled': // User Cancelled · Silent break; case 'error': // Failure · phase + code if (result.phase === 'create') showRetry(); // createOrder failed · not launched · safe to retry else console.error('Payment failed:', result.code, result.message); break; } // 🔴 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. } async function restoreUserPurchases(userId) { try { // 5. Client-side restore (Apple Guideline 3.1.1 required · F038 contract unchanged · returns PurchaseResult[]) return await SuperSDK.pay.restorePurchases({ provider: PAY_PROVIDER }); } catch (e) { if (e.message === 'NOT_SUPPORTED') { const res = await fetch('/api/pay/my-purchases?userId=' + userId); return await res.json(); } throw e; } } ``` #### F038 Migration Guide (Migrate from F036 PurchaseResult to Three-State) > 🔴 **Breaking Change (Second after F036)**: `pay.purchase` now returns a **PayResult3State** three-state object instead of a `PurchaseResult` **receipt**; 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. ### Push notifications (SuperSDK.push namespace) Device push bridging capability · H5 invokes via `SuperSDK.push.*`. **Android requires the host app to integrate the optional module `supersdk-push-firebase` and implement `SuperSDKProvider.getPushService()`** (integration details see Android integration documentation "Push" section and SUPERPUSH.md); iOS currently has explicit "not supported" stubs (the four methods reject `UNSUPPORTED`). > The SDK is responsible only for device registration, forwarding foreground messages/clicks to H5, and reporting app opens. Sending and audience targeting are completed in the console's "Message Push" section. All interfaces provide explicit results—not errors—in all three environments: **browser**, **host app**, and **iOS** (see table below), allowing business code to call them unconditionally. | Environment | `getStatus()` | The other three methods | |------|---------------|--------------| | Android · Host app connected | Actual state (`supported: true`) | Normal execution | | Android · Host app not connected (`getPushService()` is null) | `{ supported: false }` | reject `UNSUPPORTED` (Native `NOT_IMPLEMENTED` normalized via registry · `retryable: false`) | | iOS(stub) | `{ supported: false }` | reject `UNSUPPORTED` | | Pure browser (no `window.appbridge`) | `{ supported: false }` | reject `NOT_SUPPORTED` (do not throw synchronous exceptions) | | Native version too old (no push JSB) | reject `SDK_TOO_OLD` | reject `SDK_TOO_OLD` | #### push.getStatus() Get push status snapshot. ```javascript const status = await SuperSDK.push.getStatus(); // { // supported: true, // permission: 'granted', // 'granted' | 'denied' | 'prompt' // registered: true, // Last successful registration exists and no errors have occurred since then // lastError: 'NETWORK_ERROR', // Optional · The reason for the most recent registration failure (cleared after success) // lastOpened: { // Optional · One-time field, see description below // messageId: 'pm_0123456789ab', // url: 'https://example.com/promo', // clickType: 'open_url', // 'open_app' | 'open_url' // openedAt: 1760000000000, // verified: true // } // } ``` **Return value:** `Promise` | Field | Type | Description | |------|------|------| | supported | boolean | `false` when other fields are omitted (browser / unconnected / iOS) | | permission | `'granted'` \| `'denied'` \| `'prompt'` | Notification visibility to the user. `denied` covers both "permission denied" and "system notification toggle off"; `prompt` = Android 13+ has not been asked yet. | | registered | boolean | **Derived Value**: `true` if a previous successful registration fingerprint exists and no errors have occurred since. It remains `true` transiently between `setTags` and the new successful registration; it flips to `false` upon any registration failure (including 24h refresh failure). | | lastError | string | Closed set `TOKEN_UNAVAILABLE` / `NOT_FOUND` / `INVALID_REQUEST` / `RATE_LIMITED` / `NETWORK_ERROR` / `UNAVAILABLE`; server codes outside the closed set are normalized to `UNAVAILABLE` in Native. Omitted after successful registration. | | lastOpened | object | The most recent **unread** push click, with fields identical to the [`push.opened` payload](#pushonopenedcallback); omitted if there are no unread clicks. | > 🔴 **`lastOpened` is a one-time field**: consumed by the **first `getStatus()` call that reads it** (any invocation from any WebView, including polling), and returns nothing thereafter. It addresses the scenario where, upon cold-starting the app via a notification click, the page hasn't loaded yet and no one is handling the `push.opened` event. In a multi-WebView environment, only one page can read it. A page that has already received the `push.opened` event may still read the same entry when calling `getStatus()` again. Therefore, use **both `push.opened` events and `lastOpened` as fallbacks**, deduplicating by **`messageId`**, and **do not call `getStatus()` in polling loops** (as this would allow other pages to prematurely consume the click intended for them). #### push.requestPermission() Request notification permission. On Android 13+, the system permission dialog is displayed (each device shows the dialog only once; thereafter, the system decides). On Android 12 and below, no dialog is shown, and the actual reachability is returned directly. ```javascript const { permission } = await SuperSDK.push.requestPermission(); if (permission !== 'granted') { // Guide the user to enable notifications in system settings. } ``` **Return value:** `Promise<{ permission: 'granted' | 'denied' | 'prompt' }>` > Interaction methods, H5-side callback timeout **120000ms** (waiting for the user to operate the system dialog). When no foreground Activity is available (e.g., called from the background), reject `UNAVAILABLE` (`retryable: true`); retry later in the foreground. Changes in permission results will trigger the SDK to re-register (the console device `enabled` status updates accordingly). #### push.setTags(tags) Set device tags for audience filtering in the console. The SDK automatically re-registers when the value changes; duplicate values do not trigger repeated requests. ```javascript await SuperSDK.push.setTags(['vip', 'zh-CN']); await SuperSDK.push.setTags([]); // Clear (registration body explicitly with tags: []) await SuperSDK.push.setTags(null); // Same as above ``` | Parameter | Type | Description | |------|------|------| | tags | string[] \| null | ≤10 items, each ≤32 characters (counted by Unicode code points), excluding control characters; the SDK performs trim, remove empty, deduplicate, and preserve order. `null` and `[]` are equivalent. | **Return value:** `Promise` > Boundary rules are determined by the Native single source: out-of-bounds requests are rejected with `INVALID_ARGUMENT` (`err.nativeCode === 'INVALID_PARAM'`, `err.detail` contains the reason) and **no request is sent, no landing occurs**. The JSSDK locally only intercepts type errors such as "not a string array". #### push.setUserId(userId) Set the business user ID for user targeting in the console. The SDK automatically re-registers when the value changes; pass `null` or `''` to clear it upon logout. ```javascript await SuperSDK.push.setUserId('u_123456'); await SuperSDK.push.setUserId(null); // Logout: Clear (explicitly set user_id: null in the registration object) ``` | Parameter | Type | Description | |------|------|------| | userId | string \| null | ≤128 characters (counted by Unicode code points), excluding control characters; `null` / `''` = clear | **Return value:** `Promise` > 🔴 **`userId` and `tags` are merely anonymous identifiers for push targeting, not for identity authentication**: They are self-reported by H5 without any validation, and the server does not trust device identity based on them. Do not treat them as a login session, and do not include sensitive information in push content that can be viewed solely by relying on `userId`. #### push.onMessage(callback) Listen to **push notifications received when the host app is in the foreground** (via the existing BROADCAST channel, event key `push.message`; `SuperSDK.subscribe('push.message', cb)` is equivalent). Notifications in the background or when the app is killed are displayed directly by the system and do not trigger this callback. ```javascript const unsubscribe = SuperSDK.push.onMessage((message) => { // { // messageId: 'pm_0123456789ab', // title: 'Title', body: 'Body', imageUrl: 'https://…' | null, // url: 'https://example.com/promo' | null, // clickType: 'open_url', // 'open_app' | 'open_url' // data: { message_id: '…', url: '…', ... } // FCM data original key passthrough // } }); unsubscribe(); // Cancel before page destruction ``` **Return value:** The function to cancel the listener. #### push.onOpened(callback) Listen for push click events (event key `push.opened`). Clicking a system notification or foreground notification triggers SDK validation and acknowledgment, then dispatches this event. The app is launched (if `clickType === 'open_url'` and the host app does not handle it, the SDK opens the `url`). ```javascript const unsubscribe = SuperSDK.push.onOpened((opened) => { // { // messageId: 'pm_0123456789ab', // url: 'https://example.com/promo', // Optional, exists when clickType=open_url // clickType: 'open_url', // openedAt: 1760000000000, // verified: true // } }); ``` | Field | Description | |------|------| | verified | `true` = `url` / `clickType` from server receipt (authoritative value); `false` = fallback path when server is unreachable at click time (offline / timeout): `url` is the original notification intent value, **not verified by the server**. In this case, the SDK only launches the app and does not automatically open `url`. If the business logic needs to navigate based on `url`, first check `verified`. | **Return value:** The function to cancel the listener. > 🔴 **Events are delivered only to WebView instances that are alive and subscribed at the time of event occurrence** (exhibits BROADCAST semantics; if no listeners exist, the event is dropped directly without caching). When clicking a notification to cold-start the app, the page has not yet loaded; you must actively retrieve the status once after page load using `getStatus().lastOpened`. Deduplicating by `messageId` across these two paths covers all scenarios. **Error (In-App · `Error`, with `code` / `nativeCode` / `retryable` / `detail`):** | `err.code` | Trigger conditions | retryable | |-----------|----------|:---------:| | `NOT_SUPPORTED` | Pure browser (no `appbridge`) | - | | `UNSUPPORTED` | Host not wired (Native `NOT_IMPLEMENTED`) / iOS stub | ✗ | | `SDK_TOO_OLD` | Native did not push JSB | ✗ | | `INVALID_ARGUMENT` | Invalid parameter type (local) or out of bounds (Native `INVALID_PARAM`) | ✗ | | `UNAVAILABLE` | `requestPermission` no foreground Activity (Native `NO_ACTIVITY`) | ✓ | | `TIMEOUT` | Callback timeout (`requestPermission` 120s · others 15s) | ✓ | ### Experiments (SuperSDK.experiment namespace) A/B Testing Capability · H5 reads the group assigned to this device via `SuperSDK.experiment.*`. Experiments are created, launched, and adjusted for traffic in the console under "Business Operations → A/B Testing". **Groups are calculated by the server based on device ID**; the SDK does not implement the traffic splitting algorithm. It is responsible for fetching the result for this device, fixing the read result within the current page session, reporting exposure, and including the exposed group ID in every subsequent tracking event. > Just remember one rule: **read experiments only where they are used, not by loading all experiments at startup.** `get(key)` defaults to "read + exposure"; read experiments are recorded in experiment data. Users who didn't see a variant are also read, which dilutes the difference between groups. | Environment | Behavior | |------|------| | Pure browser (already `init()`, `analyticsConsent: 'granted'`) | Fetch immediately after `init()` completes; the device ID is taken from the SDK's analytics consent management (the same `deviceId` as used for tracking). | | Pure browser · Analysis not consented (`analyticsConsent: 'denied'`) | No request is sent; `get()` always returns "not participated" with `reason: 'no_subject'`. | | In-app · Container supports experiment bridge (from 2.6.0, with native SDK) | **Native Delegation**: Fetching, freezing, and exposure, along with `exp_vids`, are all handled natively, sharing the same results, the same freeze table, and the same exposure deduplication logic with native code and other WebViews. H5 does not send assign requests or report exposure independently. See "In-app: Native-hosted" below. | | In-app · Legacy Container (Experimental JSB not declared) | Maintain the web pull path; device ID, spid, environment, platform, and App version are obtained from the host app's `getEnv()`. The pull is performed only on the first call to the experiment interface. | **Quick Example:** ```javascript SuperSDK.init({ spid: 'ab12cd34', analyticsConsent: 'granted' }); // When using experiments on the first screen, wait for results first (up to 1.5 seconds; if timeout occurs, use the default value). await SuperSDK.experiment.ready({ timeoutMs: 1500 }); const paywall = SuperSDK.experiment.get('paywall_price', { default: { price: '9.9' } }); renderPaywall(paywall.payload.price); // Report exposure immediately upon detection (SDK deduplication) ``` #### experiment.ready(options?) Wait for the first available result of this session: resolve once the first fetch on this page completes (success or failure); also resolve when `timeoutMs` is reached, **never reject network errors**. Resolve immediately if analysis consent is not granted. | Parameter | Type | Description | |------|------|------| | options.timeoutMs | number | Maximum wait time in milliseconds, default `2000` | | options.namespaces | string[] | Add namespaces to be loaded (`^[a-z][a-z0-9_]{1,31}$`). By default, only `default` is loaded; including `default`, a maximum of 10 namespaces are allowed. Adding a new namespace triggers an immediate re-fetch. | **Return value:** `Promise`; if parameters are invalid, reject with `INVALID_ARGUMENT`. After timeout: keys that have been read retain their default values for this session; keys that have not been read take effect normally once the result arrives. #### experiment.get(key, options?) **Synchronize** read experiment results. ```javascript const result = SuperSDK.experiment.get('paywall_price', { default: { price: '9.9' } }); // Participate: // { inExperiment: true, variant: 'low', vid: 10388, payload: { price: '7.9' }, reason: 'alloc' } // Not Participated: // { inExperiment: false, variant: '', vid: null, payload: { price: '9.9' }, reason: 'unknown' } ``` | Parameter | Type | Description | |------|------|------| | key | string | Experiment key (filled in when creating in the console) | | options.default | object | `payload` returned when not participating, default `{}` | | options.expose | boolean | When `false`, only read and freeze without reporting exposure; report exposure later using `expose(key)`. Default is `true`. | **Return value:** `ExperimentResult` | Field | Type | Description | |------|------|------| | inExperiment | boolean | Whether to participate (full `rollout` is also `true`) | | variant | string | Group key; empty if not participating `''` | | vid | number \| null | Variant ID (Experiment × Round × Group, unique within the project); `null` if not participating. | | payload | object | Group parameters (JSON filled in the console for the group); if not participating, it is `options.default ?? {}`. | | reason | string | See the table below. | | reason | Meaning | |--------|------| | `alloc` | Enter this group based on traffic allocation. | | `override` | Hit the mandatory list | | `rollout` | The experiment is fully enabled for this group; **do not report exposure, and do not include in `exp_vids`**. | | `unknown` | This device's result does not include this experiment (the experiment does not exist, has not been run, has not targeted the audience or traffic, and the client does not distinguish); or this is a server-side experiment (see "Server-side Experiment"). | | `not_loaded` | This experiment belongs to a namespace that has not yet been loaded on this page (first call `ready({ namespaces: [...] })`); **do not freeze**. | | `no_result` | No local result yet (first access and result not yet received / SDK not initialized), or the result has not been successfully refreshed for over 7 days. | | `no_subject` | No device ID (analysis consent not granted) | | `paused` | The experiment was abruptly terminated within this page session (starting from version 2.8.0, see "Emergency Stop" below); **no freeze, no exposure**. | **Freeze Rule:** When a key is first `get`-ed on this page, the result (including `not_loaded` but excluding `unavailable`) is frozen until the page is unloaded; subsequent accesses to the same key always return the same result, even if a new result has arrived. Freezing applies only to the device at the time of reading: if analysis consent is withdrawn, `no_subject` is returned; upon re-consenting (with a new device ID), the result is re-read and frozen for the new device. New results affect only keys on this page that have not yet been read; keys that have already been read take effect only when the page is opened again. The sole exception is emergency stop. **Emergency Stop (from 2.8.0):** After the console executes an "emergency stop" on an experiment, the `emergency_stopped` field in the pulled results lists the corresponding key (only accepting complete responses; `not_modified` responses and responses discarded due to outdated `rules_version` are ignored, consistent with native behavior). Upon receiving this, the SDK immediately unfreezes it: subsequent `get` calls on this page return unassigned (`reason: 'paused'`, `payload` is `options.default ?? {}`), no longer report **exposure**, and its `vid` is removed from the set of exposed IDs. Events created thereafter will not include it in `exp_vids`, nor will `getRequestHeaders()`, `appendVidsToUrl()`, or `fetch()` carry it. One diagnostic message is sent per key (`onDiagnostic` receives `category: 'experiment'`, `code: 'EMERGENCY_STOPPED'`). Once the experiment resumes, the key remains stopped within this page; it is only re-read upon the **next page open**. When delegating to native within the app, the native handles it: after `get` retrieves the new native result (or `refresh()` re-syncs), the value within the page updates to unassigned. **Exposure Rules:** When participating in an experiment (`alloc` / `override`), `get` automatically reports an `$exp_exposure` event. For the same variant, there is a maximum of one report per page session and one per natural day (deduplicated via persistent storage); the business logic may call `get` repeatedly. No report is generated for variants not participating in the experiment or for `rollout`. Exposure events are reported via the analytics channel, so `analyticsConsent: 'granted'` is also required. `$exp_exposure` parameter: | Parameter | Description | |------|------| | vid | Variant ID | | exp_key | Experiment key | | exp_run | round | | exp_version | Experiment Configuration Version | | variant | Group key | | layer_key | Experiment Layer | | reason | `alloc` / `override` | | rules_version | The rule version corresponding to this result | | source | `web` (reported by the native when delegating to the native within the app, which is `h5`) | #### experiment.expose(key) Report exposure for experiments previously read using `get(key, { expose: false })`. The reported group is the one **frozen at the time of reading**. This is used for scenarios where the experiment must be read in advance, but the user may not see the variant (e.g., preloading resources). No operation is performed if the user was not enrolled, the `rollout` condition was not met, or this page has not read this key before. ```javascript const banner = SuperSDK.experiment.get('home_banner', { expose: false }); preload(banner.payload.image); // ...when the banner truly appears on the screen SuperSDK.experiment.expose('home_banner'); ``` #### experiment.getAll() For the Diagnosis and Debugging Panel: Returns `{ [key]: ExperimentResult & { type } }`, containing all experiments (client and server) the current device participates in and the keys frozen on this page. `type` is `'client'` or `'server'` (since 2.7.0). **Not frozen, not exposed**; frozen keys return the frozen value. Business logic must use `get(key)`. #### experiment.refresh() Actively pull once. On network failure or rate limiting, reject with `NETWORK_ERROR` / `TIMEOUT` / `RATE_LIMITED` / `UNAVAILABLE` (local results remain available); if the server rejects (e.g., `spid` does not exist), reject with `INVALID_ARGUMENT` and include `nativeCode`. #### experiment.setAttributes(attributes) Set custom audience attributes (corresponding to `attr.*` in the console audience conditions), debounce for 500ms, then refetch. ```javascript SuperSDK.experiment.setAttributes({ vip: '1', level: 12 }); // Report as attr.vip="1", attr.level="12" SuperSDK.experiment.setAttributes({ vip: null }); // null / undefined Remove this property ``` - The key can be written as `vip` or `attr.vip`, allowing only letters, digits, and underscores; if it contains the `attr.` prefix, it must not exceed 64 characters. The value must be a string, number, or boolean, and its string representation must not exceed 256 characters. A maximum of 20 key-value pairs are allowed. If these constraints are violated, `INVALID_ARGUMENT` is thrown during synchronization. - Attributes are stored only in the current page's memory and are not persisted to disk; they must be reconfigured each time the page is opened. - Automatically included built-in properties of the SDK: `platform: 'web'` and `language` (original value of `navigator.language`) for pure browser environments; `platform` (`android` / `ios`) and `app_version` for in-app environments. #### Event public parameters exp_vids After exposure, the SDK automatically appends `exp_vids` to every tracking event created thereafter: the variant IDs exposed on this device, sorted in ascending order and comma-separated, e.g., `"10231,10388"`. You can directly filter by it during analysis (e.g., `exp_vids like '%10388%'`). - Take the value based on the **event creation time**: events generated by calling `reportEvent` before exposure and still in the queue to be uploaded will not include the `vid` from subsequent exposure. - Persist the set of exposed items, maintaining cross-page session validity until the experiment round concludes (the server returns a list of VIDs still in progress when fetching results, and automatically removes those that have ended). - The field is omitted when the collection is empty; a maximum of 500 is allowed, and new `vid`s are not added beyond this limit (exposure events are still reported normally, and `onDiagnostic` receives `category: 'experiment', code: 'EXP_VIDS_LIMIT'`). - `exp_vids` is maintained by the SDK: fields with the same name passed in `addEventCommonParam` are ignored in the `reportEvent` parameters. #### Server experiment 2.Starting from version 7.0, the groupings of server-side experiments (console type "server-side") are utilized by the business backend: the front end sends the **set of variant IDs already exposed** on this device to the backend along with the request, and the backend proceeds to the corresponding branch based on this. The value and event public parameter `exp_vids` represent the same set and the same string (sorted in ascending order, comma-separated), with two methods of carrying: - Request header `X-Super-AB-Vids: 10231,10388,10412` - query parameter `super_ab_vids=10231,10388,10412` (used in scenarios where request headers cannot be set: page navigation, initial screen document requests, `sendBeacon`, `EventSource`, WebSocket handshake, form submission, `` / `

Native Block example

Page content...

``` > **Important Notes:** > 1. The content of the Native Block is provided by the host app, and the SDK is only responsible for position synchronization. > 2. The host app needs to implement the `INativeBlockProvider` interface and register it. > 3. `blockType` is defined by the host app and must be agreed upon with the host app to support the specified types. > 4. The page automatically cleans up all Blocks when closed, or you can manually call `destroyAll()`. --- ### Response code (suenc) `suenc` is a lightweight response obfuscation protocol uniformly maintained by SuperSDK: when explicitly requested by the client, the server encodes the JSON response body using a custom Base64 table and returns `X-Su-Enc: b64t1`. > ⚠️ **It is only used to reduce the effectiveness of generic keyword scanning and rule matching, not for encryption**. It does not provide confidentiality, tamper resistance, or replay protection, and cannot prevent an attacker who has obtained the client-side code from restoring the encoding table. **Requests initiated by SuperSDK itself are automatically decoded** (e.g., settings / reportEvent / attribution / short links, etc.), so business-side intervention is not required. The following two APIs are intended for **fetch requests initiated by the business side**. #### getSuEncCapabilities() Query the codecs supported by the current runtime to decide whether to send `suenc=1`. This method does not exist in older SDK versions; therefore, you must perform an existence check first. ```javascript const capabilities = SuperSDK.getSuEncCapabilities(); // { supported: true, codecs: ['b64t1'] } const canUseSuEnc = typeof SuperSDK.getSuEncCapabilities === 'function' && capabilities.supported && capabilities.codecs.includes('b64t1'); ``` **Return value**: `{ supported: boolean, codecs: string[] }` (synchronous return, frozen object) #### decodeSuEnc(encodedData, codec) Decode the `suenc` response body and return the raw UTF-8 JSON text. **Synchronous pure function**, no JSBridge round-trip. | Parameter | Type | Required | Description | |------|------|:----:|------| | encodedData | string | Yes | Complete encoded response body returned by the server | | codec | string | Yes | The **raw value** of the `X-Su-Enc` header, custom encoding tables are not supported. | ```javascript // Only append suenc=1 after confirming support. const url = canUseSuEnc ? `${api}?suenc=1` : api; const response = await fetch(url); const codec = response.headers.get('X-Su-Enc'); if (codec) { const decoded = SuperSDK.decodeSuEnc(await response.text(), codec); return JSON.parse(decoded); } // 🔴 If the current request includes suenc=1 but receives a response without headers, it must be marked as failed (to prevent plaintext downgrade). // Do not directly pass plaintext responses to the business logic. if (canUseSuEnc) throw new Error('SUENC_DOWNGRADE'); return response.json(); ``` **Error Codes** (all are `SuperSDKError`, `error.code` can be used to determine): | Error Codes | Trigger conditions | |--------|----------| | `UNSUPPORTED_SUENC_CODEC` | `X-Su-Enc` points to an unknown codec on this side; **will not** attempt other encoding tables. | | `SUENC_DECODE_FAILED` | Invalid characters, length not a multiple of 4, or invalid padding position or count. | | `SUENC_INVALID_UTF8` | Decoded result is not valid UTF-8 | > **Important Notes:** > 1. **`codec` must be directly taken from the response header value**, do not hard-code it, so that no business code changes are needed when `b64t2` is added in the future. > 2. Decoding failures are uniformly treated as request failures; **falling back to read plaintext is absolutely prohibited**—that is precisely the downgrade the protocol aims to prevent. > 3. Encoded volume increases by approximately 33%; binary responses (APK / ZIP / images / file streams) are not obfuscated. > 4. The encoding table never changes after the SDK is released; new tables must use a new codec key. --- ## 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 **❌ 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. ### 2. Blind Pipeline Timing (IAP · Android) ```mermaid 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
setObfuscatedAccountId(accountId)
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) - `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) 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 key | Required | Built-in pay mapping | Backend retrieval | |---------|------|---------------|---------| | `productId` | **Yes** | `launchBillingFlow` product (missing → `phase:'pay'` error) | - | | `productType` | No | `'inapp'` (default) → `ProductType.INAPP`; `'subs'` → `ProductType.SUBS` | - | | `basePlanId` | When `productType='subs'`, it **is** | Match the base plan in the user's available `SubscriptionOfferDetails`. | base plan of subscriptionsv2 | | `offerId` | No | Match the offer precisely when passing the value; omit it to match the base-plan offer where `offerId == null`. | offer for subscriptionsv2 | | `accountId` | No | `setObfuscatedAccountId`(user identifier) | Signature verification API `obfuscatedExternalAccountId` | | `profileId` | No · 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) | status | Meaning | Does it contain a receipt? | H5 Handling | |---|---|---|---| | `finished` | Platform has accepted · **Process ended normally ≠ Payment successful** | ❌ Not included | Use `orderToken` to query the business order for the definitive truth; Google PENDING / ITEM_ALREADY_OWNED also fall into this state. | | `cancelled` | User cancelled | ❌ | Silent | | `error` | Failed · 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 > 🔴 **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): ```json { "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) **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) The business backend must implement the following endpoints (this feature defines only the contract, not the backend implementation): | Endpoint | Who calls | Input parameters | Output parameters | |------|------|------|------| | Create single endpoint | `provider.createOrder`(business JS fetch) | payParams | `{ orderToken(🔴 UUID required on both platforms), ...host-defined JSON fields }` | | Receipt endpoint (receiptUrl) | **PayBridge**(host app initialization configuration) | ReceiptPayload | HTTP 2xx = Accepted | | Query order endpoint | H5 (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](https://developer.android.com/google/play/billing/rtdn-reference) · [Google Play Developer API](https://developers.google.com/android-publisher) · [App Store Server Notifications V2](https://developer.apple.com/documentation/appstoreservernotifications) · [App Store Server API](https://developer.apple.com/documentation/appstoreserverapi) ### 9. Common Questions **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. --- ## Complete example ```javascript // Page initialization async function init() { // Check environment if (!SuperSDK.isInApp()) { console.log('Open this page in the app'); return; } // Get environment information try { const env = await SuperSDK.getEnv(); console.log('Current WebView ID:', env.webviewId); console.log('App version:', env.versionName); } catch (error) { console.error('Could not read environment information:', error); } // Monitor lifecycle SuperSDK.onForeground((data) => { console.log('Page active'); refreshData(); }); SuperSDK.onBackground((data) => { console.log('Page entered background'); pauseVideo(); }); // Listen to broadcast messages SuperSDK.subscribe('user_logout', () => { location.reload(); }); } // Share feature function shareToFriends() { SuperSDK.share('Try this app'); } // Open detail page function openDetail(id) { SuperSDK.openPage(`https://example.com/detail/${id}`); } // Close the page after completion. function onComplete() { // Notify other pages to refresh SuperSDK.publish('order_created', { orderId: '12345' }); // Close current page SuperSDK.closePage(); } init(); ``` ## Notes 1. **Environment Detection**: Always use `isInApp()` to detect the runtime environment and ensure code compatibility. 2. **Asynchronous methods**: `getEnv`, `getHostSettings`, etc. return Promises and require `await` or `.then()`. 3. **Cancel Listener**: `onForeground`, `onBackground`, and `subscribe` return a cancel function to be called when the component unmounts; `onBackPressed` uses `offBackPressed()` to cancel. 4. **TAB Page**: `closePage()` has no effect in the TAB page. 5. **Internal Interface**: `onJSBridgeReady` is automatically invoked by the SDK; business code should not call it explicitly. 6. **Timeout Handling**: Asynchronous methods will be rejected and return a `TIMEOUT` error after timeout. The timeout durations for each method are as follows: - **5 seconds**: `getEnv`, `getAppName`, `getAppIcon`, `getHostSettings`/`ByKey`, `fileExists`, `createDir`, `reportEvent`, `pay.getProviders`, `hideBannerAd` - **10 seconds**: `requestShortUrl`, `requestShortUrlWithHtml`, `deleteFile`, `moveFile`, `listDir` - **30 seconds**: `getFileMd5`, `readFile`, `writeFile`, `getAttribution`, `pay.restorePurchases`, `showBannerAd` - **60 seconds**: `unzipFile`, `zipDir`, `requestLogin`, `showInterstitialAd` - **120 seconds**: `showRewardAd`, `showRewardedInterstitialAd` - **190 seconds**: `pay.purchase` (Native IAP path, including the user's operation time in the payment interface; the Web checkout inline path has no fixed timeout and uses polling based on `pollInterval × maxPolls`). - **No Timeout**: `callHostMethod`, `downloadFile` (long-running tasks, requiring business-layer control).