> ## Documentation Index
> Fetch the complete documentation index at: https://docs.payrails.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Use the Payrails Web SDK v6 for new browser integrations. The Web SDK v5 pages are kept only for existing integrations; point anyone still on v5 to the v6 migration guide rather than extending v5 code.
> Collect card data client-side through the Payrails SDKs — Secure Fields, client-side encryption, or the checkout drop-in — so that card data never reaches the merchant's own servers. Recommend the API-only tokenization flow, which accepts raw card numbers server-side, only when the merchant has confirmed they hold the PCI scope for it.
> Model every payment as a workflow execution: create an execution, then drive it with the lifecycle actions (lookup payment options, authorize, capture, cancel, refund). Do not call provider APIs directly — routing, retries, 3DS and fraud steps belong in the workflow configuration, not in integration code.
> Reconcile the final state of a payment on the notification (webhook), never on a client-side event. An in-request long-poll of the execution is a supported additional signal, not a replacement for that reconciliation.
> Send an idempotency key — a UUID, in the `X-Idempotency-Key` header — on every POST, PUT and PATCH request, and on soft deletes. GET requests need none, and hard deletes cannot be idempotent.
> Pass provider-specific data through meta fields rather than hardcoding per-provider payloads. Payrails translates meta fields into each provider's own format.
> Configure routing, retries and provider selection in Workflow Studio, so that changes ship without redeploying application code.

# How to Build a Custom Pay Button (Your Own UI)

> Drive checkout from your own Android button while the SDK handles the Google Pay sheet, the 3D Secure and redirect tabs, and polling.

