|
| 1 | +/* |
| 2 | + * MIT License |
| 3 | + * |
| 4 | + * Copyright 2023-present, Shopify Inc. |
| 5 | + * |
| 6 | + * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | + * of this software and associated documentation files (the "Software"), to deal |
| 8 | + * in the Software without restriction, including without limitation the rights |
| 9 | + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | + * copies of the Software, and to permit persons to whom the Software is |
| 11 | + * furnished to do so, subject to the following conditions: |
| 12 | + * |
| 13 | + * The above copyright notice and this permission notice shall be included in all |
| 14 | + * copies or substantial portions of the Software. |
| 15 | + * |
| 16 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 22 | + */ |
| 23 | +package com.shopify.checkoutkit |
| 24 | + |
| 25 | +import android.net.Uri |
| 26 | +import com.shopify.checkoutkit.ShopifyCheckoutKit.log |
| 27 | +import kotlinx.serialization.json.Json |
| 28 | +import kotlinx.serialization.json.JsonElement |
| 29 | +import kotlinx.serialization.json.decodeFromJsonElement |
| 30 | +import kotlinx.serialization.json.jsonObject |
| 31 | + |
| 32 | +/** |
| 33 | + * Entry point for the typed Embedded Checkout Protocol (ECP) client. |
| 34 | + * |
| 35 | + * Provides static [NotificationDescriptor] instances for every EC notification method, |
| 36 | + * plus a fluent [Client] builder that implements [CheckoutCommunicationClient]. |
| 37 | + * |
| 38 | + * Example usage: |
| 39 | + * ```kotlin |
| 40 | + * val client = CheckoutProtocol.Client() |
| 41 | + * .on(CheckoutProtocol.start) { checkout -> showProgressUI(checkout) } |
| 42 | + * .on(CheckoutProtocol.complete) { checkout -> navigateToConfirmation(checkout) } |
| 43 | + * .onOpenExternalUrl { uri -> startActivity(Intent(Intent.ACTION_VIEW, uri)); true } |
| 44 | + * |
| 45 | + * ShopifyCheckoutKit.present(url, activity, eventProcessor, client) |
| 46 | + * ``` |
| 47 | + */ |
| 48 | +public object CheckoutProtocol { |
| 49 | + |
| 50 | + public val specVersion: String = "2026.01.23" |
| 51 | + |
| 52 | + // Notifications — checkout carries the full current state |
| 53 | + public val start: NotificationDescriptor<Checkout> = checkoutDescriptor("ec.start") |
| 54 | + public val complete: NotificationDescriptor<Checkout> = checkoutDescriptor("ec.complete") |
| 55 | + public val messagesChange: NotificationDescriptor<Checkout> = checkoutDescriptor("ec.messages.change") |
| 56 | + public val lineItemsChange: NotificationDescriptor<Checkout> = checkoutDescriptor("ec.line_items.change") |
| 57 | + public val buyerChange: NotificationDescriptor<Checkout> = checkoutDescriptor("ec.buyer.change") |
| 58 | + public val paymentChange: NotificationDescriptor<Checkout> = checkoutDescriptor("ec.payment.change") |
| 59 | + |
| 60 | + /** Fires on the initial handshake; payload carries the delegations the page has requested. */ |
| 61 | + public val ready: NotificationDescriptor<ReadyPayload> = NotificationDescriptor( |
| 62 | + method = "ec.ready", |
| 63 | + decode = { params -> |
| 64 | + val delegate = params?.jsonObject?.get("delegate") |
| 65 | + val delegations = delegate?.let { |
| 66 | + try { json.decodeFromJsonElement<List<String>>(it) } catch (_: Exception) { emptyList() } |
| 67 | + } ?: emptyList() |
| 68 | + ReadyPayload(delegations) |
| 69 | + } |
| 70 | + ) |
| 71 | + |
| 72 | + private fun checkoutDescriptor(method: String): NotificationDescriptor<Checkout> = |
| 73 | + NotificationDescriptor( |
| 74 | + method = method, |
| 75 | + decode = { params -> |
| 76 | + params?.jsonObject?.get("checkout")?.let { |
| 77 | + try { json.decodeFromJsonElement<Checkout>(it) } catch (_: Exception) { null } |
| 78 | + } |
| 79 | + } |
| 80 | + ) |
| 81 | + |
| 82 | + internal val json: Json = Json { ignoreUnknownKeys = true } |
| 83 | + |
| 84 | + /** |
| 85 | + * A typed, fluent implementation of [CheckoutCommunicationClient]. |
| 86 | + * |
| 87 | + * Each [on] call returns a new [Client] instance (value semantics), |
| 88 | + * making it safe to share a base configuration across multiple presents. |
| 89 | + */ |
| 90 | + public class Client private constructor( |
| 91 | + private val handlers: Map<String, HandlerEntry>, |
| 92 | + private val urlHandler: ((Uri) -> Boolean)?, |
| 93 | + ) : CheckoutCommunicationClient { |
| 94 | + |
| 95 | + public constructor() : this(emptyMap(), null) |
| 96 | + |
| 97 | + /** |
| 98 | + * Register a handler for an EC notification descriptor. |
| 99 | + * |
| 100 | + * The handler is invoked on the **main thread** whenever the checkout page |
| 101 | + * sends the corresponding notification. Returning from the handler sends |
| 102 | + * no response to the page (notifications are fire-and-forget). |
| 103 | + */ |
| 104 | + public fun <P : Any> on( |
| 105 | + descriptor: NotificationDescriptor<P>, |
| 106 | + handler: (P) -> Unit, |
| 107 | + ): Client { |
| 108 | + @Suppress("UNCHECKED_CAST") |
| 109 | + val entry = HandlerEntry( |
| 110 | + decode = descriptor.decode, |
| 111 | + invoke = { payload -> (payload as? P)?.let { handler(it) } }, |
| 112 | + ) |
| 113 | + return Client(handlers + (descriptor.method to entry), urlHandler) |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Register a handler for [ec.window.open_request]. |
| 118 | + * |
| 119 | + * Called on the **main thread** (the SDK uses a latch to dispatch from the |
| 120 | + * JavascriptInterface thread). Return `true` if the URL was opened externally, |
| 121 | + * `false` to let the SDK report an error back to the page. |
| 122 | + */ |
| 123 | + public fun onOpenExternalUrl(handler: (Uri) -> Boolean): Client = |
| 124 | + Client(handlers, handler) |
| 125 | + |
| 126 | + /** Called by [EmbeddedCheckoutProtocol] for every delegated EC message. */ |
| 127 | + override fun process(message: String): String? { |
| 128 | + try { |
| 129 | + val request = json.decodeFromString<EcpRequest>(message) |
| 130 | + val entry = handlers[request.method] ?: return null |
| 131 | + val payload = entry.decode(request.params) ?: return null |
| 132 | + onMainThread { entry.invoke(payload) } |
| 133 | + } catch (e: Exception) { |
| 134 | + log.d(LOG_TAG, "Error processing ECP message in typed client: $e") |
| 135 | + } |
| 136 | + return null |
| 137 | + } |
| 138 | + |
| 139 | + /** Called by [EmbeddedCheckoutProtocol] on the main thread for [ec.window.open_request]. */ |
| 140 | + override fun openExternalUrl(url: Uri): Boolean = urlHandler?.invoke(url) ?: false |
| 141 | + |
| 142 | + private companion object { |
| 143 | + private const val LOG_TAG = "CheckoutProtocol.Client" |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + private class HandlerEntry( |
| 148 | + val decode: (JsonElement?) -> Any?, |
| 149 | + val invoke: (Any) -> Unit, |
| 150 | + ) |
| 151 | +} |
| 152 | + |
| 153 | +/** |
| 154 | + * Describes a typed EC notification handler binding. |
| 155 | + * |
| 156 | + * Create instances via [CheckoutProtocol] static properties; do not instantiate directly. |
| 157 | + */ |
| 158 | +public class NotificationDescriptor<P : Any> @PublishedApi internal constructor( |
| 159 | + public val method: String, |
| 160 | + internal val decode: (JsonElement?) -> P?, |
| 161 | +) |
| 162 | + |
| 163 | +/** Payload delivered with the [CheckoutProtocol.ready] notification. */ |
| 164 | +public data class ReadyPayload(public val delegations: List<String>) |
0 commit comments