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

> ## Agent Instructions
> Treat these docs and the Whop MCP server as the source of truth for Whop API behavior. Don't infer endpoint behavior from marketing pages.
> MCP server: connect https://mcp.whop.com/mcp (streamable HTTP, browser sign-in, no API key in the client config) to search these docs and read or change live Whop data. Setup: https://docs.whop.com/developer/guides/ai_and_mcp.md
> Whop CLI: install with `curl -fsSL https://whop.com/install.sh | sh` to scaffold, run, and deploy Whop apps and websites. It acts on production, not the sandbox. Overview: https://docs.whop.com/cli/overview.md Agent mode: https://docs.whop.com/cli/agent-mode.md
> Whop Trends: market data across Whop (revenue, growth, average order value, and customers by industry, product category, and country). Read it with no API key at `GET https://api.whop.com/api/v1/stats/reports/platform_trends`, or through the MCP server operation `get_platform_trends_report`. Guide and use cases: https://docs.whop.com/developer/guides/trends.md
> Hosting: Whop serves a site or app from the build `whop apps deploy` uploads, with rollbacks, secrets, and server logs. Guide: https://docs.whop.com/developer/websites/hosting.md
> Plugins: in Claude Code, run `/plugin marketplace add whopio/plugins`, then `/plugin install whop@whop`. Guide: https://docs.whop.com/developer/guides/plugins/claude-code.md Every agent tool: https://docs.whop.com/developer/ai/overview.md
> Environments: build and test in the sandbox (API `https://sandbox-api.whop.com/api/v1`, keys at https://sandbox.whop.com/dashboard/developer, SDK environment `Sandbox`; no real money). Production (API `https://api.whop.com/api/v1`, keys at https://whop.com/dashboard/developer, SDK environment `Production`, the SDK default) moves real money, so use it only at launch. The two share no accounts, keys, products, or webhooks, and their keys look identical: never mix them. Sandbox guide: https://docs.whop.com/developer/guides/sandbox.md Comparison: https://docs.whop.com/developer/quickstart.md
> API: send `Authorization: Bearer <API_KEY>` from your server only, and pin a dated version with the `Api-Version-Date` header. OpenAPI spec: https://api.whop.com/api/v1/openapi.json
> Which API: build on the Current API, whose pages live under https://docs.whop.com/api-reference/ (start at https://docs.whop.com/api-reference/overview.md). Pages under /api-reference/legacy/ are the Legacy API. Use one only when https://docs.whop.com/api-reference/stability.md lists the resource as Legacy-only.

# Tap to Pay SwiftUI Example

> A complete SwiftUI payment screen that uses the Tap to Pay SDK: readiness, charges, progress, cancel, errors, and a receipt by email.

This screen uses all parts of the SDK. It does a readiness check. It charges a variant or an amount that the seller types. It shows each phase and lets the seller cancel. It changes errors into messages. After a payment, it sends a receipt to an email from the buyer.

It uses the `TapToPayTokens.fetch()` helper from [Authentication](https://docs.whop.com/tap-to-pay/authentication.md#pass-a-token-provider-to-the-sdk). Your Info.plist must contain the keys from [Before you start](https://docs.whop.com/tap-to-pay/getting-started.md#before-you-start).

```swift PaymentScreen.swift theme={null}
import CoreLocation
import SwiftUI
import WhopTTP

struct PaymentScreen: View {
    let variantID: String

    @Environment(\.scenePhase) private var scenePhase
    @State private var tapToPay: TapToPay
    @State private var location = CLLocationManager()
    @State private var readiness: TapToPayReadiness.Status?
    @State private var customAmount = ""
    @State private var payment: TapToPayPayment?
    @State private var email = ""
    @State private var message: String?

    init(accountID: String, variantID: String, environment: TapToPayEnvironment = .production) {
        self.variantID = variantID
        _tapToPay = State(initialValue: TapToPay(accountID: accountID, environment: environment) {
            try await TapToPayTokens.fetch()
        })
    }

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    Text(status)
                    if case let .updatingReader(progress) = tapToPay.phase {
                        ProgressView(value: progress)
                    }
                }

                Section("Charge") {
                    Button("Charge variant") { Task { await charge(.variant) } }
                    TextField("Amount", text: $customAmount)
                        .keyboardType(.decimalPad)
                    Button("Charge amount") { Task { await charge(.amount) } }
                        .disabled(Decimal(string: customAmount) == nil)
                }
                .disabled(!canCharge)

                if tapToPay.isBusy {
                    Button("Cancel", role: .cancel) { tapToPay.cancel() }
                }

                if let payment, payment.canAttachBuyer {
                    Section("Receipt") {
                        TextField("Buyer email", text: $email)
                            .textContentType(.emailAddress)
                            .keyboardType(.emailAddress)
                            .textInputAutocapitalization(.never)
                        Button("Send receipt") { Task { await sendReceipt(for: payment) } }
                            .disabled(email.isEmpty)
                    }
                }
            }
            .navigationTitle("Tap to Pay")
            .task {
                location.requestWhenInUseAuthorization()
                await checkReadiness()
                await prepare()
            }
            .onChange(of: scenePhase) { _, newPhase in
                if newPhase == .active { Task { await prepare() } }
            }
        }
    }

    private var canCharge: Bool {
        tapToPay.isSupported && readiness == .active && !tapToPay.isBusy
    }

    private var status: String {
        if !tapToPay.isSupported { return "This iPhone can't take Tap to Pay." }
        switch tapToPay.phase {
        case .idle: return message ?? readinessText
        case .connecting: return "Connecting…"
        case let .updatingReader(progress): return "Updating reader \(progress.formatted(.percent.precision(.fractionLength(0))))"
        case .waitingForCard: return "Hold a card near the iPhone"
        case .processing: return "Processing…"
        }
    }

    private var readinessText: String {
        switch readiness {
        case .active: "Ready"
        case .needsOnboarding: "Tap to Pay isn't turned on for this business yet."
        case .pending: "Whop is setting up card payments. Try again later."
        case .unsupported: "Tap to Pay isn't available for this business."
        case nil: "Checking…"
        }
    }

    private enum Item { case variant, amount }

    private func charge(_ item: Item) async {
        do throws(TapToPayError) {
            let payment: TapToPayPayment
            switch item {
            case .variant: payment = try await tapToPay.charge(variantID: variantID)
            case .amount: payment = try await tapToPay.charge(Decimal(string: customAmount) ?? 0, currency: "usd")
            }
            self.payment = payment
            email = ""
            message = "Paid" + (payment.total.map { " \($0.amount.formatted(.currency(code: $0.currency)))" } ?? "")
        } catch {
            message = Self.text(for: error)
        }
    }

    private func sendReceipt(for payment: TapToPayPayment) async {
        do throws(TapToPayError) {
            try await tapToPay.attachBuyer(email: email, to: payment)
            self.payment = nil
            message = "Receipt sent to \(email)"
        } catch {
            message = Self.text(for: error)
        }
    }

    private func prepare() async {
        guard readiness == .active, tapToPay.isSupported, !tapToPay.isBusy else { return }
        do throws(TapToPayError) {
            try await tapToPay.prepare()
        } catch {
            message = Self.text(for: error)
        }
    }

    private func checkReadiness() async {
        do throws(TapToPayError) {
            readiness = try await tapToPay.readiness().status
        } catch {
            message = Self.text(for: error)
        }
    }

    private static func text(for error: TapToPayError) -> String {
        switch error.code {
        case .cancelled: "Payment cancelled."
        case .declined: "Card declined. Try another card."
        case .outcomeUnknown: "Couldn't confirm payment \(error.paymentID ?? ""). Check it before charging again."
        case .network: "Check your connection and try again."
        case .passcodeRequired: "Set a passcode in Settings to take Tap to Pay."
        case .termsNotAccepted: "Accept Apple's Tap to Pay terms. Sign in to an Apple Account first."
        default: error.message
        }
    }
}
```

```swift TapToPayTokens.swift theme={null}
import Foundation

enum TapToPayTokens {
    private struct Response: Decodable {
        let token: String
    }

    static func fetch() async throws -> String {
        var request = URLRequest(url: URL(string: "https://shinetime.example/api/tap-to-pay/token")!)
        request.httpMethod = "POST"
        // Add your own session credential here.
        let (data, response) = try await URLSession.shared.data(for: request)
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
            throw URLError(.badServerResponse)
        }
        return try JSONDecoder().decode(Response.self, from: data).token
    }
}
```

```swift ShineTimeApp.swift theme={null}
import SwiftUI

@main
struct ShineTimeApp: App {
    var body: some Scene {
        WindowGroup {
            PaymentScreen(accountID: "biz_xxxxxxxxxxxxx", variantID: "plan_xxxxxxxxxxxxx")
        }
    }
}
```

## How the example operates

**1. One TapToPay per screen**

The screen creates its `TapToPay` one time, in `@State`. Thus, the reader connection and the token stay when SwiftUI updates the screen.

**2. Readiness and permission on appear**

`.task` asks for location permission and reads `readiness()`. The charge buttons stay off until the account is `.active`.

**3. Prepare at launch and on return**

When the account is `.active`, `prepare()` connects the reader. It runs again each time that the app comes back to the foreground.

**4. Status from phase**

`status` uses a `switch` on `phase`. The progress bar shows only during `.updatingReader`.

**5. Cancel while busy**

The cancel button shows only while `isBusy` is `true`.

**6. Receipt after payment**

The email field shows only for a payment with `canAttachBuyer` set to `true`.

To try the example in [sandbox](https://docs.whop.com/tap-to-pay/testing.md), give `environment: .sandbox` to `PaymentScreen`.

## Next steps

> [card] [SDK reference](https://docs.whop.com/tap-to-pay/reference.md)
>
> All public types and members.

> [card] [Go live](https://docs.whop.com/tap-to-pay/go-live.md)
>
> The checklist to complete before you release your app.


## Related topics

- [Build the Tap to Pay Payment Screen](https://docs.whop.com/tap-to-pay/payment-screen.md)
- [Tap to Pay SDK Reference](https://docs.whop.com/tap-to-pay/reference.md)
- [Getting Started with Tap to Pay](https://docs.whop.com/tap-to-pay/getting-started.md)
