Skip to content

iOS (WKWebView + StoreKit 2)

Documents @snap4id-sdk/embed-protocol 1.0.0 · protocol 1.0

A sketch of the host side in Swift: every piece the host contract asks for, without your app’s structure around it. Message shapes: bridge messages.

Ship this script with your app (it is generated from @snap4id-sdk/embed-protocol; refresh it when you update to a new protocol major). It posts page messages to the snap4idHost script message handler.

snap4id-shim.js
(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) { window.webkit.messageHandlers.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;
import WebKit
final class Snap4IdHostController: NSObject, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate {
let webView: WKWebView
private let handlerName = "snap4idHost"
init(shim: String) {
let content = WKUserContentController()
content.addUserScript(WKUserScript(source: shim, injectionTime: .atDocumentStart, forMainFrameOnly: true))
let config = WKWebViewConfiguration()
config.userContentController = content
config.allowsInlineMediaPlayback = true
webView = WKWebView(frame: .zero, configuration: config)
super.init()
content.add(self, name: handlerName) // weak-wrap in production to avoid a retain cycle
webView.navigationDelegate = self
webView.uiDelegate = self
}
func open(partnerId: String) {
webView.load(URLRequest(url: URL(string: "https://snap4.id/embed/\(partnerId)")!))
}
// Page → host: one JSON string per message, from the Snap4ID main frame only.
func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
let origin = message.frameInfo.securityOrigin
guard message.frameInfo.isMainFrame, origin.protocol == "https", origin.host == "snap4.id",
let json = message.body as? String else { return }
handle(json) // parse { v, id, type, payload, replyTo? }, validate, dispatch on type
}
// Host → page: hand the JSON string to the shim's deliver function.
func send(_ json: String) {
let literal = String(data: try! JSONEncoder().encode(json), encoding: .utf8)! // a JS string literal
webView.evaluateJavaScript("window.__snap4idHostDeliver && window.__snap4idHostDeliver(\(literal));")
}
// Only Snap4ID in the main frame; other links open outside (or not at all).
func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard action.targetFrame?.isMainFrame == true else { return decisionHandler(.allow) }
let url = action.request.url
decisionHandler(url?.scheme == "https" && url?.host == "snap4.id" ? .allow : .cancel)
}
// Camera for the capture step (NSCameraUsageDescription in Info.plist).
func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin,
initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType,
decisionHandler: @escaping (WKPermissionDecision) -> Void) {
decisionHandler(origin.host == "snap4.id" ? .grant : .deny)
}
}

The photo-library picker of <input type="file"> needs NSPhotoLibraryUsageDescription; saving to Photos needs NSPhotoLibraryAddUsageDescription.

Reply at once with replyTo = the page hello’s id:

{ "v": 1, "id": "<new uuid>", "type": "hello", "replyTo": "<page hello id>",
"payload": { "protocolVersion": "1.0", "platform": "ios", "appVersion": "4.2.0",
"consent": { "statistics": true }, "capabilities": { "save": true, "share": true } } }

Then send the price of the product the page named for the App Store (payload.productIds.ios), also with replyTo = the page hello’s id. It comes from StoreKit (Product.products(for: [id]): displayPrice; amount_minor from price in minor units, currency from priceFormatStyle.currencyCode); no product ⇒ "products": {}:

{ "v": 1, "id": "<new uuid>", "type": "price.result", "replyTo": "<page hello id>",
"payload": { "products": { "pl.example.app.idphoto": { "amount_minor": 1999, "currency": "PLN", "display_price": "19,99 zł" } } } }
import StoreKit
func buy(productId: String, appAccountToken: String) async throws -> [String: Any] {
guard let product = try await Product.products(for: [productId]).first,
let token = UUID(uuidString: appAccountToken) else { return ["status": "failed", "reason": "no_product"] }
switch try await product.purchase(options: [.appAccountToken(token)]) {
case .success(let verification):
// Do NOT finish yet. Record (paymentRef, transaction id) for recovery first.
return ["status": "succeeded", "receipt": ["kind": "app-store", "jws": verification.jwsRepresentation]]
case .pending:
return ["status": "pending"]
case .userCancelled:
return ["status": "cancelled"]
@unknown default:
return ["status": "failed", "reason": "unknown"]
}
}

Answer purchase.result with jobId, paymentRef and this outcome, replyTo = the request’s id. With your backend checking receipts, send the jws to your backend first and answer succeeded without receipt once it unlocked the job.

func finishPurchase(appAccountToken: UUID) async {
for await result in Transaction.unfinished {
if case .verified(let transaction) = result, transaction.appAccountToken == appAccountToken {
await transaction.finish()
}
}
}

Call it 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, walk Transaction.unfinished and listen to Transaction.updates: unlock what is still unfinished (an approved “Ask to Buy” becomes an unsolicited purchase.result while the page is open), and reopen /embed/{partnerId}/job/{jobId} for paid jobs you have not delivered.