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
}
}
}