Modern Apps git

← Modern-Apps.git

shop: pay in app via UCP Embedded Checkout (merchant checkout in a WebView, origin-scoped ECP bridge)

Commit
b2b14839d25ab32c8c47b15e347799f791948ac3
Author
Vayun Mathur <[email protected]>
When
2026-11-01 20:48 UTC (1 month ago)
Parents
22b2eb6

Diff

metadata_data/shop.md
diff --git a/metadata_data/shop.md b/metadata_data/shop.mdindex 1e088ff038..ba32fd83d5 100644--- a/metadata_data/shop.md+++ b/metadata_data/shop.md@@ -8,6 +8,6 @@ Features: - Prepare checkout sessions with per-merchant totals plus authoritative checkout totals and legal links - Save your name, contact details and delivery address once in an encrypted profile; checkout fills them in automatically - Pending sessions and cart lines survive browser handoffs and partial failures without confirming a paid order-- Native payment completion stays disabled without a supported handler, provider approval, and authorized merchant access+- Pay in app inside the store's own secure checkout, already filled in from your profile; completed orders appear under Orders  Requires internet
shop/AGENTS.md
diff --git a/shop/AGENTS.md b/shop/AGENTS.mdindex 75dc8d9df0..b601ef29fd 100644--- a/shop/AGENTS.md+++ b/shop/AGENTS.md@@ -15,7 +15,7 @@ Entry types: MainActivity, Route, Navigation. Navigation remains a root-only gra - Checkout takes no buyer input: every session field comes from the saved profile (`ProfileCheckout`). Merchant shipping-option choices remain selectable. Merchant totals and legal links are authoritative. - Checkout writes require explicit user action and a stable idempotency key per intent. Never replay an uncertain mutation automatically. One Create press may issue a second write that carries the saved delivery address, only after the create succeeded and the merchant advertised shipping or reported `delivery_address_required`. - Preserve cart lines through partial failures and browser handoffs. A session or browser return is not a paid order.-- No raw card entry, wallet tokenization, completion or authenticated order-read integration while provider authorization is unavailable.+- Payment happens only inside the merchant's own checkout via UCP Embedded Checkout (ECP) without payment delegation: `ui/EmbeddedCheckoutScreen` loads the merchant `continue_url` with `ec_version`/`ec_color_scheme`/`ec_delegate=window.open` in a WebView. The app never sees card data or tokens and never calls Complete Checkout. The `EmbeddedCheckoutProtocolConsumer` bridge is an origin-scoped `WebViewCompat.addWebMessageListener` (merchant domain, its subdomains, the handoff host, shop.app); `domain/EmbeddedCheckout` answers `ec.ready`, opens `ec.window.open_request` links in a Custom Tab, and treats `ec.complete` as the only completion signal. Only the order id, order permalink and total are persisted; the session URL stays in memory. - Only supported integer quantities can be added. Detail refresh sends the product ID and selected options, and must confirm the exact variant before cart actions. If a valid detail response returns only another featured option, one fresh advertised merchant search may confirm the exact SKU. Cached snapshots and empty lookup responses are not verification; denied/rate-limited calls are never retried automatically. - Use variant seller identity for Global Catalog routing, not the shop.app product-page host. Show store names (cart lines and pending orders persist `storeName`); fall back to the domain only when no name is known. - Product HTML is converted to inert styled text without a WebView; only validated public HTTPS description links may open externally.
shop/build.gradle.kts
diff --git a/shop/build.gradle.kts b/shop/build.gradle.ktsindex 257bd303d7..7dfb3d6a79 100644--- a/shop/build.gradle.kts+++ b/shop/build.gradle.kts@@ -26,4 +26,6 @@ dependencies {     // Buyer profile (name, contact, delivery address), encrypted at rest.     implementRoom(libs)     implementation(project(":library:room"))+    // Embedded Checkout bridge (origin-scoped web message listener) and in-page Payment Request.+    implementation(libs.androidx.webkit) }
shop/src/main/AndroidManifest.xml
diff --git a/shop/src/main/AndroidManifest.xml b/shop/src/main/AndroidManifest.xmlindex 07abf7003a..9cdf1f7466 100644--- a/shop/src/main/AndroidManifest.xml+++ b/shop/src/main/AndroidManifest.xml@@ -5,6 +5,19 @@     <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> +    <!-- Lets the embedded checkout's Payment Request find wallet apps such as Google Pay. -->+    <queries>+        <intent>+            <action android:name="org.chromium.intent.action.PAY" />+        </intent>+        <intent>+            <action android:name="org.chromium.intent.action.IS_READY_TO_PAY" />+        </intent>+        <intent>+            <action android:name="org.chromium.intent.action.UPDATE_PAYMENT_DETAILS" />+        </intent>+    </queries>+     <application         android:allowBackup="false"         android:dataExtractionRules="@xml/data_extraction_rules"
shop/src/main/java/com/vayunmathur/shop/Navigation.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt b/shop/src/main/java/com/vayunmathur/shop/Navigation.ktindex ad8c463895..a54ea7213a 100644--- a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt+++ b/shop/src/main/java/com/vayunmathur/shop/Navigation.kt@@ -8,6 +8,7 @@ import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.shop.platform.ShopViewModel import com.vayunmathur.shop.ui.CartScreen import com.vayunmathur.shop.ui.CheckoutScreen+import com.vayunmathur.shop.ui.EmbeddedCheckoutScreen import com.vayunmathur.shop.ui.OrdersScreen import com.vayunmathur.shop.ui.ProductScreen import com.vayunmathur.shop.ui.ProfileScreen@@ -52,7 +53,14 @@ fun Navigation(viewModel: ShopViewModel) {             CartScreen(viewModel, onCheckout = { backStack.add(Route.Checkout) })         }         entry<Route.Checkout> {-            CheckoutScreen(viewModel = viewModel, onBack = { backStack.pop() })+            CheckoutScreen(+                viewModel = viewModel,+                onBack = { backStack.pop() },+                onPayInApp = { backStack.add(Route.EmbeddedCheckout) },+            )+        }+        entry<Route.EmbeddedCheckout> {+            EmbeddedCheckoutScreen(viewModel = viewModel, onClose = { backStack.pop() })         }         entry<Route.Orders> { OrdersScreen(viewModel = viewModel) }     }
shop/src/main/java/com/vayunmathur/shop/Route.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/Route.kt b/shop/src/main/java/com/vayunmathur/shop/Route.ktindex 8e9e94d79f..2f4053f6e5 100644--- a/shop/src/main/java/com/vayunmathur/shop/Route.kt+++ b/shop/src/main/java/com/vayunmathur/shop/Route.kt@@ -23,4 +23,8 @@ sealed interface Route : NavKey {      @Serializable     data object Orders : Route++    /** Request (with its secret-bearing URL) lives in ShopViewModel, never in saved state. */+    @Serializable+    data object EmbeddedCheckout : Route }
shop/src/main/java/com/vayunmathur/shop/data/EmbeddedCheckoutRequest.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/EmbeddedCheckoutRequest.kt b/shop/src/main/java/com/vayunmathur/shop/data/EmbeddedCheckoutRequest.ktnew file mode 100644index 0000000000..22004d8792--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/EmbeddedCheckoutRequest.kt@@ -0,0 +1,12 @@+package com.vayunmathur.shop.data++/** An open Embedded Checkout session. In-memory only; [url] carries a merchant session key. */+data class EmbeddedCheckoutRequest(+    val platformId: String,+    val shopDomain: String,+    val storeName: String,+    val url: String,+    val browserUrl: String,+) {+    override fun toString(): String = "EmbeddedCheckoutRequest($shopDomain)"+}
shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.kt b/shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.ktnew file mode 100644index 0000000000..f906e3fd5f--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.kt@@ -0,0 +1,121 @@+package com.vayunmathur.shop.domain++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonArray+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull+import kotlinx.serialization.json.put++/** What the host should do with one message from the merchant's Embedded Checkout. */+sealed interface EcAction {+    data class Reply(val json: String) : EcAction+    data class OpenWindow(val id: JsonElement, val url: String) : EcAction+    data class Completed(val orderId: String, val permalinkUrl: String?, val totalMinor: Long?) : EcAction+    data class Failed(val message: String) : EcAction+    data object Ignore : EcAction+}++/**+ * UCP Embedded Checkout Protocol host logic without payment delegation: the merchant page+ * handles payment; the host only completes the handshake, opens links and observes completion.+ * Buyer data in checkout payloads is never retained.+ */+object EmbeddedCheckout {+    const val VERSION = "2026-08-25"+    private const val METHOD_NOT_FOUND = -32601+    private val json = Json { ignoreUnknownKeys = true }++    fun embeddedUrl(continueUrl: String, dark: Boolean): String? {+        val base = MerchantUrls.httpsUrl(continueUrl) ?: return null+        val separator = if ('?' in base) '&' else '?'+        val scheme = if (dark) "dark" else "light"+        return "$base${separator}ec_version=$VERSION&ec_color_scheme=$scheme&ec_delegate=window.open"+    }++    fun handle(message: String): EcAction {+        val obj = runCatching { json.parseToJsonElement(message).jsonObject }.getOrNull() ?: return EcAction.Ignore+        val method = obj["method"]?.jsonPrimitive?.contentOrNull ?: return EcAction.Ignore+        val id = obj["id"]+        val params = obj["params"] as? JsonObject+        return when (method) {+            "ec.ready" -> id?.let { EcAction.Reply(success(it)) } ?: EcAction.Ignore+            "ec.window.open_request" -> {+                val url = (params?.get("url") as? JsonPrimitive)?.contentOrNull?.let(MerchantUrls::httpsUrl)+                when {+                    id == null -> EcAction.Ignore+                    url == null -> EcAction.Reply(windowOpenResult(id, ok = false))+                    else -> EcAction.OpenWindow(id, url)+                }+            }+            "ec.complete" -> completed(params)+            "ec.error" -> EcAction.Failed(errorText(params))+            else -> if (id != null) EcAction.Reply(methodNotFound(id, method)) else EcAction.Ignore+        }+    }++    fun windowOpenResult(id: JsonElement, ok: Boolean): String = buildJsonObject {+        put("jsonrpc", "2.0")+        put("id", id)+        put("result", buildJsonObject {+            put("ucp", ucp(if (ok) "success" else "error"))+            if (!ok) {+                put("messages", buildJsonArray {+                    add(buildJsonObject {+                        put("type", "error")+                        put("code", "window_open_rejected_error")+                        put("content", "Window open rejected by host")+                    })+                })+            }+        })+    }.toString()++    private fun success(id: JsonElement): String = buildJsonObject {+        put("jsonrpc", "2.0")+        put("id", id)+        put("result", buildJsonObject { put("ucp", ucp("success")) })+    }.toString()++    private fun methodNotFound(id: JsonElement, method: String): String = buildJsonObject {+        put("jsonrpc", "2.0")+        put("id", id)+        put("error", buildJsonObject {+            put("code", METHOD_NOT_FOUND)+            put("message", "Unsupported by host: $method")+        })+    }.toString()++    private fun ucp(status: String) = buildJsonObject {+        put("version", VERSION)+        put("status", status)+    }++    private fun completed(params: JsonObject?): EcAction {+        val checkout = params?.get("checkout") as? JsonObject ?: return EcAction.Ignore+        val order = checkout["order"] as? JsonObject+        val orderId = (order?.get("id") as? JsonPrimitive)?.contentOrNull+            ?: (checkout["id"] as? JsonPrimitive)?.contentOrNull+            ?: return EcAction.Ignore+        val permalink = (order?.get("permalink_url") as? JsonPrimitive)?.contentOrNull?.let(MerchantUrls::httpsUrl)+        return EcAction.Completed(orderId, permalink, totalMinor(checkout))+    }++    private fun totalMinor(checkout: JsonObject): Long? =+        (checkout["totals"] as? kotlinx.serialization.json.JsonArray)+            ?.mapNotNull { it as? JsonObject }+            ?.firstOrNull { (it["type"] as? JsonPrimitive)?.contentOrNull == "total" }+            ?.let { (it["amount"] as? JsonPrimitive)?.longOrNull }++    private fun errorText(params: JsonObject?): String {+        val error = params?.get("error") as? JsonObject+        return (error?.get("message") as? JsonPrimitive)?.contentOrNull+            ?: (error?.get("content") as? JsonPrimitive)?.contentOrNull+            ?: "The store's checkout reported an error."+    }+}
shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.ktindex 1c48142d76..3cae1ba284 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt@@ -58,6 +58,12 @@ internal class NativeCheckoutCoordinator(         }     } +    fun forget(platform: String, shop: String) {+        val key = platform to shop+        if (states.remove(key) != null) changed(snapshot)+        createdAt.remove(key)+    }+     fun refreshExpiry() {         states.toMap().forEach { (key, state) ->             if (!state.busy && state.checkout != null && state.phase != CheckoutPhase.Uncertain && expired(key, state.checkout)) {
shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.ktindex f2600dd26b..3548b05101 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -14,6 +14,8 @@ import com.vayunmathur.shop.domain.PendingCheckoutSink import com.vayunmathur.shop.data.CartLine import com.vayunmathur.shop.data.MerchantListing import com.vayunmathur.shop.data.OrderStore+import com.vayunmathur.shop.data.EmbeddedCheckoutRequest+import com.vayunmathur.shop.data.Money import com.vayunmathur.shop.data.PlacedOrder import com.vayunmathur.shop.data.ProfileRepository import com.vayunmathur.shop.data.ShopCartStore@@ -21,6 +23,7 @@ import com.vayunmathur.shop.data.ShopProfile import com.vayunmathur.shop.data.UcpCheckout import com.vayunmathur.shop.data.UcpProduct import com.vayunmathur.shop.data.message+import com.vayunmathur.shop.domain.EmbeddedCheckout import com.vayunmathur.shop.domain.MerchantLink import com.vayunmathur.shop.domain.MerchantLinks import com.vayunmathur.shop.domain.MerchantUrls@@ -49,6 +52,9 @@ class ShopViewModel(         private set     private var merchants: List<MerchantListing>? = null     var launchLinkHandled = false+    /** Held in memory only: the URL carries a merchant session key. */+    var embeddedCheckout by mutableStateOf<EmbeddedCheckoutRequest?>(null)+        private set     var results by mutableStateOf<List<UcpProduct>>(emptyList())         private set     var searching by mutableStateOf(false)@@ -271,6 +277,38 @@ class ShopViewModel(     fun dismissCheckoutError() { checkoutError = null }     fun dismissSearchError() { searchError = null } +    fun openEmbeddedCheckout(platformId: String, shop: String, continueUrl: String, dark: Boolean): Boolean {+        val url = EmbeddedCheckout.embeddedUrl(continueUrl, dark) ?: return false+        val storeName = cart.firstOrNull { it.platformId == platformId && it.shopDomain == shop }?.displayName ?: shop+        embeddedCheckout = EmbeddedCheckoutRequest(platformId, shop, storeName, url, continueUrl)+        return true+    }++    fun closeEmbeddedCheckout() { embeddedCheckout = null }++    /** The merchant's `ec.complete` is the only signal that an order was placed and paid. */+    fun embeddedCheckoutCompleted(orderId: String, permalinkUrl: String?, totalMinor: Long?, context: Context) {+        val request = embeddedCheckout ?: return+        val lines = cart.filter { it.platformId == request.platformId && it.shopDomain == request.shopDomain }+        val currency = lines.firstOrNull()?.unitPrice?.currency ?: "USD"+        val total = totalMinor ?: lines.sumOf { it.unitPrice.amount * it.quantity }+        val order = PlacedOrder(+            checkoutId = orderId, placedAtMs = System.currentTimeMillis(), total = Money(total, currency),+            itemCount = lines.sumOf { it.quantity }, continueUrl = permalinkUrl.orEmpty(), status = "completed",+            platformId = request.platformId, shopDomain = request.shopDomain, storeName = request.storeName,+            lines = lines.map { it.copy(imageUrl = "") },+        )+        cart = cart - lines.toSet()+        ShopCartStore.save(context, cart)+        nativeCheckout.forget(request.platformId, request.shopDomain)+        nativeCheckout.cartChanged(cart)+        embeddedCheckout = null+        viewModelScope.launch {+            OrderStore.add(context, order)+            orders = OrderStore.getAll(context)+        }+    }+     private fun Throwable.toBackendMessage(): String =         (this as? ShopBackendException)?.error?.message()             ?: "Couldn't reach the store. Check your connection and try again."
shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.ktindex 9e42f9df12..67342badd6 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt@@ -1,5 +1,6 @@ package com.vayunmathur.shop.ui +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize@@ -19,6 +20,7 @@ import com.vayunmathur.library.ui.DetailSection import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.shop.R import com.vayunmathur.shop.data.CheckoutPhase@@ -31,8 +33,9 @@ import kotlinx.coroutines.isActive  /** Native session review only. Payment and purchase confirmation remain on the merchant website. */ @Composable-fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit) {+fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit, onPayInApp: () -> Unit) {     val context = LocalContext.current+    val dark = isSystemInDarkTheme()     LaunchedEffect(viewModel) {         while (isActive) { viewModel.refreshCheckoutExpiry(); delay(1000) }     }@@ -81,13 +84,19 @@ fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit) {                         val merchantSiteUrl = MerchantUrls.domain(key.second)?.let { "https://$it" }                         val checkoutUrl = (checkout?.continueUrl ?: state.handoffUrl)?.let(MerchantUrls::httpsUrl)                         val cartUrl = MerchantUrls.shopifyCartUrl(key.second, lines.map { it.variantId to it.quantity })-                        (checkoutUrl ?: cartUrl ?: merchantSiteUrl)?.let { url ->-                            OutlinedButton(modifier = Modifier.fillMaxWidth(), onClick = { openContinueUrl(context, url) }) {-                                Text(when (url) {-                                    checkoutUrl -> "Continue checkout on merchant website"-                                    cartUrl -> "Open cart on merchant website"-                                    else -> "Open merchant website"-                                })+                        if (checkoutUrl != null) {+                            Button(+                                modifier = Modifier.fillMaxWidth(),+                                onClick = {+                                    if (viewModel.openEmbeddedCheckout(key.first, key.second, checkoutUrl, dark)) onPayInApp()+                                },+                            ) { Text("Pay in app") }+                            TextButton(onClick = { openContinueUrl(context, checkoutUrl) }) { Text("Open in browser") }+                        } else {+                            (cartUrl ?: merchantSiteUrl)?.let { url ->+                                OutlinedButton(modifier = Modifier.fillMaxWidth(), onClick = { openContinueUrl(context, url) }) {+                                    Text(if (url == cartUrl) "Open cart on merchant website" else "Open merchant website")+                                }                             }                         }                     }
shop/src/main/java/com/vayunmathur/shop/ui/EmbeddedCheckoutScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/EmbeddedCheckoutScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/EmbeddedCheckoutScreen.ktnew file mode 100644index 0000000000..0d4319587c--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/ui/EmbeddedCheckoutScreen.kt@@ -0,0 +1,193 @@+package com.vayunmathur.shop.ui++import android.annotation.SuppressLint+import android.content.ActivityNotFoundException+import android.content.Intent+import android.net.Uri+import android.webkit.CookieManager+import android.webkit.WebResourceError+import android.webkit.WebResourceRequest+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.activity.compose.BackHandler+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import androidx.compose.ui.viewinterop.AndroidView+import androidx.webkit.WebSettingsCompat+import androidx.webkit.WebViewCompat+import androidx.webkit.WebViewFeature+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconLanguage+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.shop.data.EmbeddedCheckoutRequest+import com.vayunmathur.shop.domain.EcAction+import com.vayunmathur.shop.domain.EmbeddedCheckout+import com.vayunmathur.shop.domain.MerchantUrls+import com.vayunmathur.shop.platform.ShopViewModel++private const val BRIDGE = "EmbeddedCheckoutProtocolConsumer"++/**+ * Hosts the merchant's own checkout (UCP Embedded Checkout, no payment delegation). Payment is+ * entered on the merchant page; the app only answers the handshake, opens links and records+ * completion. The bridge is injected only into the merchant's origins.+ */+@Composable+fun EmbeddedCheckoutScreen(viewModel: ShopViewModel, onClose: () -> Unit) {+    val request = viewModel.embeddedCheckout+    if (request == null) {+        onClose()+        return+    }+    val context = LocalContext.current+    val messenger = rememberMessenger()+    var loading by remember { mutableStateOf(true) }+    var failed by remember { mutableStateOf(false) }+    var webView by remember { mutableStateOf<WebView?>(null) }+    val close = {+        viewModel.closeEmbeddedCheckout()+        onClose()+    }+    BackHandler {+        val view = webView+        if (view != null && view.canGoBack()) view.goBack() else close()+    }+    DisposableEffect(Unit) { onDispose { webView?.destroy() } }+    AppScaffold(+        title = request.storeName,+        onClose = close,+        actions = {+            IconButton(onClick = { openContinueUrl(context, request.browserUrl) }) { IconLanguage() }+        },+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        Box(Modifier.fillMaxSize().padding(padding)) {+            if (failed) {+                Column(+                    Modifier.align(Alignment.Center).padding(24.dp),+                    verticalArrangement = Arrangement.spacedBy(12.dp),+                    horizontalAlignment = Alignment.CenterHorizontally,+                ) {+                    Text("The store's checkout didn't load.")+                    Button(onClick = { openContinueUrl(context, request.browserUrl) }) { Text("Open in browser") }+                }+            } else {+                CheckoutWebView(+                    request = request,+                    onCreated = { webView = it },+                    onLoaded = { loading = false },+                    onFailed = { failed = true },+                    onAction = { view, action ->+                        when (action) {+                            is EcAction.Reply -> view.send(action.json)+                            is EcAction.OpenWindow -> {+                                openContinueUrl(context, action.url)+                                view.send(EmbeddedCheckout.windowOpenResult(action.id, ok = true))+                            }+                            is EcAction.Completed -> {+                                viewModel.embeddedCheckoutCompleted(action.orderId, action.permalinkUrl, action.totalMinor, context)+                                messenger.show("Order placed with ${request.storeName}")+                                onClose()+                            }+                            is EcAction.Failed -> messenger.show(action.message)+                            EcAction.Ignore -> Unit+                        }+                    },+                )+                if (loading) CircularProgressIndicator(Modifier.align(Alignment.Center))+            }+        }+    }+}++@SuppressLint("SetJavaScriptEnabled", "RequiresFeature")+@Composable+private fun CheckoutWebView(+    request: EmbeddedCheckoutRequest,+    onCreated: (WebView) -> Unit,+    onLoaded: () -> Unit,+    onFailed: () -> Unit,+    onAction: (WebView, EcAction) -> Unit,+) {+    AndroidView(+        modifier = Modifier.fillMaxSize(),+        factory = { context ->+            WebView(context).apply {+                settings.javaScriptEnabled = true+                settings.domStorageEnabled = true+                CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)+                if (WebViewFeature.isFeatureSupported(WebViewFeature.PAYMENT_REQUEST)) {+                    WebSettingsCompat.setPaymentRequestEnabled(settings, true)+                }+                if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {+                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(settings, false)+                }+                if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {+                    WebViewCompat.addWebMessageListener(this, BRIDGE, bridgeOrigins(request)) { view, message, _, isMainFrame, _ ->+                        val data = message.data+                        if (isMainFrame && data != null) onAction(view, EmbeddedCheckout.handle(data))+                    }+                }+                webViewClient = CheckoutClient(onLoaded, onFailed)+                onCreated(this)+                loadUrl(request.url)+            }+        },+    )+}++/** Merchant domain (and subdomains), the handoff host, and Shopify's hosted checkout. */+private fun bridgeOrigins(request: EmbeddedCheckoutRequest): Set<String> {+    val hosts = buildSet {+        MerchantUrls.domain(request.shopDomain)?.let { add(it.removePrefix("www.")) }+        Uri.parse(request.browserUrl).host?.let { add(it.removePrefix("www.")) }+    }+    return hosts.flatMap { listOf("https://$it", "https://*.$it") }.toSet() + "https://shop.app"+}++private fun WebView.send(json: String) {+    evaluateJavascript(+        "window.EmbeddedCheckoutProtocol&&window.EmbeddedCheckoutProtocol.postMessage($json)",+        null,+    )+}++private class CheckoutClient(private val onLoaded: () -> Unit, private val onFailed: () -> Unit) : WebViewClient() {+    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {+        val scheme = request.url.scheme?.lowercase()+        if (scheme == "https") return false+        // Bank apps, wallets and mailto links leave the checkout; plain http is never followed.+        if (scheme != "http") {+            try {+                view.context.startActivity(Intent(Intent.ACTION_VIEW, request.url).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+            } catch (_: ActivityNotFoundException) {+                // Nothing can handle it; stay on the checkout.+            }+        }+        return true+    }++    override fun onPageFinished(view: WebView, url: String?) = onLoaded()++    override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {+        if (request.isForMainFrame) onFailed()+    }+}
shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.ktindex b47e22f58e..7a0ab82c34 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.kt@@ -79,7 +79,11 @@ private fun OrderRow(order: PlacedOrder, onOpen: () -> Unit) {                     "${order.itemCount} item(s) · ${MoneyFormat.format(order.total)}",                     style = MaterialTheme.typography.titleSmall,                 )-                Text(stringResource(R.string.checkout_pending), style = MaterialTheme.typography.labelMedium)+                val completed = order.status == "completed"+                Text(+                    stringResource(if (completed) R.string.order_placed else R.string.checkout_pending),+                    style = MaterialTheme.typography.labelMedium,+                )                 if (order.displayName.isNotBlank()) Text(order.displayName, style = MaterialTheme.typography.bodySmall)                 Spacer(Modifier.height(2.dp))                 Text(@@ -92,7 +96,7 @@ private fun OrderRow(order: PlacedOrder, onOpen: () -> Unit) {             Spacer(Modifier.width(8.dp))             if (order.continueUrl.isNotBlank()) {                 Button(onClick = onOpen) {-                    Text(stringResource(R.string.continue_in_browser))+                    Text(stringResource(if (order.status == "completed") R.string.view_order else R.string.continue_in_browser))                 }             }         }
shop/src/main/res/values/strings.xml
diff --git a/shop/src/main/res/values/strings.xml b/shop/src/main/res/values/strings.xmlindex 92414cea6c..e25709cd0d 100644--- a/shop/src/main/res/values/strings.xml+++ b/shop/src/main/res/values/strings.xml@@ -14,6 +14,8 @@     <string name="place_order">Prepare checkout</string>     <string name="estimated_subtotal">Estimated subtotal</string>     <string name="checkout_pending">Payment not confirmed</string>+    <string name="order_placed">Order placed</string>+    <string name="view_order">View order</string>     <string name="checkout_handoff_notice">Review final prices, shipping and payment on the merchant site. Cart items remain until you remove them.</string>     <string name="buy_now">Buy now</string>     <string name="add_to_cart">Add to cart</string>
shop/src/test/java/com/vayunmathur/shop/domain/EmbeddedCheckoutTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/domain/EmbeddedCheckoutTest.kt b/shop/src/test/java/com/vayunmathur/shop/domain/EmbeddedCheckoutTest.ktnew file mode 100644index 0000000000..16b3fface9--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/domain/EmbeddedCheckoutTest.kt@@ -0,0 +1,70 @@+package com.vayunmathur.shop.domain++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue++class EmbeddedCheckoutTest {+    @Test+    fun embeddedUrlAppendsEcParams() {+        assertEquals(+            "https://allbirds.com/cart/c/abc?key=k&ec_version=2026-08-25&ec_color_scheme=dark&ec_delegate=window.open",+            EmbeddedCheckout.embeddedUrl("https://allbirds.com/cart/c/abc?key=k", dark = true),+        )+        assertEquals(+            "https://allbirds.com/checkout?ec_version=2026-08-25&ec_color_scheme=light&ec_delegate=window.open",+            EmbeddedCheckout.embeddedUrl("https://allbirds.com/checkout", dark = false),+        )+        assertNull(EmbeddedCheckout.embeddedUrl("http://allbirds.com/checkout", dark = false))+        assertNull(EmbeddedCheckout.embeddedUrl("https://localhost/checkout", dark = false))+    }++    @Test+    fun readyIsAnsweredWithMatchingIdAndVersion() {+        val reply = EmbeddedCheckout.handle("""{"jsonrpc":"2.0","id":"ready_1","method":"ec.ready","params":{"delegate":["window.open"]}}""")+        val json = Json.parseToJsonElement(assertIs<EcAction.Reply>(reply).json).jsonObject+        assertEquals("ready_1", json["id"]!!.jsonPrimitive.content)+        val ucp = json["result"]!!.jsonObject["ucp"]!!.jsonObject+        assertEquals("2026-08-25", ucp["version"]!!.jsonPrimitive.content)+        assertEquals("success", ucp["status"]!!.jsonPrimitive.content)+    }++    @Test+    fun windowOpenAcceptsOnlyPublicHttps() {+        val open = EmbeddedCheckout.handle("""{"jsonrpc":"2.0","id":7,"method":"ec.window.open_request","params":{"url":"https://allbirds.com/policies/privacy"}}""")+        assertEquals(EcAction.OpenWindow(JsonPrimitive(7), "https://allbirds.com/policies/privacy"), open)+        listOf("javascript:alert(1)", "intent://x#Intent;end", "https://localhost/x").forEach { url ->+            val rejected = EmbeddedCheckout.handle("""{"jsonrpc":"2.0","id":8,"method":"ec.window.open_request","params":{"url":"$url"}}""")+            assertTrue(assertIs<EcAction.Reply>(rejected).json.contains("window_open_rejected_error"), url)+        }+        assertTrue(EmbeddedCheckout.windowOpenResult(JsonPrimitive(7), ok = true).contains("\"success\""))+    }++    @Test+    fun completionKeepsOnlyOrderReferenceAndTotal() {+        val message = """{"jsonrpc":"2.0","method":"ec.complete","params":{"checkout":{"id":"checkout_123",+            "buyer":{"email":"[email protected]","first_name":"Ada"},+            "totals":[{"type":"subtotal","amount":9800},{"type":"total","amount":10584}],+            "order":{"id":"ord_1","permalink_url":"https://allbirds.com/orders/ord_1"}}}}"""+        val done = assertIs<EcAction.Completed>(EmbeddedCheckout.handle(message))+        assertEquals(EcAction.Completed("ord_1", "https://allbirds.com/orders/ord_1", 10584), done)+        assertFalse(done.toString().contains("[email protected]"))+    }++    @Test+    fun unknownRequestsGetMethodNotFoundAndNoiseIsIgnored() {+        val reply = EmbeddedCheckout.handle("""{"jsonrpc":"2.0","id":"p1","method":"ec.payment.credential_request","params":{}}""")+        assertTrue(assertIs<EcAction.Reply>(reply).json.contains("-32601"))+        assertEquals(EcAction.Ignore, EmbeddedCheckout.handle("""{"jsonrpc":"2.0","method":"ec.start","params":{}}"""))+        assertEquals(EcAction.Ignore, EmbeddedCheckout.handle("not json"))+        assertEquals(EcAction.Ignore, EmbeddedCheckout.handle("""{"jsonrpc":"2.0","result":{}}"""))+        assertIs<EcAction.Failed>(EmbeddedCheckout.handle("""{"jsonrpc":"2.0","method":"ec.error","params":{"error":{"message":"Session expired"}}}"""))+    }+}