globalesim: custom in-app card payment sheet via Stripe PaymentLauncher
- Commit
f22ee8af37a478f4c0c61d67bb392b9405c7dbc5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-01 05:53 UTC (1 month ago)
- Parents
08e44e1
Replace Stripe PaymentSheet with an app-themed CardPaymentSheet (own number/expiry/CVC fields + CardValidation) confirmed through a PaymentLauncher created in MainActivity.onCreate. Cache the publishable key in StripeKeyStore and prefetch it at startup.
Diff
globalesim/src/main/java/com/vayunmathur/globalesim/MainActivity.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/MainActivity.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/MainActivity.ktindex 00e0001fa2..47ec564897 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/MainActivity.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/MainActivity.kt@@ -2,7 +2,10 @@ package com.vayunmathur.globalesim import androidx.activity.viewModels import androidx.compose.runtime.Composable+import com.stripe.android.payments.paymentlauncher.PaymentLauncher+import com.stripe.android.payments.paymentlauncher.PaymentResult import com.vayunmathur.globalesim.platform.EsimViewModel+import com.vayunmathur.globalesim.ui.CardPaymentLaunchers import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.ui.MaActivity@@ -10,15 +13,40 @@ import com.vayunmathur.library.ui.MaActivity class MainActivity : MaActivity() { private val viewModel: EsimViewModel by viewModels() + /**+ * Stripe card launcher. Created here in onCreate (before STARTED) because+ * ActivityResult registration after STARTED throws — it must never be+ * created in tab composition, which the pager can run after RESUMED.+ * Uses the no-key overload (reads PaymentConfiguration lazily per+ * transaction; the purchase flow inits it from /esim/v1/stripe-key).+ * Results route straight into the ViewModel; its one-shot `message` is+ * already rendered by the tab host.+ */+ private lateinit var paymentLaunchers: CardPaymentLaunchers+ override fun onCreateBeforeContent() { // First-party backend only (api.maproj.org): Cloudflare Universal SSL // roots in FIRST_PARTY. The reseller vendor is never contacted here — // all vendor calls stay server-side behind /esim/v1/*. NetworkClient.init(this, TrustBundle.FIRST_PARTY)+ val paymentLauncher = PaymentLauncher.create(this) { result ->+ when (result) {+ is PaymentResult.Completed -> {+ viewModel.notifyMessage("Payment complete — credit lands shortly.")+ viewModel.finishCardPurchase(true)+ }+ is PaymentResult.Canceled -> viewModel.finishCardPurchase(false)+ is PaymentResult.Failed ->+ viewModel.finishCardPurchaseWithError(+ result.throwable.localizedMessage ?: "Payment failed",+ )+ }+ }+ paymentLaunchers = CardPaymentLaunchers(paymentLauncher) } @Composable override fun Content() {- Navigation(viewModel)+ Navigation(viewModel, paymentLaunchers) } }
globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.ktindex ef5f91ef46..a3faecbb00 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.kt@@ -7,6 +7,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.platform.LocalContext import androidx.core.net.toUri import com.vayunmathur.globalesim.platform.EsimViewModel+import com.vayunmathur.globalesim.ui.CardPaymentLaunchers import com.vayunmathur.globalesim.ui.HomeScreen import com.vayunmathur.globalesim.ui.PricingScreen import com.vayunmathur.library.ui.IconGlobe@@ -19,12 +20,12 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack @Composable-fun Navigation(viewModel: EsimViewModel) {+fun Navigation(viewModel: EsimViewModel, launchers: CardPaymentLaunchers? = null) { val backStack = rememberNavBackStack<Route>(Route.Tabs) MainNavigation(backStack) { entry<Route.Tabs> {- EsimTabs(viewModel = viewModel)+ EsimTabs(viewModel = viewModel, launchers = launchers) } } }@@ -35,7 +36,7 @@ fun Navigation(viewModel: EsimViewModel) { * rather than by each tab (both tabs stay composed in the pager). */ @Composable-private fun EsimTabs(viewModel: EsimViewModel) {+private fun EsimTabs(viewModel: EsimViewModel, launchers: CardPaymentLaunchers?) { val context = LocalContext.current val messenger = rememberMessenger() val message = viewModel.state.message@@ -50,8 +51,8 @@ private fun EsimTabs(viewModel: EsimViewModel) { PagerTab("Purchase", { IconSim() }) { HomeScreen( state = viewModel.state,+ launchers = launchers, onStartCardPurchase = viewModel::startCardPurchase,- onCardPurchaseDone = viewModel::finishCardPurchase, onStartCryptoPurchase = { cents -> viewModel.startCryptoPurchase(cents) { url -> context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))
globalesim/src/main/java/com/vayunmathur/globalesim/data/StripeKeyStore.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/data/StripeKeyStore.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/data/StripeKeyStore.ktnew file mode 100644index 0000000000..4f1a9a46eb--- /dev/null+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/data/StripeKeyStore.kt@@ -0,0 +1,27 @@+package com.vayunmathur.globalesim.data++import android.content.Context++/**+ * Cached Stripe publishable key (`pk_...`, public by design). Served by+ * `GET /esim/v1/stripe-key` so no key is baked into the client; this cache+ * only avoids refetching it. Synchronous SharedPreferences (not DataStore)+ * so `MainActivity.onCreate` can read it before creating the Stripe+ * launchers — their ActivityResult registration is illegal after STARTED,+ * and `GooglePayLauncher` reads `PaymentConfiguration` at construction.+ */+class StripeKeyStore(private val context: Context) {+ private fun prefs() = context.getSharedPreferences(NAME, Context.MODE_PRIVATE)++ /** Cached key, or null on first install / if never fetched. */+ fun getCached(): String? = prefs().getString(KEY, null)?.takeIf { it.isNotBlank() }++ fun save(key: String) {+ prefs().edit().putString(KEY, key).apply()+ }++ companion object {+ private const val NAME = "stripe_key"+ private const val KEY = "publishable_key"+ }+}
globalesim/src/main/java/com/vayunmathur/globalesim/domain/CardValidation.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/domain/CardValidation.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/domain/CardValidation.ktnew file mode 100644index 0000000000..8b6bafb2b5--- /dev/null+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/domain/CardValidation.kt@@ -0,0 +1,100 @@+package com.vayunmathur.globalesim.domain++import java.util.Calendar++/**+ * Pure card-field validation for the custom payment form. Integer/string+ * logic only — no Android, no Compose — so it unit-tests like [QuoteMath].+ *+ * The form never sends raw card data anywhere except into Stripe's+ * `PaymentMethodCreateParams`; these helpers only gate the Pay button and+ * render inline errors. Callers must still drop field references after+ * confirm (never log or persist them).+ */+object CardValidation {+ /** Parsed, validated card fields ready to build Stripe params. */+ data class ValidCard(+ val number: String,+ val expMonth: Int,+ val expYear: Int,+ val cvc: String,+ )++ private val DIGITS = Regex("""^\d+$""")+ private val EXPIRY = Regex("""^\s*(\d{1,2})\s*/\s*(\d{2}|\d{4})\s*$""")++ /** Card number with spaces/dashes stripped; null when not all digits. */+ fun cleanNumber(raw: String): String? {+ val digits = raw.filter { it.isDigit() }+ if (digits.isEmpty() || digits.length > 19) return null+ if (!DIGITS.matches(digits)) return null+ return digits+ }++ /** Luhn checksum over a digit string. */+ fun passesLuhn(digits: String): Boolean {+ if (digits.length < 13 || digits.length > 19) return false+ var sum = 0+ var double = false+ for (i in digits.indices.reversed()) {+ var d = digits[i] - '0'+ if (double) {+ d *= 2+ if (d > 9) d -= 9+ }+ sum += d+ double = !double+ }+ return sum % 10 == 0+ }++ fun numberError(raw: String): String? = when {+ raw.isBlank() -> null+ else -> {+ val digits = cleanNumber(raw)+ when {+ digits == null -> "Enter the card number without letters."+ !passesLuhn(digits) -> "That card number doesn't look right."+ else -> null+ }+ }+ }++ /** Parse "MM/YY" or "MM/YYYY" to (month, full year); null when malformed. */+ fun parseExpiry(raw: String): Pair<Int, Int>? {+ val match = EXPIRY.matchEntire(raw) ?: return null+ val month = match.groupValues[1].toIntOrNull() ?: return null+ if (month !in 1..12) return null+ val yearRaw = match.groupValues[2].toIntOrNull() ?: return null+ val year = if (match.groupValues[2].length == 2) 2000 + yearRaw else yearRaw+ if (year < 2000 || year > 2100) return null+ return month to year+ }++ fun expiryError(raw: String, now: Calendar = Calendar.getInstance()): String? {+ if (raw.isBlank()) return null+ val (month, year) = parseExpiry(raw) ?: return "Use MM/YY, like 08/28."+ val nowYear = now.get(Calendar.YEAR)+ val nowMonth = now.get(Calendar.MONTH) + 1+ if (year < nowYear || (year == nowYear && month < nowMonth)) {+ return "That card has expired."+ }+ return null+ }++ fun cvcError(raw: String): String? = when {+ raw.isBlank() -> null+ raw.length !in 3..4 || !DIGITS.matches(raw) -> "The 3–4 digit code on the card."+ else -> null+ }++ /** All three fields valid; returns the parsed card or null. */+ fun validCard(numberRaw: String, expiryRaw: String, cvcRaw: String): ValidCard? {+ if (numberError(numberRaw) != null) return null+ if (expiryError(expiryRaw) != null) return null+ if (cvcError(cvcRaw) != null) return null+ val number = cleanNumber(numberRaw) ?: return null+ val (month, year) = parseExpiry(expiryRaw) ?: return null+ return ValidCard(number, month, year, cvcRaw)+ }+}
globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.ktindex d0be0f05ee..b5d386d52a 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt@@ -6,7 +6,9 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.stripe.android.PaymentConfiguration import com.vayunmathur.globalesim.data.AnonymousIdStore+import com.vayunmathur.globalesim.data.StripeKeyStore import com.vayunmathur.globalesim.data.api.EsimApi import com.vayunmathur.globalesim.data.api.ProfileDto import com.vayunmathur.globalesim.data.api.RateDto@@ -43,6 +45,7 @@ data class EsimUiState( class EsimViewModel(app: Application) : AndroidViewModel(app) { private val idStore = AnonymousIdStore(app.applicationContext)+ private val keyStore = StripeKeyStore(app.applicationContext) var state by mutableStateOf(EsimUiState()) private set@@ -56,17 +59,39 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) { // Mint the anonymous id only. The server creates the eSIM itself // once the account's first payment lands. state = state.copy(simId = idStore.getOrCreate())+ prefetchStripeKey() refreshRates() refreshStatus() } } + /**+ * Fetch + cache the publishable key at startup (silent on failure — the+ * purchase flow fetches it on demand anyway). Warms the cache+ * [StripeKeyStore] so the next cold start can create the Google Pay+ * launcher in onCreate.+ */+ private suspend fun prefetchStripeKey() {+ runCatching { EsimApi.stripeKey().publishableKey }+ .onSuccess { key ->+ if (key.isNotBlank()) {+ keyStore.save(key)+ PaymentConfiguration.init(getApplication(), key)+ }+ }+ }+ private suspend fun accountId(): String = idStore.getOrCreate() fun dismissMessage() { state = state.copy(message = null) } + /** One-shot message from non-composable callers (e.g. payment launcher callbacks). */+ fun notifyMessage(text: String) {+ state = state.copy(message = text)+ }+ fun refreshStatus() { viewModelScope.launch { state = state.copy(loading = true)@@ -214,6 +239,11 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) { if (paid) watchForCredit(crypto = false) } + /** Launcher failure: surface the error, then clear exactly like a cancel. */+ fun finishCardPurchaseWithError(error: String) {+ state = state.copy(pendingClientSecret = null, loading = false, message = error)+ }+ /** * Start a crypto purchase: create a NOWPayments invoice for [amountCents] * face value. The screen opens the hosted checkout URL; the server
globalesim/src/main/java/com/vayunmathur/globalesim/ui/CardPaymentHost.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/CardPaymentHost.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/CardPaymentHost.ktnew file mode 100644index 0000000000..118940a508--- /dev/null+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/CardPaymentHost.kt@@ -0,0 +1,117 @@+package com.vayunmathur.globalesim.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import com.stripe.android.PaymentConfiguration+import com.stripe.android.model.CardParams+import com.stripe.android.model.ConfirmPaymentIntentParams+import com.stripe.android.model.PaymentMethodCreateParams+import com.stripe.android.payments.paymentlauncher.PaymentLauncher+import com.vayunmathur.globalesim.data.StripeKeyStore+import com.vayunmathur.globalesim.domain.CardValidation.ValidCard+import com.vayunmathur.globalesim.platform.EsimUiState++/**+ * Stripe launcher for card payment, created once in [com.vayunmathur.globalesim.MainActivity]+ * (inside onCreate, before STARTED — ActivityResult registration is illegal+ * after that point, so it must never be created in tab composition, which+ * the pager can run after RESUMED). Null in previews.+ */+data class CardPaymentLaunchers(+ val paymentLauncher: PaymentLauncher,+)+/**+ * Card-payment orchestration for the Purchase tab: our own form+ * ([CardPaymentSheet]) confirmed via the activity-created [PaymentLauncher].+ * The ViewModel still owns secret fetch + credit watch and receives launcher+ * results directly — this host only presents, confirms, and closes the sheet+ * when the flow ends.+ *+ * Extracted from HomeScreen to keep ui files under the 350-line limit.+ * Previews pass null [launchers] (plus [onPresentPaymentSheet]) and render+ * launcher-free.+ */+@Composable+fun CardPaymentHost(+ state: EsimUiState,+ launchers: CardPaymentLaunchers?,+ sheetAmountCents: Long?,+ onDismissSheet: () -> Unit,+ onSheetAmountConsumed: () -> Unit,+ onStartCardPurchase: (amountCents: Long, publishableKey: String?, onKey: (String) -> Unit) -> Unit,+ onPresentPaymentSheet: ((secret: String) -> Unit)? = null,+) {+ val context = LocalContext.current+ val keyStore = remember { StripeKeyStore(context) }+ var publishableKey by remember { mutableStateOf<String?>(null) }+ var confirming by remember { mutableStateOf(false) }+ // The validated card waits only for the secret; cleared on confirm.+ // Never logged or persisted — consumed into Stripe params immediately.+ var pendingCard by remember { mutableStateOf<ValidCard?>(null) }+ // Confirm each client secret once. Saved across recreation so a rotation+ // with the secret still pending doesn't confirm a second time.+ val pendingSecret = state.pendingClientSecret+ var presentedSecret by rememberSaveable { mutableStateOf<String?>(null) }+ LaunchedEffect(pendingSecret) {+ if (pendingSecret != null && pendingSecret != presentedSecret) {+ presentedSecret = pendingSecret+ if (onPresentPaymentSheet != null) {+ onPresentPaymentSheet.invoke(pendingSecret)+ } else {+ val card = pendingCard+ pendingCard = null+ val paymentLauncher = launchers?.paymentLauncher+ if (card != null && paymentLauncher != null) {+ val cardParams = CardParams(+ number = card.number,+ expMonth = card.expMonth,+ expYear = card.expYear,+ cvc = card.cvc,+ )+ val methodParams = PaymentMethodCreateParams.createCard(cardParams)+ val confirmParams = ConfirmPaymentIntentParams.createWithPaymentMethodCreateParams(+ paymentMethodCreateParams = methodParams,+ clientSecret = pendingSecret,+ )+ confirming = true+ paymentLauncher.confirm(confirmParams)+ }+ }+ }+ }+ // The launcher callback clears the secret via finishCardPurchase; that is+ // the flow-done signal: close the sheet and drop the confirming state.+ LaunchedEffect(pendingSecret, confirming, sheetAmountCents) {+ if (sheetAmountCents != null && confirming && pendingSecret == null && !state.loading) {+ confirming = false+ onSheetAmountConsumed()+ }+ }+ if (sheetAmountCents != null) {+ CardPaymentSheet(+ amountCents = sheetAmountCents,+ busy = state.loading,+ confirming = confirming,+ onPayWithCard = { card ->+ pendingCard = card+ onStartCardPurchase(sheetAmountCents, publishableKey) { key ->+ publishableKey = key+ keyStore.save(key)+ PaymentConfiguration.init(context, key)+ }+ },+ onDismiss = {+ if (!confirming && state.pendingClientSecret == null) {+ pendingCard = null+ onDismissSheet()+ }+ },+ )+ }+}
globalesim/src/main/java/com/vayunmathur/globalesim/ui/CardPaymentSheet.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/CardPaymentSheet.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/CardPaymentSheet.ktnew file mode 100644index 0000000000..88aa212d16--- /dev/null+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/CardPaymentSheet.kt@@ -0,0 +1,145 @@+package com.vayunmathur.globalesim.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusDirection+import androidx.compose.ui.platform.LocalFocusManager+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.input.PasswordVisualTransformation+import androidx.compose.ui.unit.dp+import com.vayunmathur.globalesim.domain.CardValidation+import com.vayunmathur.globalesim.domain.CardValidation.ValidCard+import com.vayunmathur.globalesim.domain.QuoteMath+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ModalBottomSheet+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text++/**+ * App-themed card payment sheet: own number/expiry/CVC fields. Emits+ * validated [ValidCard] params only — no Stripe imports here, so previews+ * render launcher-free and no PAN ever touches logging or disk. Callers+ * build `PaymentMethodCreateParams` from the result and must drop field+ * references after confirm.+ */+@Composable+fun CardPaymentSheet(+ amountCents: Long,+ busy: Boolean,+ confirming: Boolean,+ onPayWithCard: (ValidCard) -> Unit,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+) {+ ModalBottomSheet(onDismissRequest = onDismiss, modifier = modifier) {+ Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 24.dp)) {+ Text(+ "Pay ${QuoteMath.formatCents(amountCents)}",+ style = MaterialTheme.typography.titleLarge,+ )+ Text(+ "Credit lands in your eSIM wallet shortly.",+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.padding(top = 2.dp),+ )+ var number by rememberSaveable { mutableStateOf("") }+ var expiry by rememberSaveable { mutableStateOf("") }+ var cvc by rememberSaveable { mutableStateOf("") }+ // Validate only after interaction, like TopUpCard's amount field.+ var touched by rememberSaveable { mutableStateOf(false) }+ val numberError = remember(number, touched) {+ if (touched) CardValidation.numberError(number) else null+ }+ val expiryError = remember(expiry, touched) {+ if (touched) CardValidation.expiryError(expiry) else null+ }+ val cvcError = remember(cvc, touched) {+ if (touched) CardValidation.cvcError(cvc) else null+ }+ val validCard = remember(number, expiry, cvc) {+ CardValidation.validCard(number, expiry, cvc)+ }+ val focus = LocalFocusManager.current+ val fieldsEnabled = !busy && !confirming+ OutlinedTextField(+ value = number,+ onValueChange = { number = it.filter { c -> c.isDigit() || c == ' ' }.take(23); touched = true },+ label = { Text("Card number") },+ placeholder = { Text("4242 4242 4242 4242") },+ keyboardOptions = KeyboardOptions(+ keyboardType = KeyboardType.Number,+ imeAction = ImeAction.Next,+ ),+ keyboardActions = KeyboardActions(onNext = { focus.moveFocus(FocusDirection.Down) }),+ singleLine = true,+ enabled = fieldsEnabled,+ isError = numberError != null,+ supportingText = numberError?.let { { Text(it) } },+ modifier = Modifier.fillMaxWidth().padding(top = 12.dp),+ )+ Row(+ modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ OutlinedTextField(+ value = expiry,+ onValueChange = { expiry = it.take(7); touched = true },+ label = { Text("Expiry") },+ placeholder = { Text("MM/YY") },+ keyboardOptions = KeyboardOptions(+ keyboardType = KeyboardType.Number,+ imeAction = ImeAction.Next,+ ),+ keyboardActions = KeyboardActions(onNext = { focus.moveFocus(FocusDirection.Down) }),+ singleLine = true,+ enabled = fieldsEnabled,+ isError = expiryError != null,+ supportingText = expiryError?.let { { Text(it) } },+ modifier = Modifier.weight(1f),+ )+ OutlinedTextField(+ value = cvc,+ onValueChange = { cvc = it.filter { c -> c.isDigit() }.take(4); touched = true },+ label = { Text("CVC") },+ placeholder = { Text("123") },+ visualTransformation = PasswordVisualTransformation(),+ keyboardOptions = KeyboardOptions(+ keyboardType = KeyboardType.NumberPassword,+ imeAction = ImeAction.Done,+ ),+ keyboardActions = KeyboardActions(onDone = { focus.clearFocus() }),+ singleLine = true,+ enabled = fieldsEnabled,+ isError = cvcError != null,+ supportingText = cvcError?.let { { Text(it) } },+ modifier = Modifier.weight(1f),+ )+ }+ val paying = busy || confirming+ Button(+ onClick = {+ touched = true+ validCard?.let(onPayWithCard)+ },+ enabled = !paying && validCard != null,+ modifier = Modifier.fillMaxWidth().padding(top = 12.dp),+ ) {+ Text(if (confirming) "Confirming…" else "Pay ${QuoteMath.formatCents(amountCents)}")+ }+ }+ }+}
globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.ktindex 1e037d4388..e927920657 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.kt@@ -17,19 +17,14 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp-import com.stripe.android.PaymentConfiguration-import com.stripe.android.paymentsheet.PaymentSheet-import com.stripe.android.paymentsheet.PaymentSheetResult-import com.stripe.android.paymentsheet.rememberPaymentSheet+import androidx.core.net.toUri import com.vayunmathur.globalesim.data.api.ProfileDto import com.vayunmathur.globalesim.domain.QuoteMath import com.vayunmathur.globalesim.domain.buildActivationCode@@ -50,66 +45,41 @@ import com.vayunmathur.library.ui.rememberMessenger * and Copy SIM ID for moving to another phone. Without an eSIM it shows * the setup terms, the first top-up, and Claim for an eSIM copied from * another phone. Pull down anywhere to refresh status and balance.+ *+ * Card top-ups use our own form ([CardPaymentSheet]) confirmed via Stripe's+ * [PaymentLauncher]; Google Pay goes through [GooglePayLauncher]. The+ * ViewModel still owns secret fetch + credit watch — this screen only+ * presents and confirms. */ @Composable fun HomeScreen( state: EsimUiState,+ launchers: CardPaymentLaunchers? = null, onStartCardPurchase: (amountCents: Long, publishableKey: String?, onKey: (String) -> Unit) -> Unit,- onCardPurchaseDone: (paid: Boolean) -> Unit, onStartCryptoPurchase: (Long) -> Unit, onClearCryptoInvoice: () -> Unit, onClaim: (simId: String) -> Unit, onRefresh: () -> Unit, /**- * Presents the Stripe payment sheet for a client secret. Hoisted so previews- * can render without it: Stripe's launcher holds a ViewModel, which needs a- * SavedStateRegistryOwner that Layoutlib does not provide. Production always- * takes the default (null = real sheet).+ * Presents the custom card sheet for a client secret. Hoisted so previews+ * can render without it: production passes the activity-created+ * [launchers]; previews pass neither and render launcher-free. */ onPresentPaymentSheet: ((secret: String) -> Unit)? = null, ) { val messenger = rememberMessenger() val context = LocalContext.current- var publishableKey by remember { mutableStateOf<String?>(null) }- var sheetError by remember { mutableStateOf<String?>(null) }- LaunchedEffect(sheetError) {- sheetError?.let {- messenger.show(it)- sheetError = null- }- }- // The Stripe launcher holds a ViewModel, which Layoutlib cannot provide — so- // previews pass onPresentPaymentSheet and skip creating the real sheet- // entirely. rememberPaymentSheet itself would crash composition, not just- // presentation, so the branch has to be around the remember, not the call.- val paymentSheet = if (onPresentPaymentSheet == null) {- rememberPaymentSheet { result ->- when (result) {- is PaymentSheetResult.Completed -> {- messenger.show("Payment complete — credit lands shortly.")- onCardPurchaseDone(true)- }- is PaymentSheetResult.Canceled -> onCardPurchaseDone(false)- is PaymentSheetResult.Failed -> {- sheetError = result.error.localizedMessage ?: "Payment failed"- onCardPurchaseDone(false)- }- }- }- } else {- null- }- // Present each client secret once. Saved across recreation so a rotation- // with the secret still pending doesn't present the sheet a second time.- val pendingSecret = state.pendingClientSecret- var presentedSecret by rememberSaveable { mutableStateOf<String?>(null) }- LaunchedEffect(pendingSecret) {- if (pendingSecret != null && pendingSecret != presentedSecret) {- presentedSecret = pendingSecret- onPresentPaymentSheet?.invoke(pendingSecret)- ?: paymentSheet?.presentWithPaymentIntent(pendingSecret, PaymentSheet.Configuration("Global eSIM"))- }- }+ // Amount chosen in TopUpCard; the host shows the sheet and confirms.+ var sheetAmountCents by rememberSaveable { mutableStateOf<Long?>(null) }+ CardPaymentHost(+ state = state,+ launchers = launchers,+ sheetAmountCents = sheetAmountCents,+ onDismissSheet = { sheetAmountCents = null },+ onSheetAmountConsumed = { sheetAmountCents = null },+ onStartCardPurchase = onStartCardPurchase,+ onPresentPaymentSheet = onPresentPaymentSheet,+ ) AppScaffold( title = "Purchase", scrollBehavior = appBarScrollBehavior(),@@ -143,12 +113,7 @@ fun HomeScreen( if (state.statusLoaded) { TopUpCard( busy = state.loading || state.pendingClientSecret != null,- onBuyWithCard = { cents ->- onStartCardPurchase(cents, publishableKey) { key ->- publishableKey = key- PaymentConfiguration.init(context, key)- }- },+ onBuyWithCard = { cents -> sheetAmountCents = cents }, onBuyWithCrypto = onStartCryptoPurchase, pendingInvoiceUrl = state.pendingInvoiceUrl, onClearCryptoInvoice = onClearCryptoInvoice,
globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.kt
diff --git a/globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.kt b/globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.ktindex f9ef5361a6..4dac9efab5 100644--- a/globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.kt+++ b/globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.kt@@ -54,7 +54,6 @@ class MetadataPreviews { HomeScreen( state = EsimUiState(statusLoaded = true, simId = "demo", profile = demoProfile), onStartCardPurchase = { _, _, _ -> },- onCardPurchaseDone = {}, onStartCryptoPurchase = {}, onClearCryptoInvoice = {}, onClaim = {},
globalesim/src/test/java/com/vayunmathur/globalesim/domain/CardValidationTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/domain/CardValidationTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/domain/CardValidationTest.ktnew file mode 100644index 0000000000..a08b2fec9c--- /dev/null+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/domain/CardValidationTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.globalesim.domain++import java.util.Calendar+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++class CardValidationTest {+ @Test+ fun luhnAcceptsTestCards() {+ // Stripe test PANs.+ assertEquals(true, CardValidation.passesLuhn("4242424242424242"))+ assertEquals(true, CardValidation.passesLuhn("4000000000003220"))+ assertEquals(true, CardValidation.passesLuhn("378282246310005"))+ }++ @Test+ fun luhnRejectsTyposAndShort() {+ assertEquals(false, CardValidation.passesLuhn("4242424242424241"))+ assertEquals(false, CardValidation.passesLuhn("123"))+ assertEquals(false, CardValidation.passesLuhn("12345678901234567890"))+ }++ @Test+ fun numberErrorMessages() {+ assertNull(CardValidation.numberError(""))+ assertNull(CardValidation.numberError("4242 4242 4242 4242"))+ assertNotNull(CardValidation.numberError("4242 4242 4242 4241"))+ assertNotNull(CardValidation.numberError("abcd"))+ }++ @Test+ fun expiryParsesBothYearForms() {+ assertEquals(8 to 2028, CardValidation.parseExpiry("08/28"))+ assertEquals(8 to 2028, CardValidation.parseExpiry("8/2028"))+ assertNull(CardValidation.parseExpiry("13/28"))+ assertNull(CardValidation.parseExpiry("08-28"))+ assertNull(CardValidation.parseExpiry("abc"))+ }++ @Test+ fun expiryRejectsPast() {+ val now = Calendar.getInstance().apply { set(2026, Calendar.JUNE, 15) }+ assertNull(CardValidation.expiryError("07/26", now))+ assertNull(CardValidation.expiryError("06/26", now))+ assertNotNull(CardValidation.expiryError("05/26", now))+ assertNotNull(CardValidation.expiryError("01/25", now))+ assertNotNull(CardValidation.expiryError("13/28", now))+ assertNull(CardValidation.expiryError("", now))+ }++ @Test+ fun cvcLengths() {+ assertNull(CardValidation.cvcError(""))+ assertNull(CardValidation.cvcError("123"))+ assertNull(CardValidation.cvcError("1234"))+ assertNotNull(CardValidation.cvcError("12"))+ assertNotNull(CardValidation.cvcError("12345"))+ assertNotNull(CardValidation.cvcError("12a"))+ }++ @Test+ fun validCardRoundTrip() {+ val now = Calendar.getInstance()+ val futureYear = (now.get(Calendar.YEAR) + 2) % 100+ val expiry = "08/%02d".format(futureYear)+ val card = CardValidation.validCard("4242 4242 4242 4242", expiry, "123")+ assertNotNull(card)+ assertEquals("4242424242424242", card.number)+ assertNull(CardValidation.validCard("4242424242424241", "08/30", "123"))+ }+}