Android (WebView + Play Billing)
Documents @snap4id-sdk/embed-protocol 1.0.0 · protocol 1.0
A sketch of the host side in Kotlin with AndroidX WebKit (androidx.webkit) and Play Billing: every piece the
host contract asks for. Message shapes: bridge messages.
The shim
Section titled “The shim”Ship this script with your app (generated from @snap4id-sdk/embed-protocol; refresh it on a new protocol major).
It posts page messages to the snap4idHost object that addWebMessageListener injects.
(function () { if (window.Snap4IdHost) return; var queue = []; var isReady = false; function deliver(json) { var bridge = window.Snap4IdBridge; if (bridge && typeof bridge.receive === 'function') bridge.receive(json); else queue.push(json); } window.Snap4IdHost = { postMessage: function (json) { snap4idHost.postMessage(json); }, ready: function () { isReady = true; var pending = queue; queue = []; pending.forEach(deliver); } }; window.__snap4idHostDeliver = function (json) { if (!isReady) { queue.push(json); return; } deliver(json); };})();true;WebView and bridge
Section titled “WebView and bridge”private val snap4id = setOf("https://snap4.id")
fun setUp(webView: WebView, shim: String) { webView.settings.javaScriptEnabled = true webView.settings.domStorageEnabled = true webView.settings.mediaPlaybackRequiresUserGesture = false
// Page → host, from the Snap4ID main frame only. WebViewCompat.addWebMessageListener(webView, "snap4idHost", snap4id) { _, message, origin, isMainFrame, _ -> if (isMainFrame && origin.toString() == "https://snap4.id") message.data?.let(::handle) } // The shim before the page's first script (else the page waits up to 1.5 s for a late one). if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { WebViewCompat.addDocumentStartJavaScript(webView, shim, snap4id) }
webView.webViewClient = object : WebViewClientCompat() { override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = request.isForMainFrame && !(request.url.scheme == "https" && request.url.host == "snap4.id") } webView.webChromeClient = object : WebChromeClient() { override fun onPermissionRequest(request: PermissionRequest) { // CAMERA granted to the app first if (request.origin.host == "snap4.id") request.grant(arrayOf(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) else request.deny() } override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean = launchPicker(callback, params) } webView.loadUrl("https://snap4.id/embed/your-partner-id")}
// Host → page: hand the JSON string to the shim's deliver function (main thread).fun send(webView: WebView, json: String) { webView.evaluateJavascript("window.__snap4idHostDeliver && window.__snap4idHostDeliver(${JSONObject.quote(json)});", null)}On the system back gesture: send back while the page reported canGoBack: true, else close the screen.
Answer hello
Section titled “Answer hello”Reply at once with replyTo = the page hello’s id and platform: "android". Then send price.result (also
replyTo = the page hello’s id) with the price of the product the page named for Google Play
(payload.productIds.android), from Play (queryProductDetailsAsync, oneTimePurchaseOfferDetails: formattedPrice
→ display_price; amount_minor = priceAmountMicros / 10_000 for two-decimal currencies; priceCurrencyCode);
no product ⇒ "products": {}.
Buy on purchase.request
Section titled “Buy on purchase.request”fun buy(activity: Activity, details: ProductDetails, paymentRef: String) { val params = BillingFlowParams.newBuilder() .setProductDetailsParamsList(listOf( BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(details).build())) .setObfuscatedProfileId(paymentRef) // = storeBinding.obfuscatedProfileId .build() billingClient.launchBillingFlow(activity, params)}
// PurchasesUpdatedListener: do NOT consume yet. Record the purchase for recovery first.fun resultFor(purchase: Purchase): JSONObject = when (purchase.purchaseState) { Purchase.PurchaseState.PURCHASED -> JSONObject() .put("status", "succeeded") .put("receipt", JSONObject().put("kind", "play") .put("originalJson", purchase.originalJson).put("signature", purchase.signature)) Purchase.PurchaseState.PENDING -> JSONObject().put("status", "pending") else -> JSONObject().put("status", "failed").put("reason", "unspecified")}Answer purchase.result with jobId, paymentRef, this outcome and the store price ({ amount_minor, currency }:
Play receipts carry no price), replyTo = the request’s id. USER_CANCELED answers cancelled. With your
backend checking receipts, send originalJson + signature to your backend first and answer succeeded without
receipt once it unlocked the job.
Consume after the unlock
Section titled “Consume after the unlock”suspend fun finishPurchase(purchase: Purchase) { billingClient.consumePurchase(ConsumeParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build())}Consume when job.completed arrives for the job (the page had the receipt checked) or when your own backend
confirmed the unlock, and for
a duplicate_purchase (then refund it). At every app start, queryPurchasesAsync (INAPP) lists what is still
unconsumed: unlock it (a pending purchase approved later becomes an unsolicited purchase.result while the page is
open), and reopen /embed/{partnerId}/job/{jobId} for paid jobs you have not delivered.