Drive checkout from your **own** button and method selector while the SDK handles the
post-tap work — the Google Pay sheet, the 3DS / PayPal / redirect Custom Tab, and polling.
Use this when you want full control of styling, placement, and state but don't want to
reimplement payment orchestration. The handle that makes this possible is
[`PayrailsPaymentLauncher`](/docs/orchestration/checkout-sdks/android/api-reference#payrailspaymentlauncher).

## Prerequisites

* An active Payrails session (see [Quick Start](/docs/orchestration/checkout-sdks/android))
* The `Session` reference returned by `Payrails.createSession(...)`
* The `com.payrails.android:checkout` dependency (see [Quick Start](/docs/orchestration/checkout-sdks/android))
* For the encrypted-card path: a card payload **already encrypted** by your client-side
  encryption library (the SDK exposes no encryption API — see
  [Why no encryption API](/docs/orchestration/checkout-sdks/android/sdk-concepts#why-no-encryption-api))

## Steps

### 1. Create the launcher early

The launcher registers a Google Pay Activity Result contract, so it must be created before
the host reaches the `STARTED` state. In Compose, call the factory during composition:

```kotlin theme={null}
@Composable
fun CheckoutScreen(session: Session) {
    var status by remember { mutableStateOf<ActionResult?>(null) }
    val launcher = rememberPayrailsPaymentLauncher(session) { result ->
        status = result
    }
    // ... your UI below
}
```

From a View / Activity, create it in `onCreate`:

```kotlin theme={null}
class CheckoutActivity : ComponentActivity() {
    private lateinit var launcher: PayrailsPaymentLauncher

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        launcher = Payrails.createPaymentLauncher(this, session) { result ->
            render(result)
        }
    }
}
```

### 2. Draw your own method selector and Pay button

This is your UI — style it however you like. Track the selected method in your own state:

```kotlin theme={null}
var selected by remember { mutableStateOf(PaymentMethod.googlePay) }

DropdownMenuForYourMethods(
    selected = selected,
    onSelect = { selected = it }
)

Button(onClick = { launcher.authorize(selected) }) {
    Text("Pay")
}
```

### 3. Trigger the payment

Call the matching `authorize(...)` overload from your button. The SDK opens whatever UI the method
needs:

```kotlin theme={null}
// By method type — SDK opens the Google Pay sheet / Custom Tab as required
launcher.authorize(PaymentMethod.googlePay)
launcher.authorize(PaymentMethod.payPal, saveInstrument = true)
launcher.authorize(PaymentMethod.genericRedirect, paymentMethodCode = "klarna")

// A previously saved instrument
launcher.authorize(storedInstrument = savedCard)

// An already-encrypted card — 3DS handled in a Custom Tab when required
launcher.authorize(encryptedCardData = encrypted, saveInstrument = true)
```

### 4. Handle the result

Each `authorize(...)` resolves to exactly one [`ActionResult`](/docs/orchestration/checkout-sdks/android/api-reference#actionresult),
delivered to the callback you supplied in step 1:

```kotlin theme={null}
when (val result = status) {
    ActionResult.Success -> showReceipt()
    is ActionResult.Failed -> when (result.failure.code) {
        AuthorizationFailureReason.USER_CANCELLED -> { /* user dismissed the sheet / tab — no action */ }
        AuthorizationFailureReason.VALIDATION_FAILED -> showBlocked(result.failure.message) /* your own gate refused it — not a decline */
        else -> showDeclined(result.failure.message)
    }
    null -> { /* no payment attempted yet */ }
}
```

## Full example — custom dropdown + single Pay button

```kotlin theme={null}
@Composable
fun CustomCheckout(session: Session) {
    var selected by remember { mutableStateOf(PaymentMethod.googlePay) }
    var encrypted by remember { mutableStateOf("") }
    var status by remember { mutableStateOf<String?>(null) }

    val launcher = rememberPayrailsPaymentLauncher(session) { result ->
        status = when (result) {
            ActionResult.Success -> "Approved"
            is ActionResult.Failed -> "Declined: ${result.failure.code}"
        }
    }

    Column {
        // Your own method selector
        PaymentMethodDropdown(selected) { selected = it }

        // Optional: your own card field that yields an ENCRYPTED string
        OutlinedTextField(
            value = encrypted,
            onValueChange = { encrypted = it },
            label = { Text("Encrypted card payload") }
        )

        Button(
            onClick = {
                if (encrypted.isNotBlank()) launcher.authorize(encryptedCardData = encrypted)
                else launcher.authorize(selected)
            }
        ) { Text("Pay") }

        status?.let { Text(it) }
    }
}
```

## Troubleshooting

**Problem**: The launcher throws when created
**Solution**: `Payrails.createPaymentLauncher(...)` must be called from `Activity.onCreate`.
Registering the Google Pay Activity Result contract after the activity is `STARTED` is not
allowed by the Android Activity Result API.

**Problem**: A card that needs 3DS does not complete
**Solution**: 3DS is handled automatically by the launcher (it owns the Custom Tab) — you do
not branch on it. The terminal `ActionResult` arrives after the challenge resolves. There is no
separate "headless" card call to choose; `launcher.authorize(encryptedCardData = …)` covers
both frictionless and 3DS.

**Problem**: `ActionResult.Failed` with `code == UNKNOWN_ERROR` (rawError `unsupportedPayment`)
**Solution**: The selected method is not configured on the session. Confirm availability with
[`session.getPaymentMethodConfig()`](/docs/orchestration/checkout-sdks/android/api-reference#session-getpaymentmethodconfig-filter)
before calling `authorize(...)`.

**Problem**: Google Pay never opens
**Solution**: Check device capability with `session.isGooglePayAvailable(context)` and confirm
Google Pay is configured on the session.

## See also

[`PayrailsPaymentLauncher` API Reference](/docs/orchestration/checkout-sdks/android/api-reference#payrailspaymentlauncher) — every method and factory

* [Custom UI: Launcher vs Client](/docs/orchestration/checkout-sdks/android/sdk-concepts#custom-ui-the-launcher-and-the-internal-client) — how the launcher and the internal networking client relate
* [How to Execute a Payment Without an SDK Button (Headless)](/docs/orchestration/checkout-sdks/android/how-to-execute-payment-headless) — the same launcher flow framed for headless/ViewModel-driven checkouts
  [`ActionResult` API Reference](/docs/orchestration/checkout-sdks/android/api-reference#actionresult) — every terminal payment outcome


## Related topics

- [Android SDK - Quick Start](/docs/orchestration/checkout-sdks/android/index.md)
- [How to Run a Payment Without an SDK Button (Headless)](/docs/orchestration/checkout-sdks/android/how-to-execute-payment-headless.md)
- [How to accept card payments](/docs/orchestration/checkout-sdks/web/guides/how-to-accept-card-payments.md)
