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

# Show custom success message

> Display a custom success message or modal after payment completion.

Display a personalized success message or modal to users after their payment completes.

## Recipe

> [tab] Web
>
> ```javascript theme={"dark"}
> checkout.addEventListener('primer:ready', (event) => {
>   const primer = event.detail;
>
>   primer.onPaymentSuccess = ({ payment, paymentMethodType }) => {
>     const message = `Payment of ${payment.amount} completed via ${paymentMethodType}`;
>     showSuccessModal(message);
>   };
> });
> ```

> [tab] Android
>
> ```kotlin theme={"dark"}
> val state by checkout.state.collectAsStateWithLifecycle()
> LaunchedEffect(state) {
>     when (val s = state) {
>         is PrimerCheckoutState.Success -> {
>             val payment = s.checkoutData.payment
>             Log.d("Checkout", "Payment completed: ${payment.id}")
>
>             navController.navigate("confirmation/${payment.id}") {
>                 popUpTo("checkout") { inclusive = true }
>             }
>         }
>         is PrimerCheckoutState.Failure -> {
>             val error = s.primerError
>             Log.e("Checkout", "Failed: ${error.description}")
>             Log.e("Checkout", "Diagnostics: ${error.diagnosticsId}")
>         }
>         else -> Unit
>     }
> }
>
> PrimerCheckoutSheet(checkout = checkout)
> ```

> [tab] iOS
>
> ```swift theme={"dark"}
> struct CheckoutView: View {
>   let clientToken: String
>   @State private var showSuccess = false
>
>   var body: some View {
>     ZStack {
>       PrimerCheckout(
>         clientToken: clientToken,
>         primerSettings: PrimerSettings(uiOptions: PrimerUIOptions(isSuccessScreenEnabled: false)),
>         onCompletion: { state in
>           if case .success = state {
>             withAnimation { showSuccess = true }
>           }
>         }
>       )
>
>       if showSuccess {
>         SuccessOverlay()
>           .transition(.opacity)
>       }
>     }
>   }
> }
> ```

> [tab] React Native
>
> ```tsx theme={"dark"}
> import { useEffect, useState } from 'react';
> import { Button, View } from 'react-native';
> import {
>   PrimerCheckoutProvider,
>   PrimerCheckoutSheet,
>   PrimerSuccessScreen,
>   usePrimerCheckout,
> } from '@primer-io/react-native';
> import type { PrimerSettings } from '@primer-io/react-native';
>
> const settings: PrimerSettings = {
>   uiOptions: { isSuccessScreenEnabled: false },
> };
>
> function SuccessListener({ onSuccess }: { onSuccess: () => void }) {
>   const { paymentOutcome } = usePrimerCheckout();
>
>   useEffect(() => {
>     if (paymentOutcome?.status === 'success') {
>       onSuccess();
>     }
>   }, [paymentOutcome, onSuccess]);
>
>   return null;
> }
>
> export function CheckoutScreen({ fetchClientToken }: { fetchClientToken: () => Promise<string> }) {
>   const [clientToken, setClientToken] = useState<string | null>(null);
>   const [visible, setVisible] = useState(false);
>   const [showSuccess, setShowSuccess] = useState(false);
>
>   const openCheckout = async () => {
>     setClientToken(await fetchClientToken());
>     setVisible(true);
>   };
>
>   if (showSuccess) {
>     return (
>       <View style={{ flex: 1, justifyContent: 'center', padding: 24 }}>
>         <PrimerSuccessScreen title="Thank you" subtitle="Your order is confirmed." />
>       </View>
>     );
>   }
>
>   return (
>     <View style={{ padding: 24 }}>
>       <Button title="Checkout" onPress={openCheckout} />
>       {clientToken !== null && (
>         <PrimerCheckoutProvider clientToken={clientToken} settings={settings}>
>           <SuccessListener onSuccess={() => setShowSuccess(true)} />
>           <PrimerCheckoutSheet
>             visible={visible}
>             onRequestDismiss={() => setVisible(false)}
>             onDismiss={() => setClientToken(null)}
>           />
>         </PrimerCheckoutProvider>
>       )}
>     </View>
>   );
> }
> ```
>
> `fetchClientToken` stands for the call to your backend that returns a new client token. Each checkout attempt mounts a new `PrimerCheckoutProvider` with a new client token, as in the [`PrimerCheckoutSheet` example](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/primer-checkout-sheet#usage). Keep the success state in `CheckoutScreen`, outside the provider, because `onDismiss` unmounts the provider.

## How it works

> [tab] Web
>
> 1. Listen for the `primer:ready` event to access the Primer SDK instance
> 2. Set the `onPaymentSuccess` callback
> 3. Access `payment` details and `paymentMethodType` from the callback parameters
> 4. Display your custom UI (modal, toast, inline message, etc.)

> [tab] Android
>
> 1. Observe `checkout.state` with `collectAsStateWithLifecycle()` and react in a `LaunchedEffect`
> 2. Handle `PrimerCheckoutState.Success` to access `PrimerCheckoutData` with payment details
> 3. Navigate to a confirmation screen or update your order UI
>
> | Property | Type | Description |
> | - | - | - |
> | `payment.id` | `String` | The Primer payment ID |
> | `payment.orderId` | `String?` | Your order ID |
>
> > [!NOTE]
> >
> > When using `PrimerCheckoutSheet`, the SDK shows a default success screen that auto-dismisses after 3 seconds. The `Success` state emits immediately -- you do not need to wait for the dismiss. Navigate as soon as you observe the state.

> [tab] iOS
>
> 1. Turn off the SDK success screen with `PrimerUIOptions(isSuccessScreenEnabled: false)`
>
> 2. Use the `onCompletion` callback on `PrimerCheckout`
>
> 3. Match on `.success` to detect payment completion (bind it with `case .success(let result)` to read `result.paymentId`)
>
> 4. Update your SwiftUI state to show a custom success view
>
> > [!NOTE]
> >
> > By default, `PrimerCheckout` shows its own success screen for 3 seconds and delivers `.success` to `onCompletion` when that screen closes. With `isSuccessScreenEnabled: false`, the SDK shows nothing and delivers `.success` as soon as the payment completes.

> [tab] React Native
>
> 1. Turn off the sheet's success screen with `settings.uiOptions.isSuccessScreenEnabled: false`
>
> 2. Read `paymentOutcome` from [`usePrimerCheckout()`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/use-primer-checkout) in a component inside `PrimerCheckoutProvider`, and react to it in a `useEffect`
>
> 3. When `status` is `'success'`, keep the result in your own state (`paymentOutcome.data.payment` holds `id` and `orderId`)
>
> 4. Show your own success UI. [`PrimerSuccessScreen`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/common/status-screens) renders the SDK's success screen with your title and subtitle
>
> > [!NOTE]
> >
> > By default, `PrimerCheckoutSheet` shows its own success screen for 3 seconds and then calls `onRequestDismiss`. `paymentOutcome` is set as soon as the payment completes, so you don't need to wait for the screen to close. With `isSuccessScreenEnabled: false`, the sheet shows no success screen: it clears `paymentOutcome` and calls `onRequestDismiss` right away. Keep what you need in your own state, as in the recipe.

## Variations

### Custom success with payment details

> [tab] Web
>
> ```javascript theme={"dark"}
> primer.onPaymentSuccess = ({ payment }) => {
>   document.getElementById('success-container').innerHTML = `
>     <h2>Thank you for your order!</h2>
>     <p>Order ID: ${payment.orderId}</p>
>     <p>Amount: ${formatCurrency(payment.amount, payment.currencyCode)}</p>
>   `;
> };
> ```

> [tab] Android
>
> Display payment details from the `Success` event:
>
> ```kotlin theme={"dark"}
> val state by checkout.state.collectAsStateWithLifecycle()
> LaunchedEffect(state) {
>     when (val s = state) {
>         is PrimerCheckoutState.Success -> {
>             val payment = s.checkoutData.payment
>             showSuccessScreen(
>                 orderId = payment.orderId,
>                 paymentId = payment.id,
>             )
>         }
>         is PrimerCheckoutState.Failure -> {
>             Log.e("Checkout", "Failed: ${s.primerError.diagnosticsId}")
>         }
>         else -> Unit
>     }
> }
>
> PrimerCheckoutSheet(checkout = checkout)
> ```

> [tab] iOS
>
> Display payment details from the success result:
>
> ```swift theme={"dark"}
> PrimerCheckout(
>   clientToken: clientToken,
>   primerSettings: PrimerSettings(uiOptions: PrimerUIOptions(isSuccessScreenEnabled: false)),
>   onCompletion: { state in
>     switch state {
>     case .success(let result):
>       showSuccessScreen(paymentId: result.paymentId)
>     case let .failure(error, _):
>       print("Failed [\(error.errorId)]: \(error.diagnosticsId)")
>     default:
>       break
>     }
>   }
> )
> ```

> [tab] React Native
>
> Display payment details from the success outcome:
>
> ```tsx theme={"dark"}
> import { useEffect, useState } from 'react';
> import { Button, Text, View } from 'react-native';
> import {
>   PrimerCheckoutProvider,
>   PrimerCheckoutSheet,
>   usePrimerCheckout,
> } from '@primer-io/react-native';
> import type { CheckoutDataPayment, PrimerSettings } from '@primer-io/react-native';
>
> const settings: PrimerSettings = {
>   uiOptions: { isSuccessScreenEnabled: false },
> };
>
> function OutcomeListener({ onSuccess }: { onSuccess: (payment: CheckoutDataPayment) => void }) {
>   const { paymentOutcome } = usePrimerCheckout();
>
>   useEffect(() => {
>     if (paymentOutcome?.status === 'success') {
>       onSuccess(paymentOutcome.data.payment ?? {});
>     } else if (paymentOutcome?.status === 'error') {
>       console.error(`Failed [${paymentOutcome.error.errorId}]: ${paymentOutcome.error.diagnosticsId ?? 'N/A'}`);
>     }
>   }, [paymentOutcome, onSuccess]);
>
>   return null;
> }
>
> export function CheckoutScreen({ fetchClientToken }: { fetchClientToken: () => Promise<string> }) {
>   const [clientToken, setClientToken] = useState<string | null>(null);
>   const [visible, setVisible] = useState(false);
>   const [payment, setPayment] = useState<CheckoutDataPayment | null>(null);
>
>   const openCheckout = async () => {
>     setClientToken(await fetchClientToken());
>     setVisible(true);
>   };
>
>   if (payment) {
>     return (
>       <View style={{ gap: 8, padding: 24 }}>
>         <Text style={{ fontSize: 20, fontWeight: '600' }}>Thank you for your order</Text>
>         <Text>Order ID: {payment.orderId ?? 'N/A'}</Text>
>         <Text>Payment ID: {payment.id ?? 'N/A'}</Text>
>       </View>
>     );
>   }
>
>   return (
>     <View style={{ padding: 24 }}>
>       <Button title="Checkout" onPress={openCheckout} />
>       {clientToken !== null && (
>         <PrimerCheckoutProvider clientToken={clientToken} settings={settings}>
>           <OutcomeListener onSuccess={setPayment} />
>           <PrimerCheckoutSheet
>             visible={visible}
>             onRequestDismiss={() => setVisible(false)}
>             onDismiss={() => setClientToken(null)}
>           />
>         </PrimerCheckoutProvider>
>       )}
>     </View>
>   );
> }
> ```
>
> `fetchClientToken` stands for the call to your backend that returns a new client token, as in the recipe.

### Handle checkout dismissal

> [tab] Web
>
> ```javascript theme={"dark"}
> primer.onPaymentSuccess = () => {
>   const successEl = document.getElementById('success-message');
>   successEl.classList.add('visible');
>
>   // Hide checkout form
>   document.querySelector('primer-checkout').style.display = 'none';
> };
> ```

> [tab] Android
>
> Use the `onDismiss` callback to detect when the checkout sheet is closed:
>
> ```kotlin theme={"dark"}
> PrimerCheckoutSheet(
>     checkout = checkout,
>     onDismiss = {
>         navController.popBackStack()
>     },
> )
> ```
>
> > [!NOTE]
> >
> > `onDismiss` fires after the sheet closes. If you already navigated away when observing `PrimerCheckoutState.Success`, guard against double navigation.

> [tab] iOS
>
> Handle the `.dismissed` case to detect when the shopper closes the checkout. The payment method list shows a close button when `dismissalMechanism` includes `.closeButton`. Tapping it ends the checkout with `.dismissed`. When other methods are available, the close button on a payment method screen, such as the card form, returns the shopper to the list. In that case, `.dismissed` does not arrive. With a single method, that close button ends the checkout with `.dismissed`. If you present `PrimerCheckout` in your own sheet, a swipe-down does not reach `onCompletion`, so use your sheet's `onDismiss` for that.
>
> ```swift theme={"dark"}
> PrimerCheckout(
>   clientToken: clientToken,
>   primerSettings: PrimerSettings(
>     uiOptions: PrimerUIOptions(
>       dismissalMechanism: [.closeButton]
>     )
>   ),
>   onCompletion: { state in
>     switch state {
>     case .success:
>       withAnimation { showSuccess = true }
>     case .dismissed:
>       // The shopper closed the checkout
>       break
>     default:
>       break
>     }
>   }
> )
> ```

> [tab] React Native
>
> Use the dismissal callbacks of `PrimerCheckoutSheet` to detect when the checkout closes: `onRequestDismiss` runs when the shopper or the sheet asks to close (backdrop tap, swipe down on the drag handle, Android back on a screen without a Back button, Cancel, or the end of the success screen), and `onDismiss` runs after the sheet has finished closing:
>
> ```tsx theme={"dark"}
> import { useState } from 'react';
> import { PrimerCheckoutProvider, PrimerCheckoutSheet } from '@primer-io/react-native';
>
> export function CheckoutScreen({
>   clientToken,
>   navigation,
> }: {
>   clientToken: string;
>   navigation: { goBack: () => void };
> }) {
>   const [visible, setVisible] = useState(true);
>
>   return (
>     <PrimerCheckoutProvider clientToken={clientToken}>
>       <PrimerCheckoutSheet
>         visible={visible}
>         onRequestDismiss={() => setVisible(false)}
>         onDismiss={() => navigation.goBack()}
>       />
>     </PrimerCheckoutProvider>
>   );
> }
> ```
>
> > [!NOTE]
> >
> > The sheet closes only when `onRequestDismiss` sets `visible` to `false`. `onDismiss` also runs after a successful payment, because the sheet asks to close after its success screen, or right away when that screen is turned off. If you already navigated away when you read `paymentOutcome`, guard against double navigation.

## See also

> [card] [Redirect after payment](https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/redirect-after-payment.md)
>
> Navigate to a confirmation page after payment

> [card] [Error handling](https://primer.io/docs/checkout/primer-checkout/build-your-ui/error-handling.md)
>
> Handle payment failures and display error messages


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.