# Content Security Policy Source: https://primer.io/docs/checkout/advanced/content-security-policy > [!NOTE] > > This guide is only relevant for the Web integration. A `Content-Security-Policy` header helps to protect your checkout page from cross-site scripting attacks by allowing you to define where resources can be loaded from. You'll need to add a few things to your allowlist: | **Policy** | **Origin** | **Notes** | | :- | :- | :- | | `script-src` | `sdk.primer.io` | required | | `frame-src` | `*.primer.io` | required | | `style-src` | `*.primer.io` | required | | `style-src` | `'unsafe-inline'` | required | | `connect-src` | `*.primer.io` | required | | `frame-src` | `*.3dsecure.io` | For 3DS | | `script-src` | `x.klarnacdn.net` | For Klarna Payments | | `connect-src` | `x.klarna.com` | For Klarna Payments | | `script-src` | `*.paypal.com` | For PayPal Payments | | `frame-src` | `*.paypal.com` | For PayPal Payments | | `connect-src` | `*.paypal.com` | For PayPal Payments | | `img-src` | `*.paypal.com` | For PayPal Payments | | `script-src` | `*.paypalobjects.com` | For PayPal Payments | | `img-src` | `*.paypalobjects.com` | For PayPal Payments | | `script-src` | `js.stripe.com` | For Stripe Payments | | `connect-src` | `*.stripe.com` | For Stripe Payments | # Manual payment creation Source: https://primer.io/docs/checkout/advanced/manual-payment-creation ## Overview With version 2 of our Web SDK, Universal Checkout automatically creates and handles Payments by default. This greatly reduces the complexity and amount of boilerplate required to integrate Primer. For backward compatibility reasons, it is still possible to manually create and resume payments. Follow this guide to setup Universal Checkout so that you handle the payment lifecycle. ### Flow ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/advanced/flow.png) Manual payment creation flow 1. Generate a `clientToken` on your backend by creating a *Client Session* with POST 2. Initialize Universal Checkout with the `clientToken` to render the UI. 3. Universal Checkout will generate a `paymentMethodToken` when the customer submits their payment data, or when they select particular payment methods. 4. Create a payment using the `paymentMethodToken` via the Payments API POST 5. If the response indicates a `requiredAction`, you'll get a new `clientToken`. 6. Pass the `clientToken` back to Universal Checkout to render next steps, like 3DS, and get a `resumeToken`. 7. Call POST with the `resumeToken` to resume the payment and wrap things up. (If a new `requiredAction` is returned, you'll have to go back to step 5.) ## Generate a Client Token ### Get an API Key Ensure you have [an API key configured](/docs/api-reference/get-started/authentication). Make sure to set the following scopes for your API Key: * `client_tokens:write` * `transactions:authorize` ### Generate a Client Session Follow the instructions [here](/docs/checkout/client-session#create-a-client-session) to create a client session, which will be used to initialize the checkout. ## Set up Universal Checkout > [tab] Web > > ### Step 1. Turn off automatic payment creation > > The Universal Checkout option `paymentHandling` defines how the SDK should handle payment creation and resume. > > Set `paymentHandling` to `MANUAL` to turn off automatic payment handling. > > This disables the callbacks `onBeforePayment` and `onCheckoutComplete`. > > ```typescript Typescript theme={"dark"} > Primer.showUniversalCheckout(clientToken, { > /* Other options... */ > > paymentHandling: 'MANUAL', > }) > ``` > > ### Step 2. Handle callbacks for creating and resuming payments > > Two callbacks must be implemented: > > * `onTokenizeSuccess()` to create payments with `paymentMethodToken` > * `onResumeSuccess()` to resume payments with `resumeToken` > > ```typescript Typescript theme={"dark"} > Primer.showUniversalCheckout(clientToken, { > /* Other options... */ > > paymentHanding: 'MANUAL', > async onTokenizeSuccess(paymentMethodTokenData, handler) { > // Send the Payment Method Token to your server > // to create a payment using Payments API > const response = await createPayment(paymentMethodTokenData.token) > > // Call `handler.handleFailure` to cancel the flow and display an error message > if (!response) { > return handler.handleFailure('The payment failed. Please try with another payment method.') > } > > // If a new clientToken is available, call `handler.continueWithNewClientToken` to refresh the client session. > // The checkout will automatically perform the action required by the Workflow. > if (response.requiredAction.clientToken) { > return handler.continueWithNewClientToken(response.requiredAction.clientToken) > } > > // Display the success screen > return handler.handleSuccess() > }, > > async onResumeSuccess(resumeTokenData, handler) { > // Send the resume token to your server to resume the payment > const response = await resumePayment(resumeTokenData.resumeToken) > > // Call `handler.handleFailure` to cancel the flow and display an error message > if (!response) { > return handler.handleFailure('The payment failed. Please try with another payment method.') > } > > // If a new clientToken is available, call `handler.continueWithNewClientToken` to refresh the client session. > // The checkout will automatically perform the action required by the Workflow > if (response.requiredAction.clientToken) { > return handler.continueWithNewClientToken(response.requiredAction.clientToken) > } > > // Display the success screen > return handler.handleSuccess() > }, > }) > ``` > > #### Handle `onTokenizeSuccess()` callback > > * When a customer submits their payment data, the payment details are tokenized and you'll receive a `paymentMethodToken` in `onTokenizeSuccess()` > * [Create a payment request](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment) with the `paymentMethodToken` > * If the payment is successful, call `handler.handleSuccess()` in order to display a success screen. > * If the payment is unsuccessful, call `handler.handleFailure(errorMessage)` to display an error / failed message. > * Payments API may return a new `clientToken` for additional steps (in the `requiredActions` on the response). In this case, call `handler.continueWithNewClientToken(clientToken)` to the checkout. > > #### Handle `onResumeSuccess()` callback > > > [!WARNING] > > > > Handling `onResumeSuccess()` is required to fully support 3DS and the majority of payment methods. > > * You will receive a `resumeToken` via the `onResumeSuccess()` callback if applicable > * [Send a resume payment request](/docs/api-reference/v2.4/api-reference/payments-api/resume-a-payment) with the `resumeToken` > * If the payment is successful, call `handler.handleSuccess()` in order to display a success screen. > * If the payment is unsuccessful, call `handler.handleFailure(errorMessage)` to display an error / failed message. > * Payments API may *again* return a new `clientToken` for additional steps. In this case, call `handler.continueWithNewClientToken(clientToken)` again. > [tab] Android - Kotlin > > ### Step 1. Install > > Add the Primer BOM and the SDK to your app module's `build.gradle.kts` or `build.gradle` file, replacing `` with the latest version from the [Android SDK changelog](/docs/changelogs/android-sdk). The BOM keeps the SDK and any Primer payment method libraries on the same version: > > ```kotlin Kotlin theme={"dark"} > repositories { > mavenCentral() > } > > dependencies { > implementation(platform("io.primer:bom:")) > implementation("io.primer:android") > } > ``` > > ```groovy Groovy theme={"dark"} > repositories { > mavenCentral() > } > > dependencies { > implementation platform('io.primer:bom:') > implementation 'io.primer:android' > } > ``` > > It is highly recommended to add following settings to your `app/build.gradle` file: > > ```kotlin KOTLIN theme={"dark"} > android { > kotlinOptions { > freeCompilerArgs += '-Xjvm-default=all' > } > } > ``` > > ### Step 2. Initialize the SDK > > Prepare the `PrimerCheckoutListener` that will handle the callbacks that happen during the lifecycle. > > Import the Primer SDK and set its listener as shown in the following example. > > In order to use manual payment handling, you have to set `paymentHandling` to `**PrimerPaymentHandling.MANUAL**` in the `PrimerSettings`. > > ```kotlin KOTLIN theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > > private val listener = object : PrimerCheckoutListener { > > override fun onTokenizeSuccess( > paymentMethodToken: PrimerPaymentMethodToken, > decisionHandler: PrimerResumeDecisionHandler > ) { > // use the received paymentMethodToken to make the payment > // and use decisionHandler to instruct SDK about next steps based on payment status > } > > override fun onResumeSuccess(resumeToken: String, decisionHandler: PrimerResumeDecisionHandler) { > // use the received resumeToken to resume the payment > // and use decisionHandler to instruct SDK about next steps based on payment status > } > } > > override fun onCreate(savedInstanceState: Bundle?) { > super.onCreate(savedInstanceState) > setContentView(R.layout.activity_main) > > configureCheckout() > } > > private fun configureCheckout() { > // Set the paymentHandling to manual > val settings = PrimerSettings(paymentHandling = PrimerPaymentHandling.MANUAL) > Primer.instance.configure(settings, listener) > } > } > ``` > > > [!NOTE] > > > > Check the SDK API [here](https://www.notion.so/primerio/API-Reference-e58ee6d184ff4cd7ae2f90c6b28aaaba) to customize your SDK settings. > > ### Step 3. Generate a client token > > > [!TIP] > > > > For more information on generating a client token, take a look at our *[client session guide](#generate-a-client-token).* > > Make an API call to your backend to fetch a Client Token. Here is a simple example of how it can be done from your activity: > > ```kotlin KOTLIN theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > > // Other code goes here > > private lateinit var viewModel: CheckoutViewModel > > override fun onCreate(savedInstanceState: Bundle?) { > super.onCreate(savedInstanceState) > setContentView(R.layout.activity_main) > > configureCheckout() > setupViewModel() > setupObservers() > fetchClientToken() > } > > private fun setupViewModel() { > viewModel = ViewModelProvider(this).get(CheckoutViewModel::class.java) > } > > private fun fetchClientToken() = viewModel.fetchClientToken() > > private fun setupObservers() { > viewModel.clientToken.observe(this) { clientToken -> > // show checkout > } > } > } > ``` > > Your view model code may look something like this: > > ```kotlin KOTLIN theme={"dark"} > class CheckoutViewModel : ViewModel() { > > private val _clientToken = MutableLiveData() > val clientToken: LiveData = _clientToken > > fun fetchClientToken() { > // fetch your token here (ask your backend to provide token) > _clientToken.postValue("retrieved_token") > } > } > ``` > > ### Step 4. Show **Universal Checkout** > > When the client token is retrieved, show Universal Checkout. > > ```kotlin KOTLIN theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > > // other code goes here > > private fun setupObservers() { > viewModel.clientToken.observe(this) { clientToken -> > showUniversalCheckout(clientToken) > } > } > > private fun showUniversalCheckout(clientToken: String) { > Primer.instance.showUniversalCheckout(this, clientToken) > } > } > ``` > > > [!NOTE] > > > > You should now be able to see Universal Checkout! The user can now interact with Universal Checkout. > > ### Step 5. Handle callbacks for creating and resuming payments > > Once the payment method data has been securely captured, Primer will return a uniform `paymentMethodToken` via `onTokenizeSuccess` that can be safely passed to your server to create a payment with the Payments API. > > #### Handle `onTokenizeSuccess` callback > > * When a customer submits their payment data, the payment details are tokenized and you'll receive a `paymentMethodToken` in `onTokenizeSuccess`. > > * [Create a payment request](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment) with the payment method token data. > > * If the payment is successful, call `decisionHandler.handleSuccess()` in order to display a success screen. > > * If the payment is unsuccessful, call `decisionHandler.handleFailure("Your error message")` to display an error / failed message. > > * Payments API may return a `requiredAction` with a new `clientToken` for additional steps. In this case, call `decisionHandler.continueWithNewClientToken(clientToken)`. > > ```kotlin KOTLIN theme={"dark"} > private val listener = object: PrimerCheckoutListener { > > override fun onTokenizeSuccess( > paymentMethodToken: PrimerPaymentMethodToken, > decisionHandler: PrimerResumeDecisionHandler > ) { > viewModel.sendPaymentMethodToken(paymentMethodToken, decisionHandler) > } > } > ``` > > ```kotlin KOTLIN theme={"dark"} > class CheckoutViewModel : ViewModel() { > > // ⚠️ remember to call decisionHandler to resume SDK flow. > fun sendPaymentMethodToken(paymentMethodToken: PrimerPaymentMethodToken, decisionHandler: PrimerResumeDecisionHandler) { > val paymentResponse = //... > if (paymentResponse.isSuccessful()) { > decisionHandler.handleSuccess() > } else if (paymentResponse.isPending()) { > decisionHandler.continueWithNewClientToken(paymentResponse.requiredAction.clientToken) > } else { > decisionHandler.handleFailure("Your error message.") > } > } > } > ``` > > #### Handle `onResumeSuccess` callback > > Once the required actions are completed, Primer will return `resumeToken` via `onResumeSuccess` that can be safely passed to your server to resume a payment with the Payments API. > > * You will receive a `resumeToken` via the `onResumeSuccess()` callback if applicable. > > * [Send a resume payment request](/docs/api-reference/v2.4/api-reference/payments-api/resume-a-payment) with `resumeToken` > > * If the payment is successful, call `decisionHandler.handleSuccess()` in order to display a success screen. > > * If the payment is unsuccessful, call `decisionHandler.handleFailure("Your error message")` to display an error / failed message. > > * Payments API may return a `requiredAction` with a new `clientToken` for additional steps. In this case, call `decisionHandler.continueWithNewClientToken(clientToken)`. > > ```kotlin KOTLIN theme={"dark"} > private val listener = object : PrimerCheckoutListener { > > override fun onResume(resumeToken: String, decisionHandler: PrimerResumeDecisionHandler) { > viewModel.sendResumeToken(resumeToken, decisionHandler) > } > } > ``` > > ```kotlin KOTLIN theme={"dark"} > class CheckoutViewModel : ViewModel() { > > // ⚠️ remember to call decisionHandler to resume SDK flow. > fun sendResumeToken(resumeToken: String, decisionHandler: PrimerResumeDecisionHandler) { > val paymentResponse = //... > if (paymentResponse.isSuccessful()) { > decisionHandler.handleSuccess() > } else if (paymentResponse.isPending()) { > decisionHandler.continueWithNewClientToken(paymentResponse.requiredAction.clientToken) > } else { > decisionHandler.handleFailure("Your error message.") > } > } > } > ``` > [tab] Android - Java > > ### Step 1. Install > > Add the Primer BOM and the SDK to your app module's `build.gradle.kts` or `build.gradle` file, replacing `` with the latest version from the [Android SDK changelog](/docs/changelogs/android-sdk). The BOM keeps the SDK and any Primer payment method libraries on the same version: > > ```kotlin Kotlin theme={"dark"} > repositories { > mavenCentral() > } > > dependencies { > implementation(platform("io.primer:bom:")) > implementation("io.primer:android") > } > ``` > > ```groovy Groovy theme={"dark"} > repositories { > mavenCentral() > } > > dependencies { > implementation platform('io.primer:bom:') > implementation 'io.primer:android' > } > ``` > > ### Step 2. Initialize the SDK > > Prepare the `PrimerCheckoutListener` that will handle the callbacks that happen during the lifecycle. > > Import the Primer SDK and set its listener as shown in the following example. > > In order to use manual payment handling, you have to set `paymentHandling` to `**PrimerPaymentHandling.MANUAL**` in the `PrimerSettings`. > > ```java Java theme={"dark"} > public class CheckoutActivity extends AppCompatActivity { > > private final PrimerCheckoutListener listener = new PrimerCheckoutListener() { > > @Override > public void onTokenizeSuccess(@NonNull PrimerPaymentMethodToken primerPaymentMethodToken, > @NonNull PrimerResumeDecisionHandler decisionHandler) { > // use the received paymentMethodToken to make the payment > // and use decisionHandler to instruct SDK about next steps based on payment status > } > > @Override > public void onResumeSuccess(@NonNull String resumeToken, > @NonNull PrimerResumeDecisionHandler decisionHandler) { > // use the received resumeToken to resume the payment > // and use decisionHandler to instruct SDK about next steps based on payment status > } > }; > > @Override > protected void onCreate(@Nullable Bundle savedInstanceState) { > super.onCreate(savedInstanceState); > setContentView(R.layout.activity_main); > > configureCheckout(); > } > > private void configureCheckout() { > // Set the paymentHandling to manual > PrimerSettings settings = new PrimerSettings(); > settings.setPaymentHandling(PrimerPaymentHandling.MANUAL); > > Primer.getInstance().configure(settings, listener); > } > } > ``` > > > [!NOTE] > > > > Check the SDK API [here](https://www.notion.so/primerio/API-Reference-e58ee6d184ff4cd7ae2f90c6b28aaaba) to customize your SDK settings. > > ### Step 3. Generate a client token > > > [!TIP] > > > > For more information on generating a client token, take a look at our *[client session guide](#generate-a-client-token).* > > Make an API call to your backend to fetch a client token. Here is a simple example of how it can be done from your activity: > > ```java Java theme={"dark"} > public class CheckoutActivity extends AppCompatActivity { > > private CheckoutViewModel viewModel; > > @Override > protected void onCreate(@Nullable Bundle savedInstanceState) { > super.onCreate(savedInstanceState); > setContentView(R.layout.activity_main); > > configureCheckout(); > setupViewModel(); > setupObservers(); > fetchClientToken(); > } > > private void setupViewModel() { > viewModel = new ViewModelProvider(this).get(CheckoutViewModel.class); > } > > private void fetchClientToken() { > viewModel.fetchClientToken(); > } > > private void setupObservers() { > viewModel.clientToken.observe(this, clientToken -> { > > }); > } > } > ``` > > Your view model code may look something like this: > > ```java Java theme={"dark"} > public class CheckoutViewModel extends ViewModel { > > private final MutableLiveData _clientToken = new MutableLiveData<>(); > public LiveData clientToken = _clientToken; > > public void fetchClientToken() { > // fetch your token here (ask your backend to provide token) > _clientToken.postValue("retrieved_token"); > } > } > ``` > > ### Step 4. Show **Universal Checkout** > > When the client token is retrieved, show Universal Checkout. > > ```java Java theme={"dark"} > public class CheckoutActivity extends AppCompatActivity { > > // other code goes here > > private void setupObservers() { > viewModel.clientToken.observe(this, this::showUniversalCheckout); > } > > private void showUniversalCheckout(String clientToken) { > Primer.getInstance().showUniversalCheckout(this, clientToken); > } > } > ``` > > > [!NOTE] > > > > You should now be able to see Universal Checkout! The user can now interact with Universal Checkout. > > ### Step 5. Handle callbacks for creating and resuming payments > > Once the payment method data has been securely captured, Primer will return a uniform `paymentMethodToken` via `onTokenizeSuccess` that can be safely passed to your server to create a payment with the Payments API. > > #### Handle `onTokenizeSuccess` callback > > * When a customer submits their payment data, the payment details are tokenized and you'll receive a `paymentMethodToken` in `onTokenizeSuccess`. > > * [Create a payment request](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment) with the payment method token data. > > * If the payment is successful, call `decisionHandler.handleSuccess()` in order to display a success screen. > > * If the payment is unsuccessful, call `decisionHandler.handleFailure("Your error message")` to display an error / failed message. > > * Payments API may return a `requiredAction` with a new `clientToken` for additional steps. In this case, call `decisionHandler.continueWithNewClientToken(clientToken)`. > > ```java Java theme={"dark"} > private final PrimerCheckoutListener listener = new PrimerCheckoutListener() { > > @Override > public void onTokenizeSuccess(@NonNull PrimerPaymentMethodToken primerPaymentMethodToken, > @NonNull PrimerResumeDecisionHandler decisionHandler) { > > viewModel.sendPaymentMethodToken(primerPaymentMethodToken) > // ⚠️ remember to call decisionHandler to resume SDK flow. > } > }; > ``` > > #### Handle `onResumeSuccess` callback > > Once the required actions are completed, Primer will return `resumeToken` via `onResumeSuccess` that can be safely passed to your server to resume a payment with the Payments API. > > * You will receive a `resumeToken` via the `onResumeSuccess()` callback if applicable. > > * [Send a resume payment request](/docs/api-reference/v2.4/api-reference/payments-api/resume-a-payment) with `resumeToken` > > * If the payment is successful, call `decisionHandler.handleSuccess()` in order to display a success screen. > > * If the payment is unsuccessful, call `decisionHandler.handleFailure("Your error message")` to display an error / failed message. > > * Payments API may return a `requiredAction` with a new `clientToken` for additional steps. In this case, call `decisionHandler.continueWithNewClientToken(clientToken)`. > > ```java Java theme={"dark"} > private final PrimerCheckoutListener listener = new PrimerCheckoutListener() { > > @Override > public void onResumeSuccess(@NonNull String resumeToken, > @NonNull PrimerResumeDecisionHandler primerResumeDecisionHandler) { > viewModel.sendResumeToken(resumeToken) > // ⚠️ remember to call decisionHandler to resume SDK flow. > } > }; > ``` > [tab] iOS > > ### Step 1. Install the SDK > > #### With CocoaPods > > The iOS SDK is available with Cocoapods. Just add the PrimerSDK pod and run `pod install` . > > ```ruby RUBY theme={"dark"} > target 'MyApp' do > # Other pods... > > # Add this to your Podfile > pod 'PrimerSDK', '~> 2.0.0' # Add this line > end > ``` > > Then run `pod install` to install `PrimerSDK` on your workspace. > > For specific versions of the SDK, please refer to the [changelog](/docs/changelogs/ios-sdk). > > > [!NOTE] > > > > In case you encounter an error that the bundle needs signing on Xcode 14, add the following post-install script in your podfile. > > > > ```ruby RUBY theme={"dark"} > > post_install do |installer| > > installer.pods_project.targets.each do |target| > > if target.respond_to?(:product_type) and target.product_type == "com.apple.product-type.bundle" > > target.build_configurations.each do |config| > > config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' > > end > > end > > end > > end > > ``` > > #### With Swift Package Manager > > The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into Xcode. In order to add PrimerSDK with Swift Package Manager; > > 1. Select your project, and then navigate to `Package Dependencies` > 2. Click on the **+** button at the bottom-left of the `Packages` section > 3. Paste [https://github.com/primer-io/primer-sdk-ios.git](https://github.com/primer-io/primer-sdk-ios.git) into the **Search Bar** > 4. Press **Add Package** > 5. Let Xcode download the package and set everything up > > ![schema](https://mintcdn.com/primer-cc826789/dM-udzSll5kL79ou/images/checkout/advanced/spm-3.png?fit=max\&auto=format\&n=dM-udzSll5kL79ou\&q=85\&s=ab14396cc8485f895bf2bfa319b41e6f) > > ### Step 2. Initialize the SDK > > Import the Primer SDK and set its delegate as shown in the following example. You have to set `paymentHandling: .manual` in the `PrimerSettings`. > > ```swift SWIFT theme={"dark"} > import PrimerSDK > > class MyViewController: UIViewController { > > override func viewDidLoad() { > super.viewDidLoad() > > // Set the paymentHandling to manual. > let settings = PrimerSettings(paymentHandling: .manual) > Primer.shared.configure(settings: settings, delegate: self) > } > } > > extension MyViewController: PrimerDelegate { > > func primerDidTokenizePaymentMethod(_ paymentMethodTokenData: PrimerPaymentMethodTokenData, decisionHandler: @escaping (PrimerResumeDecision) -> Void) { > // Use this method to create a payment. > } > > func primerDidResumeWith(_ resumeToken: String, decisionHandler: @escaping (PrimerResumeDecision) -> Void) { > // If needed, use this method to resume the previously created payment. > } > } > ``` > > > [!NOTE] > > > > Check the SDK API [here](https://www.notion.so/primerio/API-Reference-f62b4be8f24642989e63c25a8fb5f0ba) to customize your SDK settings. > > ### Step 3. Generate a client token > > > [!TIP] > > > > Check our guide on how to set up the client session [here](#generate-a-client-token). > > Make an API call to your backend to fetch a client token. Here is a simple example of how it can be done from your view controller. Once successful store your client token for future use. > > ```swift SWIFT theme={"dark"} > extension MyViewController { > > func requestClientToken(data: [String: Any], completion: @escaping (String?, Error?) -> Void) { > Networking.createClientSession(data: data) { (clientToken, err) in > completion(clientToken, err) > } > } > } > ``` > > ### Step 4. Show Universal Checkout > > At this step you should have a client token available. Call the `showUniversalCheckout(clientToken:)` function (as shown below) to present the Universal Checkout. > > ```swift SWIFT theme={"dark"} > class MyViewController: UIViewController { > > func startUniversalCheckout() { > Primer.shared.showUniversalCheckout(clientToken: self.clientToken) > } > } > ``` > > ### Step 5. Handle callbacks for creating and resuming payments > > Once the payment method data has been securely captured, Primer will return a uniform `paymentMethodTokenData` via `primerDidTokenizePaymentMethod(:decisionHandler:)`. This can be safely passed to your server to create a payment with the Payments API. > > #### Handle `primerDidTokenizePaymentMethod(:decisionHandler:)` > > * When a customer submits their payment data, the payment details are tokenized and you'll receive a `paymentMethodTokenData` in `primerDidTokenizePaymentMethod`. > > * [Create a payment request](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment) with the payment method token data. > > * If the payment is successful, call `decisionHandler(.succeed())` in order to display a success screen. > > * If the payment is unsuccessful, call `decisionHandler(.fail(withErrorMessage: "YOUR_ERROR_MESSAGE"))` to display an error / failed message. > > * Payments API may return a `requiredAction` with a new `clientToken` for additional steps. In this case, call `decisionHandler(.continueWithNewClientToken(clientToken))`. > > ```swift SWIFT theme={"dark"} > // use this method to create a payment. > func primerDidTokenizePaymentMethod(_ paymentMethodTokenData: PrimerPaymentMethodTokenData, decisionHandler: @escaping (PrimerResumeDecision) -> Void) { > // ... > // Call the resumeHandler to continue > // ... > > // Send the payment method token data to your server to create a payment > sendPaymentMethodToken(token: paymentMethodTokenData) { (res, err) in > if let err = err { > decisionHandler(.fail(withErrorMessage: "YOUR_ERROR_MESSAGE")) > } else if let res = res { > guard let requiredActionDic = res["requiredAction"] as? [String: Any], > let clientToken = requiredActionDic["clientToken"] as? String > else { > decisionHandler(.succeed()) > return > } > > decisionHandler(.continueWithNewClientToken(clientToken)) > } > } > } > ``` > > Once the above operation has finished, the SDK will return an error or a new token through its delegate. You can use this token to resume the payment, i.e. send this token to your backend. > > #### Handle `primerDidResumeWith(:decisionHandler:)` > > * You will receive a `resumeToken` via the `primerDidResumeWith(:decisionHandler:)` callback if applicable. > > * [Send a resume payment request](/docs/api-reference/v2.4/api-reference/payments-api/resume-a-payment) with `resumeToken` > > * If the payment is successful, call `decisionHandler(.succeed())` in order to display a success screen. > > * If the payment is unsuccessful, call `decisionHandler(.fail(withErrorMessage: "YOUR_ERROR_MESSAGE"))` to display an error / failed message. > > * Payments API may return a `requiredAction` with a new `clientToken` for additional steps. In this case, call `decisionHandler(.continueWithNewClientToken(clientToken))`. > > ```swift SWIFT theme={"dark"} > func primerDidResumeWith(_ resumeToken: String, decisionHandler: @escaping (PrimerResumeDecision) -> Void) { > sendResumeToken(resumeToken) { (res, err) in > if let err = err { > decisionHandler(.continueWithNewClientToken(clientToken)) > } else if let res = res { > decisionHandler(.succeed()) > } > } > } > ``` > > > [!NOTE] > > > > You should now be able to see Universal Checkout! The user can now interact with Universal Checkout, and you can create the payment. > [tab] React Native > > ### Step 1. Turn off automatic payment creation > > The Universal Checkout option `paymentHandling` defines how the SDK should handle payment creation. > > Set `paymentHandling` to `MANUAL` to turn off automatic payment handling. This will allow you to create the payment yourself (via your backend). > > This disables the callback `onCheckoutComplete`. > > ```typescript Typescript theme={"dark"} > import { > Primer, > PrimerSettings, > PrimerCheckoutData, > PrimerTokenizationHandler, > PrimerResumeHandler, > PrimerPaymentMethodTokenData, > } from '@primer-io/react-native' > > const CheckoutScreen = (props: any) => { > const onUniversalCheckoutButtonTapped = async () => { > try { > const settings: PrimerSettings = { > paymentHandling: 'MANUAL', > /* Other options and callbacks */ > } > > await Primer.configure(settings) > } catch (err) { > // Handle error > } > } > } > ``` > > > [!NOTE] > > > > See our [SDK API Reference](https://www.notion.so/1ce697cf1de6425794df9feeb831f3c3) for more info on available settings. > > ### Step 2. Handle callbacks for creating and resuming payments > > There are two required callbacks: > > * `onTokenizeSuccess` to create payments with `paymentMethodToken` > * `onResumeSuccess` to resume payments with `resumeToken` > > ```typescript Typescript theme={"dark"} > const CheckoutScreen = (props: any) => { > > const onTokenizeSuccess: async ( > paymentMethodTokenData: PrimerPaymentMethodTokenData, > handler: PrimerTokenizationHandler > ) => { > // Will be fired when the payment method has been tokenized. > > // See implementation details below > } > > const onResumeSuccess: async ( > resumeToken: string, > handler: PrimerResumeHandler > ) => { > // Will be fired if the SDK is resumed after handling an action > // like 3DS or a redirect-based payment method. > > // See implementation details below > } > > const onError = ( > error: PrimerError, > checkoutData: PrimerCheckoutData | null, > handler: PrimerErrorHandler | undefined > ) => { > // Handle any errors. > // checkoutData might be null if the payment creation flow hasn't reached the payment step. > } > > const onUniversalCheckoutButtonTapped = async () => { > try { > const settings: PrimerSettings = { > paymentHandling: "MANUAL", > /* Other options... */ > onTokenizeSuccess, > onResumeSuccess, > onError, > } > > await Primer.configure(settings); > > } catch (err) { > // Handle error > } > }; > } > ``` > > > [!NOTE] > > > > See our [SDK API Reference](https://www.notion.so/1ce697cf1de6425794df9feeb831f3c3) for the full list of callbacks. > > #### Handle `onTokenizeSuccess()` callback > > * When a customer submits their payment data, the payment details are tokenized and you'll receive a `PrimerPaymentMethodTokenData` object in `onTokenizeSuccess()` > * [Create a payment request](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment) with the `token` of the `PrimerPaymentMethodTokenData` received. > * If the payment is successful, call `handler.handleSuccess()` in order to display a success screen. > * If the payment is unsuccessful, call `handler.handleFailure(errorMessage)` to display an error / failed message. > * Payments API may return a new `clientToken` for additional steps (in the `requiredActions` on the response). In this case, call `handler.continueWithNewClientToken(clientToken)` to the checkout. > > See below for an example integration: > > ```typescript Typescript theme={"dark"} > const onTokenizeSuccess: async ( > paymentMethodTokenData: PrimerPaymentMethodTokenData, > handler: PrimerTokenizationHandler > ) => { > // Make an API call to your backend to create a payment. > try { > const paymentResponse = await createPayment(paymentMethodTokenData.token); > > // If the request failed you can cancel the flow and display an error message > if (!paymentResponse) { > handler.handleFailure('The payment failed. Please try with another payment method.'); > return; > } > > // If the payment has any actions for the SDK to complete > if (paymentResponse.requiredAction?.clientToken) { > this.paymentId = paymentResponse.id; // This will be used for resuming later > handler.continueWithNewClientToken(paymentResponse.requiredAction.clientToken); > return; > } > > // Display the success screen > handler.handleSuccess(); > return; > > } catch (error) { > // Handle error > } > } > ``` > > #### Handle `onResumeSuccess()` callback > > > [!WARNING] > > > > Handling `onResumeSuccess()` is required to fully support 3DS and the majority of payment methods. > > * You will receive a `resumeToken` via the `onResumeSuccess()` callback if applicable > * [Send a resume payment request](/docs/api-reference/v2.4/api-reference/payments-api/resume-a-payment) with the `resumeToken` > * If the payment is successful, call `handler.handleSuccess()` in order to display a success screen. > * If the payment is unsuccessful, call `handler.handleFailure(errorMessage)` to display an error / failed message. > * Payments API may *again* return a new `clientToken` for additional steps. In this case, call `handler.continueWithNewClientToken(clientToken)` to the checkout. > > ```typescript Typescript theme={"dark"} > const onResumeSuccess: async ( > resumeToken: string, > handler: PrimerResumeHandler > ) => { > // Make an API call to resume the payment. > try { > const resumePaymentResponse = await resumePayment(this.paymentId, resumeToken); > > // If the request failed you can cancel the flow and display an error message > if (!resumePaymentResponse) { > handler.handleFailure('The payment failed. Please try with another payment method.'); > return; > } > > // The checkout will automatically perform the action required by the Workflow > if (resumePaymentResponse.requiredAction?.clientToken) { > handler.continueWithNewClientToken(resumePaymentResponse.requiredAction.clientToken); > return; > } > > // Display the success screen > handler.handleSuccess(); > return; > > } catch (error) { > // Handle error > } > } > ``` > > ### Step 3. Generate a client token > > Make an API call to your backend to generate a [Client Session](/docs/checkout/client-session). The Client Session request returns a client token, which you will need to initialize the checkout. > > Here is an example of how it can be done from your component. Once successful, store your client token for future use. > > ```typescript Typescript theme={"dark"} > const CheckoutScreen = (props: any) => { > // ... > > const onUniversalCheckoutButtonTapped = async () => { > try { > // ... > // Ask your backend to create a client session > const clientToken = await createClientSession() > } catch (err) { > // Handle error > } > } > } > ``` > > ### Step 4. Show Universal Checkout > > At this point, you should have a client token available. To present Universal Checkout, call `showUniversalCheckout(clientToken)` as shown below. > > ```typescript Typescript theme={"dark"} > const CheckoutScreen = async (props: any) => { > // ... > > const onUniversalCheckoutButtonTapped = async () => { > // ... > > try { > // Present Universal Checkout > await Primer.showUniversalCheckout(clientToken) > } catch (err) { > // Handle error > } > } > } > ``` > > > [!NOTE] > > > > You should now be able to see Universal Checkout, and the user can now interact with it. When the user tries to pay, we will tokenize the payment method and invoke `onTokenizeSuccess`. You can then create the payment as mentioned in Step 4. > > ### Full Snippet > > ```typescript Typescript theme={"dark"} > import { > Primer, > PrimerSettings, > PrimerCheckoutData, > PrimerTokenizationHandler, > PrimerResumeHandler, > PrimerPaymentMethodTokenData > } from '@primer-io/react-native' > > const CheckoutScreen = (props: any) => { > > const onTokenizeSuccess: async ( > paymentMethodTokenData: PrimerPaymentMethodTokenData, > handler: PrimerTokenizationHandler > ) => { > try { > const paymentResponse = await createPayment(paymentMethodTokenData.token); > > if (!paymentResponse) { > handler.handleFailure('The payment failed. Please try with another payment method.'); > return; > } > > if (paymentResponse.requiredAction?.clientToken) { > this.paymentId = paymentResponse.id; // This will be used for resuming later > handler.continueWithNewClientToken(paymentResponse.requiredAction.clientToken); > return; > } > > handler.handleSuccess(); > return; > > } catch (error) { > // Handle error > } > } > > const onResumeSuccess: async ( > resumeToken: string, > handler: PrimerResumeHandler > ) => { > try { > const resumePaymentResponse = await resumePayment(this.paymentId, resumeToken); > > if (!resumePaymentResponse) { > handler.handleFailure('The payment failed. Please try with another payment method.'); > return; > } > > if (resumePaymentResponse.requiredAction?.clientToken) { > handler.continueWithNewClientToken(resumePaymentResponse.requiredAction.clientToken); > return; > } > > handler.handleSuccess(); > return; > > } catch (error) { > // Handle error > } > } > > const onError = ( > error: PrimerError, > checkoutData: PrimerCheckoutData | null, > handler: PrimerErrorHandler | undefined > ) => { > // Handle the error > } > > const onUniversalCheckoutButtonTapped = async () => { > try { > const settings: PrimerSettings = { > paymentHandling: "MANUAL", > /* Other options... */ > onTokenizeSuccess, > onResumeSuccess, > onError > } > > await Primer.configure(settings); > > const clientToken = await createClientSession(); > > await Primer.showUniversalCheckout(clientToken) > } catch (err) { > // Handle error > } > }; > } > ``` # Capture billing address Source: https://primer.io/docs/checkout/capture-billing-address ## How to capture the billing address Some payment methods such as Cards have additional features that you can activate without a line of code from within the settings tab in the right panel. ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/universal-checkout/settings.png) Settings # Checkout Builder Source: https://primer.io/docs/checkout/checkout-builder > [!NOTE] > > This guide outlines how to configure Primer Checkout with all the payment methods and features you need. > > Make sure to follow these steps before integrating Primer Checkout into your website or mobile application. The Dashboard features a no-code interface enabling you to simply activate payment methods and checkout modules and create conditions that determine when and how they are displayed in the Primer Checkout. ## Configure your checkout ### Step 1. Connect a payment method to Primer > [!NOTE] > > Payment methods are at the core of Primer Checkout's capabilities. They collect and pass information from the customer to the processor for the payment to be processed. > > Check our [Payment methods overview page](/docs/connections/payment-methods/) to learn more about payment methods and processors. The first step is to connect a payment method to your Primer account. This is done via the [Integrations section](https://dashboard.primer.io/integrations) in the Dashboard - all without a single line of code. * **For card payments** \ You are already all set! * **For Apple Pay and Google Pay** \ Click on "+ New Integration", search for Apple Pay or Google Pay, and follow the instructions. * **For payment methods that are also processors (e.g. PayPal, Klarna, ...)** \ Click on "+ New Integration", search for the processor, and follow the instructions. * **For payment methods that come bundled with a processor** \ Click on "New integration", search for the processor - such as PayPal or Buckaroo - and follow the instructions. Then, select the payment methods you want to use via Primer. ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/universal-checkout/add-payment-methods.png) Add payment methods to the dashboard ### Step 2. Configure your checkout Now that your payment methods are properly connected to Primer, head over to the [Checkout section](https://dashboard.primer.io/checkout) of the Dashboard to configure the Primer Checkout. This section enables you to: * Create conditions that determine which payment methods to display * Reorder the payment methods * Activate checkout modules such as capturing the billing address ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/universal-checkout/checkout-builder.png) Add payment methods to the dashboard #### Create payment method conditions First, activate the payment method by toggling it on. ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/universal-checkout/toggle-paypal.gif) PayPal is toggled on Then click on the payment method to show the payment method settings in the right-hand panel. There, you can create conditions to decide when to display this payment method. Conditions can be based on the currency, amount, country, and metadata that are passed in the [client session](/docs/checkout/client-session). ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/universal-checkout/condition-builder.png) Condition builder Some payment methods can be used with multiple processors, all of which appear in the side panel. For instance, PayPal can be used directly with the PayPal processor, with Pay., or with others. For such a payment method, only one processor can be used at a time. Create conditions for each processor you want to leverage in a checkout session. ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/universal-checkout/conditions.png) Conditions The Primer Checkout selects the processor like so: * It evaluates these conditions in order from top to bottom and selects the first processor that matches the client session. Feel free to reorder the processors to better suit your use case. * If no processor has matched, the processor specified in the "All other conditions" section is used. * If no processor is specified in the "All other conditions" section, the payment method is not presented to the user. This enables you to show a given payment method with certain conditions. #### Reorder payment methods The Dashboard enables you to specify the order used to present the payment methods to your customer. You can reorder the payment methods on the left panel by simply dragging and dropping to better suit your needs. ### Step 3. Publish your checkout configuration Click on the "Publish" button to immediately make your checkout configuration available to all users. ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/universal-checkout/publish.png) Publish ## To go further Now that your checkout is properly configured, take a look at our [Primer Checkout guide](/docs/checkout/overview) to avail it to your customers, or to [this tutorial video explaining how to build your Primer Checkout in minutes](https://www.youtube.com/watch?v=fafXux4KPxo). # Client Session Source: https://primer.io/docs/checkout/client-session A client session is the starting point for integrating payments with the Primer Checkout. You can attach all the metadata associated with the order to the client session, and generate a `clientToken`, a temporary key used to initialize Primer Checkout. The information you include in the client session is used in the Dashboard: * to conditionally route payments with Workflows * to activate payment methods and other features in Primer Checkout. So pass as much information as you can! > [!NOTE] > > The `clientToken` is a key concept within Primer. You may receive a client token from various places but as long as you pass it to the SDK, Primer Checkout knows where to start/resume the flow. ## Create a client session On your server, create a client session with POST . Make sure to pass at least the following data: | Field | Description | | - | - | | `orderId` | Your reference for the payment. *Make sure to keep track of orderId - you will later receive updates to the payment via Webhooks. The payment will contain the orderId specified in the client session.* | | `currencyCode` | The three-letter currency code in ISO 4217 format. e.g. use USD for US dollars. | | `order.lineItems` | The details of the line items of the order. | Use the [metadata](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-metadata) field to attach arbitrary data. Use this to build custom conditions in Workflows for routing and A/B testing. > [!NOTE] > > Data you pass when creating a client session is used when creating a payment, unless explicitly overwritten. > [!NOTE] > > Make sure to pass all the information required by the payment methods and features activated on your [Dashboard](https://dashboard.primer.io/). Example request: ```bash BASH theme={"dark"} curl --location --request \ POST 'https://api.sandbox.primer.io/client-session' \ --header 'X-Api-Key: ' \ --header 'X-Api-Version: 2.4' \ --data '{ "orderId": "", "currencyCode": "GBP", "amount": 4999, "order": { "lineItems": [{ "itemId": "shoes-123", "description": "Some shoes", "amount": 2500, "quantity": 2 }] } }' ``` The body of a successful response contains a [clientToken](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#response-client-token) that you will use to initialize Primer Checkout. Check the [warnings](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#response-warnings) array for missing data which may be required to display certain payment methods and checkout modules in the Primer Checkout. ```json JSON theme={"dark"} { "clientToken": "", "clientTokenExpirationDate": "2021-08-12T16:14:08.578695", "orderId": "", "currencyCode": "GBP", "amount": 5000, "customerId": "", "metadata": {}, "warnings": ["Apple Pay is missing 'customerDetails.countryCode'"] } ``` > [!NOTE] > > ️ As a `clientToken` is a temporary key, it has an expiration time of 24 hours. > [!WARNING] > > The length of the `clientToken` is not fixed. Treat it as an opaque string and do not rely on a maximum length when storing it. ## Update a client session Primer Checkout automatically updates the Client Session as it captures more data such as the billing address. Alternatively, you can manually update the Client Session to update the line items or the customer details. Make a request to PATCH to update the Client Session tied to a Client Token. ```bash BASH theme={"dark"} curl --location --request \ PATCH 'https://api.sandbox.primer.io/client-session' \ --header 'X-Api-Key: ' \ --header 'X-Api-Version: 2.4' \ --data '{ "clientToken": "", "order": { "lineItems": [{ "itemId": "shoes-123", "description": "Some shoes", "amount": 2500, "quantity": 1 }] } }' ``` Then, call `refreshClientSession()` to ask the Checkout to get the latest client session. With Drop-in Checkout: ```typescript Typescript theme={"dark"} const checkout = await Primer.showUniversalCheckout(clientToken, options) // Refresh the internal client session await checkout.refreshClientSession() ``` With Headless Checkout: ```typescript Typescript theme={"dark"} const headless = await Primer.createHeadless(clientToken, options) // Refresh the internal client session await headless.refreshClientSession() ``` # Customization Source: https://primer.io/docs/checkout/drop-in/customization ## > [!NOTE] > > This guide is designed to help you style our default Drop-in Checkout UI. > > If you would like to build your own UI from scratch then consider integrating [Headless Checkout](/docs/checkout/headless). Primer Drop-in Checkout look and feel can be styled to suit your preferred branding and make it blend seamlessly in your website or mobile app. ## [Web](/docs/checkout/drop-in/customization/web) ## [iOS](/docs/checkout/drop-in/customization/ios) ## [Android](/docs/checkout/drop-in/customization/android) ## [React Native](/docs/checkout/drop-in/customization/react-native) # Android Source: https://primer.io/docs/checkout/drop-in/customization/android This guide is designed to help you style our default Universal Checkout UI. If you would like to build your own UI from scratch then check out our [Headless Universal Checkout guide](/docs/checkout/headless/). ## Localization and languages Universal Checkout supports multiple languages out of the box, enabling you to adapt its UI to the relevant market. > [!NOTE] > > Universal Checkout uses the device language by default. If this language is not supported, Universal Checkout automatically falls back to English. ### Supported locales | Language | Minimum versions | | - | - | | Arabic | v2.36.0 | | Bulgarian | v2.36.0 | | Catalan | v2.29.0 | | Czech | v2.36.0 | | Danish | v1.9.0 | | German | v1.9.0 | | Greek | v1.9.0 | | English | v1.0.0 | | English (United States) | v1.0.0 | | Spanish (Argentina) | v2.36.0 | | Spanish (Spain) | v1.9.0 | | Spanish (Mexico) | v2.36.0 | | Estonian | v2.36.0 | | Finnish | v2.29.0 | | French (France) | v1.9.0 | | Hebrew | v2.29.0 | | Croatian | v2.36.0 | | Hungarian | v2.36.0 | | Indonesian | v2.29.0 | | Italian | v1.9.0 | | Japanese | v2.36.0 | | Korean | v2.29.0 | | Lithuanian | v2.29.0 | | Latvian | v2.36.0 | | Malay | v2.16.3 | | Norwegian | v1.9.0 | | Dutch | v1.9.0 | | Polish | v1.9.0 | | Portuguese | v1.9.0 | | Portuguese (Brazil) | v2.36.0 | | Romanian | v2.36.0 | | Russian | v2.36.0 | | Slovak | v2.36.0 | | Slovenian | v2.29.0 | | Serbian | v2.29.0 | | Swedish | v1.9.0 | | Thai | v2.16.3 | | Turkish | v1.9.0 | | Ukrainian | v2.29.0 | | Vietnamese | v2.36.0 | | Chinese (Mainland China - Simplified characters) | v2.16.3 | | \[BETA] Chinese (Hong-Kong - Traditional characters) | v2.16.3 | | \[BETA] Chinese (Taiwan - Traditional characters) | v2.16.3 | ### Right-to-left Universal Checkout automatically switches to a right-to-left layout when necessary. ## Resource Styling (Recommended) The fastest way to add custom colors and dimensions to the Android SDK is to override the SDK's resource values. To learn more see the complete set of resources below or check out one of our theming examples: ### Colors ```xml theme={"dark"} @color/primer_app_primary @color/primer_app_background #8FBEC2C4 @color/primer_android_red @color/primer_secondary @color/primer_secondary #808080 @color/primer_primary @color/primer_secondary @color/primer_disabled @color/primer_primary @color/primer_error @color/primer_secondary @color/primer_background @color/primer_background @color/primer_disabled @color/primer_disabled @color/primer_primary @color/primer_error @android:color/white @color/primer_primary @color/primer_disabled @color/primer_error @color/primer_primary @color/primer_primary @color/primer_error @color/primer_app_background @color/primer_disabled @color/primer_primary #DBDBDB #000000 @android:color/transparent #E5E5EA ``` ### Dimensions ```xml theme={"dark"} 1dp 6dp 24dp 56dp 12dp 40dp 18sp 20sp 34sp 14sp @dimen/primer_subtitle_fontsize @dimen/primer_default_corner_radius @dimen/primer_subtitle_fontsize 1dp @dimen/primer_default_corner_radius @dimen/primer_subtitle_fontsize 0dp @dimen/primer_default_corner_radius @dimen/primer_default_fontsize 1dp 0.5dp ``` ### Dark Theme ![](https://mintcdn.com/primer-cc826789/dM-udzSll5kL79ou/images/checkout/drop-in/night-theme.png?fit=max\&auto=format\&n=dM-udzSll5kL79ou\&q=85\&s=536149688075a3db2af24be4f5cabff4) Dark Theme ```xml theme={"dark"} #8E8E93 #48484A #2C2C2E #1C1C1E #F2F2F7 #0A84FF #FF375F #FFD60A #FF9F0A #FF453A @color/apple_dark_6 @color/apple_dark_4 @color/apple_dark_3 @color/apple_dark_5 @color/apple_dark_1 @color/apple_dark_6 @color/apple_dark_5 @color/apple_dark_3 @color/apple_dark_6 @color/apple_dark_5 @color/apple_dark_4 @color/apple_dark_5 @color/apple_dark_6 @color/apple_dark_1 @color/apple_dark_5 @color/apple_dark_5 ``` ## Dynamic Styling with Resources Apart from overriding Primer SDK resource colors and dimensions, it's also possible to achieve a custom theme by passing in references to your app's resources when defining the SDK's `PrimerTheme` object in Kotlin/Java. ### XML Resource ```xml theme={"dark"} #8E8E93 #48484A #2C2C2E #1C1C1E #F2F2F7 #0A84FF #FF375F #FFD60A #FF9F0A #FF453A ``` ### YourActivity.kt ```kotlin Kotlin theme={"dark"} // define the theme object val darkTheme = PrimerTheme.build( primaryColor = R.color.apple_dark_6, backgroundColor = R.color.apple_dark_4, disabledColor = R.color.apple_dark_3, input = InputThemeData( backgroundColor = R.color.apple_dark_2, cursorColor = R.color.apple_dark_5, hintText = TextThemeData(defaultColor = R.color.apple_dark_3), cornerRadius = R.dimen.primer_input_corner_radius, border = BorderThemeData(defaultColor = R.color.apple_dark_1), text = TextThemeData(defaultColor = R.color.apple_dark_5) ), mainButton = ButtonThemeData( defaultColor = R.color.apple_dark_6, text = TextThemeData(defaultColor = R.color.apple_dark_5), ), titleText = TextThemeData(defaultColor = R.color.apple_dark_5), amountLabelText = TextThemeData(defaultColor = R.color.apple_dark_5), subtitleText = TextThemeData(defaultColor = R.color.apple_dark_1), paymentMethodButton = ButtonThemeData( defaultColor = R.color.apple_dark_4, text = TextThemeData(defaultColor = R.color.apple_dark_5), border = BorderThemeData( defaultColor = R.color.apple_dark_3, selectedColor = R.color.apple_dark_6, ), ), systembutton = TextThemeData(defaultColor = R.color.apple_dark_6), divider = DividerThemeData( backgroundColor = R.color.apple_dark_6, height = R.dimen.primer_divider_height ) ) // initialize the SDK Primer.initialize(context, clientToken, theme = darkTheme) ``` # iOS Source: https://primer.io/docs/checkout/drop-in/customization/ios This guide is designed to help you style our default Universal Checkout UI. If you would like to build your own UI from scratch then check out our [Headless Universal Checkout guide](/docs/checkout/headless). ## Localization and languages Universal Checkout supports multiple languages out of the box, enabling you to adapt its UI to the relevant market. > [!NOTE] > > Universal Checkout uses the device language by default. If this language is not supported, Universal Checkout automatically falls back to English. ### Supported locales | Language | Minimum versions | | - | - | | Arabic | v1.29.0 | | Bulgarian | v2.35.0 | | Catalan | v2.30.0 | | Czech | v2.35.0 | | Danish | v1.26.0 | | German | v1.26.0 | | Greek | v1.26.0 | | English | v1.0.0 | | Spanish | v1.26.0 | | Spanish (Argentina) | v2.35.0 | | Spanish (Mexico) | v2.35.0 | | Estonian | v2.35.0 | | Finnish | v2.30.0 | | French | v1.26.0 | | Hebrew | v2.30.0 | | Croatian | v2.35.0 | | Hungarian | v2.35.0 | | Indonesian | v2.30.0 | | Italian | v1.26.0 | | Japanese | v2.35.0 | | Korean | v2.30.0 | | Lithuanian (Lithuania) | v2.30.0 | | Latvian | v2.35.0 | | Malay | v2.16.3 | | Norwegian | v1.26.0 | | Dutch | v1.26.0 | | Polish | v1.26.0 | | Portuguese | v1.26.0 | | Portuguese (Brazil) | v2.35.0 | | Romanian | v2.35.0 | | Russian | v2.35.0 | | Slovak | v2.35.0 | | Slovenian | v2.30.0 | | Serbian | v2.30.0 | | Swedish | v1.0.2 | | Thai | v2.16.3 | | Turkish | v1.26.0 | | Ukrainian | v2.30.0 | | Vietnamese | v2.35.0 | | Chinese (Mainland China - Simplified characters) | v2.16.3 | | \[BETA] Chinese (Hong-Kong - Traditional characters) | v2.16.3 | | \[BETA] Chinese (Taiwan - Traditional characters) | v2.16.3 | ### Right-to-left Universal Checkout automatically switches to a right-to-left layout when necessary. ## Theme To customize the appearance of the SDK define the `PrimerTheme` object, then pass it in as an argument when configuring the SDK. ```swift SWIFT theme={"dark"} // example: let theme = PrimerTheme( cornerRadiusTheme: CornerRadiusTheme(textFields: 8), colorTheme: PrimerDefaultTheme(tint1: themeColor), layout: PrimerLayout(showTopTitle: false, textFieldHeight: 44), textFieldTheme: .outlined ) Primer.shared.configure(theme: theme) ``` ### Custom Colors Access the `colorTheme` property to add custom colors. ```swift SWIFT theme={"dark"} PrimerTheme( colorTheme: ColorTheme darkTheme: ColorTheme // iOS 13.0+ only ) protocol ColorTheme { var text1: UIColor { get } // headers, main text var text2: UIColor { get } // white text for darker buttons var text3: UIColor { get } // system text, theme colored text var secondaryText1: UIColor { get } // less visible subheaders var main1: UIColor { get } // backgrounds var main2: UIColor { get } // table cells, default buttons var tint1: UIColor { get } // borders, theme colored components var neutral1: UIColor { get } // unselected buttons var disabled1: UIColor { get } // disabled components var error1: UIColor { get } // error borders and messages } // example: let colorTheme = PrimerDefaultTheme(tint1: .systemPink) ``` ### Rounded Corners Update the `cornerRadiusTheme` to change the corner radius of different components. ```swift SWIFT theme={"dark"} let cornerRadiusTheme = CornerRadiusTheme(buttons: 8, sheetView: 18) let theme = PrimerTheme(cornerRadiusTheme: cornerRadiusTheme) ``` # React Native Source: https://primer.io/docs/checkout/drop-in/customization/react-native This guide is designed to help you style our default Universal Checkout UI. If you would like to build your own UI from scratch then check out our [Headless Universal Checkout guide](/docs/checkout/headless/). ## Localization and languages Universal Checkout supports multiple languages out of the box, enabling you to adapt its UI to the relevant market. > [!NOTE] > > Universal Checkout uses the device language by default. If this language is not supported, Universal Checkout automatically falls back to English. ### Supported locales | Language | Minimum versions | | - | - | | Arabic | v2.30.0 | | Bulgarian | v2.30.0 | | Catalan | v2.27.0 | | Czech | v2.30.0 | | Danish | v0.15.5 | | German | v0.15.5 | | Greek | v0.15.5 | | English | v0.1.0 | | Spanish | v0.15.5 | | Spanish (Argentina) | v2.30.0 | | Spanish (Mexico) | v2.30.0 | | Estonian | v2.30.0 | | Finnish | v2.27.0 | | French | v0.15.5 | | Hebrew | v2.27.0 | | Croatian | v2.30.0 | | Hungarian | v2.30.0 | | Indonesian | v2.27.0 | | Italian | v0.15.5 | | Japanese | v2.30.0 | | Korean | v2.27.0 | | Lithuanian | v2.27.0 | | Latvian | v2.30.0 | | Malay | v2.19.2 | | Norwegian | v0.15.5 | | Dutch | v0.15.5 | | Polish | v0.15.5 | | Portuguese | v0.15.5 | | Portuguese (Brazil) | v2.30.0 | | Romanian | v2.30.0 | | Russian | v2.30.0 | | Slovak | v2.30.0 | | Slovenian | v2.27.0 | | Serbian | v2.27.0 | | Swedish | v1.15.5 | | Thai | v2.19.2 | | Turkish | v0.15.5 | | Ukrainian | v2.27.0 | | Vietnamese | v2.30.0 | | Chinese (Mainland China - Simplified characters) | v2.19.2 | | \[BETA] Chinese (Hong-Kong - Traditional characters) | v2.19.2 | | \[BETA] Chinese (Taiwan - Traditional characters) | v2.19.2 | ### Right-to-left Universal Checkout automatically switches to a right-to-left layout when necessary. ## Theme To customize the appearance of the SDK, pass a `theme` mapping under `uiOptions` in `PrimerSettings`, for example: ```json JSON theme={"dark"} uiOptions: { /* ... other options ... */ theme: { colors: { mainColor: { red: 7, green: 138, blue: 88, alpha: 255 }, background: { red: 216, green: 242, blue: 240, alpha: 255 }, text: { red: 7, green: 138, blue: 88, alpha: 255 }, disabled: { red: 100, green: 100, blue: 100, alpha: 255 }, error: { red: 235, green: 126, blue: 16, alpha: 255 }, borders: { red: 209, green: 96, blue: 209, alpha: 255 } }, darkModeColors: { mainColor: { red: 1, green: 255, blue: 1, alpha: 255 }, background: { red: 255, green: 1, blue: 255, alpha: 255 }, text: { red: 1, green: 255, blue: 1, alpha: 255 }, disabled: { red: 100, green: 100, blue: 100, alpha: 255 }, error: { red: 173, green: 10, blue: 10, alpha: 255 }, borders: { red: 209, green: 96, blue: 209, alpha: 255 } } } }, ``` Minimally, you can set only `mainColor` and `background` to achieve a basic two-tone theme. Other properties can be used to override specific styles: | Property | Description | | :- | :- | | `mainColor` | The default primary color used to theme text and accents. | | `background` | The default background color for views. | | `text` | Overrides `mainColor` with a specific color for text labels. | | `disabled` | Overrides `mainColor` with a specific color for disabled buttons. | | `error` | A specific color for validation error label text. Red by default. | | `borders` | Overrides `mainColor` for button borders and view borders. | # Web Source: https://primer.io/docs/checkout/drop-in/customization/web This guide is designed to help you style our default Universal Checkout UI. If you would like to build your own UI from scratch then check out our [Headless Universal Checkout guide](/docs/checkout/headless/). ## Localization and languages ### Set the locale Universal Checkout supports multiple languages out of the box, enabling you to adapt its UI to the relevant market. You can specify the language using the `locale` option. If not provided, the locale is automatically derived from the browser: ```typescript Typescript theme={"dark"} const options = { /* Other checkout options ... */ locale: 'fr-FR', // Renders Universal Checkout in French } ``` > [!NOTE] > > Universal Checkout automatically falls back to English if the provided locale is not supported. ### Supported locales | Locale | Language | Minimum versions | | - | - | - | | ar | Arabic | v1.22.1 | | bg-BG | Bulgarian (Bulgaria) | v2.1.1, v1.37.0 | | cs-CZ | Czech (Czech Republic) | v2.3.0, v1.38.0 | | da-DA | Danish | v1.22.1 | | de-DE | German | v1.22.0 | | el-GR | Greek (Greece) | v1.22.1 | | en-US | English (United States) | v1.0.0 | | es | Spanish | v1.22.0 | | es-AR | Spanish (Argentina) | v2.2.1 | | et-EE | Estonian (Estonia) | v2.3.0, v1.38.0 | | fr-FR | French (France) | v1.19.0 | | hr-HR | Croatian (Croatia) | v2.3.0, v1.38.0 | | hu-HU | Hungarian (Hungary) | v1.18.0 | | it-IT | Italian (Italy) | v2.1.1, v1.37.0 | | ja-JP | Japanese (Japan) | v2.3.0, v1.38.0 | | lt-LT | Lithuanian (Lithuania) | v2.3.0, v1.38.0 | | ms | Malay | v2.26.1 | | nb-NO | Norwegian (Norway) | v1.22.1 | | nl-NL | Dutch (Netherlands) | v1.22.1 | | pl-PL | Polish (Poland) | v1.22.1 | | pt-BR | Portuguese (Brazil) | v2.3.0, v1.38.0 | | pt-PT | Portuguese (Portugal) | v1.22.0 | | ro-RO | Romanian (Romania) | v1.37.0 | | ru-RU | Russian (Russia) | v2.1.1, v1.37.0 | | sk-SK | Slovak (Slovakia) | v2.1.1, v1.37.0 | | sv-SE | Swedish (Sweden) | v1.22.1 | | th | Thai | v2.26.1 | | tr-TR | Turkish (Turkey) | v1.22.1 | | vi-VN | Vietnamese (Vietnam) | v2.3.0, v1.38.0 | | zh-CN | Chinese (Mainland China - Simplified characters) | v2.26.1 | | zh-HK | \[BETA] Chinese (Hong-Kong - Traditional characters) | v2.26.1 | | zh-TW | \[BETA] Chinese (Taiwan - Traditional characters) | v2.26.1 | ### Right-to-left Universal Checkout automatically switches to a right-to-left layout for the relevant languages. Make sure to pass the right `locale` to activate right-to-left: ```typescript Typescript theme={"dark"} const options = { /* Other checkout options ... */ locale: 'ar-AR', // Renders Universal Checkout in Arabic with right-to-left layout } ``` ## Styling Universal Checkout > [!TIP] > > For styling Universal Checkout, do not use custom CSS. Rather pass the `style` object as a checkout option when calling `showUniversalCheckout`. You can use the general styling options to style specific UI elements such as form inputs, text labels and several other elements within Universal Checkout. ```typescript Typescript theme={"dark"} const options = { /* Other checkout options ... */ style: { /* Style options */ }, } ``` ### Text Styling Options Text elements within Universal Checkout can be styled using the following interface: ```typescript Typescript theme={"dark"} interface TextStyle { color?: string fontFamily?: string fontWeight?: string fontSize?: string fontSmoothing?: string lineHeight?: string textTransform?: string letterSpacing?: string } ``` ### Block Styling Options Block elements within Universal Checkout can be styled using the following interface: ```typescript Typescript theme={"dark"} interface BlockStyle { background?: string borderRadius?: number | string boxShadow?: string borderStyle?: string borderColor?: number | string borderWidth?: number | string } ``` > [!TIP] > > Both of the above mentioned interfaces will be referred to regularly in this guide when covering the styling of specific UI elements. ## Styling Inputs ### Styling Font Family (Card Input) Universal Checkout style inherits from the style of its container as most of it is rendered directly within your page and not within an `iframe.` So any `font-family` that you have set in the CSS file will be used by the Universal Checkout. The example below uses `MyFont` as the preferred font family for card input. ```css CSS theme={"dark"} #my-checkout { font-family: 'MyFont', sans-serif; } ``` However, in order to be fully PCI-compliant, the card code field, the card expiry field and the CVV field are rendered in isolated `iframe`. This means that `font-family` declarations, and `@font-face` directives that load and define fonts are not passed to these specific fields. To forward `font-family` and `@font-face` to the card input fields, you can set `style.input.base.fontFamily` and `style.fontFaces`. Alternatively, to `style.fontFaces`, you can forward stylesheets to the `iframe` using the `style.stylesheets` option, which facilitates the integration of fonts coming from services such as Google Fonts. ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { /* Forwarded to iframes */ fontFaces: [ { fontFamily: 'Open Sans', src: 'url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"), url("/fonts/OpenSans-Regular-webfont.woff") format("woff")', }, ], /* Forwarded to iframes */ stylesheets: [ { href: '', }, ], /* Unified across all inputs: inside and outside iframes */ input: { base: { fontFamily: 'Open Sans', }, }, }, } ``` ### InputStyle Options You can style all the inputs on Universal Checkout in all their different states. By default, the `InputStyle` defined in `input:base` will be used everywhere. You need to add value for `InputStyle` only if you wish to override this style for inputLabel, hover, placeholder etc. ```typescript Typescript theme={"dark"} interface InputStyle { height?: number paddingHorizontal?: number background?: string borderRadius?: number | string boxShadow?: string borderStyle?: string borderColor?: string borderWidth?: number | string color?: string fontFamily?: string fontWeight?: string fontSize?: string fontSmoothing?: string lineHeight?: string } ``` ```typescript Typescript theme={"dark"} interface CheckoutStyle { // Input styling input?: { // Base style base?: InputStyle & { hover?: InputStyle // :hover focus?: InputStyle // :focus placeholder?: InputStyle // ::placeholder webkitAutofill?: InputStyle // :-webkit-autofill selection?: InputStyle // ::selection } // Style of the label displayed above the input fields inputLabel?: TextStyle } } ``` #### Example ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/drop-in/style-example.png) Styling Example ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { inputLabel: { fontFamily: 'courier new', color: '#000000', }, input: { base: { borderStyle: 'none none solid none', borderColor: '#000000', boxShadow: '0px', background: '#ffffff', fontFamily: 'courier new', borderRadius: '0px', paddingHorizontal: '0px', lineHeight: '', color: '#000000', placeholder: { color: '#e1deda', }, }, }, }, } ``` > [!TIP] > > You can hide the default input labels using the `inputLabelsVisible` option. ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ form: { inputLabelsVisible: false, }, } ``` ### Styling Input Errors You can customize the style of Universal Checkout error state. By default, the `InputStyle` defined in `input.base` will be used everywhere. But you can override this where you need different error message styling by specifying the style for `input.error` and `inputErrorText`. `inputErrorText` also uses `TextAlignmentStyle`. ```typescript Typescript theme={"dark"} interface TextAlignmentStyle { textAlign?: string } ``` ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { input: { error: InputStyle & { hover: InputStyle, focus: InputStyle, placeholder: InputStyle, webkitAutofill: InputStyle, selection: InputStyle, }, }, // Style of the error messages displayed below the input fields inputErrorText: TextStyle & TextAlignmentStyle, }, } ``` #### Example ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/drop-in/error-styling-example.png) Error Input Styling Example ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { inputErrorText: { fontFamily: 'courier new', textAlign: 'left', color: '#e70909', }, inputLabel: { fontFamily: 'courier new', color: '#000000', }, input: { base: { borderStyle: 'none none solid none', borderColor: '#000000', boxShadow: '0px', background: '#ffffff', fontFamily: 'courier new', borderRadius: '0px', paddingHorizontal: '0px', lineHeight: '', color: '#000000', placeholder: { color: '#e1deda', }, error: { borderStyle: 'solid', borderColor: '#d0021b', }, }, }, }, } ``` ## Styling Error Messages You can also style the error message shown in the event of an unsuccessful payment using `ErrorMessageStyle` interface which extends [Block Styling Options](#block-styling-options) and [Text Styling Options](#text-styling-options) mentioned above. ```typescript Typescript theme={"dark"} // Error Message Interface interface ErrorMessageStyle extends BlockStyle, TextStyle { color?: string } // Example const options = { /* Other options ... */ style: { errorMessage: ErrorMessageStyle, }, } ``` > [!TIP] > > Universal Checkout can display error messages, or you can create your own. Refer to [Configuring Error Message Guide](https://www.npmjs.com/package/@primer-io/checkout-web#%EF%B8%8F-error-message-options--callbacks) for details. ## Styling Form Spacing You can change the vertical spacing between inputs or the spacing between labels and inputs by using the `formSpacings` properties. ```typescript Typescript theme={"dark"} // Form Spacings Interface interface FormSpacings { betweenLabelAndInput?: string betweenInputs?: string } // Example const options = { style: { formSpacings: { betweenLabelAndInput: '0px', betweenInputs: '10px', }, }, } ``` ## Styling Submit Button The default submit button in Universal Checkout can be styled to match your brand. The `submitButton` uses [TextStyle](#text-styling-options) and [BlockStyle](#block-styling-options) to define the style of the button. By default, the style defined in `submitButton.base` will be used everywhere. If you wish to override the default style for loading, disabled, hover or focus or other states, you will be required to add values for [TextStyle](#text-styling-options) and [BlockStyle](#block-styling-options) properties. ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { submitButton: { base: { hover: TextStyle & BlockStyle, focus: TextStyle & BlockStyle, }, disabled: { hover: TextStyle & BlockStyle, focus: TextStyle & BlockStyle, }, loading: { hover: TextStyle & BlockStyle, focus: TextStyle & BlockStyle, }, }, }, } ``` #### Example ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/drop-in/submit-styling-example.png) Submit Button Styling Example ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { submitButton: { base: { color: '#ffffff', background: '#000000', borderRadius: '3px', fontFamily: 'courier new', fontWeight: 'bold', boxShadow: 'none', }, disabled: { color: '#9b9b9b', background: '#e1deda', }, }, }, } ``` > [!TIP] > > You can also use [custom submit button](#displaying-custom-submit-button) instead of styling the Universal Checkout default submit button. ## Styling Back Button Some scenes in Universal Checkout will have a back button which allows the user to navigate back to the previous scene. You can style the back button as shown below: ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { backButton: { color: string, }, }, } ``` ## Styling Transitions When multiple scenes are present in Universal Checkout, you can override the default transitions to better match your website transitions. ```typescript Typescript theme={"dark"} type SceneOptions = { // A callback for receiving the current scene that is entering onEntering?: (sceneId: string) => void // Specify options relating to scene transitions // Setting to false disables all scene transitions // Defaults to a 'SLIDE_UP' type transition with a duration of 700ms transition?: SceneTransitionOptions | false } type SceneTransitionOptions = { // The type of transition animation which will be used type: TransitionType // The duration of the transition animation duration: number } type TransitionType = 'SLIDE_UP' | 'SLIDE_DOWN' | 'SLIDE_HORIZONTAL' ``` ```typescript Typescript theme={"dark"} const handleOnSceneEntering = (sceneId: string) => { // perform action based on current scene being entered } const options = { /* Other options ... */ // Example 1 - scene with custom transitions enabled scene: { onEntering: handleOnSceneEntering, transition: { type: 'SLIDE_DOWN', duration: 650, // duration in milliseconds }, }, // Example 2 - scene with all transitions disabled scene: { onEntering: handleOnSceneEntering, transition: false, }, } ``` ## Styling Loading indicator While Universal Checkout loads, a loading screen indicator is displayed to the customers. You can customize the color of the loading screen indicator as shown below: ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { loadingScreen: { // Color of the loading screen indicator color: string, }, }, } ``` ## Styling Vault By default, any previously vaulted payment methods are shown to customers in Universal Checkout. This happens only when the `customerId` is included in the [client session](/docs/checkout/client-session/). ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ vault: { // Fetch the vaulted payment methods for the customerId //of the current session and display them // Default to true visible: boolean, // Disable the option to delete a saved payment method. // Default to false deletionDisabled: boolean, }, } ``` ### Styling Vault Display The vault display in Universal Checkout can be styled if you wish to change the defaults. `showMorePaymentMethodsButton` uses [TextStyle](#text-styling-options) to define the style of the button. By default, the style defined in `showMorePaymentMethodsButton.base` will be used everywhere. Add values for [TextStyle](#text-styling-options) only if you wish to override this style for the disabled state. ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { showMorePaymentMethodsButton: { base: TextStyle, disabled: TextStyle, }, }, } ``` You also have the option to style the edit icons and menu. The `actionButton` uses [TextStyle](#text-styling-options) to define the style of the button. The `confirmButton` uses both [TextStyle](#text-styling-options) and [BlockStyle](#block-styling-options) interfaces. ```typescript Typescript theme={"dark"} // Pop-up menu to manage the vaulted payment methods const options = { /* Other options ... */ // Pop-up menu to manage the vaulted payment methods vaultMenu: { // Pencil icon editButton: { // Backround of the pencil icon background: string, // Color of the pencil icon color: string, }, item: { label: textStyle, // Delete & Cancel button actionButton: TextStyle, confirmButton: TextStyle & BlockStyle, }, }, } ``` ## Displaying Custom Errors > [!TIP] > > Universal Checkout can display error messages, or you can create your own. Refer to the [Configuring Error Message Guide](https://www.npmjs.com/package/@primer-io/checkout-web#%EF%B8%8F-error-message-options--callbacks) for details. In case of an error, Universal Checkout presents a default message to the customers. This error message can be disabled if you wish to display a custom error message. ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ errorMessage: { // Disable the appearance of the //default error message // Default to false disabled: boolean, // A callback for when the error message //should be displayed onErrorMessageShow(message: string) { // Choose to use provided message for own purposes }, // A callback for when the error message //should be hidden onErrorMessageHide() { // Update own UI accordingly }, }, } ``` ## Displaying Pay by Card Button By default, the card form is automatically displayed on the first scene of Universal Checkout. You can replace it and display a 'Pay by Card' button instead of the form. Clicking on the button will show the card form on another scene. ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/drop-in/pay-by-card.png) Pay by Card ```typescript Typescript theme={"dark"} type CardPreferredFlow = 'DEDICATED_SCENE' | 'EMBEDDED_IN_HOME' // Example Primer.showUniversalCheckout(clientToken, { // ... card: { preferredFlow: 'DEDICATED_SCENE', // Show the card form on a separate scene }, }) ``` You can assign the following values to `card.preferredFlow` field: * `DEDICATED_SCENE` * `EMBEDDED_IN_HOME` (default) The style of the card form in the second dedicated scene remains defined by the `style.input` property. The pay with card button can also be styled, if you prefer not to use the default styling. See [Styling Payment Method Button](#styling-payment-method-button) for details. ## Styling Payment Method Button The `paymentMethodButton` uses [TextStyle](#text-styling-options) to define the style of the button. ```typescript Typescript theme={"dark"} const options = { /* Other options ... */ style: { paymentMethodButton: { background: string, borderRadius: number | string, boxShadow: string, borderColor: string, height: number, primaryText: TextStyle, logoColor: logoColor, marginTop: string, }, }, } ``` ## Displaying Custom Submit Button The Universal Checkout now enables you to use your own custom submit button. Follow these three simple steps to replace default submit button with your own custom one: ### Step 1. Hide the Built-in Submit Button ```typescript Typescript theme={"dark"} const checkout = await primer.showUniversalCheckout(clientToken, { submitButton: { useBuiltInButton: false, // Hide the built-in submit button }, }) ``` ### Step 2. Forward clicks to checkout.submit() ```typescript Typescript theme={"dark"} const checkout = await primer.showUniversalCheckout(clientToken, options) const handleMySubmitButtonClick = e => { checkout.submit() } ``` ### Step 3. Dynamically Update Your Submit Button The Universal Checkout expects the submit button to be visible and enabled in specific conditions. You don't have to care about these conditions - the Universal Checkout will tell you when and how to display the Submit Button. ```typescript Typescript theme={"dark"} const checkout = await primer.showUniversalCheckout(clientToken, { /* Other options ... */ submitButton: { useBuiltInButton: false, // Hide the built-in submit button // The Universal Checkout expects the button to be showed or hidden onVisible: (isVisible: boolean) => { // Show / Hide the submit button }, // The Universal Checkout expects the button to be enabled or disabled onDisable: (isDisabled: boolean) => { // Enable / Disable the submit button }, // The Universal Checkout expects the button to have a loading indicator // to indicate that it is processing/loading something // "isLoading: true" also means that the button is disabled onLoading: (isLoading: boolean) => { // Set the submit button to loading or not }, // Set the content of your submit button onContentChange: (content: string) => { // Set the text content of the submit button }, }, }) ``` > [!WARNING] > > These callback functions are called every time the scene changes. ### Handle Multiple Submit Buttons Each callback has a second argument called `context` with the `currentSceneId`. This enables you to determine which submit button to show/hide, enable/disable, or modify the content. In addition, the `onVisible` callback also contains `previousSceneId` in the context object. This enables you to hide the button of the previous scene if necessary. ```typescript Typescript theme={"dark"} const getSubmitButtonFromSceneId = (sceneId: string) => { if (sceneId === 'UniversalCheckout/Home') { return 'SideButton' } else if (sceneId === '...') { return 'TopButton' } return 'BottomButton' } const onVisible = (isVisible, context) => { const { prevousSceneId, currentSceneId } = context if (!isVisible) { hideAllSubmitButtons() } else { hideSubmitButton(getSubmitButtonFromSceneId(previousSceneId)) showSubmitButton(getSubmitButtonFromSceneId(currentSceneId)) } } const onContentChange = (content, context) => { const { currentSceneId } = context setSubmitButtonContent(getSubmitButtonFromSceneId(currentSceneId), content) } ``` ## Success Screen By default, what happens after `onTokenizeSuccess` depends on the payment method that the customer chooses. Some of them require the display of a screen that summarizes the order. It is recommended best practice to show a success screen once the payment is validated. You can use the `successScreen` options to determine whether to show a built-in success screen or a custom one. The available built-in success screen types are `'PAYMENT_METHOD'` and `'CHECK'`. > [!TIP] > > The default `successScreen` used when no type is defined is `'CHECK'`. ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/drop-in/success-screen.png) Success Screen - Check ### Custom Title When using `'CHECK'` as a success screen type, it is also possible to specify a custom success title which will be displayed under the success check mark icon. ```typescript Typescript theme={"dark"} await primer.showUniversalCheckout(clientToken, { /* Other options ... */ successScreen: { type: 'CHECK', title: 'My custom title', }, }) ``` Setting `successScreen` to `false` overrides the default behavior so that you can show a custom success screen after `onTokenizeSuccess` is called: ```typescript Typescript theme={"dark"} await primer.showUniversalCheckout(clientToken, { /* Other options ... */ successScreen: false, }) ``` ## Further Information To find out more, explore the [full API in our npm docs](https://www.npmjs.com/package/@primer-io/checkout-web). If there is anything beyond the styling options listed above that you’d like to modify or change, do get in touch with our [support team](https://portal.support.primer.io/servicedesk/customer/portal/11). # Drop-in Checkout: Get started Source: https://primer.io/docs/checkout/drop-in/overview > [!NOTE] > > We've introduced a new way to integrate our Checkout for Web\ > Learn how to build a fully customizable checkout using modular components through [our documentation here](/docs/checkout/overview) The simplest way to integrate Universal Checkout is with our drop-in UI. With just a few lines of code, you can display a fully in-context checkout UI with all your payment methods. > [!WARNING] > > Not all payment methods are currently compatible with Drop-in Checkout. > > Please refer to [this table](/docs/connections/payment-methods/available-payment-methods) to learn more about the payment methods available for Drop-in Checkout. ## Before you start Before you start, make sure: * you are ready to [process a payment](/docs/get-started/connect-a-processor) * Universal Checkout is properly [configured in the dashboard](/docs/checkout/checkout-builder) ## Create a client session A **client session** is the starting point for integrating payments at Primer. You can attach any data associated with the `order` to your client session. Creating a client session provides you with a **client token**, a temporary key used to initialize the Universal Checkout. The information you include in the client session is used in the Dashboard: * to conditionally route payments with Workflows * to activate payment methods and other features in Universal Checkout So pass as much information as you can! ### Generate an API key Requests to our API are authenticated using an API key in the `X-Api-Key` header. Create an API key by visiting the [developer page](https://dashboard.primer.io/developers/apiKeys) of the Primer Dashboard. Make sure to set the following scopes for your API Key: * `client_tokens:write` * `transactions:authorize` ### Make a client session request On your server, create a client session with POST . Make sure to pass at least the following data: | Field | Description | | :- | :- | | [orderId](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-order-id) | Your reference for the payment. *`Make sure to keep track of orderId - you will later receive updates to the payment via Webhooks. The payment will contain the orderId specified in the client session.`* | | [currencyCode](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-currency-code) | The three-letter currency code in [ISO 4217 format](https://en.wikipedia.org/wiki/ISO_4217#Active_codes). e.g. use `USD` for US dollars. | | [order.lineItems](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-order-line-items) | The details of the line items of the order. | > [!NOTE] > > The body of a successful response contains a [clientToken](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#response-client-token) that you will use to initialize the Universal Checkout. Here is how the client session request to the Primer API should look like: ```bash BASH theme={"dark"} curl --location --request \ POST 'https://api.sandbox.primer.io/client-session' \ --header 'X-Api-Key: ' \ --header 'X-Api-Version: 2.4' \ --header 'Content-Type: application/json' \ --data '{ "orderId": "", "currencyCode": "GBP", "amount": 5000, "order": { "lineItems": [{ "itemId": "shoes-123", "amount": 2500, "quantity": 2 }], "countryCode": "GB" } }' # Here is a (heavily truncated) example response { "clientToken": "THE_CHECKOUT_SESSION_TOKEN", "clientExpirationDate": "2022-03-08T14:00:00Z", "orderId": "", "currencyCode": "GBP", "amount": 5000, "order": { "lineItems": [{ "itemId": "shoes-123", "amount": 2500, "quantity": 2 }], "countryCode": "GB", } } ``` > [tab] Web > > ## Install the SDK > > > [!NOTE] > > > > Please review the [Content Security Policy (CSP)](/docs/checkout/advanced/content-security-policy) recommendations before installing! > > ### With npm > > Our Web SDK is available on npm under the name [`@primer-io/checkout-web`](https://www.npmjs.com/package/@primer-io/checkout-web). > > This package includes TypeScript definitions. > > ```bash BASH theme={"dark"} > # With yarn > yarn add @primer-io/checkout-web > > # With npm > npm install --save @primer-io/checkout-web > ``` > > ```typescript Typescript theme={"dark"} > import { Primer } from "@primer-io/checkout-web"; > > Primer.showUniversalCheckout(clientToken, { > /* Options */ > }); > ``` > > > [!WARNING] > > > > * The npm package only works if used alongside a bundler such as Webpack or Parcel. If you're directly writing JavaScript using `script` tag, please use our [CDN](#with-our-cdn) instead. > > * As of today, the npm package does not work in a server environment. If you are using Next.js, Gatsby, or a similar framework, make sure the `Primer` functions are called on the client side, or use our [CDN](#with-our-cdn) instead. > > ### With our CDN > > Include the `Primer.min.js` script and the `Checkout.css` stylesheet on the page where you want to render the Checkout. Make sure to pass the proper version in the URL. > > ```html HTML theme={"dark"} > > > > ``` > > The `Primer.min.js` will add the `Primer` object to the global scope: > > ```typescript Typescript theme={"dark"} > const { Primer } = window; > > Primer.showUniversalCheckout(clientToken, { > /* Options */ > }); > ``` > > ## Initialize and Show Universal Checkout > > Use the generated client token on the client-side to show Universal Checkout by calling `Primer.showUniversalCheckout(clientToken, options)`. Make sure to pass a selector to your container in the options. > > ```javascript Javascript theme={"dark"} > const universalCheckout = await Primer.showUniversalCheckout(clientToken, { > // Specify the selector of the container element > container: "#checkout-container", > > /** > * When the checkout flow has been completed, you'll receive > * the successful payment via `onCheckoutComplete`. > * Implement this callback to redirect the user to an order confirmation page. > */ > onCheckoutComplete({ payment }) { > console.log("Checkout Complete!", payment); > }, > > /** > * When the checkout flow has been fail, you'll receive > * the error via `onCheckoutFail` > */ > onCheckoutFail(error, { payment }, handler) { > console.log("Checkout Fail!", error, payment); > }, > }); > ``` > > When the user interacts with the checkout: > > * Update the client session > * Create a payment (by default) > > ## Handle successful payments > > ### Listen to callback > > On the client-side, listen to the `onCheckoutComplete` callback to be notified when the payment has been successfully completed. Use it to show an order confirmation screen. > > ### Handle webhooks > > To receive updates about the status of your payments you’ll need to listen to webhooks. This is particularly useful for updating an order or any other data stored server-side. > > Head to the [Developers section](https://dashboard.primer.io/developers) of the Primer Dashboard to setup and test a webhook for `PAYMENT.STATUS` event. > > If you are not yet ready to receive webhooks, you can use [https://webhook.site](https://webhook.site/) to test your implementation. > > ### Handle redirects > > Some payment methods require redirecting to another web page in order to capture payment details. > > Drop-in checkout automatically renders that web page in a popup window in order to maintain the current context. > > > [!NOTE] > > > > **If the browser cannot open popup windows, the current window will be redirected instead.** > > > > To ensure maximum compatibility, read the guide on [how to handle redirects](/docs/sdk/web/v2.x.x/handle-redirects-and-deeplinks). > > ## Handle failed payments > > Any errors, cancelled payment interactions or failed payments will trigger the `onCheckoutFail` callback with a [PrimerClientError](/docs/sdk/web/v2.x.x/common-objects/PrimerClientError) > > ```javascript Javascript theme={"dark"} > onCheckoutFail(error, { payment }, handler) { > // Notifies you that the checkout flow has failed and a payment could not be created > // This callback can also be used to display an error state within your own UI. > > // ⚠️ `handler` is undefined if the SDK does not expect anything from you > if (!handler) { > return; > } > > // ⚠️ If `handler` exists, you MUST call one of the functions of the handler > > // Show a default error message > return handler.showErrorMessage(); > > // Show a custom error message > return handler.showErrorMessage('This is my custom error message'); > } > ``` > > > [!WARNING] > > > > [Not all failures are retryable](/docs/sdk/web/v2.x.x/common-objects/PrimerClientError#not-all-failures-are-retryable). A client-side error doesn't always mean the payment failed, and decline reasons are intentionally generic. Verify the payment status server-side before asking the user to pay again. > [tab] iOS > > > [!NOTE] > > > > Backend API V2.4 enhances reliability and minimizes synchronization issues with external processors by significantly extending payment timeouts. This longer timeout accommodates external processor limits and internal operations, ensuring more reliable transaction handling. These improvements are fully supported starting with Primer iOS SDK 2.34.0, so upgrading your app to use the newest SDK version is highly recommended when creating client sessions with API V2.4. > > ## Install the SDK > > ### With CocoaPods > > Add the following in your `Podfile`: > > ```ruby RUBY theme={"dark"} > use_frameworks! > > target 'MyApp' do > > # 👇 Add this line > pod 'PrimerSDK' > > # ... > > end > ``` > > Then run `pod install` to install `PrimerSDK` on your workspace. > > > [!NOTE] > > > > In case you encounter an error that the bundle needs signing on Xcode 14, add the following post-install script in your podfile. > > > > ```ruby theme={"dark"} > > post_install do |installer| > > installer.pods_project.targets.each do |target| > > if target.respond_to?(:product_type) and target.product_type == "com.apple.product-type.bundle" > > target.build_configurations.each do |config| > > config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' > > end > > end > > end > > end > > ``` > > ### With Swift Package Manager > > The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into Xcode. In order to add PrimerSDK with Swift Package Manager: > > 1. Select your project, and then navigate to `Package Dependencies` > > 2. Click on the **+** button at the bottom-left of the `Packages` section > > 3. Paste [https://github.com/primer-io/primer-sdk-ios.git](https://github.com/primer-io/primer-sdk-ios.git) into the **Search Bar,** or search for `primer-sdk-ios` in the **Search Bar**. > > 4. Press **Add Package** > > 5. Let Xcode download the package and set everything up > > > [!NOTE] > > > > For more details about SDK versions, please see our [changelog](/docs/changelogs/android-sdk). > > ## Initialize Universal Checkout > > Import the `PrimerSDK` and set its delegate as shown in the following example: > > ```swift SWIFT theme={"dark"} > import PrimerSDK > > class MyViewController: UIViewController, PrimerDelegate { > > override func viewDidLoad() { > super.viewDidLoad() > > // Initialize the SDK with the default settings. > Primer.shared.configure(delegate: self) > } > > func primerDidCompleteCheckoutWithData(_ data: PrimerCheckoutData) { > // Primer checkout completed with data > // do something... > } > } > ``` > > > [!NOTE] > > > > See all the configurations in the [SDK Reference](/docs/sdk/ios/v2.x.x/installation). > > ## Show Universal Checkout > > At this step you should have a client token available - see [Manage Client Sessions](/docs/checkout/client-session) for more. > > Call the `showUniversalCheckout(clientToken:)` function (as shown below) to present Universal Checkout. > > ```swift SWIFT theme={"dark"} > class MyViewController: UIViewController, PrimerDelegate { > > func startUniversalCheckout() { > Primer.shared.showUniversalCheckout(clientToken: self.clientToken) > } > } > ``` > > > [!NOTE] > > > > You should now be able to see Universal Checkout! The user can now interact with Universal Checkout, and the SDK will create the payment. The payment’s data will be returned on `primerDidCompleteCheckoutWithData(_:)` configured in the previous step. > > When the user interacts with the checkout and clicks to pay, the Universal Checkout: > > * Shows the payment method screen if applicable > * Tokenizes the payment method for payment > * Creates the payment > * Handles any other interactions (e.g. 3DS) > > ## Handle successful payments > > ### Listen to delegate function > > Listen to the `primerDidCompleteCheckoutWithData(_:)` delegate function > > This function will notify you of a successful payment. > > ```swift SWIFT theme={"dark"} > class MyViewController: UIViewController { > > // ... > > func primerDidCompleteCheckoutWithData(_ data: PrimerCheckoutData) { > // Primer checkout completed with data > // Do something with the data, e.g. show the payment id > } > } > ``` > > ### Handle webhooks in your dashboard > > To receive updates about the status of your payments you’ll need to listen to webhooks. This is particularly useful for updating an order or any other data stored server-side. > > Head to the [Developers section](https://dashboard.primer.io/developers) of the Primer Dashboard to setup and test a webhook for `PAYMENT.STATUS` event. > > If you are not yet ready to receive webhooks, you can use [https://webhook.site](https://webhook.site/) to test your implementation. > > ## Handle failed payments > > Any errors, cancelled payment interactions or failed payments will trigger the `primerDidFailWithError(_:data:decisionHandler:)` delegate function. > > ```swift SWIFT theme={"dark"} > class MyViewController: UIViewController, PrimerDelegate { > > // ... > > func primerDidFailWithError(_ error: Error, data: PrimerCheckoutData?, decisionHandler: @escaping ((PrimerErrorDecision) -> Void)) { > // 👇 Call the decision handler to show a failure message > decisionHandler(.fail(withErrorMessage: message)) > } > } > ``` > > > [!WARNING] > > > > Not all failures are retryable. A client-side error doesn't always mean the payment failed, and decline reasons are intentionally generic. Verify the payment status server-side — through [payment webhooks](/docs/get-started/payment-updates) or the Payments API — before asking the user to pay again. > [tab] Android > > > [!NOTE] > > > > Backend API V2.4 enhances reliability and minimizes synchronization issues with external processors by significantly extending payment timeouts. This longer timeout accommodates external processor limits and internal operations, ensuring more reliable transaction handling. These improvements are fully supported starting with Primer Android SDK 2.35.0, so upgrading your app to use the newest SDK version is highly recommended when creating client sessions with API V2.4. > > ## Install the SDK > > Add the Primer BOM and the SDK to your app module's `build.gradle.kts` or `build.gradle` file, replacing `` with the latest version from the [Android SDK changelog](/docs/changelogs/android-sdk). The BOM keeps the SDK and any Primer payment method libraries on the same version: > > ```kotlin Kotlin theme={"dark"} > repositories { > mavenCentral() > } > > dependencies { > implementation(platform("io.primer:bom:")) > implementation("io.primer:android") > } > ``` > > ```groovy Groovy theme={"dark"} > repositories { > mavenCentral() > } > > dependencies { > implementation platform('io.primer:bom:') > implementation 'io.primer:android' > } > ``` > > > [!NOTE] > > > > Some payment methods and features, such as Klarna and 3D Secure, need a separate Primer library. The integration guide for each one shows the library to add, and [Version alignment](/docs/sdk/android/v2.x.x/installation#version-alignment) explains how its version is set. > > It is highly recommended adding the following settings to your `app/build.gradle` file: > > ```kotlin Kotlin theme={"dark"} > android { > kotlinOptions { > freeCompilerArgs += '-Xjvm-default=all' > } > } > ``` > > ## Initialize Universal Checkout > > Prepare the `PrimerCheckoutListener` that will handle the callbacks that happen during the lifecycle. Import the Primer SDK and set its listener as shown in the following example: > > ```kotlin Kotlin theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > > private val listener = object : PrimerCheckoutListener { > > // 👇 [Required] This function is called when the checkout has been completed > override fun onCheckoutCompleted(checkoutData: PrimerCheckoutData) { > // Show an order confirmation screen... > // checkoutData contains the payment that has been created > } > } > > override fun onCreate(savedInstanceState: Bundle?) { > super.onCreate(savedInstanceState) > setContentView(R.layout.activity_main) > > configureCheckout() > } > > private fun configureCheckout() { > // 👇 Initialize the SDK with the default settings. > Primer.instance.configure(settings = PrimerSettings(), listener = listener) > } > } > ``` > > > [!NOTE] > > > > See all the configurations in the [SDK Reference](/docs/sdk/android/v2.x.x/common-objects/PrimerSettings). > > ## Show Universal Checkout > > At this step you should have a client token available - see [Manage Client Sessions](/docs/checkout/client-session) for more. > > When the client token is retrieved, show Universal Checkout by calling `showUniversalCheckout` method: > > ```kotlin Kotlin theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > > // other code goes here > private lateinit var viewModel: CheckoutViewModel > > override fun onCreate(savedInstanceState: Bundle?) { > super.onCreate(savedInstanceState) > setContentView(R.layout.activity_main) > > setupViewModel() > setupObservers() > fetchClientToken() > } > > private fun setupViewModel() { > viewModel = ViewModelProvider(this).get(CheckoutViewModel::class.java) > } > > private fun fetchClientToken() = viewModel.fetchClientToken() > > private fun setupObservers() { > viewModel.clientToken.observe(this) { clientToken -> > showUniversalCheckout(clientToken) > } > } > > private fun showUniversalCheckout(clientToken: String) { > Primer.instance.showUniversalCheckout(this, clientToken) > } > } > ``` > > > [!NOTE] > > > > You should now be able to see Universal Checkout! The user can now interact with Universal Checkout, and the SDK will create the payment. The payment’s data will be returned on `onCheckoutCompleted()` configured in the previous step. > > When the user interacts with the checkout and clicks to pay, the Universal Checkout: > > * Shows the payment method screen if applicable > * Tokenizes the payment method for payment > * Creates the payment > * Handles any other interactions (e.g. 3DS) > > ## Handle successful payments > > ### Listen to callback > > Listen to `onCheckoutCompleted` callback > > This function will notify you of a successful payment > > ```kotlin Kotlin theme={"dark"} > private val listener = object : PrimerCheckoutListener { > > override fun onCheckoutCompleted(checkoutData: PrimerCheckoutData) { > // Show an order confirmation screen... > // checkoutData contains the payment that has been created > } > } > ``` > > ### Handle webhooks in your dashboard > > To receive updates about the status of your payments you’ll need to listen to webhooks. This is particularly useful for updating an order or any other data stored server-side. > > Head to the [Developers section](https://dashboard.primer.io/developers) of the Primer Dashboard to setup and test a webhook for `PAYMENT.STATUS` event. > > If you are not yet ready to receive webhooks, you can use [https://webhook.site](https://webhook.site/) to test your implementation. > > ## Handle failed payments > > Any errors, cancelled payment interactions or failed payments will trigger the `onFailed` callback > > ```kotlin Kotlin theme={"dark"} > private val listener = object : PrimerCheckoutListener { > > override fun onFailed( > error: PrimerError, > checkoutData: PrimerCheckoutData?, > errorHandler: PrimerErrorDecisionHandler? > ) { > // Notifies you that the checkout flow has failed and a payment could not be created > // This callback can also be used to display an error state within your own UI. > > // Show a default error message > errorHandler?.showErrorMessage(null) > > // Show a custom error message > errorHandler?.showErrorMessage("This is my custom error message") > } > } > ``` > > > [!WARNING] > > > > Not all failures are retryable. A client-side error doesn't always mean the payment failed, and decline reasons are intentionally generic. Verify the payment status server-side — through [payment webhooks](/docs/get-started/payment-updates) or the Payments API — before asking the user to pay again. > [tab] React Native > > > [!NOTE] > > > > This SDK requires React Native [v0.63](https://reactnative.dev/versions) or higher. > > > [!NOTE] > > > > Backend API V2.4 enhances reliability and minimizes synchronization issues with external processors by significantly extending payment timeouts. This longer timeout accommodates external processor limits and internal operations, ensuring more reliable transaction handling. These improvements are fully supported starting with Primer React Native SDK 2.35.0, so upgrading your app to use the newest SDK version is highly recommended when creating client sessions with API V2.4. > > ## Install the SDK > > Add the SDK package > > ```bash BASH theme={"dark"} > # With yarn > yarn add @primer-io/react-native > > # With npm > npm i @primer-io/react-native --save > ``` > > **Requirement for iOS** > > Once you are done, navigate to the `/ios` folder and run `pod install`. > > > [!NOTE] > > > > For more details about SDK versions, please see our [changelog](/docs/sdk/react-native/v2.x.x/installation). > > ## Initialize Universal Checkout > > Import the Primer SDK, construct your settings and call the SDK’s `configure` function. > > ```tsx Typescript theme={"dark"} > import { > Primer, > PrimerSettings, > PrimerCheckoutData, > } from "@primer-io/react-native"; > > const CheckoutScreen = (props: any) => { > const onCheckoutComplete = (checkoutData: PrimerCheckoutData) => { > // Perform an action based on the payment creation response > // ex. show success screen, redirect to order confirmation view, etc. > }; > > const onUniversalCheckoutButtonTapped = async () => { > try { > const settings: PrimerSettings = { > onCheckoutComplete, > }; > > await Primer.configure(settings); > } catch (err) { > // Handle error > } > }; > }; > ``` > > > [!NOTE] > > > > See all the configurations in the [SDK Reference](/docs/sdk/react-native/v2.x.x/installation). > > ## Show Universal Checkout > > First, make an API call to your backend to fetch a client token. Here is a simple example of how it can be done from your component. Once successful store your client token for future use. > > ```tsx Typescript theme={"dark"} > const CheckoutScreen = (props: any) => { > // ... > > const onUniversalCheckoutButtonTapped = async () => { > try { > // ... > // Ask your backend to create a client session > const clientToken = await createClientSession(); > } catch (err) { > // Handle error > } > }; > }; > ``` > > See [Manage Client Sessions](/docs/checkout/client-session) for more. > > Now, call the `showUniversalCheckout(clientToken)` function, with the client token to present Universal Checkout. > > ```tsx Typescript theme={"dark"} > const CheckoutScreen = async (props: any) => { > // ... > > const onUniversalCheckoutButtonTapped = async () => { > // ... > > try { > // Ask your backend to create a client session > const clientToken = await createClientSession(); > > // Present Universal Checkout > await Primer.showUniversalCheckout(clientToken); > } catch (err) { > // Handle error > } > }; > }; > ``` > > > [!NOTE] > > > > You should now be able to see Universal Checkout! The user can now interact with Universal Checkout, and the SDK will create the payment. The payment’s data will be returned on `primerDidCompleteCheckoutWithData(_:)` configured in the previous step. > > When the user interacts with the checkout and clicks to pay, the Universal Checkout: > > * Shows the payment method screen if applicable > * Tokenizes the payment method for payment > * Creates the payment > * Handles any other interactions (e.g. 3DS) > > ## Handle successful payments > > ### Listen to callback > > This function will notify you of a successful payment > > ```tsx Typescript theme={"dark"} > const onCheckoutComplete = (checkoutData: PrimerCheckoutData) => { > // Show a success screen > }; > ``` > > ### Handle webhooks in your dashboard > > To receive updates about the status of your payments you’ll need to listen to webhooks. This is particularly useful for updating an order or any other data stored server-side. > > Head to the [Developers section](https://dashboard.primer.io/developers) of the Primer Dashboard to setup and test a webhook for `PAYMENT.STATUS` event. > > If you are not yet ready to receive webhooks, you can use [https://webhook.site](https://webhook.site/) to test your implementation. > > ## Handle failed payments > > Any errors, cancelled payment interactions or failed payments will trigger the `onError` callback > > ```tsx Typescript theme={"dark"} > const onError = ( > error: PrimerError, > checkoutData: PrimerCheckoutData | null, > handler: PrimerErrorHandler | undefined, > ) => { > // Notifies you that the checkout flow has failed and a payment could not be created > // This callback can also be used to display an error state within your own UI. > > // ⚠️ `handler` is undefined if the SDK does not expect anything from you > if (!handler) { > return; > } > > // ⚠️ If `handler` exists, you MUST call one of the functions of the handler > > // Show a default error message > handler.showErrorMessage(); > > // Show a custom error message > handler.showErrorMessage('This is my custom error message'); > ``` > > > [!WARNING] > > > > Not all failures are retryable. A client-side error doesn't always mean the payment failed, and decline reasons are intentionally generic. Verify the payment status server-side — through [payment webhooks](/docs/get-started/payment-updates) or the Payments API — before asking the user to pay again. # Headless Checkout Source: https://primer.io/docs/checkout/headless > [!NOTE] > > We've introduced a new way to integrate our Checkout for Web\ > Learn how to build a fully customizable checkout using modular components through [our documentation here](/docs/checkout/overview) Where there is a need for more customization and control over the checkout experience, a headless version of Primer’s Universal Checkout is available. You can use Headless Universal Checkout with your UI, giving you more flexibility and allowing you to move faster when making design changes, while still having Universal Checkout capture sensitive PCI card data or other form data. > [!WARNING] > > Not all payment methods are currently compatible with Headless Checkout. > > Please refer to [this table](/docs/connections/payment-methods/available-payment-methods) to learn more about the payment methods available for Headless Checkout. ## Before you start Before you start, make sure: * you are ready to [process a payment](/docs/get-started/connect-a-processor) * Universal Checkout is properly [configured in the dashboard](/docs/checkout/checkout-builder) ## Create a client session A **client session** is the starting point for integrating payments at Primer. You can attach any data associated with the `order` to your client session. Creating a client session provides you with a **client token**, a temporary key used to initialize the Universal Checkout. The information you include in the client session is used in the Dashboard: * to conditionally route payments with Workflows * to activate payment methods and other features in Universal Checkout So pass as much information as you can! ### Generate an API key Requests to our API are authenticated using an API key in the `X-Api-Key` header. Create an API key by visiting the [developer page](https://dashboard.primer.io/developers/apiKeys) of the Primer Dashboard. Make sure to set the following scopes for your API Key: * `client_tokens:write` * `transactions:authorize` ### Make a client session request On your server, create a client session with POST . Make sure to pass at least the following data: | Field | Description | | :- | :- | | [orderId](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-order-id) | Your reference for the payment. *`Make sure to keep track of orderId - you will later receive updates to the payment via Webhooks. The payment will contain the orderId specified in the client session.`* | | [currencyCode](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-currency-code) | The three-letter currency code in [ISO 4217 format](https://en.wikipedia.org/wiki/ISO_4217#Active_codes). e.g. use `USD` for US dollars. | | [order ↳ lineItems](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-order-line-items) | The details of the line items of the order. | > [!NOTE] > > The body of a successful response contains a [clientToken](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#response-client-token) that you will use to initialize the Universal Checkout. Here is how the client session request to the Primer API should look like: ```bash BASH theme={"dark"} curl --location --request \ POST 'https://api.sandbox.primer.io/client-session' \ --header 'X-Api-Key: ' \ --header 'X-Api-Version: 2.2' \ --header 'Content-Type: application/json' \ --data '{ "orderId": "", "currencyCode": "GBP", "amount": 5000, "order": { "lineItems": [{ "itemId": "shoes-123", "amount": 2500, "quantity": 2 }], "countryCode": "GB" } }' # Here is a (heavily truncated) example response { "clientToken": "THE_CHECKOUT_SESSION_TOKEN", "clientExpirationDate": "2022-03-08T14:00:00Z", "orderId": "", "currencyCode": "GBP", "amount": 5000, "order": { "lineItems": [{ "itemId": "shoes-123", "amount": 2500, "quantity": 2 }], "countryCode": "GB", } } ``` ## Get Started Primer Headless Universal Checkout works in a simple way: 1. Get a `clientToken` from your server 2. Start Primer Headless Universal Checkout with the client token 3. Primer Headless Universal Checkout will then return the `available payment methods` for the session initiated. Those payment methods that have been configured in the Dashboard and whose conditions match the current client session will be returned. 4. You show the user the list of available payment methods. 5. When the user selects a payment method, show its UI to enable the user to enter their credentials. Depending on the payment method, you will have to either ask the SDK to render it, or build the UI yourself. 6. Primer's Headless Universal Checkout will then create a payment for you and manage its lifecycle. You will receive a confirmation of payment with a callback to indicate the checkout flow has completed. > [tab] Web > > > [!NOTE] > > > > This documentation is only relevant for v2.21.0 and upward. > > ## Step 1. Install the SDK > > > [!NOTE] > > > > Please review the [Content Security Policy (CSP)](/docs/checkout/advanced/content-security-policy/) recommendations before installing. > > ### With npm > > Our Web SDK is available on npm under the name [`@primer-io/checkout-web`](https://www.npmjs.com/package/@primer-io/checkout-web). > > This package includes TypeScript definitions. > > ```bash BASH theme={"dark"} > # With yarn > yarn add @primer-io/checkout-web > > # With npm > npm install --save @primer-io/checkout-web > ``` > > ```typescript Typescript theme={"dark"} > import { Primer } from '@primer-io/checkout-web' > > Primer.createHeadless(clientToken, options) > ``` > > > [!WARNING] > > > > * The npm package only works if used alongside a bundler such as Webpack or Parcel. If you're directly writing JavaScript using `script` tag, please use our [CDN](#with-our-cdn) instead. > > * As of today, the npm package does not work in a server environment. If you are using Next.js, Gatsby, or a similar framework, make sure the `Primer` functions are called on the client side, or use our [CDN](#with-our-cdn) instead. > > ### With our CDN > > Include the `Primer.min.js` script and the `Checkout.css` stylesheet on the page where you want to render the Checkout. Make sure to pass the proper version in the URL. > > ```html HTML theme={"dark"} > > > > ``` > > The `Primer.min.js` will add the `Primer` object to the global scope: > > ```typescript Typescript theme={"dark"} > const { Primer } = window > > Primer.createHeadless(clientToken, options) > ``` > > ## Step 2: Initialize Primer’s Headless Universal Checkout > > ### Generate a client token > > Request a client token from your backend by creating a client session. > > > [!TIP] > > > > Check our guide on how to create a client session [here](/docs/checkout/client-session). > > > [!NOTE] > > > > Remember that based on your client token different payment methods will be available for display. > > ### Configure Headless Universal Checkout > > Once you have a client token, initialize Primer’s headless checkout with `Primer.createHeadless(clientToken, options)`. > > ```typescript Typescript theme={"dark"} > const headless = await Primer.createHeadless(clientToken, options) > ``` > > Make sure to implement at least the following callbacks: > > * `onAvailablePaymentMethodsLoad(paymentMethodTypes)` \ > returns the available payment methods for the client session. Use it to render a list of payment methods. > > * `onCheckoutComplete(data)` \ > is called when the payment has been successfully completed. It returns a reference to the payment. > > * `onCheckoutFail(error, data, handler)` \ > is called if the payment fails to be created or processed. > > > [!NOTE] > > > > Payment methods are added and configured through your Primer Dashboard. `onAvailablePaymentMethodsLoad` will return the payment methods whose conditions match the current client session. > > Finally, call `headless.start()` to retrieve the list of payment methods, and start the checkout flow. > > ```typescript Typescript theme={"dark"} > await headless.start() > ``` > > Here is a full example to configure and start Headless Universal Checkout: > > ```typescript Typescript theme={"dark"} > window.addEventListener('load', onLoaded) > > async function onLoaded() { > // Create a client session via your backend > const clientSession = await fetch('/client-session', { > method: 'post', > headers: { 'Content-Type': 'application/json' }, > }).then(data => data.json()) > > const { clientToken } = clientSession > const { Primer } = window > > // Create an instance of the headless checkout > const headless = await Primer.createHeadless(clientToken, { > onAvailablePaymentMethodsLoad(paymentMethods) { > // Called when the available payment methods are retrieved > > for (const paymentMethod of paymentMethods) { > // `type` is a unique ID representing the payment method > const { type, managerType } = paymentMethod > > switch (managerType) { > case 'CARD': { > // Configure your card form (see Step 4.a) > // await configureCardForm(paymentMethod); > break > } > case 'NATIVE': { > // Render the native payment method button (see Step 4.b) > // Relevant for PayPal, Apple Pay and Google Pay > // configureNativeButton(paymentMethod); > break > } > case 'REDIRECT': { > // Handle redirect payment methods (see Step 4.c) > // configureRedirectPaymentMethod(paymentMethod); > break > } > case 'KLARNA': { > // Handle Klarna payment methods (see Step 4.d) > // configureklarnaPaymentMethod(paymentMethod); > break > } > case 'ACH': { > // Handle ACH payment method > // Only `STRIPE_ACH` is supported (see Step 4.e) > // configureStripeAchPaymentMethod(paymentMethod); > break > } > > // More payment methods to follow > } > } > }, > > onCheckoutComplete({ payment }) { > // Notifies you that a payment was created > // Move on to next step in your checkout flow: > // e.g. Show a success message, ... > console.log('onCheckoutComplete', payment) > }, > > onCheckoutFail(error, { payment }, handler) { > // Notifies you that the checkout flow has failed and a payment could not be created > // This callback can also be used to display an error state within your own UI. > > // ⚠️ `handler` is undefined if the SDK does not expect anything from you > if (!handler) { > return > } > > // ⚠️ If `handler` exists, you MUST call one of the functions of the handler > > // Show a default error message > return handler.showErrorMessage() > }, > }) > > // Start the headless checkout > await headless.start() > > console.log('Headless Universal Checkout is loaded!') > } > ``` > > > [!NOTE] > > > > See more options and events in the [SDK API Reference](https://www.npmjs.com/package/@primer-io/checkout-web) > > ## Step 3: Show available payment methods > > When the checkout is done initializing, the callback `onAvailablePaymentMethodsLoad` is invoked. Use this event to show the list of payment methods to the user: > > * Some payment methods such as Google Pay, Apple Pay, and PayPal require [Primer to manage their payment method button](/docs/checkout/headless#step-4-b%3A-handle-payment-methods-with-native-buttons). > * For the others, you have full control over how the payment method button should be presented. To assist you, Primer exposes the `AssetsManager` that enables you to retrieve the logo and main colors attached to each payment method. > > ```typescript Typescript theme={"dark"} > // getAssetsManager() is only available once Headless Checkout has been fully initialized > const assetsManager = headless.getAssetsManager() > > const { iconUrl, paymentMethodName, backgroundColor } = await assetsManager.getPaymentMethodAsset('ADYEN_IDEAL') // ADYEN_IDEAL comes from `paymentMethod.type` > ``` > > > [!NOTE] > > > > The assets manager is only available once `onAvailablePaymentMethodsLoad` has been called. > > ## Step 4: Handle payment method selection > > Headless Universal Checkout enables you to create any UI that suits your needs, using the components and data we provide. > > ### Step 4.a: Handle cards > > When `PAYMENT_CARD` is available as a payment method and provided via `onAvailablePaymentMethodsLoad`, build your card form using Primer input elements. > > Get started by creating a payment method manager for cards. > > ```typescript Typescript theme={"dark"} > const cardManager = await headless.createPaymentMethodManager('PAYMENT_CARD') > ``` > > #### Show card fields > > > [!NOTE] > > > > Headless Universal Checkout securely captures payment method data while fully embedded in your app. By communicating directly with Primer's PCI-L1 tokenization service, Universal Checkout transforms sensitive customer data into a secure uniform string called a payment method token. > > First, prepare containers in the DOM for the Primer hosted inputs. You would need three containers for the card number, the expiry date, and the CVV. > > ```typescript Typescript theme={"dark"} > const container = document.getElementById('my-container') > > const cardNumberInputId = 'checkout-card-number-input' > const cardNumberInputEl = document.createElement('div') > cardNumberInputEl.setAttribute('id', cardNumberInputId) > > const cardExpiryInputId = 'checkout-card-expiry-input' > const cardExpiryInputEl = document.createElement('div') > cardExpiryInputEl.setAttribute('id', cardExpiryInputId) > > const cardCvvInputId = 'checkout-card-cvv-input' > const cardCvvInputEl = document.createElement('div') > cardCvvInputEl.setAttribute('id', cardCvvInputId) > > container.append(cardNumberInputEl, cardExpiryInputEl, cardCvvInputEl) > ``` > > Then, create the hosted card inputs: > > ```typescript Typescript theme={"dark"} > const { cardNumberInput, expiryInput, cvvInput } = cardManager.createHostedInputs() > ``` > > Finally, render your inputs into the relevant containers: > > ```typescript Typescript theme={"dark"} > await Promise.all([ > cardNumberInput.render(cardNumberInputId, { > placeholder: '1234 1234 1234 1234', > ariaLabel: 'Card number', > }), > expiryInput.render(cardExpiryInputId, { > placeholder: 'MM/YY', > ariaLabel: 'Expiry date', > }), > cvvInput.render(cardCvvInputId, { > placeholder: '123', > ariaLabel: 'CVV', > }), > ]) > ``` > > ##### Customize card fields > > > [!WARNING] > > > > Card fields are rendered with individual iframes in order to remain PCI-L1 compliant. One key consequence is that the CSS of your page will not be propagated to the card fields. This includes **color**, and **font**. > > Pass a `style` object to the `render` function to configure colors and font options. > > ```typescript Typescript theme={"dark"} > const style = { > input: { > base: { > height: 'auto', > border: '1px solid rgb(0 0 0 / 10%)', > borderRadius: '2px', > padding: '12px', > boxShadow: '0 4px 8px 0 rgba(0,0,0,0.2)', > }, > }, > } > > cardNumberInput.render(cardNumberInputId, { > placeholder: '1234 1234 1234 1234', > ariaLabel: 'Card number', > style, > }) > ``` > > > [!NOTE] > > > > Check the ["Styling Inputs" section of the Customize Universal Checkout guide](/docs/checkout/drop-in/customization#styling-inputs) to learn how to adapt the style to your requirements. > > ##### Reset card form > > If needed, the card form can be cleared by calling `reset()`: > > ```typescript Typescript theme={"dark"} > cardManager.reset() > ``` > > ##### Remove card elements > > Call `removeHostedInputs()` to remove the hosted card input fields from the DOM: > > ```typescript Typescript theme={"dark"} > cardManager.removeHostedInputs() > ``` > > #### Detect card type > > When the user enters the card credentials, Headless Universal Checkout automatically detects the card type and retrieves BIN data including issuer information. > > Listen to the callback `onBinDataAvailable` on the card manager to receive card type and BIN data. > > ```typescript Typescript theme={"dark"} > const cardManager = await headless.createPaymentMethodManager('PAYMENT_CARD', { > onBinDataAvailable(event) { > // event.preferred - the recommended network > // event.alternatives - all detected networks, excluding preferred > // event.status - 'complete' or 'partial' > }, > }) > ``` > > > [!NOTE] > > > > Learn more about `onBinDataAvailable` in the [API reference](/docs/sdk/web/v2.x.x/primer-headless-checkout/methods/createPaymentMethodManager#card.parameters.options-properties.onBinDataAvailable). > > #### Capture cardholder name > > You are free to render the cardholder name input however you want. > > As the user enters their cardholder name, call `setCardholderName(cardholderName)` to pass the cardholder name to the `cardManager`: > > ```typescript Typescript theme={"dark"} > cardholderNameInput.addEventListener('change', e => { > cardManager.setCardholderName(e.target.value) > }) > ``` > > If the cardholder name is required, its content will be validated by Headless Universal Checkout. > > You can specify whether the cardholder name is required by setting an option when initializing Headless Universal Checkout: > > ```typescript Typescript theme={"dark"} > const headless = await Primer.createHeadless(clientToken, { > card: { > cardholderName: { > required: true, > }, > }, > }) > ``` > > #### Handle input errors > > The event `change`, available on each input, reacts to input changes. This returns if the input is valid or not, and the error type. > > ```typescript Typescript theme={"dark"} > cardNumberInput.addEventListener('change', (...args) => { > console.log('cardNumberInput changed', ...args) > }) > ``` > > #### Validate and Submit > > When the user submits the card information, follow the following flow: > > * First, validate all the inputs using the `validate()` function that does basic validations on the hosted inputs. > * Then, submit the validated data using the `submit()` function. This triggers the payment creation. > > For example, if the user clicks submit, you can handle it as follows: > > ```typescript Typescript theme={"dark"} > submitButton.addEventListener('click', async () => { > // Validate your card input data > const { valid } = await cardManager.validate() > if (valid) { > // Submit the card input data to Primer for tokenization > await cardManager.submit() > } } > }) > ``` > > Calling `submit()` triggers the creation and handling of the payment. > > * If `onCheckoutComplete` is called, show a success message and reset the inputs. > * If `onCheckoutFail` is called, show a failure message and allow the customer to try again with the same details. > > #### Prepare 3DS > > When the user pays by card, the [Workflow](/docs/get-started/create-workflow) will decide whether a 3DS challenge is required or not. If so, Headless Universal Checkout will automatically render the 3DS challenge in context. > > To improve 3DS success rates, it is recommended to pass the following elements in the Client Session: > > * `customer.emailAddress` > * `customer.billingAddress` > > #### Integration example snippet > > Below is an example code snippet of how it all fits together. > > ```typescript Typescript theme={"dark"} > const container = document.getElementById('my-container') > > // Create containers for your hosted inputs > const cardNumberInputId = 'checkout-card-number-input' > const cardNumberInputEl = document.createElement('div') > cardNumberInputEl.setAttribute('id', cardNumberInputId) > > const cardExpiryInputId = 'checkout-card-expiry-input' > const cardExpiryInputEl = document.createElement('div') > cardExpiryInputEl.setAttribute('id', cardExpiryInputId) > > const cardCvvInputId = 'checkout-card-cvv-input' > const cardCvvInputEl = document.createElement('div') > cardCvvInputEl.setAttribute('id', cardCvvInputId) > > const cardHolderInputId = 'checkout-card-holder-input' > const cardHolderInputEl = document.createElement('input') > cardHolderInputEl.setAttribute('id', cardHolderInputId) > cardHolderInputEl.setAttribute('placeholder', 'Cardholder Name') > > const submitButton = document.createElement('input') > const buttonId = 'submit-button' > submitButton.setAttribute('type', 'button') > submitButton.setAttribute('id', buttonId) > submitButton.value = 'Submit' > > // Add them to your container > container.append(cardNumberInputEl, cardExpiryInputEl, cardCvvInputEl, cardHolderInputEl, submitButton) > async function configureCardForm() { > const baseStyles = { > height: 'auto', > border: '1px solid rgb(0 0 0 / 10%)', > borderRadius: '2px', > padding: '12px', > boxShadow: '0 4px 8px 0 rgba(0,0,0,0.2)', > } > > // Create the payment method manager > const cardManager = await headless.createPaymentMethodManager('PAYMENT_CARD') > > // Create the hosted inputs > const { cardNumberInput, expiryInput, cvvInput } = cardManager.createHostedInputs() > > await Promise.all([ > cardNumberInput.render(cardNumberInputId, { > placeholder: '1234 1234 1234 1234', > ariaLabel: 'Card number', > style: baseStyles, > }), > expiryInput.render(cardExpiryInputId, { > placeholder: 'MM/YY', > ariaLabel: 'Expiry date', > style: baseStyles, > }), > cvvInput.render(cardCvvInputId, { > placeholder: '123', > ariaLabel: 'CVV', > style: baseStyles, > }), > ]) > > // Set the cardholder name if it changes > document.getElementById(cardHolderInputId).addEventListener('change', e => { > cardManager.setCardholderName(e.target.value) > }) > > // Configure event listeners for supported events > cardNumberInput.addEventListener('change', (...args) => { > console.log('cardNumberInput changed', ...args) > }) > > cardNumberInput.focus() > > submitButton.addEventListener('click', async () => { > // Validate your card input data > const { valid } = await cardManager.validate() > if (valid) { > // Submit the card input data to Primer for tokenization > await cardManager.submit() > } > }) > } > ``` > > > [!NOTE] > > > > See more options and events in the [SDK API Reference](https://www.npmjs.com/package/@primer-io/checkout-web#user-content--headless-options) > > ### Step 4.b: Handle payment methods with native buttons > > > [!NOTE] > > > > This applies to PayPal, Apple Pay and Google Pay. > > Some payment methods require Primer to manage the payment method’s button and implementation, and only require you to display the button to your customer. > > Follow this approach when `PAYPAL`, `APPLE_PAY` or `GOOGLE_PAY` is available as a payment method and provided via `onAvailablePaymentMethodsLoad`. > > #### Render the button > > Get started by creating the payment method manager: > > ```typescript Typescript theme={"dark"} > const paymentMethodManager = await headless.createPaymentMethodManager('PAYPAL') // or APPLE_PAY / GOOGLE_PAY > ``` > > Then, create an instance of a payment method button and render it: > > ```typescript Typescript theme={"dark"} > // Create the button container > const payPalButton = document.createElement('div') > const payPalButtonId = 'paypal-button' > payPalButton.setAttribute('type', 'button') > payPalButton.setAttribute('id', payPalButtonId) > > // Create and render the button > const button = paymentMethodManager.createButton() > button.render(payPalButtonId, { > style: { > buttonColor: 'silver', > }, > }) > ``` > > > [!NOTE] > > > > See additional style options in the [SDK API Reference](https://www.npmjs.com/package/@primer-io/checkout-web#user-content-style-options). > > #### Handle button clicks (optional) > > When the payment method button is clicked, Headless Universal Checkout automatically handles the rendering of the payment method screen and the payment. Based on the result of the payment, you should handle different callbacks. > > * If `onCheckoutComplete` is called, show a success message and hide the button. > * If `onCheckoutFail` is called, show a failure message and allow the customer to try again. > > You can also listen to the click event for logging or analytics purposes: > > ```typescript Typescript theme={"dark"} > button.addEventListener('click', () => { > // React to click > // E.g. send off analytics > }) > ``` > > #### Other button methods > > The button object also supports other methods: > > ```typescript Typescript theme={"dark"} > // Hide the button > button.clean() > > // Set the button to disabled > button.setDisabled(true | false) > > // Focus the button (not supported for PayPal) > button.focus() > > // Unfocus the button (not supported for PayPal) > button.blur() > ``` > > #### Integration example snippet > > Below is an example code snippet of how it all fits together. > > ```typescript Typescript theme={"dark"} > // Create your button container > const payPalButton = document.createElement('div') > const payPalButtonId = 'paypal-button' > payPalButton.setAttribute('type', 'button') > payPalButton.setAttribute('id', payPalButtonId) > > function configurePayPalButton() { > // Create the payment method manager > const button = paymentMethodManager.createButton() > > // Render the button > button.render(paypalButtonId, { > style: { > buttonColor: 'silver', > }, > }) > } > ``` > > ### Step 4.c: Handle payment methods with redirect > > Some payment methods require redirecting to another web page in order to capture payment details. > > Headless checkout automatically renders that web page in a popup window in order to maintain the current context. > > Get started by creating a payment method manager: > > ```typescript Typescript theme={"dark"} > const manager = await headless.createPaymentMethodManager(paymentMethod.type) > ``` > > When the user has selected the payment method, call the `start` function. This function automatically: > > * opens a popup to present a loading indicator, then the payment method web page > * shows an overlay on top of your page that prompts the user to focus on the popup > > ```typescript Typescript theme={"dark"} > myButton.addEventListener('click', () => { > manager.start() > }) > ``` > > > [!WARNING] > > > > **`Make sure start is called synchronously after a click`** > > > > `start` opens a popup. However, most browsers have strict popup-blocking rules to protect the user. One such rule is to only allow popups that result from a direct user action. > > > > Therefore, to ensure that the popup is properly rendered, make sure to call this function immediately after a user click. > > > [!NOTE] > > > > **If the browser cannot open popup windows, the current window will be redirected instead.** > > > > To ensure maximum compatibility, read the guide on [how to handle redirects](/docs/sdk/web/v2.x.x/handle-redirects-and-deeplinks). > > ### Step 4.d: Handle Klarna > > The Klarna payment method requires selecting a payment category before redirecting to capture payment details and finalize the payment. > > You can create the interface for selecting a payment category before the redirect. Using an api function exposed by the payment method manager you can `start` the checkout, after the payment category has been selected and confirmed, and it will automatically render the payment web page in a popup window. > > Get started by creating a payment method manager. You need to provide a callback function, `onPaymentMethodCategoriesChange`, in the options parameter of the `createPaymentMethodManager` function: > > ```typescript Typescript theme={"dark"} > const manager = await headless.createPaymentMethodManager(paymentMethod.type, { > onPaymentMethodCategoriesChange, > }) > ``` > > Use the data sent through the `onPaymentMethodCategoriesChange` callback and use it to render a custom user interface for the user to be able to select payment categories. More details about the callback can be found [here](/docs/sdk/web/v2.x.x/primer-headless-checkout/methods/createPaymentMethodManager#klarna.parameters.options-properties.onPaymentMethodCategoriesChange) > > ```typescript Typescript theme={"dark"} > function onPaymentMethodCategoriesChange(paymentMethodCategories) { > // Use the paymentMethodCategories sent through the onPaymentMethodCategoriesChange function and render a custom user interface to the user > // This example assumes that you implement displayCategory that will render a custom user interface that will display the DOM structure for payment categories for Klarna > for (let paymentMethodCategory in paymentMethodCategories) { > displayCategory(paymentMethodCategory, handlePaymentCategoryClick) > } > } > ``` > > Klarna will need to render more details about the payment method inside a container. You need to provide a `containerId`, that belongs to a container in the DOM, which will later be used to render payment details about the selected payment method category. When a payment method category has been selected call the `renderCategory` function from the payment method manager. The `renderCategory` function uses the id of the selected payment method category, a `containerId` and an `onHeightChange` callback in order to render more details about the category in the selected container. > > The `onHeightChange` callback will return a new height based on the selected payment method category. Use the new height to change the height of the container in which Klarna will render the payment category details. More details about the callback can be found [here](/docs/sdk/web/v2.x.x/primer-headless-checkout/methods/createPaymentMethodManager#klarna.returns.PromiselessIKlarnaPaymentMethodManager-or-nullgreater-iklarnapaymentmethodmanager.renderCategory) > > ```typescript Typescript theme={"dark"} > // This example assumes that you implement the handleHeightChange function that will update > // the height of the container in which Klarna will display the payment category details > function handlePaymentCategoryClick(paymentMethodCategoryId) { > manager.renderCategory({ > paymentMethodCategoryId, > containerId, > onHeightChange: newHeight => { > handleHeightChange(paymentMethodCategoryId, newHeight) > }, > }) > } > ``` > > When the user has selected a payment category and has confirmed the start of the payment, call the `start` function. This function automatically: > > * opens a popup to present a loading indicator, then the payment method web page > * shows an overlay on top of your page that prompts the user to focus on the popup > > ```typescript Typescript theme={"dark"} > function handleCategorySelected(selectedCategory) { > manager.start({ > paymentMethodCategoryId: selectedCategory.id, > }) > } > ``` > > ### Step 4.e: Handle Stripe ACH > > The Stripe ACH payment method requires filling in a form with the customer's first name, last name, and email, and then going through the Stripe interface to collect the bank account details. Once the bank details are collected, the mandate should be displayed together with a button so the customer can click to confirm it. > > Optionally, if it's an existing customer, the existing customer details can be used to pre-populate the input fields. > > You can grab the details from the [`onClientSessionUpdate callback`](/docs/sdk/web/v2.x.x/primer/methods/createHeadless#parameters.options-client-session-lifecycle-callbacks.onClientSessionUpdate) and store them on a variable, example: > > ```typescript Typescript theme={"dark"} > let initialCustomerDetails = { firstName: '', lastName: '', emailAddress: '' }; > > await Primer.createHeadless(clientToken, { > onClientSessionUpdate(clientSession) { > initialCustomerDetails.firstName = clientSession.customer?.firstName ?? ''; > initialCustomerDetails.lastName = clientSession.customer?.lastName ?? ''; > initialCustomerDetails.emailAddress = clientSession.customer?.emailAddress ?? ''; > } > }) > ``` > > > [!WARNING] > > > > **`The customer client session property can be undefined.`** > > The `onClientSessionUpdate` is always called once before the `onAvailablePaymentMethodsLoad`, so the payment method manager can be created as usual. > > When creating the ACH payment method manager, the `stripePublishableKey` needs to be provided, and optionally, the `onCollectBankAccountDetailsComplete` callback. > > ```typescript Typescript theme={"dark"} > const manager = await headless.createPaymentMethodManager(paymentMethod.type, { > stripePublishableKey: 'pk_...', > onCollectBankAccountDetailsComplete, > }) > > // Display your own form with the first name, last name and email input fields > ``` > > After creating the manager and displaying the form, the data can be submitted. > > In case something is wrong, a validation result will be returned, and if there's no validation error, the `collectBankAccountDetails` method can be called to start the Stripe flow. > > ```typescript Typescript theme={"dark"} > const validationError = await manager.start({ firstName, lastName, emailAddress }) > > if (validationError) { > // Handle the validation errors updating the form accordingly > } else { > await manager.collectBankAccountDetails() > > // Display the mandate text and the Confirm button > } > ``` > > Alternatively, instead of awaiting for the `collectBankAccountDetails` promise to be resolved, the `onCollectBankAccountDetailsComplete` callback can be set up to display the mandate screen. > > ```typescript Typescript theme={"dark"} > function onCollectBankAccountDetailsComplete() { > // Display the mandate text and the Confirm button > } > ``` > > Once the customer clicks the `confirm` button, the `confirmMandate` method can be called. > > ```typescript Typescript theme={"dark"} > await manager.confirmMandate() > > // Display a success screen > ``` > [tab] iOS > > > [!NOTE] > > > > This documentation is only relevant for **v2.17.0** and upward. > > > > The **migration guide** to update from v2.16.1 is available [here](/docs/changelogs/migration-guides/). > > > > The documentation for versions v2.5.0 up to v2.16.1 is available [here](#i-os). > > > [!NOTE] > > > > Backend API V2.4 enhances reliability and minimizes synchronization issues with external processors by significantly extending payment timeouts. This longer timeout accommodates external processor limits and internal operations, ensuring more reliable transaction handling. These improvements are fully supported starting with Primer iOS SDK 2.34.0, so upgrading your app to use the newest SDK version is highly recommended when creating client sessions with API V2.4. > > ## Install the SDK > > ### With CocoaPods > > Add the following in your `Podfile`: > > ```ruby RUBY theme={"dark"} > use_frameworks! > > target 'MyApp' do > > # 👇 Add this line > pod 'PrimerSDK' > > # ... > > end > ``` > > Then run `pod install` to install `PrimerSDK` on your workspace. > > > [!NOTE] > > > > In case you encounter an error that the bundle needs signing on Xcode 14, add the following post-install script in your podfile. > > > > ```ruby theme={"dark"} > > post_install do |installer| > > installer.pods_project.targets.each do |target| > > if target.respond_to?(:product_type) and target.product_type == "com.apple.product-type.bundle" > > target.build_configurations.each do |config| > > config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' > > end > > end > > end > > end > > ``` > > ### With Swift Package Manager > > The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into Xcode. In order to add PrimerSDK with Swift Package Manager: > > 1. Select your project, and then navigate to `Package Dependencies` > > 2. Click on the **+** button at the bottom-left of the `Packages` section > > 3. Paste [https://github.com/primer-io/primer-sdk-ios.git](https://github.com/primer-io/primer-sdk-ios.git) into the **Search Bar,** or search for `primer-sdk-ios` in the **Search Bar**. > > 4. Press **Add Package** > > 5. Let Xcode download the package and set everything up > > > [!NOTE] > > > > For more details about SDK versions, please see our [changelog](/docs/changelogs/ios-sdk). > > ## Step 1: Prepare Headless Universal Checkout > > First, import the `PrimerSDK`. Then call `PrimerHeadlessUniversalCheckout.current.start` to start the checkout session with your client token and a delegate to receive important events. > > The completion handler will return the available payment methods for the current session. We will use them later to present a list of payment methods. > > Each available payment method contains the following: > > * `paymentMethodType` \ > a unique string identifier for the payment method (e.g. `ADYEN_IDEAL`) > * `paymentMethodName` \ > a user friendly English localized string identifier for the payment method (e.g. `Apple Pay`) > * `supportedPrimerSessionIntents` \ > an array of `PrimerSessionIntent` which defines what intents can be used with this payment method (i.e. `.checkout` or `.vault`). > * `paymentMethodManagerCategories` \ > an array which defines the payment method managers that can be used with this payment method (i.e. `.nativeUI` or `.rawData`). > * \[Optional] `requiredInputDataClass` \ > the class type that should be used with the raw data manager. > > Implement the `primerHeadlessUniversalCheckoutDidCompleteCheckoutWithData(_:)` which will notify you when the checkout is complete with a payment. > > ```swift SWIFT theme={"dark"} > import UIKit > // 👇 Import the SDK > import PrimerSDK > > class ViewController: UIViewController { > > // ... > > var availablePaymentMethods: [PrimerHeadlessUniversalCheckout.PaymentMethod]? > > override func viewDidLoad() { > super.viewDidLoad() > > // ... > > // 👇 Start Headless Universal Checkout with your session's client token > PrimerHeadlessUniversalCheckout.current.start(withClientToken: clientToken, delegate: self) { availablePaymentMethods, err in > if let err = err { > // Handle error > } else if let availablePaymentMethods = availablePaymentMethods { > // Payment methods that are available for this session > self.availablePaymentMethods = availablePaymentMethods > } > } > } > } > > extension ViewController: PrimerHeadlessUniversalCheckoutDelegate { > > // 👇 [Required] This function will return the checkout data once the payment is finished > func primerHeadlessUniversalCheckoutDidCompleteCheckoutWithData(_ data: PrimerCheckoutData) { > // ... > } > } > ``` > > > [!WARNING] > > > > **Only render payment methods from `availablePaymentMethods`** > > > > The `availablePaymentMethods` returned by the SDK is the **only source of truth** for which payment methods are available for this session. Do not hardcode or assume payment method availability. > > > > Payment methods may be unavailable for various reasons: > > > > * **Apple Pay**: User hasn't set up Apple Pay or has no cards in their Wallet > > * **Device limitations**: Payment method not supported on the current device > > * **Configuration**: Payment method not enabled for this client session > > * **Region restrictions**: Payment method not available in user's region > > > > Attempting to present a payment method that is not in `availablePaymentMethods` will result in an `unable-to-present-payment-method` error. > > ## Step 2: Render available payment methods UI > > You should now have the available payment methods for the client session. > > You can render your own UI for each payment method, or take advantage of the `PrimerHeadlessUniversalCheckout.AssetsManager` helper to get access to payment methods' assets. > > **Always check availability before rendering a payment button:** > > ```swift SWIFT theme={"dark"} > // ✅ Correct: Only show payment methods that are available > func renderPaymentMethods() { > guard let availablePaymentMethods = self.availablePaymentMethods else { return } > > // Check if Apple Pay is available before showing the button > let isApplePayAvailable = availablePaymentMethods.contains { $0.paymentMethodType == "APPLE_PAY" } > applePayButton.isHidden = !isApplePayAvailable > > // Render other payment methods similarly > for paymentMethod in availablePaymentMethods { > // Build UI only for available payment methods > } > } > ``` > > ```swift SWIFT theme={"dark"} > do { > let paymentMethodAsset = try PrimerHeadlessUniversalCheckout.AssetsManager.getPaymentMethodAsset(for: paymentMethod.paymentMethodType) > } catch { > // Handle error > } > ``` > > The payment method asset contains the following: > > * `paymentMethodType` \ > a unique string identifier for the payment method > * `paymentMethodName`\ > a user friendly English localized string identifier for the payment method (e.g. `Apple Pay`) > * `paymentMethodLogo`\ > an instance of the `PrimerPaymentMethodLogo` > * `paymentMethodBackgroundColor` \ > an instance of the `PrimerPaymentMethodBackgroundColor` > > The `PrimerPaymentMethodLogo` holds `UIImage` objects for different scenarios > > * \[Optional] `colored` \ > a `UIImage` to be used anywhere > * \[Optional] `dark` \ > a `UIImage` to be used in dark mode > * \[Optional] `light` \ > a `UIImage` to be used in light mode > > The `PrimerPaymentMethodBackgroundColor` holds `UIColor` objects for different scenarios > > * \[Optional] `colored` \ > a `UIColor` to be used anywhere > > * \[Optional] `dark` \ > a `UIColor` to be used in dark mode > > * \[Optional] `light` \ > a `UIColor` to be used in light mode > > > [!TIP] > > > > `colored`, `dark` and `light` variables are all optional, but it is guaranteed that the objects will contain at least one of them. > > With the above images and colors you can build your own payment methods UI 💪 > > ## Step 3: Implement a payment method manager > > Now that your UI presents the available payment methods, let's use the payment method managers to allow users to go through the payment method flow. > > A payment method manager is a class abstracting the state and UI of a given payment method. Currently, 3 payment methods managers are supported, each of them responsible for a different payment method category. > > * `PrimerHeadlessUniversalCheckout.NativeUIManager` \ > The native UI manager is responsible for payment methods that need to present their own UI (e.g. Apple Pay). > > * `PrimerHeadlessUniversalCheckout.RawDataManager` \ > The raw data manager is responsible for payment methods that need to receive data from the user (e.g. card form). > > > [!TIP] > > > > Bear in mind that a payment method could be implemented by more than one payment method manager. Check which managers are supported for each payment method in the `paymentMethodManagerCategories` of the payment method objects received in [Step 1](/docs/checkout/headless#step-1%3A-prepare-headless-universal-checkout). > > > [!NOTE] > > > > A manager can only be used after Headless Checkout has been initialized. We consider Headless Checkout to be initialized after the `primerHeadlessUniversalCheckoutDidLoadAvailablePaymentMethods` is triggered and payment methods for the provided `clientToken` are returned. > > > > If that’s not the case Headless Checkout throws a `uninitialized-sdk-session` error. > > > > If a payment method manager gets initialized with an unsupported payment method type (i.e. the payment method's object doesn't include the manager's category), Headless Checkout throws an `unsupported-payment-method-type` error. > > ### Native UI manager > > This manager can be used for the payment methods that contain `.nativeUI` in the `paymentMethodManagerCategories` array. > > The native UI manager is typically used for the payment methods that need to present their own UI, such as Apple Pay. > > ```swift SWIFT theme={"dark"} > import UIKit > import PrimerSDK > > class ViewController: UIViewController { > > // ... > > @IBAction func paymentMethodButtonTapped(_ sender: UIButton) { > do { > // 👇 Create the payment method manager > let nativeUIPaymentMethodManager = try PrimerHeadlessUniversalCheckout.NativeUIManager(paymentMethodType: paymentMethod.paymentMethodType) > > // 👇 Show the payment method > try nativeUIPaymentMethodManager.showPaymentMethod(intent: .checkout) > > } catch { > // Handle error > } > } > } > ``` > > > [!NOTE] > > > > Make sure that the intent passed in the `showPaymentMethod` function (`.checkout` for making a payment, `.vault` for vaulting the payment method) is supported by the payment method. Check the `supportedPrimerSessionIntents` array of the payment method. > > That's it! The SDK will present the native UI to the user, and then attempt to create a payment. > > The payment's data will be returned on `primerHeadlessUniversalCheckoutDidCompleteCheckoutWithData` configured in [Step 1](/docs/checkout/headless#step-1%3A-prepare-headless-universal-checkout). > > ### Raw data manager > > This manager can be used for any payment method that contains `.rawData` in the `paymentMethodManagerCategories` array. > > The raw data manager can be used for payment methods that allow you to capture customer data yourself. This gives you full control over the UI while still taking advantage of all the features that make Primer great. > > At any point, you can validate your data by calling `setRawData()` and by listening to `primerRawDataManager(_: dataIsValid: errors:)` - the SDK will return errors specific to each required input. > > Once the data is valid, send it to Headless Checkout for further processing by calling `submit()`. > > #### Configure the `PrimerHeadlessUniversalCheckout.RawDataManager` and conform to its delegate > > Assuming that the payment method contains `.rawData` in the `paymentMethodManagerCategories`, create your raw data manager, and set its delegate. > > ```swift SWIFT theme={"dark"} > > import UIKit > import PrimerSDK > > class ViewController: UIViewController { > > // ... > > var rawDataManager: PrimerHeadlessUniversalCheckout.RawDataManager! > > override func viewDidLoad() { > super.viewDidLoad() > > // ... > > do { > // 👇 Initialize the raw data manager > self.rawDataManager = try PrimerHeadlessUniversalCheckout.RawDataManager(paymentMethodType: paymentMethod.paymentMethodType, delegate: self) > > } catch { > // Handle error > } > } > } > ``` > > #### Build a form > > Build your own form to let the users enter their data. You can use the `requiredInputElementTypes` of the `PrimerHeadlessUniversalCheckout.RawDataManager` object to get informed about what input fields you have to render. > > The `requiredInputElementTypes` is an array that can contain any of the following: > > * `.cardNumber` > * `.expiryDate` > * `.cvv` > * `.cardholderName` > * `.phoneNumber` > * `.retailer` > > ```swift SWIFT theme={"dark"} > func renderForm() { > let inputElementTypes = primerRawDataManager.requiredInputElementTypes > > for inputElementType in inputElementTypes { > switch inputElementType { > case .cardNumber: > // Create a card number input element and add it to your view > break > > case .expiryDate: > // Create a expiry date input element and add it to your view > break > > case .cvv: > // Create a CVV input element and add it to your view > break > > case .cardholderName: > // Create a cardholder name input element and add it to your view > break > > case .phoneNumber: > // Create a phone number input element and add it to your view > break > > case .retailer: > // Create a retailer input element and add it to your view > break > } > } > } > } > ``` > > #### Build and validate your raw data > > Use the class type that has been provided in the `requiredInputDataClass` of the payment method to build the captured data, and pass it to the manager. Here is an example for card payments: > > ```swift SWIFT theme={"dark"} > import UIKit > import PrimerSDK > > class ViewController: UIViewController { > > // ... > > func dataDidChange() { > // 👇 Create your raw data > let rawCardData = PrimerCardData( > cardNumber: cardnumberTextField.text, > expiryDate: expiryDateTextField.text, // 👈 ex. 03/2030 > cvv: cvvTextField.text, > cardholderName: cardholderNameTextField.text, > ) > > // 👇 Set your raw data on the manager > self.rawDataManager.rawData = rawCardData > } > } > ``` > > When you set the data on the raw data manager, the manager validates it and notifies you via the delegate functions. You can then change the state of your submit button based on the validation changes. > > ```swift SWIFT theme={"dark"} > extension ViewController: PrimerHeadlessUniversalCheckoutRawDataManagerDelegate { > > // 👇 Implement the validation function to receive updates on the raw data validation changes > func primerRawDataManager(_ rawDataManager: PrimerHeadlessUniversalCheckout.RawDataManager, dataIsValid isValid: Bool, errors: [Error]?) { > // Enable your submit button when `isValid == true` > } > } > ``` > > > [!NOTE] > > > > The delegate also provides a function that will notify you of metadata updates, e.g. that the card type was detected. > > #### Submit the form's data > > Once the data has been validated, call the manager's `submit()` function. > > ```swift SWIFT theme={"dark"} > import UIKit > import PrimerSDK > > class ViewController: UIViewController { > > // ... > > @IBAction func payButtonTapped(_ sender: UIButton) { > // 👇 Submit the data that have been set in prior steps > self.rawDataManager.submit() > } > } > ``` > > When the function `submit()` is called, the SDK will attempt to create a payment. The payment's data will be returned on `primerHeadlessUniversalCheckoutDidCompleteCheckoutWithData` configured in [Step 1](/docs/checkout/headless#step-1%3A-prepare-headless-universal-checkout). > > ## Step 4: Handle errors > > Some functions can throw and they will fail immediately. All other errors will end up in the SDK’s optional delegate function `func primerHeadlessUniversalCheckoutDidFail(withError:checkoutData:)`, where you can handle them accordingly. > > ```swift SWIFT theme={"dark"} > extension ViewController: PrimerHeadlessUniversalCheckoutDelegate { > > func primerHeadlessUniversalCheckoutDidFail(withError err: Error, checkoutData: PrimerCheckoutData?) { > // Handle the error > } > } > ``` > > ## Advanced Configuration > > For more customization on your needs, you can listen to all events posted by Headless Universal Checkout and react to them. Visit the [API reference](https://www.notion.so/primerio/Headless-API-Reference-e162338560a7477ebf0dc71bf10558dc) for a full list of the delegate functions. > > ## Prepare 3DS > > * In order to make the SDK lightweight, 3DS requires the addition of the Primer 3DS library. Check out our [guide](/docs/payment-services/3d-secure/get-started#ios) on how to add the Primer 3DS library to your iOS app. > * When the user pays by card, the Workflow will decide whether or not a 3DS challenge is required. If so, Headless Universal Checkout will automatically render the 3DS challenge. > * To improve 3DS success rates, it is recommended to pass the following elements in the Client Session: > > | Field | Description | > | :- | :- | > | [customer](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-customer) ↳ [emailAddress](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-customer-email-address) | The customer's email address | > | [customer](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-customer) ↳ [billingAddress](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-customer-billing-address) | The customer's billing address | > > Learn more about [how to configure 3DS](/docs/payment-services/3d-secure/overview)! > > ## Did It Work? > > If everything went well, you should be able to see the payment you just created on your [Dashboard](https://dashboard.primer.io) under the Payments menu. > > ![](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/headless/payment-list.png) > > Payment list > [tab] Android > > > [!NOTE] > > > > This documentation is only relevant for versions **v2.17.0** and upward. > > > > The **migration guide** to update from v2.16.1 is available [here](/docs/changelogs/migration-guides/). > > > > The documentation for versions v2.5.0 up to v2.16.1 is available [here](#android). > > > [!NOTE] > > > > Backend API V2.4 enhances reliability and minimizes synchronization issues with external processors by significantly extending payment timeouts. This longer timeout accommodates external processor limits and internal operations, ensuring more reliable transaction handling. These improvements are fully supported starting with Primer Android SDK 2.35.0, so upgrading your app to use the newest SDK version is highly recommended when creating client sessions with API V2.4. > > ## Install the SDK > > Add the Primer BOM and the SDK to your app module's `build.gradle.kts` or `build.gradle` file, replacing `` with the latest version from the [Android SDK changelog](/docs/changelogs/android-sdk). The BOM keeps the SDK and any Primer payment method libraries on the same version: > > ```kotlin Kotlin theme={"dark"} > repositories { > mavenCentral() > } > > dependencies { > implementation(platform("io.primer:bom:")) > implementation("io.primer:android") > } > ``` > > ```groovy Groovy theme={"dark"} > repositories { > mavenCentral() > } > > dependencies { > implementation platform('io.primer:bom:') > implementation 'io.primer:android' > } > ``` > > > [!NOTE] > > > > Some payment methods and features, such as Klarna and 3D Secure, need a separate Primer library. The integration guide for each one shows the library to add, and [Version alignment](/docs/sdk/android/v2.x.x/installation#version-alignment) explains how its version is set. > > It is highly recommended adding the following settings to your `app/build.gradle` file: > > ```kotlin Kotlin theme={"dark"} > android { > kotlinOptions { > freeCompilerArgs += '-Xjvm-default=all' > } > } > ``` > > ## Step 1: Prepare the Headless Universal Checkout Listener > > Prepare the [PrimerHeadlessUniversalCheckoutListener](/docs/sdk/android/v2.x.x/primer-headless-checkout/listeners/PrimerHeadlessUniversalCheckoutListener) that will handle callbacks that happen during the lifecycle of the payment methods and the payment. > > Import the [PrimerHeadlessUniversalCheckout](/docs/sdk/android/v2.x.x/primer-headless-checkout/) SDK and set its listener as shown in the example below. > > ```kotlin Kotlin theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > > private val listener = object : PrimerHeadlessUniversalCheckoutListener { > > // 👇 [Required] This function will return the list of payment methods > override fun onAvailablePaymentMethodsLoaded(paymentMethods: List) { > // Use it to enable users to select a payment method > } > > // 👇 [Required] This function is called when the checkout has been completed > override fun onCheckoutCompleted(checkoutData: PrimerCheckoutData) { > // Show an order confirmation screen... > // checkoutData contains the payment that has been created > } > > // 👇 [Required] This function is called if something goes wrong > override fun onFailed(error: PrimerError, checkoutData: PrimerCheckoutData?) { > // your custom method to show an error view > } > } > } > ``` > > `onAvailablePaymentMethodsLoaded` is invoked when Headless Universal Checkout is started with your provided client token. It returns a list of payment methods to render. > > Each returned payment method contains the following: > > * `paymentMethodType` \ > a unique string identifier for the payment method (e.g. `ADYEN_IDEAL`) > * `paymentMethodManagerCategories` \ > a list which defines the payment method managers that can be used with this payment method (i.e. `NATIVE_UI` or `RAW_DATA`). > * `supportedPrimerSessionIntents` \ > a list of `PrimerSessionIntent` which defines what intents can be used with this payment method (i.e. `CHECKOUT` or `VAULT`). > * \[Optional] `requiredInputDataClass` \ > the class type that should be used with the raw data manager. > > ## Step 2: Start Headless Universal Checkout > > Once you have a client token, you can initialize Primer’s Headless Checkout by calling [PrimerHeadlessUniversalCheckout.current.start(...)](/docs/sdk/android/v2.x.x/primer-headless-checkout/) > > ```kotlin Kotlin theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > > // other code goes here > private val listener = object : PrimerHeadlessUniversalCheckoutListener { > // ... > } > > private fun setupObservers() { > viewModel.clientToken.observe(this) { clientToken -> > // Start the headless checkout session upon reception of the client token > startHeadlessUniversalCheckout(clientToken) > } > } > > private fun startHeadlessUniversalCheckout(clientToken: String) { > // 👇 Start Headless Universal Checkout with your session's client token > PrimerHeadlessUniversalCheckout.current.start( > this, > clientToken, > PrimerSettings(), > listener, > ) > } > } > ``` > > Once Primer’s Headless Universal Checkout is configured, its listener functions will notify you about Headless Universal Checkout events. > > > [!NOTE] > > > > On the `PrimerHeadlessUniversalCheckout.current.start` you can optionally pass custom settings and/or add the `PrimerHeadlessUniversalCheckoutUiListener` to listen to UI events. > > > > Additionally, you can set the listener by calling `PrimerHeadlessUniversalCheckout.current.setListener(listener)` > > > [!NOTE] > > > > Check the SDK reference [here](/docs/sdk/android/v2.x.x/common-objects/) to customize your SDK settings. > > ## Step 3: Render available payment methods UI > > When the checkout is done initializing, the `onAvailablePaymentMethodsLoaded` method will be invoked. > > Use this event to show the list of payment methods to the user. > > ```kotlin Kotlin theme={"dark"} > private val listener = object : PrimerHeadlessUniversalCheckoutListener { > > override fun onAvailablePaymentMethodsLoaded( > paymentMethods: List > ) { > paymentMethods.forEach { setupPaymentMethod(it.paymentMethodType) } > } > } > > // your custom method to render list of payment method buttons UI. > private fun setupPaymentMethod(paymentMethodType: String) { > // implement payment method UI > } > ``` > > You can render your own UI for each payment method, or take advantage of the `PrimerHeadlessUniversalCheckout.AssetsManager` helper to get access to payment methods' resources. > > ```kotlin Kotlin theme={"dark"} > > private val listener = object : PrimerHeadlessUniversalCheckoutListener { > > override fun onAvailablePaymentMethodsLoaded( > paymentMethods: List > ) { > paymentMethods.forEach { setupPaymentMethod(it.paymentMethodType) } > } > } > > // your custom method to render the list of payment method buttons > private fun setupPaymentMethod(paymentMethodType: String) { > val paymentMethodResource = try { > // 👇 Retrieve the assets of a specific payment method > PrimerHeadlessUniversalCheckoutAssetsManager.getPaymentMethodResource( > this, > paymentMethodType > ) > } catch (e: SdkUninitializedException) { > null > } > > when (paymentMethodResource) { > is PrimerPaymentMethodAsset -> { > // 👇 Example of setting background color for your button > paymentMethodResource.paymentMethodBackgroundColor.colored?.let { color -> > setBackgroundColor(color) > } > > // 👇 Example of setting drawable for your button > paymentMethodResource.paymentMethodLogo.colored?.let { drawable -> > setImageDrawable(drawable) > } > } > > is PrimerPaymentMethodNativeView -> { > val paymentMethodView = paymentMethodResource.createView( > requireContext() > ) > } > > null -> { > // this should never happen in case SDK is initialized > } > } > } > ``` > > ### PrimerPaymentMethodAsset > > The payment method asset contains the following: > > * `paymentMethodType` \ > a unique string identifier for the payment method > * `paymentMethodName` \ > a user friendly English localized string identifier for the payment method (e.g. `Google Pay`) > * `paymentMethodLogo` \ > an instance of the `PrimerPaymentMethodLogo` > * `paymentMethodBackgroundColor` \ > an instance of the `PrimerPaymentMethodBackgroundColor` > > The `PrimerPaymentMethodLogo` holds `Drawable` objects for different scenarios: > > * \[Optional] `colored` \ > a `Drawable` to be used anywhere > * \[Optional] `dark` \ > a `Drawable` to be used on dark mode > * \[Optional] `light` \ > a `Drawable` to be used on light mode > > The `PrimerPaymentMethodBackgroundColor` holds `@ColorInt` values for different scenarios: > > * \[Optional] `colored` \ > a `@ColorInt` to be used anywhere > > * \[Optional] `dark` \ > a `@ColorInt` to be used on dark mode > > * \[Optional] `light` \ > a `@ColorInt` to be used on light mode > > > [!NOTE] > > > > `colored`, `dark` and `light` variables are all optional, but it is guaranteed that the objects will contain at least on of them. > > ### PrimerPaymentMethodNativeView > > Using the provided payment method views is required for certain payment methods, such as Google Pay. The Primer SDK ensures these views are seamlessly integrated and configured based on the [PrimerPaymentMethodOptions](/docs/sdk/android/v2.x.x/common-objects/) and your client session details, where applicable. > > With the above images and colors you can build your own payment methods UI 💪 > > ## Step 4: Implement a payment method manager > > Now that your UI presents the available payment methods, use the payment method managers to allow users to go through the payment method flow. > > A payment method manager is a class abstracting the state and UI of a given payment method. Currently there are 3 payment methods managers responsible for a different payment method category: > > * `PrimerHeadlessUniversalCheckoutRawDataManager` \ > The raw data manager is responsible for payment methods that need to receive data from the user (e.g. card form). > > * `PrimerHeadlessUniversalCheckoutNativeUiManager` \ > The native UI manager is responsible for payment methods that need to present their own UI (e.g. Google Pay). > > > [!TIP] > > > > Bear in mind that a payment method might be able to be implemented by more than one payment method manager. You can check which managers are supported for each payment method in the `paymentMethodManagerCategories` of the payment method objects received in [Step 1](#step-1-prepare-the-headless-universal-checkout-listener). > > > [!NOTE] > > > > A manager can only be used after Headless Checkout has been initialized. We consider Headless Checkout to be initialized after the `onAvailablePaymentMethodsLoaded` is triggered and payment methods for the provided `clientToken` are returned. > > > > If that’s not the case SDK will throw `SdkUninitializedException`. > > > > If a payment method manager gets initialized with an unsupported payment method type (i.e. the payment method's object doesn't include the manager's category), the SDK will throw an `UnsupportedPaymentMethodException` error. > > ### Native UI manager > > This manager can be used for any payment method that contains `NATIVE_UI` in the `paymentMethodManagerCategories` array. > > The native UI manager can be used for any payment method that needs to present its own UI, like Google Pay. > > ```kotlin Kotlin theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > // other code goes here > private fun onPaymentMethodSelected( > paymentMethodType: String, > sessionIntent: PrimerSessionIntent > ) { > try { > // 👇 Create the payment method manager > val nativeUiManager = > PrimerHeadlessUniversalCheckoutNativeUiManager.newInstance(paymentMethodType) > > // 👇 Show the payment method > nativeUiManager.showPaymentMethod(this, sessionIntent) > } catch (e: SdkUninitializedException) { > // handle exception > } catch (e: UnsupportedPaymentIntentException) { > // handle exception > } catch (e: UnsupportedPaymentMethodException) { > // handle exception > } > } > } > ``` > > > [!NOTE] > > > > Make sure that the `sessionIntent` in the `showPaymentMethod` function is valid and contained in the `supportedPrimerSessionIntents` array. If that’s not the case SDK will throw `UnsupportedPaymentIntentException`. > > That’s it! The SDK will present the native UI to the user, and then attempt to create a payment. > > The payment’s data will be returned on `onCheckoutCompleted` configured in [Step 1](#step-1-prepare-the-headless-universal-checkout-listener). > > ### Raw Data Manager > > This manager can be used for any payment method that contains `RAW_DATA` in the `paymentMethodManagerCategories` array. > > The raw data manager can be used for payment methods that allow you to pass the data in the SDK (an example would be card data). > > With the raw manager, you can use your fully customized UI and still use all of the features that make Primer great. > > At any point, you can validate your data by calling `setRawData()` and by listening to `onValidationChanged`. Primer will return errors specific to each required input. > > **Only** when the data is valid, you can send it to Primer for further processing by calling `submit`. > > #### Configure the `PrimerHeadlessUniversalCheckoutRawDataManager` and subscribe to callbacks > > Assuming that the payment method contains `RAW_DATA` in the `paymentMethodManagerCategories`, create your raw data manager, and optionally set the `onValidationChanged` and the `onMetadataChanged` callbacks. > > ```kotlin Kotlin theme={"dark"} > class CheckoutActivity : AppCompatActivity() { > > // val submitButton = findViewById > > ``` > [accordion] Custom success screen > > Show a custom message after successful payment: > > ```html theme={"dark"} > > >
>

Thank you for your order!

>

Order confirmation sent to your email.

>
>
>
> ``` > [accordion] Custom initialization error screen > > Show a custom message when the SDK fails to initialize: > > ```html theme={"dark"} > > >
>

We could not load the checkout

>

Please try again later or contact support.

>
>
>
> ``` *** ## See also > [card] [Using slots](/docs/checkout/primer-checkout/build-your-ui/layout-customization) > > Learn how to use slots to customize layout > [card] [Layout with event handling](/docs/checkout/primer-checkout/build-your-ui/advanced-layout-customization) > > Build fully custom checkout experiences > [card] [Design tokens explorer](/docs/checkout/primer-checkout/build-your-ui/design-tokens-explorer) > > Explore CSS variables and styling # UI styling Source: https://primer.io/docs/checkout/primer-checkout/build-your-ui/styling-customization Apply colors, typography, spacing and dark mode with CSS variables on Web, `PrimerTheme` on Android and `PrimerCheckoutTheme` on iOS. Primer Checkout is fully customizable. You can customize colors, typography, spacing, borders, and component layout (down to the smallest visual detail) without touching internal component code or breaking upgrades. ## Styling methods > [tab] Web > > On the web, Primer Checkout uses **CSS variables** for theming. You can apply styling in two ways - directly in your CSS or through component attributes. > > > [tab] CSS > > > > ```css styles.css theme={"dark"} > > primer-checkout { > > --primer-color-brand: #2f98ff; > > --primer-color-focus: #2f98ff; > > --primer-radius-medium: 8px; > > --primer-typography-brand: 'Inter', sans-serif; > > } > > ``` > > > [tab] HTML > > > > ```html index.html theme={"dark"} > > > customStyles='{"primerColorBrand":"#2f98ff","primerColorFocus":"#2f98ff","primerRadiusMedium":"8px"}' > > > > > ``` > > > > When passing through a component attribute, convert kebab-case CSS variables to camelCase properties: > > > > 1. Remove the leading dashes (`--`) > > 2. Convert hyphens to camelCase by removing the hyphen and capitalizing the next letter > > > > **Examples:** > > > > * `--primer-color-brand` → `primerColorBrand` > > * `--primer-space-medium` → `primerSpaceMedium` > > * `--primer-typography-body-large-font` → `primerTypographyBodyLargeFont` > [tab] Android > > On Android, Primer Checkout uses a token-based design system through `PrimerTheme`. Pass a custom `PrimerTheme` to your checkout component: > > ```kotlin theme={"dark"} > val theme = PrimerTheme( > lightColorTokens = object : LightColorTokens() { > override val primerColorBrand: Color = Color(0xFF6C5CE7) > }, > ) > > PrimerCheckoutSheet( > checkout = checkout, > theme = theme, > ) > ``` > [tab] iOS > > On iOS, Primer Checkout uses `PrimerCheckoutTheme` for theming. Pass a custom theme to your checkout view: > > ```swift theme={"dark"} > let theme = PrimerCheckoutTheme( > colors: ColorOverrides( > primerColorBrand: .purple > ), > radius: RadiusOverrides( > primerRadiusMedium: 12 > ) > ) > > PrimerCheckout( > clientToken: clientToken, > primerTheme: theme > ) > ``` ## Using styling variables in practice > [tab] Web > > > [tab] With CSS Variables > > > > ```css theme={"dark"} > > primer-checkout { > > --primer-color-brand: #663399; > > --primer-color-focus: #663399; > > --primer-color-loader: #663399; > > --primer-color-text-primary: #333333; > > --primer-color-text-secondary: rgba(51, 51, 51, 0.62); > > --primer-typography-brand: 'Helvetica Neue', sans-serif; > > --primer-space-medium: 16px; > > --primer-radius-medium: 8px; > > } > > ``` > > > [tab] With customStyles property > > > > ```javascript theme={"dark"} > > const myCustomStyles = { > > primerColorBrand: '#663399', > > primerColorFocus: '#663399', > > primerColorLoader: '#663399', > > primerColorTextPrimary: '#333333', > > primerTypographyBrand: 'Helvetica Neue, sans-serif', > > primerSpaceMedium: '16px', > > primerRadiusMedium: '8px', > > }; > > > > const checkoutElement = document.querySelector('primer-checkout'); > > checkoutElement.setAttribute('customStyles', JSON.stringify(myCustomStyles)); > > ``` > > > > This approach is particularly useful when working with JavaScript frameworks or when you need to apply styling variables programmatically. > > > > The component will parse the JSON and automatically apply the styles as CSS Variables internally. > > You can see all the available styling variables on [the dedicated reference page](/docs/sdk/primer-checkout-web/styling-variables). > [tab] Android > > `PrimerTheme` contains five token groups: > > | Token Group | Class | What It Controls | > | - | - | - | > | Light colors | `LightColorTokens` | All colors in light mode | > | Dark colors | `DarkColorTokens` | All colors in dark mode | > | Spacing | `SpacingTokens` | Padding and margins | > | Typography | `TypographyTokens` | Font sizes, weights, line heights | > | Radius | `RadiusTokens` | Corner radius for cards, inputs, sheets | > | Border widths | `WidthTokens` | Border widths for inputs, focus rings | > | Sizes | `SizeTokens` | Icon sizes and touch targets | > > ```kotlin theme={"dark"} > val brandTheme = PrimerTheme( > lightColorTokens = object : LightColorTokens() { > override val primerColorBrand: Color = Color(0xFF6C5CE7) > override val primerColorBackgroundSecondary: Color = Color(0xFFF7F7F8) > }, > darkColorTokens = object : DarkColorTokens() { > override val primerColorBrand: Color = Color(0xFFA29BFE) > }, > spacingTokens = SpacingTokens( > small = 6.dp, > medium = 10.dp, > large = 14.dp, > ), > radiusTokens = RadiusTokens( > medium = 12.dp, > large = 20.dp, > ), > ) > > PrimerCheckoutSheet( > checkout = checkout, > theme = brandTheme, > ) > ``` > > See the [Design Tokens Reference](/docs/checkout/primer-checkout/build-your-ui/design-tokens-explorer-web) for a complete list of all available tokens. > [tab] iOS > > `PrimerCheckoutTheme` is organized into seven override categories: > > | Category | Parameter | Type | Controls | > | - | - | - | - | > | **Colors** | `colors` | `ColorOverrides` | Brand, text, backgrounds, borders, icons in light mode | > | **Dark colors** | `darkColors` | `ColorOverrides` | The same color tokens in dark mode | > | **Radius** | `radius` | `RadiusOverrides` | Corner radius for inputs, buttons, cards | > | **Spacing** | `spacing` | `SpacingOverrides` | Padding and margins | > | **Sizes** | `sizes` | `SizeOverrides` | Icon sizes and tap targets | > | **Typography** | `typography` | `TypographyOverrides` | Font family, size, weight, line height, letter spacing | > | **Border width** | `width` | `WidthOverrides` | Border widths for the default, focus, error and selected states | > > ```swift theme={"dark"} > let theme = PrimerCheckoutTheme( > colors: ColorOverrides( > primerColorBrand: .indigo, > primerColorBackgroundPrimary: Color(.systemBackground), > primerColorTextPrimary: Color(.label), > primerColorBorderOutlinedFocus: .indigo > ), > darkColors: ColorOverrides( > primerColorBrand: .indigo, > primerColorBorderOutlinedFocus: .indigo > ), > radius: RadiusOverrides( > primerRadiusMedium: 10, > primerRadiusLarge: 16 > ), > spacing: SpacingOverrides( > primerSpaceMedium: 12, > primerSpaceLarge: 16 > ), > typography: TypographyOverrides( > bodyMedium: .init(font: "Inter", size: 14) > ), > width: WidthOverrides( > primerWidthFocus: 3 > ) > ) > > PrimerCheckout( > clientToken: clientToken, > primerTheme: theme > ) > ``` > > Set `brand` in `TypographyOverrides` to one font family name that your app can load, such as a system font or a font you bundle. The default is Inter. Font weights use `Font.Weight` steps, such as `.regular`, `.medium`, `.semibold` and `.bold`. > > See the [Design Tokens Explorer](/docs/checkout/primer-checkout/build-your-ui/design-tokens-explorer-ios) to preview how tokens affect the checkout, and the [Theming reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) for the complete list of `PrimerCheckoutTheme` tokens. ## Theme support Primer Checkout supports both light and dark themes. > [tab] Web > > The default option is light. To use a dark theme, pass a `primer-dark-theme` CSS class: > > ```html theme={"dark"} > > > ``` > > You can toggle between themes using JavaScript: > > ```javascript theme={"dark"} > function toggleTheme(isDark) { > const container = document.querySelector('primer-checkout'); > container.className = isDark ? 'primer-dark-theme' : 'primer-light-theme'; > } > > toggleTheme(true); > toggleTheme(false); > ``` > [tab] Android > > `DarkColorTokens` extends `LightColorTokens` and overrides base color values. Semantic tokens automatically resolve to the correct values through inheritance: > > ``` > Light mode: primerColorBackgroundPrimary → #FFFFFF > Dark mode: primerColorBackgroundPrimary → #171619 > ``` > > By default the checkout follows the system theme. Set `appearanceMode` to `PrimerAppearanceMode.LIGHT` or `PrimerAppearanceMode.DARK` to pin it to one appearance. > > ```kotlin theme={"dark"} > val theme = PrimerTheme( > lightColorTokens = object : LightColorTokens() { > override val primerColorBrand: Color = Color(0xFFE53E3E) > override val primerColorBackgroundPrimary: Color = Color(0xFFF8F8F8) > }, > darkColorTokens = object : DarkColorTokens() { > override val primerColorBrand: Color = Color(0xFFFF6B6B) > }, > appearanceMode = PrimerAppearanceMode.SYSTEM, > ) > ``` > > `PrimerTheme` automatically maps color tokens to a Material 3 `ColorScheme`. Material components used within the checkout (like `ModalBottomSheet`) inherit your Primer color tokens without additional configuration. > [tab] iOS > > The checkout follows the system appearance, or the mode you force with `PrimerUIOptions(appearanceMode: .light)` or `.dark`. `colors` applies in light mode only and `darkColors` in dark mode only. Any color you leave out of `darkColors` uses Primer's dark default, not the value from `colors`. To keep a color in dark mode, set it in `darkColors` as well: > > ```swift theme={"dark"} > let theme = PrimerCheckoutTheme( > colors: ColorOverrides( > primerColorBrand: Color("BrandColor"), // Asset catalog color, light appearance > primerColorBackgroundPrimary: Color(.systemBackground) // Resolves to its light value > ), > darkColors: ColorOverrides( > primerColorBrand: Color("BrandColor"), // Same asset, dark appearance > primerColorBackgroundPrimary: Color(.systemBackground) // Resolves to its dark value > ) > ) > ``` > > > [!TIP] > > > > Each color resolves for the appearance being drawn. An adaptive color, such as an asset catalog color, `Color(.label)` or `Color(.systemBackground)`, gives its light value in `colors`. In `darkColors` it gives its dark value. Pass the same adaptive color in both to get both variants. `radius`, `spacing`, `sizes`, `typography` and `width` are the same in light and dark mode. ## Try it out Select a preset or adjust individual tokens to see how styling variables affect the checkout appearance. > [!NOTE] > > This preview shows a subset of styling variables. Interactive states (hover, focus) are not displayed. See [Styling Variables](/docs/sdk/primer-checkout-web/styling-variables) for a complete reference. ### Theme Builder Preview ### Payment Details Enter your card information Card Number 4242 4242 4242 4242 Expiry 12/25 CVV ••• Pay styles.css theme.json Theme.kt Theme.swift Copy to clipboard

## Try it live in StackBlitz

See styling in action with these interactive examples:

Example Description
**Theme variations** Explore light, dark and more [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/primer-io/examples/tree/main/examples/primer-checkout-themes)
**Custom form styling** See custom CSS styling applied to a reordered payment form layout [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/primer-io/examples/tree/main/examples/primer-checkout-custom-form)
# Integration best practices Source: https://primer.io/docs/checkout/primer-checkout/configuration/best-practices State management, error diagnostics, performance, security and testing patterns for Web, iOS and Android integrations. ## State management Manage checkout state carefully to avoid re-initialization and stale data. Keep configuration objects stable and observe state changes with lifecycle-aware collectors. > [tab] Web > > ### Define options outside functions > > Create options objects once and reuse them to avoid unnecessary re-initialization: > > > [!TIP] > > > > Define static options outside your function scope. The SDK uses deep comparison to detect actual changes, but stable object references reduce comparison overhead and improve performance. > > ```javascript theme={"dark"} > // ✅ GOOD: Created once > const SDK_OPTIONS = { > locale: 'en-GB', > }; > > function initCheckout() { > const checkout = document.querySelector('primer-checkout'); > checkout.options = SDK_OPTIONS; // Same reference every time > } > > // ❌ AVOID: Created every time function runs > function initCheckout() { > const checkout = document.querySelector('primer-checkout'); > checkout.options = { locale: 'en-GB' }; // New object every execution > } > ``` > > > [!NOTE] > > > > The SDK performs deep comparison to detect actual changes in the `options` object. Using stable references (the GOOD pattern above) minimizes comparison overhead and remains the recommended best practice for optimal performance. > [tab] Android > > ### Use lifecycle-aware state collection > > Always use `collectAsStateWithLifecycle()` instead of `collectAsState()` to prevent unnecessary work when the app is in the background: > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > ``` > > ### Avoid wrapping the controller in a ViewModel > > The checkout controller is already a ViewModel internally. Don't wrap it in another ViewModel unless you need to coordinate with other app state. > [tab] iOS > > ### Define settings and theme as constants > > Create `PrimerSettings` and `PrimerCheckoutTheme` outside your view `body` to avoid unnecessary re-creation on each SwiftUI render cycle: > > > [!TIP] > > > > SwiftUI re-evaluates `body` frequently. Defining configuration objects as constants ensures they are created once and reused. > > ```swift theme={"dark"} > // ✅ GOOD: Created once > private let primerSettings = PrimerSettings(paymentHandling: .auto) > private let primerTheme = PrimerCheckoutTheme( > colors: ColorOverrides(primerColorBrand: .blue) > ) > > struct CheckoutView: View { > let clientToken: String > > var body: some View { > PrimerCheckout( > clientToken: clientToken, > primerSettings: primerSettings, > primerTheme: primerTheme > ) > } > } > > // ❌ AVOID: Created every render > struct CheckoutView: View { > let clientToken: String > > var body: some View { > PrimerCheckout( > clientToken: clientToken, > primerSettings: PrimerSettings(paymentHandling: .auto), > primerTheme: PrimerCheckoutTheme(colors: ColorOverrides(primerColorBrand: .blue)) > ) > } > } > ``` > > ### Use proper @State management > > When storing checkout-related values in SwiftUI state, use `@State` for simple values and `@StateObject` for observable objects: > > ```swift theme={"dark"} > struct CheckoutView: View { > let clientToken: String > @State private var paymentCompleted = false > @State private var paymentResult: PaymentResult? > > var body: some View { > if paymentCompleted, let result = paymentResult { > ConfirmationView(result: result) > } else { > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > if case .success(let result) = state { > paymentResult = result > paymentCompleted = true > } > } > ) > } > } > } > ``` > > ### Observe the lifecycle through the session > > For composable, inline checkout, hold a `PrimerCheckoutSession` as a `@StateObject`. Observe its `@Published` properties for lifecycle and per-feature state, and receive outcomes through `onCompletion`. The session is automatically started on appear and torn down on disappear by the `.primerCheckoutSession(_:theme:onCompletion:)` modifier — you don't manage an `AsyncStream` or a manual `Task`: > > ```swift theme={"dark"} > struct CheckoutView: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject( > wrappedValue: PrimerCheckoutSession(clientToken: clientToken) > ) > } > > var body: some View { > ScrollView { > PrimerCardForm() > } > .primerCheckoutSession(session) { state in > // .failure once per failed attempt, then .success or .dismissed exactly once > handleStateChange(state) > } > } > } > ``` > > Outcomes arrive through `onCompletion`. A `.failure` after the checkout is ready is delivered once per failed attempt, such as a declined payment or a failed `refresh()`. The checkout stays usable so the shopper can retry, so don't tear it down on `.failure`. `.success` and `.dismissed` are delivered exactly once, and nothing is delivered after them. A `.failure` while the checkout is still initializing ends the session and is delivered once. The lifecycle comes from the session's `@Published` `phase` and `clientSession`. The per-feature sessions (`cardForm`, `selection`) become available once `phase` is `.ready`, and their `@Published` `state` drives your custom slots. ## Error handling Log diagnostics IDs and handle failures gracefully. Every error from the SDK includes identifiers that help Primer support diagnose issues. > [tab] Web > > ### Monitor SDK initialization > > ```javascript theme={"dark"} > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > console.log('SDK initialized'); > console.log('Applied locale:', checkout.options?.locale); > console.log('Active payment methods:', primer.getPaymentMethods?.()); > }); > ``` > > ### Debug configuration issues > > Common debugging approaches for options-related issues: > > > [!TIP] > > > > When options aren't working as expected, check these common issues first: > > **Check object reference stability:** > > ```javascript theme={"dark"} > const options = { locale: 'en-GB' }; > console.log('Options reference:', options); > > // Later in code > checkout.options = options; > console.log('Applied options:', checkout.options); > console.log('References match:', checkout.options === options); > ``` > > **Verify component properties vs SDK options:** > > ```javascript theme={"dark"} > // Component properties use setAttribute() > const checkout = document.querySelector('primer-checkout'); > > checkout.setAttribute('client-token', 'new-token'); > console.log('Token attribute:', checkout.getAttribute('client-token')); > > // SDK options use direct property assignment > checkout.options = { locale: 'en-GB' }; > console.log('Options object:', checkout.options); > ``` > [tab] Android > > ### Always handle outcomes > > The Android Components SDK always uses `AUTO` mode — there is no manual mode. Even with default screens, observe `checkout.state` for logging and analytics: > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { > analytics.trackPurchase(s.checkoutData) > } > is PrimerCheckoutState.Failure -> { > analytics.trackError(s.primerError.diagnosticsId) > } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > ``` > > ### Log diagnostics IDs > > Every `PrimerError` includes a `diagnosticsId`. Log it for troubleshooting with Primer support: > > ```kotlin theme={"dark"} > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Error: ${s.primerError.diagnosticsId}") > } > ``` > [tab] iOS > > ### Handle all completion states > > Handle every outcome in the `onCompletion` callback. `.failure` arrives once per failed attempt, including a failed initialization. While `uiOptions.isErrorScreenEnabled` is `true` (the default), the checkout stays open so the shopper can retry, so don't close the checkout on `.failure`. `.success` or `.dismissed` arrives exactly once and ends the checkout. `onCompletion` never receives `.initializing` or `.ready`. The `switch` lists them only to stay exhaustive: > > ```swift theme={"dark"} > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > switch state { > case .success(let result): > handleSuccess(result) > case let .failure(error, _): > handleFailure(error) > case .dismissed: > handleDismissal() > case .initializing, .ready: > break // not delivered to onCompletion > } > } > ) > ``` > > > [!WARNING] > > > > `.dismissed` arrives when the shopper closes the checkout from the SDK's own screens. If you present `PrimerCheckout` in your own `.sheet`, a swipe-down closes your sheet without calling `onCompletion`. Also reset your presentation state in `.sheet(isPresented:onDismiss:)`. > > ### Log diagnostics IDs > > Every error includes a `diagnosticsId`. Log it, together with `recoverySuggestion`, for troubleshooting with Primer support. `recoverySuggestion` is developer-facing English text, so show the shopper your own message: > > ```swift theme={"dark"} > case let .failure(error, _): > print("Error diagnosticsId: \(error.diagnosticsId)") > if let suggestion = error.recoverySuggestion { > print("Recovery suggestion: \(suggestion)") > } > ``` ## Performance Minimize unnecessary re-renders and keep configuration stable. Initialize the SDK as early as possible so it can prefetch configuration while the user navigates. > [tab] Web > > ### Use TypeScript interfaces for type safety > > Define TypeScript interfaces for your options objects to catch errors at compile time: > > ```typescript theme={"dark"} > interface PrimerSDKOptions { > locale: string; > paymentMethodOptions?: { > PAYMENT_CARD?: { > requireCVV?: boolean; > requireBillingAddress?: boolean; > }; > APPLE_PAY?: { > merchantName?: string; > merchantCountryCode?: string; > }; > }; > } > > const options: PrimerSDKOptions = { > locale: 'en-GB', > paymentMethodOptions: { > PAYMENT_CARD: { > requireCVV: true, > requireBillingAddress: true, > }, > }, > }; > ``` > > ### Test options configuration separately > > Create isolated tests for your options configuration: > > ```typescript theme={"dark"} > describe('SDK Options Configuration', () => { > it('should create valid options object', () => { > const options = { > locale: 'en-GB', > }; > > expect(options.locale).toBe('en-GB'); > }); > > it('should maintain stable reference', () => { > const options = { locale: 'en-GB' }; > const checkout = document.querySelector('primer-checkout'); > checkout.options = options; > > expect(checkout.options).toBe(options); // Same reference > }); > }); > ``` > [tab] Android > > ### Initialize early > > Create the checkout controller as early as possible so the SDK can fetch configuration while the user navigates to checkout: > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > // SDK starts loading immediately > } > ``` > > ### Avoid recreating the controller > > `rememberPrimerCheckoutController` survives recomposition. Don't call it conditionally or inside callbacks. > [tab] iOS > > ### Avoid creating objects in SwiftUI `body` > > Define `PrimerSettings` and `PrimerCheckoutTheme` as constants outside the view body. SwiftUI re-evaluates `body` frequently, so inline allocations waste resources: > > ```swift theme={"dark"} > // ✅ GOOD: Defined once outside body > private let primerSettings = PrimerSettings(paymentHandling: .auto) > > struct CheckoutView: View { > let clientToken: String > > var body: some View { > PrimerCheckout( > clientToken: clientToken, > primerSettings: primerSettings > ) > } > } > ``` > > ### Let the session own its lifecycle > > For composable checkout, hold the `PrimerCheckoutSession` as a `@StateObject` and attach the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. The modifier starts the session on appear and tears it down on disappear, so you never manage a manual `Task` or `AsyncStream`: > > ```swift theme={"dark"} > struct CheckoutView: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject( > wrappedValue: PrimerCheckoutSession(clientToken: clientToken) > ) > } > > var body: some View { > ScrollView { > PrimerCardForm() > } > .primerCheckoutSession(session) { state in > handleStateChange(state) > } > } > } > ``` > > ### Don't retain self in `onCompletion` > > The completion closure can outlive the view that created it. When forwarding the outcome to a long-lived object such as a view model, capture it weakly to avoid retain cycles: > > ```swift theme={"dark"} > .primerCheckoutSession(session) { [weak viewModel] state in > Task { await viewModel?.handleState(state) } > } > ``` ## Security Never expose API keys in client code. Keep configuration minimal and handle sensitive data on your server. > [tab] Web > > ### Distinguish between component properties and SDK options > > **Component Properties** are HTML attributes that configure the component container. **SDK Options** are configuration settings for the SDK itself. > > > [!WARNING] > > > > Mixing these up will cause silent failures. Component properties must use `setAttribute()`. SDK options must be assigned directly to `.options`. > > **Component Properties** (use `setAttribute()`): > > * `client-token` - API authentication > * `custom-styles` - Visual theming > * `loader-disabled` - Loader behavior > > **SDK Options** (use `options` object): > > * `locale` - UI language > * Payment method configuration > * Feature settings > * Merchant domain and API settings > > ```javascript theme={"dark"} > // ✅ CORRECT: Clear separation > const checkout = document.querySelector('primer-checkout'); > > // Component properties > checkout.setAttribute('client-token', 'your-token'); > checkout.setAttribute('loader-disabled', 'false'); > > // SDK options > checkout.options = { > locale: 'en-GB', > applePay: { buttonType: 'buy' }, > }; > > // ❌ WRONG: Mixing them up > checkout.setAttribute('locale', 'en-GB'); // Won't work - locale is an SDK option > checkout.options = { > clientToken: 'your-token', // Wrong - this is a component property > }; > ``` > > ### Keep options simple and focused > > Only configure what you need: > > ```javascript theme={"dark"} > // ✅ GOOD: Simple, focused configuration > checkout.options = { > locale: 'en-GB', > }; > > // ❌ AVOID: Over-configuration with unused options > checkout.options = { > locale: 'en-GB', > paymentMethodOptions: { > PAYMENT_CARD: { > requireCVV: true, > requireBillingAddress: false, > // ... 20 more unused options > }, > APPLE_PAY: { > // ... configured but not used > }, > }, > }; > ``` > [tab] Android > > ### Client token handling > > * Generate client tokens on your server, never hardcode them > * Client tokens are single-use and expire -- generate a fresh one for each checkout session > * Never log or persist client tokens > > ### ProGuard > > The SDK includes its own ProGuard rules. Don't add additional rules that might strip required classes. > [tab] iOS > > ### Client token handling > > * Generate client tokens on your server, never hardcode them > * Client tokens are single-use and expire -- generate a fresh one for each checkout session > * Never log or persist client tokens > > ### Keep configuration minimal > > Only configure what you need in `PrimerSettings`. The SDK ships with sensible defaults: > > ```swift theme={"dark"} > // ✅ GOOD: Only override what you need > private let primerSettings = PrimerSettings(paymentHandling: .auto) > > // ❌ AVOID: Over-configuration with defaults > private let primerSettings = PrimerSettings( > paymentHandling: .auto, > localeData: nil, > uiOptions: nil > ) > ``` ## Testing Use sandbox mode with test cards to verify your integration before going to production. > [tab] Web > > Test your checkout in a sandbox environment. Verify that: > > * Options are applied correctly > * Events fire as expected > * Error handling works for declined cards > * All payment methods render properly > [tab] Android > > ### Use sandbox environment > > Always test with sandbox client tokens before going to production. Use test card numbers: > > | Card | Result | > | - | - | > | `4111 1111 1111 1111` | Success | > | `4000 0000 0000 0002` | Declined | > > ### Test dark mode > > Verify your custom theme looks correct in both light and dark modes: > > ```kotlin theme={"dark"} > // Force dark mode for testing > val theme = PrimerTheme( > darkColorTokens = object : DarkColorTokens() { > override val primerColorBrand: Color = Color(0xFFA29BFE) > }, > ) > ``` > > ### Accessibility > > The SDK supports TalkBack and other accessibility services. Default components include: > > * Content descriptions for all interactive elements > * Semantic roles (buttons, inputs, headings) > * Focus management for screen transitions > > When building custom layouts, ensure your custom components also include accessibility annotations: > > ```kotlin theme={"dark"} > Modifier.semantics { > contentDescription = "Pay with Visa ending in 4242" > role = Role.Button > } > ``` > [tab] iOS > > ### Use sandbox environment > > Always test with sandbox client tokens before going to production. Use test card numbers: > > | Card | Result | > | - | - | > | `4111 1111 1111 1111` | Success | > | `4000 0000 0000 0002` | Declined | > > Use the [Primer Dashboard](https://sandbox-dashboard.primer.io) to configure test payment methods. > > ### Test dark mode > > Verify your custom theme looks correct in both light and dark modes using the iOS simulator's appearance settings or by overriding the color scheme in your preview: > > ```swift theme={"dark"} > #Preview { > CheckoutView(clientToken: "sandbox-token") > .preferredColorScheme(.dark) > } > ``` > > ### Accessibility > > The SDK supports VoiceOver and other iOS accessibility services. Default components include: > > * Accessibility labels for all interactive elements > * Trait annotations (button, header, text field) > * Focus management for screen transitions > > When building custom layouts, ensure your custom components include accessibility modifiers: > > ```swift theme={"dark"} > Text("Pay with Visa ending in 4242") > .accessibilityLabel("Pay with Visa ending in 4242") > .accessibilityAddTraits(.isButton) > ``` # Components Source: https://primer.io/docs/checkout/primer-checkout/configuration/components The full component catalog: core, card form and utility components, their hierarchy, and how they communicate. Primer Checkout provides a set of components that work together to create a complete payment experience. This page gives you an overview of all available components and how they relate to each other. ## Component Hierarchy > [tab] Web > > The components follow a hierarchical structure where parent components provide context to their children. Each parent literally contains its children. The spatial nesting mirrors the DOM nesting. > > > [tab] Without vault > > > [tab] With vault > [tab] Android > > The components follow a hierarchical structure where the checkout controller manages presentation components, which in turn contain SDK UI elements. > > > [tab] CheckoutSheet > > > [tab] CheckoutHost > [tab] iOS > > The iOS SDK uses a SwiftUI slot hierarchy. The managed `PrimerCheckout` view renders the full flow on its own and exposes no slots. For a composable layout, the `.primerCheckoutSession` modifier places your `PrimerCheckoutSession` in the environment. Composable views such as `PrimerCardForm` and `PrimerPaymentMethods` resolve it from there. ## Core Components > [tab] Web > > | Component | Purpose | > | - | - | > | [``](/docs/sdk/primer-checkout-web/components/primer-checkout) | Root component that initializes the SDK and provides checkout context | > | [``](/docs/sdk/primer-checkout-web/components/primer-main) | Manages checkout states and provides layout customization | > | [``](/docs/sdk/primer-checkout-web/components/primer-payment-method) | Renders a specific payment method (card, PayPal, Apple Pay, etc.) | > | [``](/docs/sdk/primer-checkout-web/components/primer-payment-method-container) | Container for filtering and organizing multiple payment methods | > [tab] Android > > ### Checkout controllers > > | Function | Returns | Purpose | > | - | - | - | > | `rememberPrimerCheckoutController()` | `PrimerCheckoutController` | Main session controller | > | `rememberCardFormController()` | `PrimerCardFormController` | Card form state and actions | > | `rememberPaymentMethodsController()` | `PrimerPaymentMethodsController` | Available payment methods | > | `rememberVaultedPaymentMethodsController()` | `PrimerVaultedPaymentMethodsController` | Saved payment methods | > > ### Presentation components > > | Component | Description | API Reference | > | - | - | - | > | `PrimerCheckoutSheet` | Modal bottom sheet checkout | [Reference](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-sheet) | > | `PrimerCheckoutHost` | Inline checkout host | [Reference](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-host) | > | `PrimerCardForm` | Card payment form | [Reference](/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/primer-card-form) | > | `PrimerPaymentMethods` | Payment method list | [Reference](/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) | > [tab] iOS > > ### Entry points > > | Component | Description | API Reference | > | - | - | - | > | `PrimerCheckout` | Managed SwiftUI view that renders the full default flow | [Reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) | > | `PrimerCheckoutSession` + `.primerCheckoutSession` | Session owner for inline, composable SwiftUI layouts | [Reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) | > | `PrimerCheckoutPresenter` | UIKit presenter (modal sheet) with a delegate | [Reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) | > > ### Composable views > > Each composable view exposes slots and resolves its session from the environment injected by `.primerCheckoutSession(_:theme:onCompletion:)`. > > | Component | Description | API Reference | > | - | - | - | > | `PrimerCardForm` | Card payment form with `cardDetails`, `billingAddress`, and `submitButton` slots | [Reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) | > | `PrimerPaymentMethods` | Available payment method list with `header`, `method`, and `emptyState` slots | [Reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) | > | `PrimerVaultedPaymentMethods` | Saved payment method shortcut for returning customers, with `header`, `item`, and `submitButton` slots. It pays with the selected saved method and renders nothing when none is saved. | [Reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) | ## Card Form Components > [tab] Web > > | Component | Purpose | > | - | - | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form) | Container that provides context for card inputs | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-number) | Secure hosted input for card number | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-expiry) | Secure hosted input for expiry date | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-cvv) | Secure hosted input for CVV | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-holder-name) | Input for cardholder name | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form-submit) | Submit button with built-in loading states | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-label) | Label component for card inputs | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-wrapper) | Wrapper for styling and layout of inputs | > | [``](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-billing-address) | Billing address collection form | > [tab] Android > > ### Defaults objects > > | Object | Parent Component | Sub-components | > | - | - | - | > | `PrimerCheckoutSheetDefaults` | `PrimerCheckoutSheet` | `Splash`, `Loading`, `Success`, `Error`, `PaymentMethodSelection`, `VaultedMethods`, `PaymentMethods` | > | `CardFormDefaults` | `PrimerCardForm` | `CardNumberField`, `ExpiryField`, `CvvField`, `CardholderField`, `CardNetworkField`, `CountryCodeField`, billing fields, `SubmitButton` | > | `PaymentMethodsDefaults` | `PrimerPaymentMethods` | `SectionHeader`, `Method`, `EmptyState` | > > ### State types > > | Type | Purpose | Values | > | - | - | - | > | `PrimerCheckoutState` | Checkout lifecycle and payment outcomes | `Loading`, `Ready`, `Success`, `Failure` | > | `PrimerCardFormController.State` | Card form state | Field values, validation, loading | > [tab] iOS > > ### Defaults namespaces > > Each composable view falls back to its `Defaults` namespace when a slot is omitted. You can also call these helpers inside your own slots to keep the SDK rendering while adding custom layout. > > | Namespace | Parent component | Section helpers | Per-field building blocks | > | - | - | - | - | > | `CardFormDefaults` | `PrimerCardForm` | `cardDetails`, `billingAddress`, `submitButton` | `cardNumber`, `expiryDate`, `cvv`, `cardholderName`, `cardNetwork`, `countryCode`, `firstName`, `lastName`, `addressLine1`, `addressLine2`, `city`, `state`, `postalCode`, `phoneNumber` | > | `PaymentMethodsDefaults` | `PrimerPaymentMethods` | `header`, `method`, `emptyState` | — | > | `VaultedPaymentMethodsDefaults` | `PrimerVaultedPaymentMethods` | `header`, `item`, `submitButton` | — | > > Each `CardFormDefaults` per-field block takes the `PrimerCardFormSession` and returns a view: `CardFieldContent`, or `CardNetworkFieldContent` for `cardNetwork`. Every block except `cardNetwork` renders nothing unless its field is part of the active `CardFormConfiguration`. `cardNetwork` is a standalone co-badged card network selector. It renders only when the card has more than one available network. The `cardNumber` block and the full `cardDetails` section already show the network selector inside the card number field. Do not add `cardNetwork` next to either, or two selectors appear. Use `cardNetwork` only when you want the selector outside the card number field. > > ### Sessions > > | Session | Purpose | Key members | > | - | - | - | > | `PrimerCardFormSession` | Card form state and actions | `state`, `updateCardNumber(_:)`, `updateCountryCode(_:)`, `selectCardNetwork(_:)`, `submit()` | > | `PrimerSelectionSession` | Payment method selection | `state`, `select(_:)`, `selectVaulted(_:)` (pays with a saved method), `vaultedPaymentMethods` | > > ### State types > > | Type | Purpose | Key properties | > | - | - | - | > | `PrimerCheckoutState` | Checkout lifecycle and outcome | `.initializing`, `.ready`, `.success`, `.failure`, `.dismissed` | > | `PrimerCardFormState` | Card form state | `isValid`, `isLoading`, `fieldErrors`, `selectedNetwork`, `selectedCountry`, `data` | > | `PrimerPaymentMethodSelectionState` | Payment method list | Available and selected payment methods | > > ### Field presence and styling > > There is no per-field configuration or styling struct. Which fields appear is Dashboard-driven through `CardFormConfiguration` (read from `session.state.configuration`), and visual styling is theme-driven via `PrimerCheckoutTheme` design tokens. To recompose a layout, arrange the `CardFormDefaults` per-field building blocks inside your own slot: > > ```swift theme={"dark"} > PrimerCardForm( > cardDetails: { session in > VStack(spacing: 12) { > CardFormDefaults.cardNumber(session) > HStack(spacing: 12) { > CardFormDefaults.expiryDate(session) > CardFormDefaults.cvv(session) > } > CardFormDefaults.cardholderName(session) > } > } > ) > ``` ## Utility Components > [tab] Web > > | Component | Purpose | > | - | - | > | [``](/docs/sdk/primer-checkout-web/components/primer-error-message-container) | Displays payment error messages | > | [``](/docs/sdk/primer-checkout-web/components/primer-vault-manager) | Manages saved payment methods | > | [``](/docs/sdk/primer-checkout-web/components/primer-show-other-payments) | Toggle button to show additional payment methods | > [tab] Android > > ### Theming > > | Class | Purpose | > | - | - | > | `PrimerTheme` | Root theme container | > | `LightColorTokens` | Light mode colors | > | `DarkColorTokens` | Dark mode colors | > | `SpacingTokens` | Spacing values | > | `TypographyTokens` | Font styles | > | `RadiusTokens` | Corner radius | > | `WidthTokens` | Border widths | > | `SizeTokens` | Component sizes | > [tab] iOS > > ### Theming > > | Struct | Purpose | > | - | - | > | `PrimerCheckoutTheme` | Root theme container | > | `ColorOverrides` | Brand, background, text, border, icon, focus, and loader colors. Set light mode with `colors` and dark mode with `darkColors`. A color left nil in `darkColors` uses Primer's dark default, even when `colors` sets it. | > | `RadiusOverrides` | Corner radius values | > | `SpacingOverrides` | Spacing values | > | `SizeOverrides` | Component sizes | > | `TypographyOverrides` | Font styles and sizes | > | `WidthOverrides` | Border widths for the default, focus, error, and selected states | > > ### Slot closures > > Customization points are the slots on the composable views. Each slot receives the relevant session (or model) and returns your view. `PrimerCardForm` and `PrimerPaymentMethods` slots are `@ViewBuilder` closures. `PrimerVaultedPaymentMethods` slots return `AnyView`, so wrap your content in `AnyView(...)`. > > | Slot | Receives | On | > | - | - | - | > | `cardDetails`, `billingAddress`, `submitButton` | `PrimerCardFormSession` | `PrimerCardForm` | > | `header`, `emptyState` | `PrimerSelectionSession` | `PrimerPaymentMethods` | > | `method` | `CheckoutPaymentMethod`, `() -> Void` | `PrimerPaymentMethods` | > | `header` | `PrimerSelectionSession` | `PrimerVaultedPaymentMethods` | > | `item` | `VaultedMethod`, `Bool` (is selected), `() -> Void` (on select) | `PrimerVaultedPaymentMethods` | > | `submitButton` | `Bool` (is loading), `Bool` (is enabled), `() -> Void` (on submit) | `PrimerVaultedPaymentMethods` | ## Basic Usage > [tab] Web > > ```html theme={"dark"} > > >
> > > > > > >
> >
>

Payment successful!

>
>
>
> ``` > [tab] Android > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> navigateToConfirmation(s.checkoutData) > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Failed: ${s.primerError.description}") > } > else -> Unit > } > } > > PrimerCheckoutSheet( > checkout = checkout, > onDismiss = { navigateBack() }, > ) > } > ``` > [tab] iOS > > ```swift theme={"dark"} > struct CheckoutView: View { > let clientToken: String > > var body: some View { > PrimerCheckout( > clientToken: clientToken, > primerSettings: PrimerSettings(paymentHandling: .auto), > primerTheme: PrimerCheckoutTheme( > colors: ColorOverrides(primerColorBrand: .blue) > ), > onCompletion: { state in > switch state { > case .success(let result): > print("Payment: \(result.paymentId)") > case let .failure(error, _): > print("Failed: \(error.errorId)") > case .dismissed: > print("Dismissed") > default: > break > } > } > ) > } > } > ``` ## How Components Communicate Components communicate through: 1. **Context inheritance** - Child components receive context from their parents (e.g., card inputs receive form context from their parent card form) 2. **Events** - Components emit events that you can listen to for state changes 3. **Customization points** (Slots on Web, Composable lambdas on Android, slot closures on iOS) - Allow you to inject custom content at specific points > [!NOTE] > > For details on events, see the [Events guide](/docs/checkout/primer-checkout/configuration/events). ## Customization at Each Level > [tab] Web > > * **``** - SDK options, theming, global configuration > * **``** - Layout structure through customization points > * **``** - Payment method-specific options > * **``** - Complete control over card form layout and styling > [tab] Android > > * **`PrimerCheckoutSheet` / `PrimerCheckoutHost`** - Presentation mode and event handling > * **`PrimerCheckoutSheetDefaults`** - Override default screens (splash, loading, success, error) > * **`CardFormDefaults`** - Customize individual card form fields > * **`PrimerTheme`** - Colors, typography, spacing, and border radius > [tab] iOS > > * **`PrimerCheckout`** - Client token, settings, theme, and completion handling for the managed flow > * **`PrimerCheckoutSession` + `.primerCheckoutSession`** - Inline, composable layouts and completion handling through `onCompletion` > * **`PrimerPaymentMethods`** - `header`, `method`, and `emptyState` slots for the payment method list > * **`PrimerCardForm`** - `cardDetails`, `billingAddress`, and `submitButton` slots, recomposed from `CardFormDefaults` > * **`PrimerCheckoutTheme`** - Light and dark colors, typography, spacing, sizes, radius, and border widths ## See also > [card] [Using Slots](/docs/checkout/primer-checkout/build-your-ui/layout-customization) > > Learn how to customize layout with slots > [card] [Build a custom card form](/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form) > > Step-by-step tutorial for card form customization > [card] [Styles](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Customize appearance with CSS variables > [card] [SDK Reference](/docs/sdk/primer-checkout-web/components/primer-checkout) > > Detailed API documentation for all components # Events guide Source: https://primer.io/docs/checkout/primer-checkout/configuration/events When and how to use the `primer:*` DOM events – ready, payment lifecycle, card form and vault – to drive your checkout. This guide explains the event-driven model behind Primer Checkout and walks through the integration decisions you'll face when wiring events into your application. It is organized around the questions you'll encounter as you build: where to listen, what to set up first, and how to handle each phase of the payment lifecycle. > [!TIP] > > This guide focuses on **when and why** to use each event. For the complete API surface, every event name, payload shape, type definition, and callback signature see the platform-specific SDK references. ## How events work > [tab] Web > > Primer Checkout components dispatch [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) objects. Every Primer event is created with `bubbles: true` and `composed: true`, which means events propagate up through shadow DOM boundaries and can be caught at any ancestor element, including `document`. This design gives you two choices for where to listen, covered in the next section. > [tab] Android > > The Android SDK communicates through a single channel: > > * **State** (`PrimerCheckoutState`): the full checkout lifecycle -- loading, ready, and the terminal `Success`/`Failure` outcomes > > State is a `StateFlow` you observe in Compose via `checkout.state`. Payment outcomes are terminal cases of that same flow. > [tab] iOS > > The iOS SDK communicates through two mechanisms: > > * **Published session state**: `PrimerCheckoutSession` publishes the lifecycle `phase` (`.initializing` / `.ready`) and `clientSession`. `PrimerCardFormSession` and `PrimerSelectionSession` publish `state` for field-level and selection progress > * **onCompletion callback** (`PrimerCheckoutState`): Receives `.failure` once per failed attempt, including a failed initialization. Then it receives `.success` or `.dismissed` at most once. It never receives `.initializing` or `.ready`, so read those from `phase` > > For the managed modal, pass `onCompletion` to `PrimerCheckout`. For inline, composable UI, observe each session's `@Published` state inside your SwiftUI views and receive the outcome through the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. In UIKit, conform to `PrimerCheckoutPresenterDelegate`. ## Choosing where to listen Each platform has its own mechanism for receiving SDK events and state changes. > [tab] Web > > > [tab] Component Level > > > > Attach listeners directly to the `` element. Each listener is scoped to a single checkout instance. > > > > ```javascript theme={"dark"} > > const checkout = document.querySelector('primer-checkout'); > > > > checkout.addEventListener('primer:ready', (event) => { > > // This listener only fires for this checkout instance > > const primer = event.detail; > > configureCallbacks(primer); > > }); > > ``` > > > > **Choose this when:** > > > > * You want to co-locate event logic with the component that owns it, such as inside a framework component's lifecycle hook. > > * You need to tear down listeners cleanly when a checkout is removed from the DOM. > > > [tab] Document Level > > > > Attach listeners to `document`. Because Primer events bubble and are composed, they reach the document root regardless of where the component sits in the DOM. > > > > ```javascript theme={"dark"} > > document.addEventListener('primer:payment-success', (event) => { > > // Fires when any Primer event bubbles up to document > > analytics.track('payment_completed', event.detail); > > }); > > ``` > > > > **Choose this when:** > > > > * You have a single checkout per page and prefer centralized event handling. > > * You're building cross-cutting concerns like analytics, logging, or error monitoring. > > * Your architecture already uses a global event bus pattern. > > ### Ensuring the component exists > > When using component-level listeners, make sure the element is in the DOM before attaching them. If your checkout renders dynamically (through a router transition, a conditional template, or lazy loading), the element may not exist at script-execution time. > > ```javascript theme={"dark"} > // Safe: wait for the DOM to be ready before querying > document.addEventListener('DOMContentLoaded', () => { > const checkout = document.querySelector('primer-checkout'); > if (checkout) { > checkout.addEventListener('primer:payment-success', handlePaymentSuccess); > checkout.addEventListener('primer:payment-failure', handlePaymentFailure); > } > }); > ``` > > If your framework provides a lifecycle hook that runs after the component mounts (React's `useEffect`, Vue's `onMounted`, etc.), prefer that over `DOMContentLoaded`. > [tab] Android > > State -- including the terminal `Success` and `Failure` outcomes -- is observed from `checkout.state`: > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > when (state) { > is PrimerCheckoutState.Loading -> { > CircularProgressIndicator() > } > is PrimerCheckoutState.Ready -> { > val clientSession = (state as PrimerCheckoutState.Ready).clientSession > Text("Total: ${checkout.formatAmount(clientSession.totalAmount ?: 0)}") > PrimerCheckoutSheet(checkout = checkout) > } > } > ``` > > ### PrimerCheckoutState > > | State | Description | Properties | > | - | - | - | > | `Loading` | SDK is initializing, fetching configuration | -- | > | `Ready` | Checkout is ready for payment | `clientSession: PrimerClientSession` | > | `Success` | Payment completed | `checkoutData: PrimerCheckoutData` | > | `Failure` | Payment failed or an error occurred | `error: PrimerError` | > > ### PrimerClientSession > > Available in the `Ready` state: > > | Property | Type | Description | > | - | - | - | > | `customerId` | `String?` | Customer identifier | > | `orderId` | `String?` | Order identifier | > | `currencyCode` | `String?` | Currency code (e.g., `"USD"`) | > | `totalAmount` | `Int?` | Total amount in minor units (cents) | > | `lineItems` | `List?` | Order line items | > | `orderDetails` | `PrimerOrder?` | Order details (country, shipping) | > | `customer` | `PrimerCustomer?` | Customer details (email, name, address) | > | `paymentMethod` | `PrimerPaymentMethod?` | Payment method configuration | > | `fees` | `List?` | Associated fees | > [tab] iOS > > The outcome is delivered to the `onCompletion` closure on `PrimerCheckout` (managed modal) or on the `.primerCheckoutSession(_:theme:onCompletion:)` modifier (inline), as a `PrimerCheckoutState` -- `.success`, `.failure`, or `.dismissed`. `.success` and `.dismissed` end the session and arrive at most once. `.failure` arrives once per failed attempt. While the SDK error screen is enabled (`uiOptions.isErrorScreenEnabled`, on by default), the checkout stays open on it. The closure is then called again if the customer retries. With `PrimerCheckout` this includes a failed initialization, whose error screen offers a retry. With the inline modifier, a failure before `.ready` ends the session. This example uses the managed modal: > > ```swift theme={"dark"} > PrimerCheckout(clientToken: clientToken) { state in > switch state { > case let .success(result): > print("Payment ID: \(result.paymentId)") > case let .failure(error, _): > print("Failed: \(error.errorDescription ?? "")") > case .dismissed: > print("Dismissed") > default: > break > } > } > ``` > > For inline UI you observe lifecycle and field-level progress by reading each session's `@Published` property: `PrimerCheckoutSession` publishes `phase`, while `PrimerCardFormSession` and `PrimerSelectionSession` publish `state`. > > ### PrimerCheckoutState > > | State | Description | Associated Values | > | - | - | - | > | `.initializing` | SDK is loading configuration. Not delivered to `onCompletion`. For inline UI, read `PrimerCheckoutSession.phase` | -- | > | `.ready` | Checkout is ready for payment. Not delivered to `onCompletion`. For inline UI, read `PrimerCheckoutSession.phase` and `PrimerCheckoutSession.clientSession` | `clientSession: PrimerClientSession` | > | `.success` | Payment completed. Delivered once | `PaymentResult` | > | `.failure` | A payment attempt or the initialization failed. Delivered once per failed attempt | `PrimerError`, `checkoutData: PrimerCheckoutData?` | > | `.dismissed` | Checkout was dismissed. Delivered once | -- | ## Phase 1: Initialization Every Primer Checkout integration begins with initialization. The SDK must fully initialize before you can pre-fill form fields or call SDK methods. > [tab] Web > > The `primer:ready` event fires once after the SDK has fully initialized. It delivers the `PrimerJS` instance as `event.detail`. > > ```javascript theme={"dark"} > const checkout = document.querySelector('primer-checkout'); > > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > > // Pre-fill known data (optional) > const user = getAuthenticatedUser(); > if (user?.fullName) { > primer.setCardholderName(user.fullName); > } > > // Access available methods immediately if needed > const methods = primer.getPaymentMethods(); > console.log(`${methods.length} payment method(s) available at init`); > }); > > // Handle payment outcomes via events > checkout.addEventListener('primer:payment-success', (event) => { > const { payment, paymentMethodType } = event.detail; > console.log('Payment successful:', payment.last4Digits); > window.location.href = `/confirmation?method=${paymentMethodType}`; > }); > > checkout.addEventListener('primer:payment-failure', (event) => { > const { error } = event.detail; > console.error('Payment failed:', error.message); > // The checkout UI already displays the error to the user. > // Use this event for logging, analytics, or retry logic. > }); > ``` > > > [!WARNING] > > > > If you don't listen for `primer:payment-success` and `primer:payment-failure`, successful and failed payments will complete silently with no redirect or confirmation. Always attach these event listeners. > > Before using `primer:payment-failure` to offer a retry, check the error's `code` and `origin` — [not all failures are retryable](/docs/checkout/primer-checkout/build-your-ui/error-handling#not-all-failures-are-retryable), and a network-level failure may hide a payment that actually succeeded. > [tab] Android > > The checkout controller initializes automatically when created with `rememberPrimerCheckoutController()`. Payment outcomes are terminal cases of `checkout.state` -- observe the flow to react to them: > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { > val payment = s.checkoutData > Log.d("Checkout", "Payment ID: ${payment.payment.id}") > navigateToConfirmation(payment) > } > is PrimerCheckoutState.Failure -> { > val error = s.primerError > Log.e("Checkout", "Failed: ${error.description}") > Log.e("Checkout", "Diagnostics: ${error.diagnosticsId}") > // Present when the payment was created before failing, e.g. a decline. > s.checkoutData?.payment?.let { payment -> > Log.e("Checkout", "Payment: ${payment.id} order: ${payment.orderId}") > } > } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > ``` > [tab] iOS > > The checkout initializes automatically when the `PrimerCheckout` SwiftUI view appears (or when the `.primerCheckoutSession` modifier calls `start()` on appear). Pass an `onCompletion` closure to receive the outcome: > > ```swift theme={"dark"} > PrimerCheckout(clientToken: clientToken) { state in > switch state { > case let .success(result): > print("Payment ID: \(result.paymentId)") > navigateToConfirmation(result) > case let .failure(error, checkoutData): > print("Failed: \(error.errorDescription ?? "")") > print("Diagnostics: \(error.diagnosticsId)") > // Present when the payment was created before failing, e.g. a decline. > if let payment = checkoutData?.payment { > print("Payment: \(payment.id ?? "-") order: \(payment.orderId ?? "-")") > } > case .dismissed: > navigateBack() > default: > break > } > } > ``` > > To observe the `.ready` lifecycle state for an inline integration, read the `phase` published by `PrimerCheckoutSession` (`.initializing` / `.ready`) inside your SwiftUI view. The client session that `.ready` carries is published separately as `PrimerCheckoutSession.clientSession` -- `nil` until the session is ready, then the same `PrimerClientSession` value: > > ```swift theme={"dark"} > if let total = session.clientSession?.totalAmount, > let formatted = session.formatAmount(total) { > Text("Total: \(formatted)") > } > ``` > > `totalAmount` is in minor units, so rendering it directly shows `1000` for a ten-dollar order. Use [`session.formatAmount(_:)`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) to format it the way the SDK's own screens do. > > > [!WARNING] > > > > If you don't provide an `onCompletion` closure, successful and failed payments will complete with no redirect or confirmation. Always provide this closure. ## Phase 2: Payment method discovery Shortly after initialization, the SDK provides information about available payment methods for the current session. > [tab] Web > > The SDK dispatches `primer:methods-update` with the list of payment methods available for the current session. This event fires once on load and may fire again if the session changes (e.g. after calling `primer.refreshSession()` in response to a cart update). > > You should use this event when you want to build a custom payment method selector, conditionally render UI based on what's available, or route users to a specific method. > > ```javascript theme={"dark"} > checkout.addEventListener('primer:methods-update', (event) => { > const methods = event.detail; > > // Conditionally show an "Express Checkout" section only if Apple Pay or Google Pay is available > const hasExpressMethod = methods.toArray().some( > (m) => m.type === 'APPLE_PAY' || m.type === 'GOOGLE_PAY' > ); > > document.getElementById('express-checkout-section').hidden = !hasExpressMethod; > }); > ``` > > If you're building a fully custom payment method layout (headless), you'll also iterate over the methods to create `` elements dynamically. The [Headless Vault Guide](/docs/sdk/primer-checkout-web/components/primer-vault-manager#headless-vault-implementation) covers that pattern in detail. > [tab] Android > > Payment methods are managed automatically by the SDK components (`PrimerPaymentMethods`, `PrimerVaultedPaymentMethods`). You can access the client session details from the `Ready` state: > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > > when (state) { > is PrimerCheckoutState.Ready -> { > val clientSession = (state as PrimerCheckoutState.Ready).clientSession > Text("Total: ${checkout.formatAmount(clientSession.totalAmount ?: 0)}") > } > } > ``` > [tab] iOS > > Payment methods are managed by the `PrimerPaymentMethods` view, which resolves a `PrimerSelectionSession` from the environment. Observe the session's published `state` to track available and selected methods: > > ```swift theme={"dark"} > struct MethodCount: View { > @ObservedObject var session: PrimerSelectionSession > > var body: some View { > VStack(alignment: .leading) { > Text("Methods: \(session.state.paymentMethods.count)") > if let selected = session.state.selectedPaymentMethod { > Text("Selected: \(selected.name)") > } > } > } > } > ``` > > Read `state` inside a `header` or `emptyState` slot, which receive the `PrimerSelectionSession`. The `method` slot instead receives a `CheckoutPaymentMethod` and an `onSelect` closure, so it does not have access to the session. ## Phase 3: User interaction As the user fills in payment details, the SDK provides real-time feedback. ### Showing the Card Network > [tab] Web > > `primer:bin-data-available` fires as the user types their card number. It provides the detected card network, co-badged network alternatives, and additional BIN data such as issuer information when available. Use it to display the correct card brand logo, show a co-badge network picker, or adjust UI based on card attributes. > > ```javascript theme={"dark"} > checkout.addEventListener('primer:bin-data-available', (event) => { > const { preferred, alternatives, status } = event.detail; > const logoEl = document.getElementById('card-logo'); > const cobrandEl = document.getElementById('cobrand-selector'); > > if (preferred) { > logoEl.src = `/images/${preferred.network.toLowerCase()}.svg`; > logoEl.alt = preferred.displayName; > } > > // Some cards support co-badging (e.g. Carte Bancaire / Visa). > // If there are multiple allowed networks, show a picker. > const selectableNetworks = [preferred, ...alternatives].filter(n => n?.allowed); > cobrandEl.hidden = selectableNetworks.length <= 1; > > // When status is 'complete', additional issuer data is available > if (status === 'complete' && preferred?.issuerCountryCode) { > console.log(`Card issued in: ${preferred.issuerCountryCode}`); > } > }); > ``` > > To show a loading indicator while BIN data is being fetched, listen for `primer:bin-data-loading-change`: > > ```javascript theme={"dark"} > checkout.addEventListener('primer:bin-data-loading-change', (event) => { > const { loading } = event.detail; > document.getElementById('card-logo').src = loading > ? '/images/card-placeholder.svg' > : document.getElementById('card-logo').src; > }); > ``` > > > [!NOTE] > > > > `primer:bin-data-available` replaces the older `primer:card-network-change` event with a richer payload that includes issuer details and card attributes. See the [Events Reference](/docs/sdk/primer-checkout-web/events-reference#primerbin-data-available) for the full payload shape. > [tab] Android > > The Android SDK handles card network detection and display automatically within the `PrimerCardForm` component. Card brand icons update in real-time as the user types. > [tab] iOS > > Card network detection is available via `PrimerCardFormState`. The `PrimerCardForm` view injects a `PrimerCardFormSession` into each of its slots; observe the session's published `state` and read `selectedNetwork` and `availableNetworks` as the user types: > > ```swift theme={"dark"} > PrimerCardForm(cardDetails: { session in > VStack(alignment: .leading) { > CardFormDefaults.cardNumber(session) > if let network = session.state.selectedNetwork { > Text("Detected network: \(network.displayName)") > } > // Co-badged cards expose multiple networks > if session.state.availableNetworks.count > 1 { > Text("Co-badge options: \(session.state.availableNetworks.map(\.displayName).joined(separator: ", "))") > } > } > }) > ``` > > To select a network on a co-badged card, call `session.selectCardNetwork(_:)`. ### Triggering Submission from a Custom Button > [tab] Web > > If you're using your own "Pay" button instead of the built-in one, dispatch `primer:card-submit` to tell the SDK to validate and submit the card form. > > ```javascript theme={"dark"} > document.getElementById('custom-pay-button').addEventListener('click', () => { > document.dispatchEvent( > new CustomEvent('primer:card-submit', { > bubbles: true, > composed: true, > }), > ); > }); > ``` > > > [!WARNING] > > > > `bubbles: true` and `composed: true` are required so the event crosses shadow DOM boundaries and reaches the card form component inside ``. Omitting either option will silently prevent submission. > > For vault payment submission from a custom button, dispatch `primer:vault-submit` in the same way. See the [Events Reference and Triggerable Events](/docs/sdk/primer-checkout-web/events-reference#triggerable-events) for the full list of events you can dispatch. > [tab] Android > > The Android SDK handles user interaction through Compose components. Card form state is managed via `PrimerCardFormController`: > > ```kotlin theme={"dark"} > val cardFormController = rememberCardFormController() > ``` > > The SDK provides built-in components for card input (`PrimerCardForm`), payment method selection (`PrimerPaymentMethods`), and vaulted methods (`PrimerVaultedPaymentMethods`). These handle user interaction automatically. > [tab] iOS > > If you're building a custom card form UI, drive the fields and submission through the `PrimerCardFormSession` injected into each `PrimerCardForm` slot. Bind your `TextField`s to the `update*` methods and call `submit()` from your custom button: > > ```swift theme={"dark"} > PrimerCardForm( > cardDetails: { session in > VStack(spacing: 16) { > TextField("Card number", text: Binding( > get: { session.state.data[.cardNumber] }, > set: { session.updateCardNumber($0) } > )) > TextField("Cardholder name", text: Binding( > get: { session.state.data[.cardholderName] }, > set: { session.updateCardholderName($0) } > )) > } > }, > submitButton: { session in > // Submit when your custom button is tapped > Button("Pay") { session.submit() } > .disabled(!session.state.isValid || session.state.isLoading) > } > ) > ``` > > Call `session.cancel()` to leave the card form. When other payment methods are configured, it returns to payment method selection. When the card is the only configured payment method, it dismisses the checkout and delivers `.dismissed`, even if the customer has saved methods. It is ignored while a payment is running or while your `onBeforePaymentCreate` handler has not decided yet. ## Phase 4: Payment processing and outcome Once the user submits, the SDK moves through a processing to outcome sequence. > [tab] Web > > The `primer:state-change` event fires at every step, giving you a single stream to drive your UI state. > > ```javascript theme={"dark"} > checkout.addEventListener('primer:state-change', (event) => { > const { isLoading, isProcessing, isSuccessful, paymentFailure, primerJsError } = event.detail; > const submitBtn = document.getElementById('custom-pay-button'); > const spinner = document.getElementById('loading-overlay'); > > // Disable the button during loading or processing > submitBtn.disabled = isLoading || isProcessing; > > // Show a loading overlay while the payment is in flight > spinner.hidden = !isProcessing; > > if (isSuccessful) { > // Payment succeeded — primer:payment-success will also fire > document.getElementById('checkout-form').hidden = true; > } > > if (paymentFailure) { > // The checkout component already displays the error to the user. > // Use this for supplementary logging or analytics. > console.error(`Payment error [${paymentFailure.code}]: ${paymentFailure.message}`); > } > > if (primerJsError) { > // An SDK-level error (network failure, configuration issue, etc.) > // Unlike paymentFailure, this may not be shown in the checkout UI. > reportToErrorService(primerJsError); > } > }); > ``` > [tab] Android > > | State | When | Key Properties | > | - | - | - | > | `PrimerCheckoutState.Success` | Payment completed | `checkoutData: PrimerCheckoutData` | > | `PrimerCheckoutState.Failure` | Payment failed | `primerError: PrimerError`, `checkoutData: PrimerCheckoutData?` | > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { > val payment = s.checkoutData > Log.d("Checkout", "Payment ID: ${payment.payment.id}") > navigateToConfirmation(payment) > } > is PrimerCheckoutState.Failure -> { > val error = s.primerError > Log.e("Checkout", "Failed: ${error.description}") > Log.e("Checkout", "Diagnostics: ${error.diagnosticsId}") > // Present when the payment was created before failing, e.g. a decline. > s.checkoutData?.payment?.let { payment -> > Log.e("Checkout", "Payment: ${payment.id} order: ${payment.orderId}") > } > } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > ``` > [tab] iOS > > The `onCompletion` closure receives `.failure` once per failed attempt. While the SDK error screen is enabled, the checkout stays open so the customer can retry. It then receives `.success` or `.dismissed` at most once, and after that nothing more. Read the [`PaymentResult`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) on `.success` and the [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) on `.failure`: > > ```swift theme={"dark"} > PrimerCheckout(clientToken: clientToken) { state in > switch state { > case let .success(result): > print("Payment ID: \(result.paymentId)") > print("Status: \(result.status)") > navigateToConfirmation(result) > case let .failure(error, checkoutData): > print("Error: \(error.errorDescription ?? "")") > print("Diagnostics: \(error.diagnosticsId)") > // Present when the payment was created before failing, e.g. a decline. > if let payment = checkoutData?.payment { > print("Payment: \(payment.id ?? "-") order: \(payment.orderId ?? "-")") > } > case .dismissed: > break > default: > break > } > } > ``` > > For an inline integration, drive intermediate UI (spinners, disabled buttons) from each session's `@Published` state -- for example `PrimerCardFormSession.state.isLoading` while a payment is in flight. ### State change vs. outcome events `primer:state-change` fires multiple times during a single payment. The outcome events (`primer:payment-success`, `primer:payment-failure`) fire exactly once at the end. Use `primer:state-change` for continuous UI updates (spinners, button states, progress indicators). Use the outcome events for final actions (redirects, confirmations, server notifications). ### Event timing Events may fire multiple times during a single checkout session (for example, if the user retries after a failure). > [tab] Web > > * `primer:state-change` fires at every step — use it for continuous UI updates (spinners, button states) > * `primer:payment-success` and `primer:payment-failure` fire exactly once at the end — use them for final actions > [tab] Android > > * `Success` fires immediately — the default success screen auto-dismisses after 3 seconds > * `Failure` fires immediately — the error screen stays open for retry > [tab] iOS > > * Each session's `@Published` state updates as the flow progresses -- observe it for continuous UI updates (spinners, button states) > * `.success` and `.dismissed` end the checkout. Only one of them reaches `onCompletion`, at most once -- use it for final actions (navigation, confirmation) > * `.failure` reaches `onCompletion` once per failed attempt. While the SDK error screen is enabled, the checkout stays open for a retry -- log the error or show your own message instead of navigating away > * `.dismissed` fires when the user dismisses the checkout without completing payment ### Dismissal and session refresh > [tab] Web > > Call `primer.refreshSession()` to sync the client-side SDK with your server session after a cart change. The SDK will re-dispatch `primer:methods-update` with the updated method list. > [tab] Android > > Handle checkout dismissal via the `onDismiss` callback: > > ```kotlin theme={"dark"} > PrimerCheckoutSheet( > checkout = checkout, > onDismiss = { > navigateBack() > }, > ) > ``` > > Call `checkout.refresh()` to reinitialize the checkout after updating the order on your server. > > Use `checkout.formatAmount()` to display currency-formatted values: > > ```kotlin theme={"dark"} > val formattedTotal = checkout.formatAmount(1000) // "$10.00" > ``` > [tab] iOS > > Handle dismissal by observing the `.dismissed` state in `onCompletion`: > > ```swift theme={"dark"} > PrimerCheckout(clientToken: clientToken) { state in > if case .dismissed = state { > navigateBack() > } > } > ``` > > For an inline integration, call `await session.refresh()` on your `PrimerCheckoutSession` to re-fetch configuration and payment methods after a client-session update (for example, an amount or currency change). ## Intercepting payments with primer:payment-start Sometimes you need to run a check *after* the user clicks "Pay" but *before* the payment is created — for example, confirming terms-of-service acceptance, validating inventory, or applying a last-second promotion code. > [tab] Web > > The `primer:payment-start` event gives you that interception point. > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-start', (event) => { > const { paymentMethodType, continuePaymentCreation, abortPaymentCreation } = event.detail; > > // Prevent automatic continuation > event.preventDefault(); > > const termsAccepted = document.getElementById('terms-checkbox').checked; > > if (!termsAccepted) { > showInlineError('Please accept the terms of service before paying.'); > abortPaymentCreation(); > return; > } > > // Optionally inspect paymentMethodType to apply method-specific logic > continuePaymentCreation(); > }); > ``` > > > [!WARNING] > > > > If you call `event.preventDefault()`, you must call either `continuePaymentCreation()` or `abortPaymentCreation()` in every code path. If neither is called, the payment will hang indefinitely. If you don't call `preventDefault()`, the payment continues automatically. > [tab] Android > > > [!NOTE] > > > > Payment interception is not available in the composable module. > [tab] iOS > > Set `onBeforePaymentCreate` on your `PrimerCheckoutSession` to intercept payments after the user taps "Pay" but before the payment is created. It runs for every payment method, including payments with a saved method started from the SDK's pay button or from `PrimerSelectionSession.selectVaulted(_:)`. The handler receives the payment-method data and a decision handler: > > ```swift theme={"dark"} > struct CheckoutView: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > let session = PrimerCheckoutSession(clientToken: clientToken) > session.onBeforePaymentCreate = { _, decisionHandler in > guard termsAccepted else { > decisionHandler(.abortPaymentCreation()) > return > } > decisionHandler(.continuePaymentCreation(withIdempotencyKey: nil)) > } > _session = StateObject(wrappedValue: session) > } > > var body: some View { > ScrollView { > PrimerCardForm() > } > .primerCheckoutSession(session) { state in > // Handle the outcome. > } > } > } > ``` > > > [!WARNING] > > > > You must call the `decisionHandler` closure with either `.continuePaymentCreation(withIdempotencyKey:)` or `.abortPaymentCreation()` in every code path. The SDK never times out the decision. It logs a warning after 5 seconds, and the payment hangs until you call it. `continuePaymentCreation` accepts an optional `{ idempotencyKey }` parameter. When provided, this key is sent with the payment request to prevent duplicate payments from being created. See the [Events Reference](/docs/sdk/primer-checkout-web/events-reference#preparehandler) for the full type definition. > [!TIP] > > `primer:payment-start` is for **client-side** checks that resolve in the browser. If you need a **server-side** decision (running a fraud check or inventory validation on your backend before the payment is created), use the [Manual payment approval](/docs/checkout/primer-checkout/guides-and-recipes/manual-payment-approval) flow, which pauses on the `primer:payment-approval-required` event until your backend approves or aborts the attempt. ## Working with Vaulted Payment Methods If your integration supports saved (vaulted) payment methods, additional events become relevant. > [tab] Web > > * **`primer:vault-methods-update`** — fires when vaulted payment methods are loaded or when the vault state changes. Use it to render saved cards, show a "Pay with saved card" section, or determine whether CVV re-entry is required. > * **`primer:vault-selection-change`** — fires when the user selects or deselects a saved method. Use it to enable or disable your submit button, or to toggle between "pay with saved card" and "pay with new card" views. > > ```javascript theme={"dark"} > let cvvRequired = false; > > checkout.addEventListener('primer:vault-methods-update', (event) => { > const { vaultedPayments, cvvRecapture } = event.detail; > cvvRequired = cvvRecapture; > > const savedMethodsSection = document.getElementById('saved-methods'); > if (vaultedPayments.length > 0) { > savedMethodsSection.hidden = false; > renderSavedMethodsList(vaultedPayments); > } else { > savedMethodsSection.hidden = true; > } > }); > > checkout.addEventListener('primer:vault-selection-change', (event) => { > const { paymentMethodId } = event.detail; > const vaultSubmitBtn = document.getElementById('vault-pay-button'); > > // Enable the button only when a method is selected > vaultSubmitBtn.disabled = !paymentMethodId; > > // If CVV re-entry is required, show the CVV input when a method is selected > if (paymentMethodId && cvvRequired) { > showCvvInput(paymentMethodId); > } > }); > ``` > > For full headless vault implementation, including `primer.vault.createCvvInput()`, `primer.vault.startPayment()`, and `primer.vault.delete()` see the [Headless Vault Guide](/docs/sdk/primer-checkout-web/components/primer-vault-manager#headless-vault-implementation). > [tab] Android > > Vaulted payment methods are managed by the `PrimerVaultedPaymentMethods` component and `rememberVaultedPaymentMethodsController()`: > > ```kotlin theme={"dark"} > val vaultController = rememberVaultedPaymentMethodsController() > ``` > > The SDK provides built-in UI for displaying and selecting saved payment methods within `PrimerCheckoutSheet`. > [tab] iOS > > Saved methods are rendered by the `PrimerVaultedPaymentMethods` view, backed by the same `PrimerSelectionSession`. Read the published `vaultedPaymentMethods` for the list, keep the highlight in your own view state, and call `selectVaulted(_:)` from your pay button. It is the pay verb, not a selection verb: > > ```swift theme={"dark"} > struct SavedMethodList: View { > @ObservedObject var session: PrimerSelectionSession > @State private var highlighted: String? > > var body: some View { > VStack(alignment: .leading, spacing: 8) { > ForEach(session.vaultedPaymentMethods, id: \.id) { method in > Button(method.paymentMethodType) { highlighted = method.id } > } > > Button("Pay") { > guard let method = session.vaultedPaymentMethods > .first(where: { $0.id == highlighted }) else { return } > session.selectVaulted(method) > } > } > } > } > ``` > > A card that needs CVV recapture raises the CVV recapture screen on submit, and that screen finishes the payment. > > Call `try await session.delete(_:)` to remove a saved method -- it deletes immediately, with no confirmation step -- and `session.showAll()` to present the SDK's saved-methods screen, where the customer can switch methods or delete one. The default header of `PrimerVaultedPaymentMethods` already wires `showAll()` in. ## Event flow overview The following diagram shows the typical sequence of events in a successful card payment, from initialization through confirmation. ```mermaid theme={"dark"} sequenceDiagram participant App as Your App participant SDK as Primer SDK Note over App,SDK: Phase 1 - Initialization SDK->>App: SDK ready Note right of App: Register callbacks, pre-fill fields Note over App,SDK: Phase 2 - Discovery SDK->>App: Payment methods available SDK->>App: Vaulted methods loaded Note right of App: Render payment method UI Note over App,SDK: Phase 3 - User Interaction App->>SDK: User enters card details SDK->>App: Card network detected Note right of App: Show card brand logo Note over App,SDK: Phase 4 - Processing & Outcome App->>SDK: Submit payment SDK->>App: State: processing Note right of App: Show spinner, disable button SDK->>App: State: successful SDK->>App: Payment success event Note right of App: Navigate to confirmation ``` ## Debugging tips > [tab] Web > > * **Events not firing?** Confirm the `` element is in the DOM before you add listeners. In SPAs, race conditions between route rendering and listener attachment are the most common cause. > * **Shadow DOM boundary issues?** Triggerable events (`primer:card-submit`, `primer:vault-submit`) must be dispatched with `bubbles: true` and `composed: true` or they won't reach the internal form component. > * **Stale data after a cart change?** Call `primer.refreshSession()` to sync the client-side SDK with your server session. The SDK will re-dispatch `primer:methods-update` with the updated method list. > [tab] Android > > * **State not updating?** Make sure you're using `collectAsStateWithLifecycle()` instead of `collectAsState()`. > * **Outcomes not received?** Ensure you're observing `checkout.state` and handling the terminal `PrimerCheckoutState.Success` and `PrimerCheckoutState.Failure` cases. > * **Stale data after a cart change?** Call `checkout.refresh()` to reinitialize the checkout. > * **Log diagnostics IDs.** Every `PrimerError` includes a `diagnosticsId`. Log it for troubleshooting with Primer support. > [tab] iOS > > * **State not updating?** Observe the session with `@ObservedObject` (or hold `PrimerCheckoutSession` as a `@StateObject`) so SwiftUI re-renders when its published properties change. These are `phase` and `clientSession` on `PrimerCheckoutSession`, `state` on `PrimerCardFormSession`, and `state` and `vaultedPaymentMethods` on `PrimerSelectionSession`. > * **onCompletion not firing?** It fires for `.success`, `.failure` and `.dismissed`. Read `PrimerCheckoutSession.phase` to follow `.initializing` and `.ready`. > * **Composable views not rendering?** Make sure the `.primerCheckoutSession(_:theme:onCompletion:)` modifier is applied above `PrimerCardForm` / `PrimerPaymentMethods` in the hierarchy. Without it, they cannot resolve a session from the environment. > * **Child sessions are nil?** `PrimerCheckoutSession.cardForm` and `.selection` are non-`nil` only once `phase == .ready`. > * **Log diagnostics IDs.** Every `PrimerError` includes a `diagnosticsId`. Log it for troubleshooting with Primer support. ## See also > [card] [Web events reference](/docs/sdk/primer-checkout-web/events-reference) > > Every Web event name, payload type, callback signature, and instance method > [card] [Android SDK reference](/docs/sdk/android-checkout/v3.0.0-beta/api/overview) > > Android SDK API documentation > [card] [iOS SDK reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/overview) > > iOS SDK API documentation > [card] [Recipes](/docs/checkout/primer-checkout/guides-and-recipes/overview) > > Use-case driven examples for common integration scenarios > [card] [Error handling](/docs/checkout/primer-checkout/build-your-ui/error-handling) > > Deep dive into error handling, retries, and failure recovery # Supported locales Source: https://primer.io/docs/checkout/primer-checkout/configuration/localization The full list of supported locales, and how to set one with the `locale` SDK option. Primer Checkout supports multiple languages and automatically adapts the checkout UI to the shopper's locale. ## Supported Locales Primer Checkout supports the following locales. If a specific regional variant is not supported, it falls back gracefully to the closest available language. | Locale | Language | Platforms | | - | - | - | | `ar` | Arabic | All | | `az` | Azerbaijani | iOS, Android | | `bg` | Bulgarian | All | | `bs` | Bosnian | iOS, Android | | `ca` | Catalan | All | | `cs` | Czech | All | | `da` | Danish | All | | `de` | German | All | | `el` | Greek | All | | `en` | English | All | | `es` | Spanish | All | | `es-AR` | Spanish (Argentina) | All | | `es-MX` | Spanish (Mexico) | All | | `et` | Estonian | All | | `fa` | Persian | iOS, Android | | `fi` | Finnish | All | | `fil` | Filipino | iOS, Android | | `fr` | French | All | | `he` | Hebrew | All | | `hi` | Hindi | iOS, Android | | `hr` | Croatian | All | | `hu` | Hungarian | All | | `hy` | Armenian | iOS, Android | | `id` | Indonesian | All | | `it` | Italian | All | | `ja` | Japanese | All | | `ka` | Georgian | iOS, Android | | `kk` | Kazakh | iOS, Android | | `ko` | Korean | All | | `ku` | Kurdish | iOS, Android | | `ky` | Kyrgyz | iOS, Android | | `lt` | Lithuanian | All | | `lv` | Latvian | All | | `mk` | Macedonian | iOS, Android | | `ms` | Malay | All | | `nb` | Norwegian Bokmal | All | | `nl` | Dutch | All | | `nl-BE` | Dutch (Belgium) | iOS, Android | | `pl` | Polish | All | | `pt` | Portuguese | All | | `pt-BR` | Portuguese (Brazil) | All | | `ro` | Romanian | All | | `ru` | Russian | All | | `sk` | Slovak | All | | `sl` | Slovenian | All | | `sq` | Albanian | iOS, Android | | `sr` | Serbian | All | | `sv` | Swedish | All | | `th` | Thai | All | | `tr` | Turkish | All | | `uk` | Ukrainian | All | | `ur-PK` | Urdu (Pakistan) | iOS, Android | | `uz` | Uzbek | iOS, Android | | `vi` | Vietnamese | All | | `zh-CN` | Chinese (Simplified) | All | | `zh-HK` | Chinese (Hong Kong) | All | | `zh-TW` | Chinese (Traditional) | All | > [!NOTE] > > Locales marked **iOS, Android** are not yet available on Web. Regional variants automatically fall back to the base language — for example, `pl-PL` (Polish - Poland) will use `pl` (Polish) translations. > [tab] Web > > Pass a locale to the SDK using the `options` property. See [SDK Options](/docs/checkout/primer-checkout/configuration/sdk-options) for details. > > Web supports all locales marked **All** in the table above. The remaining locales (marked **iOS, Android**) are coming soon. > [tab] Android > > The SDK automatically adapts to the device's locale for field labels, error messages, button text, currency formatting, and date formatting. No additional configuration is required. > > Android supports all locales listed in the table above. > [tab] iOS > > The SDK's text (field labels, error messages and button text) uses the language your app runs in. Amounts are formatted in the locale from `PrimerLocaleData` in `PrimerSettings`, which defaults to the device locale. No additional configuration is required. > > iOS supports all locales listed in the table above. To set the locale for amounts and for payment-provider pages such as redirect, Klarna and QR code methods, use `PrimerLocaleData` in `PrimerSettings`: > > ```swift theme={"dark"} > private let primerSettings = PrimerSettings( > localeData: PrimerLocaleData(languageCode: "fr", regionCode: "FR") > ) > ``` ## Locale Fallback Behavior > [tab] Web > > Primer Checkout Web uses [BCP 47](https://www.rfc-editor.org/info/bcp47) language tags and implements automatic fallback for regional variants. > > ### How it works > > 1. **Exact match**: The SDK first looks for an exact match (e.g., `pl-PL`) > 2. **Base language fallback**: If no exact match exists, it falls back to the base language (e.g., `pl`) > 3. **Default fallback**: If neither matches, it defaults to `en-GB` > > ### Usage > > Check [SDK options guide](/docs/checkout/primer-checkout/configuration/sdk-options#2-options-object) to learn how to pass a locale property. > [tab] Android > > The Android SDK follows the standard Android locale resolution. The device's system locale is used automatically, and Compose's built-in layout mirroring handles RTL languages. > > ### Currency formatting > > The SDK formats amounts using the currency code from your client session: > > ```kotlin theme={"dark"} > // With USD client session > checkout.formatAmount(1000) // "$10.00" > > // With EUR client session > checkout.formatAmount(1000) // "10,00 EUR" > > // With JPY client session (no minor units) > checkout.formatAmount(1000) // "JPY1,000" > ``` > > ### RTL support > > The SDK supports right-to-left (RTL) layouts automatically when the device locale is set to an RTL language. Compose's built-in layout mirroring handles the directional adjustments. > [tab] iOS > > The iOS SDK follows standard iOS localization. Its text uses the language your app runs in. > > ### How it works > > 1. **UI language**: Field labels, error messages and button text follow the language your app runs in > 2. **Base language fallback**: If only the language matches (e.g., `en` for `en-AU`), the base language strings are used > 3. **Default fallback**: If no match is found, English (`en`) is used as the fallback > 4. **Amount formatting**: Amounts are formatted in the locale from `PrimerLocaleData` in `PrimerSettings`, which defaults to the device locale > > ### Setting the amount locale > > `PrimerLocaleData` sets the locale used to format amounts and the locale sent to payment-provider pages. It does not change the language of the SDK's text. > > ```swift theme={"dark"} > private let primerSettings = PrimerSettings( > localeData: PrimerLocaleData(languageCode: "de", regionCode: "DE") > ) > ``` > > ### Currency formatting > > Use [`session.formatAmount(_:)`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) to format an amount in minor units the way the SDK's own screens do. It uses the client session's currency and the locale from `PrimerLocaleData`, and returns `nil` until the session is ready. > > ```swift theme={"dark"} > struct OrderTotal: View { > @ObservedObject var session: PrimerCheckoutSession > > var body: some View { > if let total = session.clientSession?.totalAmount, > let formatted = session.formatAmount(total) { > Text("Total: \(formatted)") > } > } > } > ``` > > ### RTL support > > The SDK supports right-to-left (RTL) layouts automatically when your app runs in an RTL language such as Arabic (`ar`) or Hebrew (`he`). The SDK applies your app's layout direction to its views, and SwiftUI's layout mirroring handles the directional adjustments. # Configuring checkout Source: https://primer.io/docs/checkout/primer-checkout/configuration/sdk-options Set component properties with `setAttribute` and SDK options with `.options`. Primer Checkout uses platform-specific configuration to control checkout behavior, appearance, and payment handling. > [tab] Web > > Primer Checkout Web uses two types of configuration: **component properties** (HTML attributes) and **SDK options** (JavaScript object). > > ```javascript theme={"dark"} > const checkout = document.querySelector('primer-checkout'); > > // Component properties - use setAttribute() > checkout.setAttribute('client-token', 'your-token'); > > // SDK options - assign directly > checkout.options = { > locale: 'en-GB', > card: { cardholderName: { required: true } } > }; > ``` > [tab] Android > > The Android SDK uses `PrimerSettings` to configure checkout behavior. Pass it when creating the checkout controller: > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > settings = PrimerSettings().apply { > locale = Locale("fr", "FR") > uiOptions.dismissalMechanism = listOf(DismissalMechanism.CLOSE_BUTTON) > }, > ) > ``` > [tab] iOS > > The iOS SDK uses `PrimerSettings` and `PrimerCheckoutTheme` to configure checkout behavior and appearance. Pass them when creating `PrimerCheckout`: > > ```swift theme={"dark"} > PrimerCheckout( > clientToken: clientToken, > primerSettings: PrimerSettings(paymentHandling: .auto), > primerTheme: PrimerCheckoutTheme( > colors: ColorOverrides(primerColorBrand: .blue) > ) > ) > ``` *** ## Configuration Overview > [tab] Web > > | Type | How to Set | Examples | > | - | - | - | > | **Component Properties** | `setAttribute()` | `client-token`, `custom-styles`, `loader-disabled` | > | **SDK Options** | Direct assignment to `.options` | `locale`, `card`, `vault`, `applePay` | > > > [!WARNING] > > > > Don't mix them up. Component properties must use `setAttribute()`. SDK options must be assigned directly to `.options`. > [tab] Android > > | Type | How to Set | Examples | > | - | - | - | > | **Client token** | `rememberPrimerCheckoutController(clientToken)` | Authentication token | > | **Settings** | `PrimerSettings` object | `locale`, `uiOptions`, `paymentMethodOptions`, `debugOptions` | > | **Theme** | `PrimerTheme` parameter on composable | `PrimerCheckoutSheet(theme = ...)` | > > > [!NOTE] > > > > Theming is **not** part of `PrimerSettings`. Pass `PrimerTheme` directly to `PrimerCheckoutSheet` or `PrimerCheckoutHost`. See [Styling Guide](/docs/checkout/primer-checkout/build-your-ui/styling-customization). > [tab] iOS > > | Type | How to Set | Examples | > | - | - | - | > | **Client token** | `PrimerCheckout(clientToken:)` | Authentication token | > | **Settings** | `PrimerSettings` parameter | `paymentHandling`, `uiOptions`, `paymentMethodOptions` | > | **Theme** | `PrimerCheckoutTheme` parameter | `colors`, `darkColors`, `radius`, `spacing`, `sizes`, `typography`, `width` | > > > [!NOTE] > > > > Theming is **not** part of `PrimerSettings`. Pass `PrimerCheckoutTheme` as a separate parameter to `PrimerCheckout` or `PrimerCheckoutPresenter`. See [Styling Guide](/docs/checkout/primer-checkout/build-your-ui/styling-customization). *** ## Component Properties / Client Token The client token authenticates your checkout session. Obtain this by [creating a client session](/docs/checkout/client-session). > [tab] Web > > ### client-token (required) > > ```javascript theme={"dark"} > // ✅ Correct > checkout.setAttribute('client-token', 'your-client-token'); > > // ❌ Wrong - won't work > checkout.clientToken = 'your-token'; > ``` > > ```html theme={"dark"} > > > ``` > > #### Updating the client token > > To start a new session, set a new client token on the existing component. The checkout tears down the current session and initializes the new one in place, so you don't need to reload the page or recreate the component. > > ```javascript theme={"dark"} > checkout.setAttribute('client-token', newClientToken); > ``` > > This is a full re-initialization: the loader shows again, entered card details are cleared, payment methods are reloaded, and `primer:ready` fires again with a new PrimerJS instance. Don't change the token while a payment is in progress. > > If you updated the existing client session on your server and the token hasn't changed, call [`primer.refreshSession()`](/docs/sdk/primer-checkout-web/events-reference#refreshsession) instead. It syncs the checkout with the session without re-initializing. > > ### custom-styles > > JSON string containing CSS variables for theming. > > ```javascript theme={"dark"} > const styles = { > primerColorBrand: '#4a6cf7', > primerTypographyBrand: 'Inter, sans-serif' > }; > > checkout.setAttribute('custom-styles', JSON.stringify(styles)); > ``` > > > See [Styling Guide](/docs/checkout/primer-checkout/build-your-ui/styling-customization) for available properties. > > ### loader-disabled > > Disables the default loading spinner. > > ```javascript theme={"dark"} > checkout.setAttribute('loader-disabled', 'true'); > ``` > [tab] Android > > Pass the client token directly when creating the checkout controller: > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > ) > ``` > [tab] iOS > > Pass the client token directly when creating `PrimerCheckout`: > > ```swift theme={"dark"} > // SwiftUI > PrimerCheckout(clientToken: clientToken) > > // UIKit > PrimerCheckoutPresenter.presentCheckout( > clientToken: clientToken, > from: viewController, > primerSettings: PrimerSettings(), > primerTheme: PrimerCheckoutTheme() > ) > ``` *** ## SDK Options / Settings > [tab] Web > > SDK options configure checkout behavior. Assign a JavaScript object directly to the `options` property. > > ```javascript theme={"dark"} > // ✅ Correct - assign directly > checkout.options = { > locale: 'en-GB', > card: { cardholderName: { required: true } } > }; > > // ❌ Wrong - don't use setAttribute for options > checkout.setAttribute('options', JSON.stringify({...})); > ``` > > > [!NOTE] > > > > For the complete list of available options, see the [SDK Options Reference](/docs/sdk/primer-checkout-web/sdk-options-reference). > [tab] Android > > `PrimerSettings` configures the SDK behavior for a checkout session. Pass it when creating the controller. > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > settings = PrimerSettings().apply { > locale = Locale("fr", "FR") > uiOptions.dismissalMechanism = listOf(DismissalMechanism.CLOSE_BUTTON) > paymentMethodOptions.redirectScheme = "myapp" > }, > ) > ``` > > > [!NOTE] > > > > For the complete list of available options, see the [SDK Options Reference](/docs/sdk/android-checkout/v3.0.0-beta/api/overview). > [tab] iOS > > `PrimerSettings` configures the SDK behavior for a checkout session. Pass it when creating `PrimerCheckout`. > > ```swift theme={"dark"} > let settings = PrimerSettings( > paymentHandling: .auto, > paymentMethodOptions: PrimerPaymentMethodOptions(), > uiOptions: PrimerUIOptions() > ) > > PrimerCheckout( > clientToken: clientToken, > primerSettings: settings > ) > ``` > > > [!NOTE] > > > > For the complete list of available options, see the [SDK Options Reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings). *** ## Common Patterns > [tab] Web > > ### Set Locale > > ```javascript theme={"dark"} > checkout.options = { > locale: 'en-GB' > }; > ``` > > > [Supported locales](/docs/checkout/primer-checkout/configuration/localization) > > ### Enable Specific Payment Methods > > ```javascript theme={"dark"} > import { PaymentMethodType } from '@primer-io/primer-js'; > > checkout.options = { > enabledPaymentMethods: [ > PaymentMethodType.PAYMENT_CARD, > PaymentMethodType.PAYPAL, > PaymentMethodType.ADYEN_BLIK > ] > }; > ``` > > ### Pre-fill Cardholder Name > > ```javascript theme={"dark"} > checkout.options = { > card: { > cardholderName: { > required: true, > visible: true, > defaultValue: 'John Doe' > } > } > }; > ``` > > For runtime updates after initialization, use `primer.setCardholderName()` instead. > > ### Enable Vault (Saved Payment Methods) > > ```javascript theme={"dark"} > checkout.options = { > vault: { > enabled: true > } > }; > ``` > > ### Configure Apple Pay Button > > ```javascript theme={"dark"} > checkout.options = { > applePay: { > buttonType: 'buy', > buttonStyle: 'black' > } > }; > ``` > > ### Configure Google Pay Button > > ```javascript theme={"dark"} > checkout.options = { > googlePay: { > buttonType: 'buy', > buttonColor: 'black', > captureBillingAddress: true > } > }; > ``` > > ### Configure Klarna > > ```javascript theme={"dark"} > checkout.options = { > klarna: { > paymentFlow: 'DEFAULT', > allowedPaymentCategories: ['pay_now', 'pay_later'], > buttonOptions: { > text: 'Pay with Klarna' > } > } > }; > ``` > > ### Configure Klarna via Adyen > > ```javascript theme={"dark"} > checkout.options = { > adyenKlarna: { > buttonOptions: { > text: 'Pay with Klarna' > } > } > }; > ``` > [tab] Android > > ### Set Locale > > ```kotlin theme={"dark"} > settings = PrimerSettings().apply { > locale = Locale("fr", "FR") > } > ``` > > Default is `Locale.getDefault()` (device locale). Controls SDK-internal strings and currency formatting. > > ### Custom Success/Error Screens > > Replace the default success and error screens with your own composables via slot parameters: > > ```kotlin theme={"dark"} > PrimerCheckoutSheet( > checkout = checkout, > success = { checkoutData -> > MyCustomSuccessScreen(checkoutData) > }, > error = { primerError, _ -> > MyCustomErrorScreen(primerError) > }, > ) > ``` > > See [Layout Customization](/docs/checkout/primer-checkout/build-your-ui/layout-customization) for more slot examples. > > ### Configure Dismissal Behavior > > ```kotlin theme={"dark"} > settings = PrimerSettings().apply { > uiOptions.dismissalMechanism = listOf(DismissalMechanism.CLOSE_BUTTON) > } > ``` > > | Value | Behavior | > | - | - | > | `GESTURES` | Swipe-to-dismiss (default) | > | `CLOSE_BUTTON` | Explicit close button | > > You can combine both: `listOf(DismissalMechanism.GESTURES, DismissalMechanism.CLOSE_BUTTON)`. > > ### Configure Google Pay > > ```kotlin theme={"dark"} > settings = PrimerSettings().apply { > paymentMethodOptions.googlePayOptions = PrimerGooglePayOptions( > merchantName = "My Store", > captureBillingAddress = true, > emailAddressRequired = true, > buttonStyle = GooglePayButtonStyle.BLACK, > ) > } > ``` > > ### Set Redirect Scheme > > Required for redirect-based payment methods (PayPal, Klarna, etc.): > > ```kotlin theme={"dark"} > settings = PrimerSettings().apply { > paymentMethodOptions.redirectScheme = "myapp" > } > ``` > [tab] iOS > > ### Set Payment Handling > > ```swift theme={"dark"} > let settings = PrimerSettings(paymentHandling: .auto) > ``` > > | Value | Behavior | > | - | - | > | `.auto` | Primer handles the full payment flow (recommended) | > | `.manual` | Not supported in Primer Checkout. The checkout fails at start with a `PrimerError` whose `errorId` is `invalid-value`. Keep `.auto`. See [PrimerPaymentHandling](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings#primerpaymenthandling). | > > ### Toggle Managed Screens > > `PrimerCheckout` renders Primer's default init, success, and error screens. Toggle them through `uiOptions` to handle results yourself instead: > > ```swift theme={"dark"} > let settings = PrimerSettings( > uiOptions: PrimerUIOptions( > isInitScreenEnabled: false, > isSuccessScreenEnabled: false, > isErrorScreenEnabled: false > ) > ) > ``` > > For fully custom screens, compose your own views under [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) instead of `PrimerCheckout` and drive them with the session's published state. > > ### Configure Theme Colors > > ```swift theme={"dark"} > let theme = PrimerCheckoutTheme( > colors: ColorOverrides( > primerColorBrand: .blue, > primerColorBackgroundPrimary: .white > ) > ) > ``` > > ### Handle Completion > > ```swift theme={"dark"} > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > switch state { > case .success(let result): > print("Payment: \(result.paymentId)") > case let .failure(error, _): > print("Failed: \(error.localizedDescription)") > case .dismissed: > print("Dismissed") > default: > break > } > } > ) > ``` *** ## Complete Example > [tab] Web > > ```javascript theme={"dark"} > import { PaymentMethodType } from '@primer-io/primer-js'; > > const checkout = document.querySelector('primer-checkout'); > > // 1. Component properties > checkout.setAttribute('client-token', 'your-client-token'); > checkout.setAttribute('custom-styles', JSON.stringify({ > primerColorBrand: '#4a6cf7' > })); > > // 2. SDK options > checkout.options = { > locale: 'en-GB', > enabledPaymentMethods: [ > PaymentMethodType.PAYMENT_CARD, > PaymentMethodType.PAYPAL > ], > card: { > cardholderName: { > required: true, > visible: true > } > }, > vault: { > enabled: true > } > }; > ``` > [tab] Android > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > settings = PrimerSettings().apply { > locale = Locale("fr", "FR") > uiOptions.dismissalMechanism = listOf(DismissalMechanism.CLOSE_BUTTON) > paymentMethodOptions.redirectScheme = "myapp" > paymentMethodOptions.googlePayOptions = PrimerGooglePayOptions( > merchantName = "My Store", > captureBillingAddress = true, > ) > }, > ) > > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> navigateToConfirmation(s.checkoutData) > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Failed: ${s.primerError.description}") > } > else -> Unit > } > } > > PrimerCheckoutSheet( > checkout = checkout, > success = { checkoutData -> MySuccessScreen(checkoutData) }, > error = { primerError, _ -> MyErrorScreen(primerError) }, > onDismiss = { > navigateBack() > }, > ) > } > ``` > [tab] iOS > > ```swift theme={"dark"} > private let primerSettings = PrimerSettings( > paymentHandling: .auto, > uiOptions: PrimerUIOptions( > dismissalMechanism: [.gestures, .closeButton] > ) > ) > > private let primerTheme = PrimerCheckoutTheme( > colors: ColorOverrides(primerColorBrand: .blue), > radius: RadiusOverrides(primerRadiusMedium: 12) > ) > > struct CheckoutView: View { > let clientToken: String > > var body: some View { > PrimerCheckout( > clientToken: clientToken, > primerSettings: primerSettings, > primerTheme: primerTheme, > onCompletion: { state in > switch state { > case .success(let result): > print("Payment: \(result.paymentId)") > case let .failure(error, _): > print("Failed: \(error.localizedDescription)") > case .dismissed: > print("Dismissed") > default: > break > } > } > ) > } > } > ``` *** ## Framework-Specific Patterns > [tab] Web > > > [tab] Vanilla JS > > > > ```javascript theme={"dark"} > > document.addEventListener('DOMContentLoaded', () => { > > const checkout = document.querySelector('primer-checkout'); > > checkout.setAttribute('client-token', 'your-token'); > > checkout.options = { locale: 'en-GB' }; > > }); > > ``` > > > [tab] React > > > > ```tsx theme={"dark"} > > const SDK_OPTIONS = { locale: 'en-GB' }; > > > > function CheckoutPage() { > > return ( > > > client-token="your-token" > > options={SDK_OPTIONS} > > /> > > ); > > } > > ``` > > > > > See [React Integration Guide](/docs/checkout/primer-checkout/frameworks/react-integration-guide) for stable references and React 18/19 differences. > > > [tab] Next.js / SSR > > > > ```tsx theme={"dark"} > > 'use client'; > > > > import { useEffect } from 'react'; > > import { loadPrimer } from '@primer-io/primer-js'; > > > > const SDK_OPTIONS = { locale: 'en-GB' }; > > > > export default function CheckoutPage() { > > useEffect(() => { > > loadPrimer(); > > }, []); > > > > return ( > > > client-token="your-token" > > options={SDK_OPTIONS} > > /> > > ); > > } > > ``` > > > > > See [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) for framework-specific patterns. > [tab] Android > > The Android SDK uses standard Jetpack Compose patterns. Configuration is passed when creating the checkout controller: > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > settings = PrimerSettings().apply { > paymentMethodOptions.redirectScheme = "myapp" > }, > ) > > PrimerCheckoutSheet(checkout = checkout) > } > ``` > > See the [Best Practices](/docs/checkout/primer-checkout/configuration/best-practices) guide for Compose-specific patterns. > [tab] iOS > > > [tab] SwiftUI > > > > ```swift theme={"dark"} > > struct CheckoutView: View { > > let clientToken: String > > > > var body: some View { > > PrimerCheckout( > > clientToken: clientToken, > > primerSettings: PrimerSettings(paymentHandling: .auto), > > onCompletion: { state in > > // Handle result > > } > > ) > > } > > } > > ``` > > > > > See the [Best Practices](/docs/checkout/primer-checkout/configuration/best-practices) guide for SwiftUI-specific patterns. > > > [tab] UIKit > > > > ```swift theme={"dark"} > > class CheckoutViewController: UIViewController, PrimerCheckoutPresenterDelegate { > > func showCheckout() { > > PrimerCheckoutPresenter.shared.delegate = self > > > > PrimerCheckoutPresenter.presentCheckout( > > clientToken: clientToken, > > from: self, > > primerSettings: PrimerSettings(paymentHandling: .auto), > > primerTheme: PrimerCheckoutTheme() > > ) > > } > > > > func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) { > > // Navigate to confirmation > > } > > > > func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) { > > print("Failed: \(error.localizedDescription)") > > } > > > > func primerCheckoutPresenterDidDismiss() { > > print("Dismissed") > > } > > } > > ``` > > > > > See [UIKit Integration Guide](/docs/sdk/ios-checkout/v3.0.0-beta/guides/uikit-integration) for more details. *** ## Advanced Configuration > [tab] Web > > > [accordion] Headless Vault > > > > Build custom vault UIs while retaining full vault functionality. Enable headless mode: > > > > ```javascript theme={"dark"} > > checkout.options = { > > vault: { > > enabled: true, > > headless: true > > } > > }; > > ``` > > > > Then use `onVaultedMethodsUpdate`, `vault.createCvvInput()`, and `vault.startPayment()` to build your custom UI. > > > > > [Headless Vault Implementation Guide](/docs/sdk/primer-checkout-web/components/primer-vault-manager#headless-vault-implementation) > > > [accordion] External Submit Button > > > > Use your own submit button instead of the built-in one: > > > > ```javascript theme={"dark"} > > checkout.options = { > > submitButton: { > > useBuiltInButton: false > > } > > }; > > > > // Trigger submission from your button > > document.getElementById('my-button').addEventListener('click', () => { > > document.dispatchEvent(new CustomEvent('primer:card-submit', { > > bubbles: true, > > composed: true > > })); > > }); > > ``` > > > > > [External Submit Button Recipe](/docs/checkout/primer-checkout/guides-and-recipes/external-submit-button) > > > [accordion] Show Amount on Button > > > > Display the payment amount on the submit button: > > > > ```javascript theme={"dark"} > > checkout.options = { > > submitButton: { > > amountVisible: true > > } > > }; > > ``` > [tab] Android > > > [accordion] Custom Submit Button > > > > Override the submit button slot in `PrimerCardForm`: > > > > ```kotlin theme={"dark"} > > PrimerCardForm( > > controller = cardFormController, > > submitButton = { > > Button( > > onClick = { cardFormController.submit() }, > > enabled = formState.isFormValid && !formState.isLoading, > > ) { > > Text("Pay") > > } > > }, > > ) > > ``` > > > > > [External Submit Button Recipe](/docs/checkout/primer-checkout/guides-and-recipes/external-submit-button) > > > [accordion] Pay Button Text > > > > Set the text of the card form Pay button. Write `{amount}` where the order total should go, and the SDK fills it in with any card surcharge included: > > > > ```kotlin theme={"dark"} > > settings = PrimerSettings().apply { > > uiOptions.cardFormUIOptions = PrimerCardFormUIOptions( > > payButtonText = "Complete order {amount}", > > ) > > } > > ``` > > > > The button reads "Complete order £11.50". Without `{amount}` it shows no amount, and unset keeps "Pay". > > > [accordion] Google Pay with Shipping > > > > Configure Google Pay to collect billing address, email, and shipping: > > > > ```kotlin theme={"dark"} > > settings = PrimerSettings().apply { > > paymentMethodOptions.googlePayOptions = PrimerGooglePayOptions( > > merchantName = "My Store", > > captureBillingAddress = true, > > emailAddressRequired = true, > > shippingAddressParameters = PrimerGoogleShippingAddressParameters( > > phoneNumberRequired = true, > > ), > > requireShippingMethod = true, > > ) > > } > > ``` > > > [accordion] Stripe ACH Mandate > > > > Configure mandate data for Stripe ACH payments: > > > > ```kotlin theme={"dark"} > > settings = PrimerSettings().apply { > > paymentMethodOptions.stripeOptions = PrimerStripeOptions( > > mandateData = MandateData.TemplateMandateData(merchantName = "My Store"), > > ) > > } > > ``` > > > [accordion] 3DS Configuration > > > > Set the 3DS App Requestor URL: > > > > ```kotlin theme={"dark"} > > settings = PrimerSettings().apply { > > paymentMethodOptions.threeDsOptions = PrimerThreeDsOptions( > > threeDsAppRequestorUrl = "https://mystore.com", > > ) > > } > > ``` > [tab] iOS > > > [accordion] Inline Custom Layout > > > > `PrimerCheckout` renders the SDK's default screens. For a fully custom layout, hold a [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) as a `@StateObject`, compose the SwiftUI views you need, and wire them up with the `.primerCheckoutSession(_:theme:onCompletion:)` modifier: > > > > ```swift theme={"dark"} > > struct CustomCheckoutView: View { > > @StateObject private var session: PrimerCheckoutSession > > > > init(clientToken: String) { > > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > > } > > > > var body: some View { > > ScrollView { > > VStack(spacing: 24) { > > Text("Secure Checkout").font(.headline) > > PrimerPaymentMethods() > > PrimerCardForm() > > } > > .padding() > > } > > .primerCheckoutSession(session) { state in > > // The closure receives .failure for each failed payment attempt, so the shopper can retry. > > // It receives .success or .dismissed once. After either, or after a failed initialization, it receives nothing more. > > } > > } > > } > > ``` > > > [accordion] Pay Button Text > > > > Set the text of the card form Pay button. Write `{amount}` where the order total should go, and the SDK fills it in with any card surcharge included: > > > > ```swift theme={"dark"} > > let settings = PrimerSettings( > > uiOptions: PrimerUIOptions( > > cardFormUIOptions: PrimerCardFormUIOptions(payButtonText: "Complete order {amount}") > > ) > > ) > > ``` > > > > The button reads "Complete order £11.50". Without `{amount}` it shows no amount, and `nil` keeps "Pay". > > > [accordion] Custom Card Form Submit Button > > > > Override the `submitButton` slot on [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form). Each slot closure receives the active [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session), so you read `session.state` and call `session.submit()`: > > > > ```swift theme={"dark"} > > PrimerCardForm(submitButton: { session in > > Button("Pay Now") { > > session.submit() > > } > > .disabled(!session.state.isValid || session.state.isLoading) > > }) > > ``` > > > > The other slots (`cardDetails`, `billingAddress`) keep their `CardFormDefaults` styling. Place `PrimerCardForm` under the `.primerCheckoutSession` modifier so it resolves its session from the environment. > > > > > [Custom Submit Button Recipe](/docs/checkout/primer-checkout/guides-and-recipes/external-submit-button) *** ## See also > [card] [Web SDK Options Reference](/docs/sdk/primer-checkout-web/sdk-options-reference) > > Complete list of all available Web options > [card] [Android SDK Reference](/docs/sdk/android-checkout/v3.0.0-beta/api/overview) > > Android SDK API documentation > [card] [Events Guide](/docs/checkout/primer-checkout/configuration/events) > > Handle payment success, failure, and state changes > [card] [Styling](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Customize colors, fonts, and spacing # How Primer Checkout works Source: https://primer.io/docs/checkout/primer-checkout/core-concepts The component model, styling approach, and event-driven architecture behind Primer Checkout. ## What is a Primer Checkout component? Primer Checkout is built from reusable UI components. Each component represents a specific part of the checkout experience — such as the payment method selector, the card form, or the pay button — and is designed to be **configured, styled, and combined** without rewriting payment logic. You don't build a checkout from scratch. You assemble and customize trusted building blocks. ## What this means for you Using Primer Checkout components allows you to: * Integrate a full checkout UI without managing sensitive payment inputs * Customize layout and appearance without breaking functionality * Keep a predictable and stable integration over time * Upgrade components without refactoring your application ## Styling model > [tab] Web > > Each Primer component uses **Shadow DOM**, which isolates its internal HTML and CSS from your application. > > You **cannot** style internal component elements with CSS selectors. Instead, Primer exposes **CSS variables** as the official customization API: > > ```css theme={"dark"} > :root { > --primer-color-brand: #6c5ce7; > --primer-radius-small: 6px; > } > ``` > > This allows safe customization, consistent theming, and runtime updates without rebuilding components. > [tab] Android > > Styling is controlled through **design tokens** via the `PrimerTheme` data class. Tokens cover colors, spacing, typography, and shapes: > > ```kotlin theme={"dark"} > val theme = PrimerTheme( > lightColorTokens = object : LightColorTokens() { > override val primerColorBrand: Color = Color(0xFF6C5CE7) > }, > radiusTokens = RadiusTokens(medium = 12.dp), > ) > > PrimerCheckoutSheet(checkout = checkout, theme = theme) > ``` > > Token changes propagate to all SDK components automatically through `CompositionLocal`. This means you can apply a custom theme, and all Primer components will inherit the values. > [tab] iOS > > Styling is controlled through **design tokens** via the `PrimerCheckoutTheme` struct. Tokens cover colors (separately for light and dark mode), spacing, typography, radius, sizes, and border widths: > > ```swift theme={"dark"} > let theme = PrimerCheckoutTheme( > colors: ColorOverrides( > primerColorBrand: .init(.systemIndigo) > ), > radius: RadiusOverrides( > primerRadiusMedium: 12 > ) > ) > > PrimerCheckout(clientToken: clientToken, primerTheme: theme) > ``` > > Token changes propagate to all SDK components automatically. ## Content and layout customization Each platform provides a way to customize the content and layout of checkout components. > [tab] Web > > Slots are named placeholders inside Web Components: > > ```html theme={"dark"} > > > > > > > ``` > [tab] Android > > Slots are Compose lambda parameters on SDK composables: > > ```kotlin theme={"dark"} > PrimerCheckoutSheet( > checkout = checkout, > cardForm = { > val controller = rememberCardFormController(checkout) > PrimerCardForm( > controller = controller, > submitButton = { /* your custom button */ }, > ) > }, > success = { data -> /* your custom success screen */ }, > ) > ``` > [tab] iOS > > Slots are closures on the composable SwiftUI views: `PrimerCardForm`, `PrimerPaymentMethods`, and `PrimerVaultedPaymentMethods`. Most slots receive the relevant session (`PrimerCardFormSession` or `PrimerSelectionSession`) so you can read state and call actions from your own SwiftUI views. The `method` slot of `PrimerPaymentMethods` and the `item` and `submitButton` slots of `PrimerVaultedPaymentMethods` receive their item data and action instead. `PrimerCardForm` and `PrimerPaymentMethods` take `@ViewBuilder` closures. `PrimerVaultedPaymentMethods` slots return `AnyView`: > > ```swift theme={"dark"} > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > PrimerCardForm( > submitButton: { cardForm in > Button("Complete Purchase") { > cardForm.submit() > } > } > ) > PrimerPaymentMethods() > } > .primerCheckoutSession(session) { state in > handle(state) > } > } > ``` > > Override only the slots you need — every slot defaults to a `CardFormDefaults` / `PaymentMethodsDefaults` / `VaultedPaymentMethodsDefaults` builder, so unspecified sections keep their default styling. ## Communication: events Primer Checkout uses an **event-driven architecture** to communicate with your application. > [tab] Web > > Standard DOM events work with any framework: > > ```javascript theme={"dark"} > const checkout = document.querySelector('primer-checkout'); > > checkout.addEventListener('primer:payment-success', (event) => { > const { payment } = event.detail; > window.location.href = `/confirmation?order=${payment.orderId}`; > }); > ``` > > | Event | When it fires | > | - | - | > | `primer:ready` | SDK is initialized and ready | > | `primer:state-change` | Checkout state changes | > | `primer:payment-success` | Payment completed successfully | > | `primer:payment-failure` | Payment failed | > > For details, see the [Events Guide](/docs/checkout/primer-checkout/configuration/events). > [tab] Android > > Payment outcomes are terminal cases of the `PrimerCheckoutState` sealed interface, observed from `checkout.state`: > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { /* payment completed */ } > is PrimerCheckoutState.Failure -> { /* payment failed */ } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > ``` > > | State | When it emits | > | - | - | > | `PrimerCheckoutState.Success` | Payment completed | > | `PrimerCheckoutState.Failure` | Payment failed or error occurred | > [tab] iOS > > Outcomes are delivered through the `onCompletion` closure as `PrimerCheckoutState` values. Once the checkout is ready, `onCompletion` receives `.failure` for each failed payment attempt, and the checkout stays open for a retry. It then receives `.success` or `.dismissed` exactly once, and nothing after that. A failed initialization is also delivered as `.failure`. With `PrimerCheckout`, the SDK error screen offers a retry unless you set `isErrorScreenEnabled` to `false`. With inline checkout (`.primerCheckoutSession`), a failed initialization ends the session: > > ```swift theme={"dark"} > PrimerCheckout(clientToken: clientToken) { state in > switch state { > case let .success(result): > print("Payment completed: \(result.paymentId)") > case let .failure(error, _): > print("Payment failed: \(error.localizedDescription)") > case .dismissed: > print("Dismissed") > default: > break > } > } > ``` > > For inline checkout, attach `onCompletion` with the `.primerCheckoutSession(_:theme:onCompletion:)` modifier, and observe the session's `@Published` `phase` (type `Phase`, cases `.initializing`/`.ready`) to react to lifecycle changes. For per-feature field or selection state, observe the child sessions via `session.cardForm?.state` / `session.selection?.state`. > > | Mechanism | When it fires | > | - | - | > | `onCompletion: ((PrimerCheckoutState) -> Void)?` | `.failure` for each failed attempt, then `.success` or `.dismissed` once | > | Observing `session.phase` (`@Published`, type `Phase`) | Every lifecycle change (`.initializing`, `.ready`) | > > For details, see the [Events Guide](/docs/checkout/primer-checkout/configuration/events). ## What the SDK handles Primer Checkout handles this for you: * Payment method logic and processor communication * Input validation and error display * 3DS challenges and redirect flows * Loading states and visual feedback * Security and PCI compliance You focus on integration and UX, not infrastructure. ## Key takeaways * Primer Checkout is built from reusable, isolated components * Customization happens through configuration, layout customization, and styling tokens * Events provide decoupled communication between your app and the SDK ## See also > [card] [Styling](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Customize colors, fonts, and spacing > [card] [Layout](/docs/checkout/primer-checkout/build-your-ui/layout-customization) > > Control component arrangement and layout > [card] [Events](/docs/checkout/primer-checkout/configuration/events) > > Handle payment lifecycle events > [card] [Components](/docs/checkout/primer-checkout/configuration/components) > > Explore all available components # Accept your first payment Source: https://primer.io/docs/checkout/primer-checkout/first-payment Create a client session, render the checkout, listen for results, and test with sandbox cards. You've installed the SDK. You're ready to accept payments. ## The default payment flow When a customer reaches your checkout, here's what happens: ```mermaid theme={"dark"} sequenceDiagram participant User participant App as Your App participant SDK as Primer SDK participant Primer as Primer API participant PSP as Payment Processor App->>Primer: Create client session Primer-->>App: clientToken App->>SDK: Initialize checkout SDK->>Primer: Load payment methods Primer-->>SDK: Available methods User->>SDK: Selects payment method User->>SDK: Enters payment details SDK->>SDK: Validates input User->>SDK: Submits payment SDK->>Primer: Submit payment Primer->>PSP: Process payment PSP-->>Primer: Result Primer-->>SDK: Payment result SDK-->>App: Success / Failure ``` 1. **Your server creates a client session** and returns a `clientToken` 2. **The SDK initializes** and loads available payment methods 3. **Customer selects a method** and enters their details 4. **Customer submits** and the SDK processes the payment 5. **Your app receives the result** via events ## Create a Client Session (Server-Side) Create a client session on your server using the [Client Session API](/docs/checkout/client-session). This returns a `clientToken` that you pass to your client. ```bash theme={"dark"} curl -X POST https://api.primer.io/client-session \ -H "X-Api-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "orderId": "order-123", "currencyCode": "USD", "amount": 1000, "order": { "lineItems": [{ "itemId": "item-1", "description": "Widget", "amount": 1000, "quantity": 1 }] } }' ``` ## Initialize and Show Checkout > [tab] Web > > ```html theme={"dark"} > > ``` > > Listen for payment results: > > ```javascript theme={"dark"} > const checkout = document.querySelector('primer-checkout'); > > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > > primer.onPaymentSuccess = ({ payment }) => { > window.location.href = `/confirmation?order=${payment.orderId}`; > }; > > primer.onPaymentFailure = ({ error }) => { > console.error('Payment failed:', error.diagnosticsId); > }; > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > PrimerCheckoutSheet( > checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > ) > ) > ``` > [tab] iOS > > ```swift theme={"dark"} > import SwiftUI > import PrimerSDK > > struct CheckoutView: View { > let clientToken: String > > var body: some View { > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > switch state { > case .success(let result): > // Navigate to confirmation > print("Payment succeeded: \(result.paymentId)") > case let .failure(error, _): > print("Payment failed: \(error.localizedDescription)") > case .dismissed: > print("Checkout was dismissed") > default: > break > } > } > ) > } > } > ``` ## What Primer handles for you Out of the box, Primer Checkout manages: | Concern | What Primer Does | | - | - | | **Validation** | Real-time input validation with inline error messages | | **Error display** | Payment failures shown automatically in the UI | | **Redirects** | 3DS challenges, bank redirects, and wallet flows | | **Loading states** | Visual feedback during processing | | **Payment method logic** | Each method's specific requirements and flows | You don't need to write code for any of these behaviors. ## Listening for results To react to payment outcomes, listen for payment events: > [tab] Web > > ```javascript theme={"dark"} > const checkout = document.querySelector('primer-checkout'); > > checkout.addEventListener('primer:payment-success', (event) => { > const { payment } = event.detail; > window.location.href = `/confirmation?order=${payment.orderId}`; > }); > > checkout.addEventListener('primer:payment-failure', (event) => { > const { error } = event.detail; > // Error is already displayed in the checkout UI > console.error('Payment failed:', error.diagnosticsId); > }); > ``` > [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 > navController.navigate("confirmation/${payment.id}") > } > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Failed: ${s.primerError.diagnosticsId}") > } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > ``` > [tab] iOS > > ```swift theme={"dark"} > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > switch state { > case .success(let result): > // Navigate to confirmation screen > print("Payment succeeded: \(result.paymentId)") > case let .failure(error, _): > // Error is already displayed in the checkout UI > print("Payment failed: \(error.localizedDescription)") > case .dismissed: > print("Checkout was dismissed") > default: > break > } > } > ) > ``` > > | State | When it fires | > | - | - | > | `.success(PaymentResult)` | Payment completed successfully | > | `.failure(PrimerError, checkoutData)` | Fires once per failed attempt, including a failed initialization. By default, the SDK error screen stays open so the customer can retry. If you set `PrimerUIOptions(isErrorScreenEnabled: false)`, the SDK shows nothing and you decide what comes next. `checkoutData` carries the payment when one was created | > | `.dismissed` | The customer closed the checkout with the SDK's close button, which appears when `PrimerUIOptions(dismissalMechanism:)` includes `.closeButton`. If you present `PrimerCheckout` in your own sheet, dismissing that sheet does not deliver `.dismissed`, so handle it in your sheet's `onDismiss` | > > `onCompletion` never receives `.initializing` or `.ready`. `.success` or `.dismissed` arrives exactly once and ends the checkout. Nothing is delivered after it. ## Testing in sandbox Use these test cards to verify your integration: | Card Number | Result | | - | - | | `4111 1111 1111 1111` | Success | | `4000 0000 0000 0002` | Declined | Use any future expiry date and any 3-digit CVV. Try the Web SDK example in your browser: [![Try it in Stackblitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/primer-io/examples/tree/main/examples/primer-checkout-basic) ## See also > [card] [Styling](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Match the checkout to your brand > [card] [Layout](/docs/checkout/primer-checkout/build-your-ui/layout-customization) > > Control the structure of checkout components > [card] [Core Concepts](/docs/checkout/primer-checkout/core-concepts) > > Understand the architecture > [card] [Track in Analytics](/docs/checkout/primer-checkout/guides-and-recipes/track-payment-analytics) > > Send events to your analytics platform # React integration guide Source: https://primer.io/docs/checkout/primer-checkout/frameworks/react-integration-guide Integrate Primer Checkout with React 18 and React 19 applications. Primer Checkout uses Web Components, which work natively in React. This guide covers React-specific patterns for both React 18 and React 19. > [!NOTE] > > **Using Next.js?** See the [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) first—you'll need to load Primer on the client side only. ## Quick start Here's a minimal working example for React 19: ```tsx theme={"dark"} import { useEffect } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; // Define options outside component for stable reference const SDK_OPTIONS = { locale: 'en-GB' }; export function Checkout({ clientToken }: { clientToken: string }) { useEffect(() => { loadPrimer(); }, []); return ( ); } ``` For React 18, you need a ref to pass the `options` object. See [React 18 Pattern](#react-18-pattern) below. ## TypeScript setup TypeScript doesn't recognize custom web component tags by default. Add this declaration to your project: ```typescript theme={"dark"} // src/types/primer.d.ts import type { CheckoutElement } from '@primer-io/primer-js'; declare global { namespace JSX { interface IntrinsicElements { 'primer-checkout': CheckoutElement; } } } ``` Without this, you'll see "Property 'primer-checkout' does not exist" errors. > [accordion] Alternative: Import all Primer component types > > For projects using multiple Primer components: > > ```typescript theme={"dark"} > import { CustomElements } from '@primer-io/primer-js/dist/jsx/index'; > > declare module 'react' { > namespace JSX { > interface IntrinsicElements extends CustomElements {} > } > } > ``` ## React 18 vs React 19 The key difference is how you pass object properties to web components. > [tab] React 19 > > React 19 passes objects directly as properties: > > ```tsx theme={"dark"} > const SDK_OPTIONS = { locale: 'en-GB' }; > > function Checkout({ clientToken }: { clientToken: string }) { > return ( > client-token={clientToken} > options={SDK_OPTIONS} > /> > ); > } > ``` > [tab] React 18 > > React 18 converts objects to `[object Object]` strings. Use a ref instead: > > ```tsx theme={"dark"} > import { useRef, useEffect } from 'react'; > > const SDK_OPTIONS = { locale: 'en-GB' }; > > function Checkout({ clientToken }: { clientToken: string }) { > const checkoutRef = useRef(null); > > useEffect(() => { > if (checkoutRef.current) { > checkoutRef.current.options = SDK_OPTIONS; > } > }, []); > > return ( > ref={checkoutRef} > client-token={clientToken} > /> > ); > } > ``` | Aspect | React 18 | React 19 | | - | - | - | | How to pass `options` | ref + useEffect | JSX prop directly | | String attributes (`client-token`) | Works normally | Works normally | ## Handling payment events Listen for payment events to handle success and failure: > [tab] React 19 > > ```tsx theme={"dark"} > import { useEffect, useRef } from 'react'; > > const SDK_OPTIONS = { locale: 'en-GB' }; > > function Checkout({ clientToken }: { clientToken: string }) { > const checkoutRef = useRef(null); > > useEffect(() => { > const checkout = checkoutRef.current; > if (!checkout) return; > > const handleSuccess = (event: PrimerEvents['primer:payment-success']) => { > const { payment } = event.detail; > console.log('Payment successful:', payment.id); > window.location.href = `/confirmation?order=${payment.orderId}`; > }; > > const handleFailure = (event: PrimerEvents['primer:payment-failure']) => { > const { error } = event.detail; > console.error('Payment failed:', error.message); > // Error is displayed in checkout UI automatically > }; > > checkout.addEventListener('primer:payment-success', handleSuccess); > checkout.addEventListener('primer:payment-failure', handleFailure); > > return () => { > checkout.removeEventListener('primer:payment-success', handleSuccess); > checkout.removeEventListener('primer:payment-failure', handleFailure); > }; > }, []); > > return ( > ref={checkoutRef} > client-token={clientToken} > options={SDK_OPTIONS} > /> > ); > } > ``` > [tab] React 18 > > ```tsx theme={"dark"} > import { useEffect, useRef } from 'react'; > > const SDK_OPTIONS = { locale: 'en-GB' }; > > function Checkout({ clientToken }: { clientToken: string }) { > const checkoutRef = useRef(null); > > useEffect(() => { > const checkout = checkoutRef.current; > if (!checkout) return; > > // Set options (React 18 requires this) > checkout.options = SDK_OPTIONS; > > const handleSuccess = (event: PrimerEvents['primer:payment-success']) => { > const { payment } = event.detail; > console.log('Payment successful:', payment.id); > window.location.href = `/confirmation?order=${payment.orderId}`; > }; > > const handleFailure = (event: PrimerEvents['primer:payment-failure']) => { > const { error } = event.detail; > console.error('Payment failed:', error.message); > }; > > checkout.addEventListener('primer:payment-success', handleSuccess); > checkout.addEventListener('primer:payment-failure', handleFailure); > > return () => { > checkout.removeEventListener('primer:payment-success', handleSuccess); > checkout.removeEventListener('primer:payment-failure', handleFailure); > }; > }, []); > > return ( > ref={checkoutRef} > client-token={clientToken} > /> > ); > } > ``` ## Stable object references Define `options` objects outside your component or use `useMemo`. This avoids unnecessary work on every render. ```tsx theme={"dark"} // ✅ Good: Constant outside component const SDK_OPTIONS = { locale: 'en-GB' }; function Checkout() { return ; } // ✅ Good: useMemo for dynamic values function Checkout({ userLocale }: { userLocale: string }) { const options = useMemo(() => ({ locale: userLocale, }), [userLocale]); return ; } // ⚠️ Avoid: Inline objects (creates new reference every render) function Checkout() { return ; } ``` > [!NOTE] > > The SDK uses deep comparison, so inline objects won't break functionality. But stable references are still recommended to avoid comparison overhead on every render. ## Common patterns ### Show loading while checkout initializes ```tsx theme={"dark"} import { useState, useEffect, useRef } from 'react'; const SDK_OPTIONS = { locale: 'en-GB' }; function Checkout({ clientToken }: { clientToken: string }) { const [isReady, setIsReady] = useState(false); const checkoutRef = useRef(null); useEffect(() => { const checkout = checkoutRef.current; if (!checkout) return; const handleReady = () => setIsReady(true); checkout.addEventListener('primer:ready', handleReady); return () => checkout.removeEventListener('primer:ready', handleReady); }, []); return (
{!isReady &&
Loading checkout...
}
); } ``` ### Fetch client token from server ```tsx theme={"dark"} import { useState, useEffect } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; const SDK_OPTIONS = { locale: 'en-GB' }; function CheckoutPage() { const [clientToken, setClientToken] = useState(null); const [error, setError] = useState(null); useEffect(() => { loadPrimer(); async function fetchToken() { try { const response = await fetch('/api/create-client-session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ amount: 1000, currency: 'GBP', }), }); const data = await response.json(); setClientToken(data.clientToken); } catch (err) { setError('Failed to initialize checkout'); } } fetchToken(); }, []); if (error) return
{error}
; if (!clientToken) return
Loading...
; return ( ); } ``` ### Checkout in a modal ```tsx theme={"dark"} import { useEffect, useRef } from 'react'; const SDK_OPTIONS = { locale: 'en-GB' }; interface CheckoutModalProps { clientToken: string; isOpen: boolean; onClose: () => void; onSuccess: (payment: any) => void; } function CheckoutModal({ clientToken, isOpen, onClose, onSuccess }: CheckoutModalProps) { const checkoutRef = useRef(null); useEffect(() => { if (!isOpen) return; const checkout = checkoutRef.current; if (!checkout) return; const handleSuccess = (event: PrimerEvents['primer:payment-success']) => { const { payment } = event.detail; onSuccess(payment); onClose(); }; const handleFailure = (event: PrimerEvents['primer:payment-failure']) => { const { error } = event.detail; console.error('Payment failed:', error.message); }; checkout.addEventListener('primer:payment-success', handleSuccess); checkout.addEventListener('primer:payment-failure', handleFailure); return () => { checkout.removeEventListener('primer:payment-success', handleSuccess); checkout.removeEventListener('primer:payment-failure', handleFailure); }; }, [isOpen, onClose, onSuccess]); if (!isOpen) return null; return (
e.stopPropagation()}>
); } ``` ### Custom hook (optional) > [!NOTE] > > This pattern is **not required**. It's provided for teams who prefer encapsulating logic in reusable hooks. The examples above work perfectly without it. Encapsulate checkout logic in a reusable hook: ```tsx theme={"dark"} import { useRef, useEffect, useState, useCallback } from 'react'; interface UsePrimerCheckoutOptions { onSuccess?: (payment: any) => void; onFailure?: (error: any) => void; } function usePrimerCheckout(options: UsePrimerCheckoutOptions = {}) { const checkoutRef = useRef(null); const [isReady, setIsReady] = useState(false); const [isProcessing, setIsProcessing] = useState(false); useEffect(() => { const checkout = checkoutRef.current; if (!checkout) return; const handleReady = () => { setIsReady(true); }; const handleSuccess = (event: PrimerEvents['primer:payment-success']) => { const { payment } = event.detail; setIsProcessing(false); options.onSuccess?.(payment); }; const handleFailure = (event: PrimerEvents['primer:payment-failure']) => { const { error } = event.detail; setIsProcessing(false); options.onFailure?.(error); }; const handleStateChange = (event: PrimerEvents['primer:state-change']) => { setIsProcessing(event.detail.isProcessing); }; checkout.addEventListener('primer:ready', handleReady); checkout.addEventListener('primer:payment-success', handleSuccess); checkout.addEventListener('primer:payment-failure', handleFailure); checkout.addEventListener('primer:state-change', handleStateChange); return () => { checkout.removeEventListener('primer:ready', handleReady); checkout.removeEventListener('primer:payment-success', handleSuccess); checkout.removeEventListener('primer:payment-failure', handleFailure); checkout.removeEventListener('primer:state-change', handleStateChange); }; }, [options.onSuccess, options.onFailure]); return { checkoutRef, isReady, isProcessing }; } // Usage function Checkout({ clientToken }: { clientToken: string }) { const { checkoutRef, isReady, isProcessing } = usePrimerCheckout({ onSuccess: (payment) => { window.location.href = `/confirmation?order=${payment.orderId}`; }, onFailure: (error) => { console.error('Payment failed:', error.message); }, }); return (
{!isReady &&
Loading checkout...
} {isProcessing &&
Processing payment...
}
); } ``` ## Complete example A production-ready checkout component with all the patterns combined: ```tsx theme={"dark"} import { useEffect, useRef, useState, useMemo } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; // Types interface CheckoutProps { amount: number; currency: string; locale?: string; onSuccess?: (payment: any) => void; onFailure?: (error: any) => void; } // Load Primer SDK once at module level loadPrimer(); export function Checkout({ amount, currency, locale = 'en-GB', onSuccess, onFailure, }: CheckoutProps) { const checkoutRef = useRef(null); const [clientToken, setClientToken] = useState(null); const [isReady, setIsReady] = useState(false); const [error, setError] = useState(null); // Stable options reference - only changes when locale changes const options = useMemo(() => ({ locale }), [locale]); // Fetch client token useEffect(() => { async function fetchToken() { try { const response = await fetch('/api/create-client-session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ amount, currency }), }); if (!response.ok) throw new Error('Failed to create session'); const data = await response.json(); setClientToken(data.clientToken); } catch (err) { setError('Unable to initialize checkout. Please try again.'); } } fetchToken(); }, [amount, currency]); // Set up event handlers useEffect(() => { const checkout = checkoutRef.current; if (!checkout || !clientToken) return; // React 18: Set options via ref checkout.options = options; const handleReady = () => { setIsReady(true); }; const handleSuccess = (event: CustomEvent) => { const { payment } = event.detail; onSuccess?.(payment); }; const handleFailure = (event: CustomEvent) => { const { error } = event.detail; onFailure?.(error); }; checkout.addEventListener('primer:ready', handleReady); checkout.addEventListener('primer:payment-success', handleSuccess); checkout.addEventListener('primer:payment-failure', handleFailure); return () => { checkout.removeEventListener('primer:ready', handleReady); checkout.removeEventListener('primer:payment-success', handleSuccess); checkout.removeEventListener('primer:payment-failure', handleFailure); }; }, [clientToken, options, onSuccess, onFailure]); // Error state if (error) { return (

{error}

); } // Loading state if (!clientToken) { return
Preparing checkout...
; } return (
{!isReady &&
Loading payment methods...
}
); } ``` Usage: ```tsx theme={"dark"} function PaymentPage() { return ( { window.location.href = `/order/${payment.orderId}/confirmation`; }} onFailure={(error) => { console.error('Payment failed:', error.diagnosticsId); }} /> ); } ``` ## Quick reference | Scenario | Solution | | - | - | | Static options | Constant outside component | | Options depend on props | `useMemo` with dependencies | | React 18 object props | Use ref + useEffect | | React 19 object props | Pass directly in JSX | | Handle payment success | Listen for `primer:payment-success` event | | Track loading state | Listen for `primer:ready` event | | Track processing state | Listen for `primer:state-change` event | ## See also > [card] [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) > > Next.js, Nuxt, and SvelteKit patterns > [card] [SDK Options](/docs/checkout/primer-checkout/configuration/sdk-options) > > All configuration options > [card] [Events Guide](/docs/checkout/primer-checkout/configuration/events) > > Complete event reference > [card] [Styling](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Customize the appearance # Server-side rendering Source: https://primer.io/docs/checkout/primer-checkout/frameworks/ssr-guide Integrate Primer Checkout with Next.js, Nuxt.js, and SvelteKit Primer Checkout requires browser APIs and must be loaded on the client side only. This guide shows the patterns for each SSR framework. ## Quick Fix The core pattern is the same for all frameworks—load Primer inside a client-side lifecycle hook: ```javascript theme={"dark"} // Load Primer only on the client useEffect(() => { loadPrimer(); }, []); ``` That's it. The sections below show this pattern for each framework. ## Next.js ### App Router (Recommended) ```tsx theme={"dark"} 'use client'; import { useEffect } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; const SDK_OPTIONS = { locale: 'en-GB' }; export default function CheckoutPage() { useEffect(() => { loadPrimer(); }, []); return ( ); } ``` The `'use client'` directive marks the component as client-side only. ### Pages Router ```tsx theme={"dark"} import { useEffect } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; const SDK_OPTIONS = { locale: 'en-GB' }; export default function CheckoutPage() { useEffect(() => { if (typeof window !== 'undefined') { loadPrimer(); } }, []); return ( ); } ``` ### Using next/dynamic (Alternative) Disable SSR for the entire checkout component: ```tsx theme={"dark"} // components/Checkout.tsx 'use client'; import { useEffect } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; const SDK_OPTIONS = { locale: 'en-GB' }; export function Checkout({ clientToken }: { clientToken: string }) { useEffect(() => { loadPrimer(); }, []); return ( ); } ``` ```tsx theme={"dark"} // pages/checkout.tsx or app/checkout/page.tsx import dynamic from 'next/dynamic'; const Checkout = dynamic( () => import('@/components/Checkout').then((mod) => mod.Checkout), { ssr: false, loading: () =>
Loading checkout...
} ); export default function CheckoutPage() { return ; } ``` > [!NOTE] > > For React 18 vs 19 patterns and handling payment events, see the [React Integration Guide](/docs/checkout/primer-checkout/frameworks/react-integration-guide). ## Nuxt.js ### Nuxt 3 ```vue theme={"dark"} ``` > [!NOTE] > > Use `import.meta.client` in Nuxt 3. The older `process.client` still works but is a legacy pattern. > [accordion] Nuxt 2 Pattern > > ```vue theme={"dark"} > > > > ``` ## SvelteKit ```svelte theme={"dark"} ``` ## Show Loading State Use the `primer:ready` event to detect when the checkout is fully initialized: > [tab] Next.js > > ```tsx theme={"dark"} > 'use client'; > > import { useEffect, useState, useRef } from 'react'; > import { loadPrimer, PrimerCheckoutComponent } from '@primer-io/primer-js'; > > export default function CheckoutPage() { > const [isReady, setIsReady] = useState(false); > const checkoutRef = useRef(null); > > useEffect(() => { > loadPrimer(); > > const checkout = checkoutRef.current; > if (!checkout) return; > > const handleReady = () => setIsReady(true); > checkout.addEventListener('primer:ready', handleReady); > > return () => checkout.removeEventListener('primer:ready', handleReady); > }, []); > > return ( >
> {!isReady &&
Loading payment options...
} > ref={checkoutRef} > client-token="your-client-token" > style={{ display: isReady ? 'block' : 'none' }} > /> >
> ); > } > ``` > [tab] Nuxt 3 > > ```vue theme={"dark"} > > > > ``` > [tab] SvelteKit > > ```svelte theme={"dark"} > > >
> {#if !isReady} >
Loading payment options...
> {/if} > bind:this={checkoutEl} > client-token="your-client-token" > style:display={isReady ? 'block' : 'none'} > /> >
> ``` > [!NOTE] > > The `primer:ready` event fires when the checkout has fully initialized with payment methods. The checkout element must be in the DOM to receive a client token and initialize. ## Troubleshooting ### "customElements is not defined" Primer code is running on the server. **Fix:** Move `loadPrimer()` inside a client-side lifecycle hook (`useEffect`, `onMounted`, `onMount`). ### "window is not defined" Code is accessing browser globals during SSR. **Fix:** Add an environment check: ```javascript theme={"dark"} if (typeof window !== 'undefined') { // Browser-only code } ``` ### Components Don't Render The checkout needs a valid client token to initialize. **Fix:** Ensure you're passing a valid `client-token` attribute. Use the `primer:ready` event to detect when initialization is complete. See [Show Loading State](#show-loading-state) above. ### TypeScript Errors TypeScript doesn't recognize `` as a valid element. **Fix:** Add type declarations: ```typescript theme={"dark"} // src/types/primer.d.ts import { CustomElements } from '@primer-io/primer-js/dist/jsx/index'; declare module 'react' { namespace JSX { interface IntrinsicElements extends CustomElements {} } } ``` ## Why SSR Needs This > [accordion] Technical explanation > > Server-side rendering frameworks execute code on the server to generate HTML before sending it to the browser. Primer Checkout depends on browser-only APIs: > > * **Web Components API** – `customElements.define()` only exists in browsers > * **DOM APIs** – Component rendering requires the Document Object Model > * **Window Object** – Payment features depend on `window` and browser globals > * **Secure Iframes** – Card inputs require a browser environment > > When SSR frameworks try to execute Primer code on the server, they encounter errors because these APIs don't exist in Node.js. The solution is to ensure Primer only loads on the client side using lifecycle hooks that run after hydration. ## Next Steps > [card] [React Integration](/docs/checkout/primer-checkout/frameworks/react-integration-guide) > > React 18/19 patterns and event handling > [card] [Styling](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Customize the appearance > [card] [Events Guide](/docs/checkout/primer-checkout/configuration/events) > > Handle payment success and failure > [card] [Troubleshooting](/docs/checkout/primer-checkout/troubleshooting) > > More solutions for common issues # Glossary Source: https://primer.io/docs/checkout/primer-checkout/glossary Definitions of key terms used throughout the Primer Checkout documentation. A reference of terms used throughout the Primer Checkout documentation. If you encounter an unfamiliar term while reading another guide, you can look it up here. ## Primer Platform > [accordion] Client Session > > A server-side object you create through the [Primer API](/docs/checkout/client-session) before rendering the checkout. The client session holds everything Primer needs to present the correct payment experience: the order amount, currency, customer information, and which payment methods are available. Creating a client session returns a **client token**. > [accordion] Client Token > > A short-lived string returned when you [create a client session](/docs/checkout/client-session). You pass it to the checkout component to initialize the session. Its length is not fixed, so treat it as an opaque string and do not rely on a maximum length when storing it. > > > [tab] Web > > > > ```html theme={"dark"} > > > > ``` > > > [tab] Android > > > > ```kotlin theme={"dark"} > > val checkout = rememberPrimerCheckoutController(clientToken = "your-client-token") > > ``` > > > [tab] iOS > > > > ```swift theme={"dark"} > > PrimerCheckout(clientToken: "your-client-token") > > ``` > [accordion] Primer Dashboard > > The web interface where you configure your Primer account. From the Dashboard you can enable payment methods, set up processors, manage API keys, and configure checkout behavior — all without changing your frontend code. > [accordion] Diagnostics ID > > A unique identifier attached to every error the SDK produces. When you contact Primer support about a failed payment or unexpected behavior, include the `diagnosticsId` so the team can locate the exact request in their logs. > > > [tab] Web > > > > ```javascript theme={"dark"} > > checkout.addEventListener('primer:payment-failure', (event) => { > > const { error } = event.detail; > > console.error('Payment failed:', error.diagnosticsId); > > }); > > ``` > > > [tab] Android > > > > ```kotlin theme={"dark"} > > val state by checkout.state.collectAsStateWithLifecycle() > > > > LaunchedEffect(state) { > > val s = state > > if (s is PrimerCheckoutState.Failure) { > > Log.e("Checkout", "diagnosticsId: ${s.primerError.diagnosticsId}") > > } > > } > > ``` > > > [tab] iOS > > > > ```swift theme={"dark"} > > if case let .failure(error, _) = state { > > print("Payment failed: \(error.diagnosticsId)") > > } > > ``` ## SDK & Architecture > [accordion] Primer Checkout SDK > > The client-side package that provides checkout UI components, payment logic, and event system. Available for Web (`@primer-io/primer-js`), Android (`io.primer:checkout`), and iOS (`PrimerSDK`). > [accordion] Web Components (Web) > > A set of browser-native APIs for creating reusable, encapsulated UI elements. The Web SDK is built on Web Components, which means its elements (like `` and ``) work in any framework. See [Core Concepts](/docs/checkout/primer-checkout/core-concepts). > [accordion] Shadow DOM (Web) > > A browser feature that isolates a component's internal HTML and CSS from the rest of the page. Every Web SDK component uses Shadow DOM. Because external CSS selectors can't reach inside, you customize appearance through **CSS variables** instead. > [accordion] Controller (Android) > > A state holder created with a `remember*` function (e.g., `rememberPrimerCheckoutController()`). Provides observable state via `StateFlow` and action methods. Follows the standard Jetpack Compose pattern. > [accordion] Composable (Android) > > A Kotlin function annotated with `@Composable` that describes a piece of UI. All Android SDK components are Composables that integrate naturally with Jetpack Compose. > [accordion] StateFlow (Android) > > A Kotlin coroutines type for observable state. The SDK uses `StateFlow` for reactive UI updates. Collect with `collectAsStateWithLifecycle()` in Compose. > [accordion] Session (iOS) > > An observable, `@MainActor` object that owns the checkout lifecycle and exposes the state and actions for a specific part of the checkout. [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) owns the top-level lifecycle and is attached with the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. Per-feature sessions ([`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) and [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session)) are passed to the section slots of the composable views so you can read state and call actions from your custom UI. Examples are the `cardDetails`, `billingAddress` and `submitButton` slots of `PrimerCardForm`, and the `header` slot of `PrimerPaymentMethods`. > [accordion] @Published / ObservableObject (iOS) > > The SwiftUI mechanism the SDK uses to expose observable state. Each session is an `ObservableObject` whose `@Published` properties drive reactive UI updates. `PrimerCheckoutSession` publishes `phase` and `clientSession`. `PrimerCardFormSession` and `PrimerSelectionSession` publish `state`, and `PrimerSelectionSession` also publishes `vaultedPaymentMethods`. Observe a session with `@StateObject` (when you own it) or `@ObservedObject` (when it is passed into a slot), and read these properties directly in your view's `body`. > [accordion] PrimerCheckoutPresenter (iOS) > > A UIKit entry point class that presents the managed checkout modally from a `UIViewController` and delivers results through a [`PrimerCheckoutPresenterDelegate`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter). Use this when integrating the SDK in a UIKit-based app. > [accordion] Customization point > > A predefined area in a component where you can insert your own content. On Web, these are named HTML slot placeholders. On Android, these are `@Composable` lambda parameters (e.g., the `submitButton` parameter on `PrimerCardForm`). On iOS, these are slot parameters on the composable views (for example, the `submitButton` slot on `PrimerCardForm`). Section slots receive the relevant session so they can read state and call actions. Examples are the `cardDetails`, `billingAddress` and `submitButton` slots on `PrimerCardForm`, and the `header` and `emptyState` slots on `PrimerPaymentMethods`. Row slots, such as `method` on `PrimerPaymentMethods`, receive the row's data and a select action instead. > [accordion] Design Token > > A named value (color, spacing, font size, corner radius) used to style components consistently. On Web, these are CSS variables (e.g., `--primer-color-brand`). On Android, they are properties in `PrimerTheme`. On iOS, they are properties in `PrimerCheckoutTheme`. > [accordion] Defaults Object > > On Android, an object (e.g., `CardFormDefaults`, `PrimerCheckoutSheetDefaults`) that provides pre-built sub-components. Use them to customize specific parts while keeping others at their defaults. > > On iOS, the `CardFormDefaults`, `PaymentMethodsDefaults` and `VaultedPaymentMethodsDefaults` namespaces provide the default slot bodies and per-field building blocks. Examples are `CardFormDefaults.submitButton(_:)` and `CardFormDefaults.cardNumber(_:)`. > [accordion] Hosted Input (Web) > > A card input field that renders inside a secure iframe managed by Primer. Sensitive card data never touches your page's DOM, keeping your integration PCI-compliant. ## Payment Concepts > [accordion] Payment Method > > A way for a customer to pay — for example, a credit card, PayPal, Apple Pay, or Google Pay. Available payment methods are configured in the Primer Dashboard and delivered to the SDK through the client session. Each method has a type string such as `PAYMENT_CARD`, `PAYPAL`, or `APPLE_PAY`. > [accordion] Vault / Vaulted Payment Methods > > Primer's system for securely storing a customer's payment details for future use. When vaulting is enabled, returning customers can pay with a saved card or payment method without re-entering their details. On Web, the SDK exposes vault data through the `primer:vault-methods-update` event and the `` component. On iOS, read `vaultedPaymentMethods` on `PrimerSelectionSession`, which is also available as `selection` on your `PrimerCheckoutSession`. Call `selectVaulted(_:)` to pay with a saved method and `delete(_:)` to remove one. You can also render the `PrimerVaultedPaymentMethods` view. It shows the selected saved method with a way to open the full list. See [SDK Options — Vault](/docs/checkout/primer-checkout/configuration/sdk-options). > [accordion] Payment Instrument Data > > The details associated with a saved (vaulted) payment method. For a stored card this includes properties like `network` (e.g. `VISA`), `last4Digits`, `expirationMonth`, and `expirationYear`. You access it via the `paymentInstrumentData` property on a vaulted payment object. > [accordion] PCI Compliance > > The Payment Card Industry Data Security Standard (PCI DSS). Primer Checkout handles card data securely so that sensitive information never enters your application, significantly reducing your PCI compliance scope. > [accordion] 3DS (3D Secure) > > An authentication protocol that adds a verification step during card payments, typically a bank-issued challenge screen or biometric prompt. Primer Checkout handles 3DS flows automatically with no additional code required. > [accordion] AUTO Payment Handling > > The default payment flow where the SDK processes the payment end-to-end. You receive success or failure events. On Web, this is the default mode. On Android, the composable module operates exclusively in AUTO mode. On iOS, the SDK also operates exclusively in AUTO mode. If you start it with `PrimerSettings(paymentHandling: .manual)`, it fails and reports a `.failure`. With `PrimerCheckoutSession`, that `.failure` ends the session. > [accordion] Co-badge > > A card that belongs to multiple card networks (e.g., both Visa and Cartes Bancaires). The SDK shows a network selector for co-badged cards. ## Events > [accordion] primer:ready > > The event fired when the SDK has fully initialized and is ready for interaction. Inside this event's handler you access the PrimerJS instance (`event.detail`) which provides SDK methods like `refreshSession()`, `getPaymentMethods()`, and `setCardholderName()`. See [Events Guide](/docs/checkout/primer-checkout/configuration/events). > > On Android, the equivalent is observing `checkout.state` for `PrimerCheckoutState.Ready` via `StateFlow`. > > On iOS, observe `phase` on your `PrimerCheckoutSession` and wait for `.ready`. From then on, `clientSession` is set. `onCompletion` only delivers outcomes (`.failure`, `.success` and `.dismissed`), never `.initializing` or `.ready`. > [accordion] primer:payment-success / primer:payment-failure > > The events fired after a payment completes. `primer:payment-success` fires after a successful payment and the event detail includes the payment summary (order ID, last 4 digits, network). `primer:payment-failure` fires after a failed payment and includes the error object with the `diagnosticsId`. These are your primary integration points for redirects, confirmations, and error logging. > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-success', (event) => { > const { payment } = event.detail; > window.location.href = `/confirmation?order=${payment.orderId}`; > }); > > checkout.addEventListener('primer:payment-failure', (event) => { > const { error } = event.detail; > console.error('Payment failed:', error.diagnosticsId); > }); > ``` > > On Android, observe `checkout.state` and handle the terminal `PrimerCheckoutState.Success` and `PrimerCheckoutState.Failure` cases. > > On iOS, results arrive as a [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) in the `onCompletion` closure on `PrimerCheckout` or the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. `.failure(error, checkoutData)` arrives once for each failed payment attempt, and the checkout stays open for a retry. The final `.success(result)` or `.dismissed` then arrives exactly once. With `PrimerCheckoutSession`, a failure during initialization arrives as a single `.failure` and ends the session. No retry screen appears, and no other outcome follows. In UIKit, implement these methods on the [`PrimerCheckoutPresenterDelegate`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter): `primerCheckoutPresenterDidCompleteWithSuccess(_:)`, `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` and `primerCheckoutPresenterDidDismiss()`. The delegate methods follow the same rules. > [accordion] primer:payment-start > > The event fired when payment creation begins. You can intercept this event with `event.preventDefault()` to run validation before the payment is created. The event detail includes `continuePaymentCreation()` and `abortPaymentCreation()` handlers to control the payment flow. See [Events Guide](/docs/checkout/primer-checkout/configuration/events) for usage. > > On Android, payment interception is not available in the Composable module. Use the headless API (`onBeforePaymentCreated`) if you need this capability. > > On iOS, payment interception is available only in the inline integration. Set the `onBeforePaymentCreate` handler on the [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). It runs before every payment, saved payment methods included. Its decision handler lets you supply an idempotency key or abort payment creation. `PrimerCheckout` and `PrimerCheckoutPresenter` do not expose it. ## Integration Modes > [accordion] Drop-in (Sheet / Full Component) > > An integration mode that provides a complete checkout flow with minimal code. On Web, use ``. On Android, use `PrimerCheckoutSheet`. On iOS, use `PrimerCheckout` as a SwiftUI view or `PrimerCheckoutPresenter` for UIKit. The SDK handles navigation between screens. > [accordion] Inline (Custom Layout) > > An integration mode where you embed individual checkout components in your own layout. On Web, use individual components like ``. On Android, use `PrimerCheckoutHost` with child composables. On iOS, hold a `PrimerCheckoutSession` and apply the `.primerCheckoutSession(_:theme:onCompletion:)` modifier, then place composable views like `PrimerCardForm` and `PrimerPaymentMethods` in your own layout — override their `@ViewBuilder` slots to build custom forms. You control navigation and layout. On iOS, the SDK still presents follow-up screens in its own sheet over your content. These are the processing, success and failure screens, native payment method screens such as Klarna or ACH, saved payment method management, and CVV entry. # Build a custom card form Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form Step-by-step guide to creating and customizing your own card payment form with Primer Checkout. This tutorial walks you through building a custom card form with Primer Checkout. You'll learn how to customize the layout, style the inputs, handle events, and avoid common pitfalls. ## Prerequisites Before starting, make sure you have: > [tab] Web > > * [Installed Primer Checkout](/docs/checkout/primer-checkout/installation) > * [Created your first payment](/docs/checkout/primer-checkout/first-payment) > * Familiarity with [layout customization](/docs/checkout/primer-checkout/build-your-ui/layout-customization) > [tab] Android > > * A working checkout integration ([First Payment](/docs/checkout/primer-checkout/first-payment)) > * Familiarity with the [controller pattern](/docs/checkout/primer-checkout/core-concepts) > * Understanding of [PrimerCheckoutHost](/docs/checkout/primer-checkout/build-your-ui/layout-customization) for inline integration > [tab] iOS > > * A working checkout integration ([First Payment](/docs/checkout/primer-checkout/first-payment)) > * Familiarity with [layout customization](/docs/checkout/primer-checkout/build-your-ui/layout-customization) > * Understanding of `PrimerCardForm` and its `@ViewBuilder` slots for card form control ## Understanding the card form architecture > [tab] Web > > The `` component provides a customizable card payment interface with PCI-compliant hosted inputs. Here's how the components relate to each other: > > slot: name > > Exposes a customizable slot > > → name > > Default content, replaced when you customize the slot > > > [!NOTE] > > > > **Security by design** > > > > The card input components (`primer-input-card-number`, `primer-input-card-expiry`, `primer-input-cvv`) render secure iframes that isolate sensitive card data. This means: > > > > * Card data never touches your page's DOM > > * Your integration remains PCI-compliant > > * Styling is applied through CSS variables that are passed to the iframe > > ### Key components > > | Component | Purpose | > | - | - | > | `primer-card-form` | Container that provides context for all card inputs | > | `primer-input-card-number` | Secure hosted input for card number | > | `primer-input-card-expiry` | Secure hosted input for expiry date | > | `primer-input-cvv` | Secure hosted input for CVV | > | `primer-input-card-holder-name` | Input for cardholder name (optional) | > | `primer-card-form-submit` | Submit button with built-in loading states | > [tab] Android > > The `PrimerCardFormController` gives you full control over the card form. You create the controller, observe its state, and build your own UI with custom `TextField` inputs bound to the controller. > > ### Key state properties > > | Property | Type | Description | > | - | - | - | > | `data` | `Map` | Current field values | > | `fieldErrors` | `List?` | Validation errors per field | > | `isFormValid` | `Boolean` | Whether all required fields pass validation | > | `isLoading` | `Boolean` | Whether a submission is in progress | > [tab] iOS > > `PrimerCardForm` is a SwiftUI view that gives you full control over the card form through three `@ViewBuilder` section slots: `cardDetails`, `billingAddress`, and `submitButton`. Each slot receives a `PrimerCardFormSession`, which publishes the form `state` and exposes the field-update and `submit()` methods. Compose your layout from the `CardFormDefaults` per-field building blocks (`cardNumber`, `expiryDate`, `cvv`, `cardholderName`). Primer handles validation, formatting, and PCI compliance. > > ### Key state properties > > The session exposes its state through `session.state`, a `PrimerCardFormState`: > > | Property | Type | Description | > | - | - | - | > | `isValid` | `Bool` | Whether all required fields pass validation | > | `isLoading` | `Bool` | Whether a submission is in progress | > | `fieldErrors` | `[FieldError]` | Validation errors per field | > | `data` | `FormData` | Current field values keyed by `PrimerInputElementType`. The card number is masked to its first six and last four digits, for example `424242••••••4242`. A number of 10 digits or fewer keeps only the last four. The CVV is always empty | ## Step 1: Create the card form > [tab] Web > > Start by creating a custom card form using the `card-form-content` slot: > > ```html theme={"dark"} > > >
> >
> > > > > Pay Now >
>
>
>
>
> ``` > > > [!WARNING] > > > > **Component hierarchy matters** > > > > All card input components must be nested inside ``. Placing them outside breaks the context connection and the form won't work. > > > > ```html theme={"dark"} > > > > > > > > > > > > > >
> > > >
> >
> > ``` > [tab] Android > > Create a `PrimerCardFormController` inside a `PrimerCheckoutHost`. The controller manages field values, validation, and submission. > > ```kotlin theme={"dark"} > @Composable > fun CustomCardFormScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val checkoutState by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(checkoutState) { > when (val s = checkoutState) { > is PrimerCheckoutState.Success -> { /* navigate */ } > is PrimerCheckoutState.Failure -> { /* log error */ } > else -> Unit > } > } > > when (checkoutState) { > is PrimerCheckoutState.Loading -> CircularProgressIndicator() > is PrimerCheckoutState.Ready -> { > PrimerCheckoutHost(checkout = checkout) { > val cardFormController = rememberCardFormController(checkout) > CustomCardForm(cardFormController) > } > } > } > } > ``` > [tab] iOS > > Hold a `PrimerCheckoutSession` as a `@StateObject` and place a `PrimerCardForm` inside a view that has the `.primerCheckoutSession(_:theme:onCompletion:)` modifier applied. `PrimerCardForm` resolves its `PrimerCardFormSession` from the environment, so it works inline anywhere under the modifier. > > ```swift theme={"dark"} > struct CustomCardFormScreen: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > PrimerCardForm() > } > .primerCheckoutSession(session) { state in > // Handle .success, .failure and .dismissed > } > } > } > ``` > > > [!WARNING] > > > > **Session resolution matters** > > > > `PrimerCardForm` and its slots resolve the active `PrimerCardFormSession` from the environment. Place the form inside a view that has the `.primerCheckoutSession(_:theme:onCompletion:)` modifier applied, or the form renders an empty placeholder. ## Step 2: Customize the layout > [tab] Web > > ### Vertical layout (default) > > Stack inputs vertically for a clean, mobile-friendly form: > > ```html theme={"dark"} > >
> > > > > Pay Now >
>
> ``` > > ```css theme={"dark"} > .card-form-vertical { > display: flex; > flex-direction: column; > gap: var(--primer-space-small); > } > ``` > > ### Grouped layout > > Place expiry and CVV side by side: > > ```html theme={"dark"} > >
> >
> > >
> > Pay Now >
>
> ``` > > ```css theme={"dark"} > .card-form-grouped { > display: flex; > flex-direction: column; > gap: var(--primer-space-small); > } > > .card-form-grouped .row { > display: flex; > gap: var(--primer-space-small); > } > > .card-form-grouped .row > * { > flex: 1; > } > ``` > > ### Responsive layout > > Adapt the layout based on screen size: > > ```css theme={"dark"} > .card-form-responsive { > display: flex; > flex-direction: column; > gap: var(--primer-space-small); > } > > .card-form-responsive .row { > display: flex; > flex-direction: column; > gap: var(--primer-space-small); > } > > @media (min-width: 480px) { > .card-form-responsive .row { > flex-direction: row; > } > > .card-form-responsive .row > * { > flex: 1; > } > } > ``` > [tab] Android > > Observe form state and bind each `OutlinedTextField` to the controller's update methods. The controller handles formatting (card number grouping, expiry date slashes) internally. > > ```kotlin theme={"dark"} > @Composable > fun CustomCardForm(controller: PrimerCardFormController) { > val formState by controller.state.collectAsStateWithLifecycle() > > Column( > modifier = Modifier.padding(16.dp), > verticalArrangement = Arrangement.spacedBy(12.dp), > ) { > OutlinedTextField( > value = formState.data[PrimerInputElementType.CARD_NUMBER].orEmpty(), > onValueChange = { controller.updateCardNumber(it) }, > label = { Text("Card number") }, > isError = hasFieldError(formState, PrimerInputElementType.CARD_NUMBER), > supportingText = fieldErrorText(formState, PrimerInputElementType.CARD_NUMBER), > keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), > singleLine = true, > modifier = Modifier.fillMaxWidth(), > ) > > Row( > modifier = Modifier.fillMaxWidth(), > horizontalArrangement = Arrangement.spacedBy(12.dp), > ) { > OutlinedTextField( > value = formState.data[PrimerInputElementType.EXPIRY_DATE].orEmpty(), > onValueChange = { controller.updateExpiryDate(it) }, > label = { Text("MM/YY") }, > isError = hasFieldError(formState, PrimerInputElementType.EXPIRY_DATE), > supportingText = fieldErrorText(formState, PrimerInputElementType.EXPIRY_DATE), > keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), > singleLine = true, > modifier = Modifier.weight(1f), > ) > OutlinedTextField( > value = formState.data[PrimerInputElementType.CVV].orEmpty(), > onValueChange = { controller.updateCvv(it) }, > label = { Text("CVV") }, > isError = hasFieldError(formState, PrimerInputElementType.CVV), > supportingText = fieldErrorText(formState, PrimerInputElementType.CVV), > keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), > singleLine = true, > modifier = Modifier.weight(1f), > ) > } > > OutlinedTextField( > value = formState.data[PrimerInputElementType.CARDHOLDER_NAME].orEmpty(), > onValueChange = { controller.updateCardholderName(it) }, > label = { Text("Cardholder name") }, > isError = hasFieldError(formState, PrimerInputElementType.CARDHOLDER_NAME), > supportingText = fieldErrorText(formState, PrimerInputElementType.CARDHOLDER_NAME), > keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Words), > singleLine = true, > modifier = Modifier.fillMaxWidth(), > ) > } > } > ``` > [tab] iOS > > Override the `cardDetails` slot and recompose the form from the `CardFormDefaults` per-field building blocks. Each block keeps the SDK's formatting, validation, and inline error display, and is self-hiding when its field is not part of the active configuration. > > ### Vertical layout > > ```swift theme={"dark"} > PrimerCardForm(cardDetails: { session in > VStack(spacing: 16) { > CardFormDefaults.cardNumber(session) > CardFormDefaults.expiryDate(session) > CardFormDefaults.cvv(session) > CardFormDefaults.cardholderName(session) > } > .padding() > }) > ``` > > ### Grouped layout > > Place expiry and CVV side by side: > > ```swift theme={"dark"} > PrimerCardForm(cardDetails: { session in > VStack(spacing: 16) { > CardFormDefaults.cardNumber(session) > > HStack(spacing: 12) { > CardFormDefaults.expiryDate(session) > CardFormDefaults.cvv(session) > } > > CardFormDefaults.cardholderName(session) > } > }) > ``` > > > [!NOTE] > > > > `CardFormDefaults.cardNumber(session)` keeps the co-badged network selector inside the card number field, so a recomposed layout handles co-badged cards without extra work. Do not add `CardFormDefaults.cardNetwork(session)` next to it, or two selectors appear. The submit button stays at its default `CardFormDefaults.submitButton` unless you also override the `submitButton` slot. ## Step 3: Style the inputs > [tab] Web > > Style card inputs using CSS variables. These properties are passed through to the secure iframes: > > ```css theme={"dark"} > primer-card-form { > /* Input styling */ > --primer-input-height: 48px; > --primer-input-padding: 12px 16px; > --primer-input-border-radius: 8px; > > /* Colors */ > --primer-color-background-input-default: #ffffff; > --primer-color-border-input-default: #e0e0e0; > --primer-color-border-input-focus: #2f98ff; > --primer-color-border-input-error: #f44336; > > /* Typography */ > --primer-input-font-size: 16px; > --primer-input-font-family: system-ui, sans-serif; > --primer-color-text-input: #333333; > --primer-color-text-placeholder: #999999; > } > ``` > > > [!NOTE] > > > > For a complete list of CSS variables, see the [Styling guide](/docs/checkout/primer-checkout/build-your-ui/styling-customization). > > ### Adding custom labels > > Wrap inputs with labels for better accessibility: > > ```html theme={"dark"} > >
> > >
> > > >
> > > > Pay Now >
>
> ``` > > ```css theme={"dark"} > .input-group { > display: flex; > flex-direction: column; > gap: 4px; > } > > .label-text { > font-size: 14px; > font-weight: 500; > color: var(--primer-color-text-primary); > } > ``` > [tab] Android > > Handle validation errors by extracting error messages from `fieldErrors` to display under each field: > > ```kotlin theme={"dark"} > private fun hasFieldError( > state: PrimerCardFormController.State, > type: PrimerInputElementType, > ): Boolean { > return state.fieldErrors?.any { it.inputElementType == type } == true > } > > private fun fieldErrorText( > state: PrimerCardFormController.State, > type: PrimerInputElementType, > ): (@Composable () -> Unit)? { > val error = state.fieldErrors?.firstOrNull { it.inputElementType == type } > return error?.let { > { Text(it.errorId) } > } > } > ``` > > > [!NOTE] > > > > Validation errors appear after the user leaves a field (on blur), not while typing. The SDK handles this timing internally. > [tab] iOS > > Field visual styling is theme-driven. Pass a `PrimerCheckoutTheme` to the session and the `CardFormDefaults` fields pick up its design tokens (colors, spacing, typography, and shape) automatically — there is no per-field styling struct. > > ```swift theme={"dark"} > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject( > wrappedValue: PrimerCheckoutSession( > clientToken: clientToken, > theme: PrimerCheckoutTheme() > ) > ) > } > ``` > > > [!NOTE] > > > > Validation errors appear automatically beneath each field. The SDK handles error timing -- errors show after the user leaves a field, not while typing. For the full list of design tokens, see the [PrimerCheckoutTheme reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme). ## Step 4: Handle events and submission > [tab] Web > > Listen for events to provide feedback and handle the payment flow: > > ```javascript theme={"dark"} > const cardForm = document.querySelector('primer-card-form'); > > // Handle validation errors > cardForm.addEventListener('primer:card-error', (event) => { > const { inputType, error } = event.detail; > console.log(`Error in ${inputType}: ${error.message}`); > > // Show error feedback to user > showFieldError(inputType, error.message); > }); > > // Handle successful validation > cardForm.addEventListener('primer:card-success', (event) => { > const { inputType } = event.detail; > console.log(`${inputType} is valid`); > > // Clear any previous error > clearFieldError(inputType); > }); > ``` > > > [!NOTE] > > > > For comprehensive event handling patterns, see the [Events guide](/docs/checkout/primer-checkout/configuration/events). > > ### Programmatic submission > > You can submit the card form programmatically instead of using the built-in submit button: > > ```javascript theme={"dark"} > const cardForm = document.querySelector('primer-card-form'); > > // Your custom submit button > document.getElementById('my-submit-button').addEventListener('click', async () => { > try { > await cardForm.submit(); > } catch (error) { > console.error('Submission failed:', error); > } > }); > ``` > > ### Setting cardholder name programmatically > > If you collect the cardholder name elsewhere (e.g., from a shipping form), you can set it programmatically: > > ```javascript theme={"dark"} > const cardForm = document.querySelector('primer-card-form'); > > // Set cardholder name from your form > const name = document.getElementById('shipping-name').value; > cardForm.setCardholderName(name); > ``` > > > [!NOTE] > > > > When using `setCardholderName()`, you don't need to include the `` component in your form. > > ### Focusing the form > > The SDK never moves focus into the card form on its own. When the form is revealed by your UI, for example behind a "Pay with a new card" toggle, focus it once it is visible: > > ```javascript theme={"dark"} > const cardForm = document.querySelector('primer-card-form'); > > showCardSection(); > cardForm.focus(); // first field in render order > ``` > > To target one input, call `focus()` on it directly, for example `document.querySelector('primer-input-card-number').focus()`. In any layout, `primer.cardForm?.focus()` from the `primer:ready` instance does the same, which is the only way to reach the form when the SDK renders it inside its own UI. > [tab] Android > > Call `controller.submit()` to tokenize the card data. Disable the button when the form is invalid or a submission is in progress: > > ```kotlin theme={"dark"} > Button( > onClick = { controller.submit() }, > enabled = formState.isFormValid && !formState.isLoading, > modifier = Modifier.fillMaxWidth(), > ) { > if (formState.isLoading) { > CircularProgressIndicator( > modifier = Modifier.size(20.dp), > color = Color.White, > strokeWidth = 2.dp, > ) > } else { > Text("Pay") > } > } > ``` > [tab] iOS > > Override the `submitButton` slot and call `session.submit()` to tokenize the card data. Read `session.state` to control the button and show loading: > > ```swift theme={"dark"} > PrimerCardForm(submitButton: { session in > Button(action: { session.submit() }) { > if session.state.isLoading { > ProgressView() > .tint(.white) > } else { > Text("Pay now") > } > } > .frame(maxWidth: .infinity, minHeight: 48) > .buttonStyle(.borderedProminent) > .disabled(!session.state.isValid || session.state.isLoading) > }) > ``` > > While a payment runs (`session.state.isLoading` is `true`), the SDK disables the card and billing address fields you compose from `CardFormDefaults`. It ignores further `submit()` calls, so a double tap starts only one payment. It ignores `session.cancel()` until the payment ends, because a running payment cannot be stopped. > > ### Pre-filling cardholder name > > If you already know the name, pre-fill it from the session. Keep `CardFormDefaults.cardholderName(session)` in your layout. The form becomes valid only after the SDK's cardholder name field validates the value. A name set without the field leaves `session.state.isValid` false. > > ```swift theme={"dark"} > session.updateCardholderName("Jane Doe") > ``` > > > [!NOTE] > > > > When billing fields come entirely from your own data, replace the `billingAddress` slot. Return `EmptyView()`, or compose only the `CardFormDefaults` billing building blocks you want. Then push the values through the session's `update*` methods. Keep the card field building blocks (`cardNumber`, `expiryDate`, `cvv`, `cardholderName`) in your layout: `session.state.isValid` only becomes `true` after each of them has validated its value. The billing address is sent with the payment only when a postal code is set. ## Step 5: Handle payment completion > [tab] Web > > Listen for the checkout state to handle successful payments: > > ```javascript theme={"dark"} > const checkout = document.querySelector('primer-checkout'); > > checkout.addEventListener('primer:state-change', (event) => { > const state = event.detail; > > if (state.isSuccessful) { > // Payment completed successfully > showSuccessMessage(); > redirectToConfirmation(); > } > > if (state.paymentFailure) { > // Payment failed > showErrorMessage(state.paymentFailure.message); > } > }); > ``` > [tab] Android > > Handle payment outcomes by observing `checkout.state`: > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { > Log.d("Checkout", "Payment ID: ${s.checkoutData.payment.id}") > } > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Diagnostics: ${s.primerError.diagnosticsId}") > } > else -> Unit > } > } > > PrimerCheckoutHost(checkout = checkout) { > // Card form content > } > ``` > [tab] iOS > > Use the `onCompletion` closure on the `.primerCheckoutSession(_:theme:onCompletion:)` modifier to handle the checkout outcome. Once the checkout is ready, `.failure` arrives once per failed attempt and the form stays usable so the shopper can retry. `.success` or `.dismissed` ends the session and arrives once. A `.failure` while the session is still initializing also ends it: > > ```swift theme={"dark"} > ScrollView { > PrimerCardForm() > } > .primerCheckoutSession(session) { state in > switch state { > case let .success(result): > print("Payment ID: \(result.paymentId)") > case let .failure(error, _): > print("Error: \(error.localizedDescription)") > case .dismissed: > break > default: > break > } > } > ``` ## Common mistakes to avoid > [tab] Web > > > [accordion] Duplicate card forms > > > > Don't include both `` and `` in your layout. The payment method component already renders a card form internally. > > > > ```html theme={"dark"} > > > >
> > ... > > > >
> > > > > >
> > ... > > > >
> > ``` > > > [accordion] Inputs outside the form context > > > > Card input components must be descendants of ``. They won't work if placed outside. > > > > ```html theme={"dark"} > > > >
> > > > > >
> > > > > > > >
> > > >
> >
> > ``` > > > [accordion] Dynamic rendering timing issues > > > > When rendering card forms dynamically, ensure the parent `` exists before adding input children: > > > > ```javascript theme={"dark"} > > // WRONG: Adding inputs before the form > > container.innerHTML = ` > > > > > > `; > > > > // CORRECT: Form first, then inputs > > container.innerHTML = ` > > > >
> > > >
> >
> > `; > > ``` > > > [accordion] Missing slot attribute > > > > When customizing the card form layout, always use the `card-form-content` slot: > > > > ```html theme={"dark"} > > > > > >
> > > >
> >
> > > > > > > >
> > > >
> >
> > ``` > [tab] Android > > > [accordion] Forgetting to observe state > > > > Always collect the controller's state using `collectAsStateWithLifecycle()`. Without it, your UI won't update when the user types or when validation changes. > > > > ```kotlin theme={"dark"} > > // WRONG: State not observed > > val formState = controller.state.value > > > > // CORRECT: State observed reactively > > val formState by controller.state.collectAsStateWithLifecycle() > > ``` > > > [accordion] Creating the controller outside PrimerCheckoutHost > > > > The card form controller must be created within the `PrimerCheckoutHost` or `PrimerCheckoutSheet` scope. > > > > ```kotlin theme={"dark"} > > // WRONG: Controller outside host > > val controller = rememberCardFormController(checkout) > > PrimerCheckoutHost(checkout = checkout) { > > CustomCardForm(controller) > > } > > > > // CORRECT: Controller inside host > > PrimerCheckoutHost(checkout = checkout) { > > val controller = rememberCardFormController(checkout) > > CustomCardForm(controller) > > } > > ``` > [tab] iOS > > > [accordion] Using the session from the wrong slot > > > > Use the `PrimerCardFormSession` passed into each slot closure. It is the session for the form you are rendering, and the form keeps passing you the current one when the checkout restarts. `checkoutSession.cardForm` is `nil` until the checkout is ready. The SDK replaces its value when the checkout restarts. Fields built from a session you kept elsewhere stay bound to the old session, not to the form on screen. > > > > ```swift theme={"dark"} > > // WRONG: Building a field from an unrelated session reference > > PrimerCardForm(cardDetails: { session in > > VStack { > > CardFormDefaults.cardNumber(otherSession) // Wrong session > > } > > }) > > > > // CORRECT: Use the session parameter from this slot > > PrimerCardForm(cardDetails: { session in > > VStack { > > CardFormDefaults.cardNumber(session) > > } > > }) > > ``` > > > [accordion] Not observing state in a custom subview > > > > When you extract a slot into its own `View`, mark the captured session as `@ObservedObject`. Without it, your UI won't update when validation changes. > > > > ```swift theme={"dark"} > > // WRONG: Session not observed — button never re-evaluates > > struct SubmitButton: View { > > let session: PrimerCardFormSession > > var body: some View { > > Button("Pay") { session.submit() } > > .disabled(false) // Always enabled > > } > > } > > > > // CORRECT: Observe the session so state changes re-render > > struct SubmitButton: View { > > @ObservedObject var session: PrimerCardFormSession > > var body: some View { > > Button("Pay") { session.submit() } > > .disabled(!session.state.isValid || session.state.isLoading) > > } > > } > > ``` ## Complete example > [tab] Web > > Here's a complete example combining all the concepts: > > ```html theme={"dark"} > > >
>

Pay with Card

> > >
> > >
> > >
> > > > > Complete Payment > >
>
> > > > >
>
>
> > > > > ``` > [tab] Android > > ```kotlin theme={"dark"} > @Composable > fun CustomCardFormScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val checkoutState by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(checkoutState) { > when (val s = checkoutState) { > is PrimerCheckoutState.Success -> { > Log.d("Checkout", "Payment ID: ${s.checkoutData.payment.id}") > } > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Diagnostics: ${s.primerError.diagnosticsId}") > } > else -> Unit > } > } > > when (checkoutState) { > is PrimerCheckoutState.Loading -> { > Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { > CircularProgressIndicator() > } > } > is PrimerCheckoutState.Ready -> { > PrimerCheckoutHost(checkout = checkout) { > val controller = rememberCardFormController(checkout) > val formState by controller.state.collectAsStateWithLifecycle() > > Column( > modifier = Modifier > .fillMaxWidth() > .padding(16.dp), > verticalArrangement = Arrangement.spacedBy(12.dp), > ) { > Text( > text = "Enter card details", > style = MaterialTheme.typography.titleMedium, > ) > > OutlinedTextField( > value = formState.data[PrimerInputElementType.CARD_NUMBER].orEmpty(), > onValueChange = { controller.updateCardNumber(it) }, > label = { Text("Card number") }, > keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), > singleLine = true, > modifier = Modifier.fillMaxWidth(), > ) > > Row( > modifier = Modifier.fillMaxWidth(), > horizontalArrangement = Arrangement.spacedBy(12.dp), > ) { > OutlinedTextField( > value = formState.data[PrimerInputElementType.EXPIRY_DATE].orEmpty(), > onValueChange = { controller.updateExpiryDate(it) }, > label = { Text("MM/YY") }, > keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), > singleLine = true, > modifier = Modifier.weight(1f), > ) > OutlinedTextField( > value = formState.data[PrimerInputElementType.CVV].orEmpty(), > onValueChange = { controller.updateCvv(it) }, > label = { Text("CVV") }, > keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), > singleLine = true, > modifier = Modifier.weight(1f), > ) > } > > OutlinedTextField( > value = formState.data[PrimerInputElementType.CARDHOLDER_NAME].orEmpty(), > onValueChange = { controller.updateCardholderName(it) }, > label = { Text("Cardholder name") }, > keyboardOptions = KeyboardOptions( > capitalization = KeyboardCapitalization.Words, > ), > singleLine = true, > modifier = Modifier.fillMaxWidth(), > ) > > Button( > onClick = { controller.submit() }, > enabled = formState.isFormValid && !formState.isLoading, > modifier = Modifier.fillMaxWidth(), > ) { > if (formState.isLoading) { > CircularProgressIndicator( > modifier = Modifier.size(20.dp), > color = Color.White, > strokeWidth = 2.dp, > ) > } else { > Text("Pay") > } > } > } > } > } > } > } > ``` > [tab] iOS > > ```swift theme={"dark"} > import SwiftUI > import PrimerSDK > > struct CustomCardFormScreen: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > PrimerCardForm( > cardDetails: { formSession in > VStack(spacing: 20) { > Text("Payment details") > .font(.title2) > .fontWeight(.semibold) > .frame(maxWidth: .infinity, alignment: .leading) > > CardFormDefaults.cardNumber(formSession) > > HStack(spacing: 12) { > CardFormDefaults.expiryDate(formSession) > CardFormDefaults.cvv(formSession) > } > > CardFormDefaults.cardholderName(formSession) > } > }, > submitButton: { formSession in > Button(action: { formSession.submit() }) { > if formSession.state.isLoading { > ProgressView() > .tint(.white) > } else { > Text("Pay now") > } > } > .frame(maxWidth: .infinity, minHeight: 48) > .background(formSession.state.isValid ? Color.blue : Color.gray) > .foregroundColor(.white) > .cornerRadius(10) > .disabled(!formSession.state.isValid || formSession.state.isLoading) > } > ) > .padding() > } > .primerCheckoutSession(session) { state in > switch state { > case let .success(result): > print("Payment ID: \(result.paymentId)") > case let .failure(error, _): > print("Error: \(error.localizedDescription)") > case .dismissed: > break > default: > break > } > } > } > } > ``` ## See also > [card] [Styling guide](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Customize colors, fonts, and spacing > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Handle checkout events across platforms > [card] [Error handling](/docs/checkout/primer-checkout/build-your-ui/error-handling) > > Display and handle payment errors > [card] [Android SDK Reference](/docs/sdk/android-checkout/v3.0.0-beta/api/overview) > > Android SDK API documentation > [card] [iOS SDK Reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > iOS SDK API documentation # Disable buttons during payment Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/disable-buttons-during-payment Disable external buttons while payment is processing. Prevent users from clicking buttons outside the checkout while payment is being processed. ## Recipe > [tab] Web > > ```javascript theme={"dark"} > const submitButton = document.getElementById('external-submit'); > > checkout.addEventListener('primer:state-change', (event) => { > submitButton.disabled = event.detail.isProcessing; > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val controller = rememberCardFormController(checkout) > val state by controller.state.collectAsStateWithLifecycle() > > MyPayButton( > enabled = !state.isLoading, > onClick = { controller.submit() }, > ) > ``` > > > [!NOTE] > > > > Android's `isLoading` only covers card form submission. There is no unified checkout-level processing state across all payment methods. For `PrimerCheckoutSheet`, swipe dismissal can be controlled via `PrimerSettings.uiOptions.dismissalMechanism`, but the back button is always active. > [tab] iOS > > ```swift theme={"dark"} > PrimerCardForm(submitButton: { session in > Button("Pay") { session.submit() } > .disabled(!session.state.isValid || session.state.isLoading) > }) > ``` > > Each `PrimerCardForm` slot receives the active `PrimerCardFormSession`. Read `session.state.isLoading` and `session.state.isValid` directly to drive button state -- the session republishes its `state` on every change. ## How it works > [tab] Web > > 1. Get a reference to your external button(s) > 2. Listen for the `primer:state-change` event > 3. Set the button's `disabled` property based on `isProcessing` > > The `isProcessing` flag is unified across all payment methods -- when any payment is in progress, it returns `true`. > [tab] Android > > 1. Create a `PrimerCardFormController` using `rememberCardFormController()` > 2. Observe its `state` with `collectAsStateWithLifecycle()` > 3. Use `state.isLoading` to disable external buttons during card payment processing > > | Scope | Property | Coverage | > | - | - | - | > | Card form | `cardFormController.state.isLoading` | Card payments only | > | Checkout session | `PrimerCheckoutState.Loading` / `.Ready` | Initialization only, **not** payment processing | > [tab] iOS > > 1. Capture the `PrimerCardFormSession` passed into a `PrimerCardForm` slot closure > 2. Read `session.state.isLoading` and `session.state.isValid` to control button state > 3. Use SwiftUI's `.disabled()` modifier to disable buttons during processing > > | Property | Type | Description | > | - | - | - | > | `session.state.isLoading` | `Bool` | `true` while a card payment is being submitted | > | `session.state.isValid` | `Bool` | `true` when all required card fields pass validation | ## Variations ### Disable multiple buttons > [tab] Web > > ```javascript theme={"dark"} > const buttons = document.querySelectorAll('.checkout-action'); > > checkout.addEventListener('primer:state-change', (event) => { > buttons.forEach((button) => { > button.disabled = event.detail.isProcessing; > }); > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val controller = rememberCardFormController(checkout) > val state by controller.state.collectAsStateWithLifecycle() > val isProcessing = state.isLoading > > Column { > MyPayButton(enabled = !isProcessing, onClick = { controller.submit() }) > MyCancelButton(enabled = !isProcessing, onClick = { onCancel() }) > MyEditCartButton(enabled = !isProcessing, onClick = { onEditCart() }) > } > ``` > [tab] iOS > > Replace the submit slot with a custom view, then disable your other action buttons from the same observed session: > > ```swift theme={"dark"} > struct CheckoutActions: View { > @ObservedObject var session: PrimerCardFormSession > let onCancel: () -> Void > let onEditCart: () -> Void > > var body: some View { > let isProcessing = session.state.isLoading > VStack { > Button("Pay") { session.submit() } > .disabled(!session.state.isValid || isProcessing) > Button("Cancel", action: onCancel) > .disabled(isProcessing) > Button("Edit Cart", action: onEditCart) > .disabled(isProcessing) > } > } > } > > PrimerCardForm(submitButton: { session in > CheckoutActions(session: session, onCancel: { /* cancel */ }, onEditCart: { /* edit */ }) > }) > ``` ### Add visual feedback > [tab] Web > > ```javascript theme={"dark"} > const submitButton = document.getElementById('external-submit'); > > checkout.addEventListener('primer:state-change', (event) => { > const { isProcessing } = event.detail; > > submitButton.disabled = isProcessing; > submitButton.textContent = isProcessing ? 'Processing...' : 'Pay Now'; > submitButton.classList.toggle('loading', isProcessing); > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val controller = rememberCardFormController(checkout) > val state by controller.state.collectAsStateWithLifecycle() > > Button( > onClick = { controller.submit() }, > enabled = !state.isLoading, > ) { > if (state.isLoading) { > CircularProgressIndicator(modifier = Modifier.size(16.dp)) > Spacer(modifier = Modifier.width(8.dp)) > Text("Processing...") > } else { > Text("Pay Now") > } > } > ``` > [tab] iOS > > ```swift theme={"dark"} > PrimerCardForm(submitButton: { session in > Button(action: { session.submit() }) { > if session.state.isLoading { > ProgressView() > .frame(width: 16, height: 16) > Text("Processing...") > } else { > Text("Pay Now") > } > } > .disabled(!session.state.isValid || session.state.isLoading) > }) > ``` ### Disable navigation during payment > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:state-change', (event) => { > const { isProcessing } = event.detail; > > document.querySelectorAll('a').forEach((link) => { > if (isProcessing) { > link.dataset.originalHref = link.href; > link.removeAttribute('href'); > link.style.pointerEvents = 'none'; > } else if (link.dataset.originalHref) { > link.href = link.dataset.originalHref; > link.style.pointerEvents = ''; > } > }); > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val controller = rememberCardFormController(checkout) > val state by controller.state.collectAsStateWithLifecycle() > > BackHandler(enabled = state.isLoading) { > // Intercept back press during payment processing > } > ``` > > > [!NOTE] > > > > `BackHandler` only intercepts the system back gesture. For `PrimerCheckoutSheet`, swipe-to-dismiss is configured separately via `PrimerSettings.uiOptions.dismissalMechanism`. The SDK does not block the back button during processing. > [tab] iOS > > Surface the session's loading state with the submit slot, then bind it to `.interactiveDismissDisabled()` on the enclosing sheet: > > ```swift theme={"dark"} > @StateObject private var checkoutSession: PrimerCheckoutSession > @State private var isLoading = false > > init(clientToken: String) { > _checkoutSession = StateObject( > wrappedValue: PrimerCheckoutSession(clientToken: clientToken) > ) > } > > var body: some View { > ScrollView { > PrimerCardForm(submitButton: { cardSession in > SubmitButton(session: cardSession, isLoading: $isLoading) > }) > } > .interactiveDismissDisabled(isLoading) > .primerCheckoutSession(checkoutSession) > } > > struct SubmitButton: View { > @ObservedObject var session: PrimerCardFormSession > @Binding var isLoading: Bool > > var body: some View { > Button("Pay") { session.submit() } > .disabled(!session.state.isValid || session.state.isLoading) > .onChange(of: session.state.isLoading) { isLoading = $0 } > } > } > ``` > > > [!NOTE] > > > > `.interactiveDismissDisabled()` stops the shopper from swiping away the sheet that holds `PrimerCardForm` while a card payment runs. This includes the time before your `onBeforePaymentCreate` handler decides. Primer's own sheets block swipe-to-dismiss while a payment is processing: the processing screen that `.primerCheckoutSession` presents, `PrimerCheckout` in a sheet, and `PrimerCheckoutPresenter`. ## See also > [card] [Show loading indicator](/docs/checkout/primer-checkout/guides-and-recipes/show-loading-indicator) > > Display a loading state during payment processing > [card] [External submit button](/docs/checkout/primer-checkout/guides-and-recipes/external-submit-button) > > Trigger payment submission from outside the checkout component # Display detected card network Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/display-card-network Show the card brand logo as users type their card number. Display the detected card network (Visa, Mastercard, etc.) as users enter their card number. ## Recipe > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:bin-data-available', (event) => { > const { preferred, status } = event.detail; > > if (preferred) { > document.getElementById('card-logo').src = `/images/${preferred.network.toLowerCase()}.svg`; > } > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val controller = rememberCardFormController(checkout) > val state by controller.state.collectAsStateWithLifecycle() > > val detected = state.networkSelection.selectedNetwork > > if (detected != null) { > Text(text = detected.displayName) > } > ``` > > > [!NOTE] > > > > `PrimerCardForm` displays the card brand icon automatically in the card number field. Custom rendering is optional -- use `state.networkSelection` only if you need to display the network outside the card form. > [tab] iOS > > ```swift theme={"dark"} > struct CardFormWithNetwork: View { > var body: some View { > PrimerCardForm(cardDetails: { session in > CardDetailsWithNetwork(session: session) > }) > } > } > > struct CardDetailsWithNetwork: View { > @ObservedObject var session: PrimerCardFormSession > > var body: some View { > VStack(alignment: .leading) { > if let network = session.state.selectedNetwork { > Text(network.displayName) > .font(.caption) > .padding(4) > .background(Color(.secondarySystemBackground)) > .cornerRadius(4) > } > CardFormDefaults.cardDetails(session) > } > } > } > ``` > > > [!NOTE] > > > > `PrimerCardForm` displays the card brand icon automatically in the card number field. Read `session.state.selectedNetwork` only if you need to display the network outside the card form. It holds the network the form uses, and it is `nil` until a network is detected from the card number. For a co-badged card, it is the first entry of `availableNetworks` until the user picks another one. ## How it works > [tab] Web > > 1. Listen for the `primer:bin-data-available` event > 2. Use `preferred.network` to get the card brand identifier > 3. Update your UI with the appropriate logo or icon > [tab] Android > > 1. Create a `PrimerCardFormController` using `rememberCardFormController()` > 2. Observe its `state` with `collectAsStateWithLifecycle()` > 3. Read `state.networkSelection.selectedNetwork` for the currently detected network > 4. The state updates reactively as the user types -- no event listener needed > > | Property | Type | Description | > | - | - | - | > | `selectedNetwork` | `PrimerCardNetwork?` | Currently detected network, or `null` | > | `availableNetworks` | `List` | All selectable networks (for co-badged cards) | > | `isNetworkSelectable` | `Boolean` | `true` when the card has multiple networks | > [tab] iOS > > 1. Mark the `PrimerCardFormSession` injected into your slot closure as `@ObservedObject` > 2. Read `session.state.selectedNetwork` for the network the form uses; it is `nil` until a network is detected from the card number > 3. Read `session.state.availableNetworks` for the detected networks your `orderedAllowedCardNetworks` allows, in that order; more than one indicates a co-badged card > 4. The state updates reactively as the user types -- no event listener needed > > | Property | Type | Description | > | - | - | - | > | `availableNetworks` | `[PrimerCardNetwork]` | Detected networks that your `orderedAllowedCardNetworks` allows, in that order, or the first detected network if none is allowed. More than one indicates a co-badged card. | > | `selectedNetwork` | `PrimerCardNetwork?` | Network the form uses: the detected network, or the user's pick for a co-badged card. `nil` until a network is detected | The `preferred` field contains the recommended card network based on `orderedAllowedCardNetworks`. It is `undefined` when no network is detected (e.g., empty input or insufficient digits). ## The preferred object > [tab] Web > > The `preferred` object contains the detected card network and, when `status` is `'complete'`, additional issuer details: > > ```typescript theme={"dark"} > { > displayName: string; // Human-readable name (e.g., "Visa", "American Express") > network: string; // Backend identifier (e.g., "VISA", "AMEX") > allowed: boolean; // Whether the network is allowed per orderedAllowedCardNetworks > // Available when status is 'complete': > issuerCountryCode?: string; > issuerName?: string; > accountFundingType?: string; > } > ``` > > > [!NOTE] > > > > See the [Events Reference](/docs/sdk/primer-checkout-web/events-reference#bindatadetails) for the full `BinDataDetails` type definition. > [tab] Android > > ```kotlin theme={"dark"} > data class PrimerCardNetwork( > val network: CardNetwork.Type, > val displayName: String, > val allowed: Boolean, > ) > ``` > > `selectedNetwork` is `null` when no card network is detected. Android uses the `CardNetwork.Type` enum with a `displayName` property. > [tab] iOS > > ```swift theme={"dark"} > @objc > public final class PrimerCardNetwork: NSObject { > public let displayName: String // Human-readable name (e.g. "Visa") > public let network: CardNetwork // String-backed enum (.visa, .masterCard, ...) > public var allowed: Bool { get } // In the client session's orderedAllowedCardNetworks > public var allowsUserSelection: Bool { get } // false for networks that auto-route (EFTPOS) > > // Issuer details: set only on `binData` entries, `nil` elsewhere > public let issuerCountryCode: String? > public let issuerName: String? > public let accountFundingType: String? > public let prepaidReloadableIndicator: String? > public let productUsageType: String? > public let productCode: String? > public let productName: String? > public let issuerCurrencyCode: String? > public let regionalRestriction: String? > public let accountNumberType: String? > } > ``` > > The network the form uses comes from `selectedNetwork`; it is `nil` until a network is detected from the card number. `availableNetworks` lists the detected networks that your `orderedAllowedCardNetworks` allows, in that order (more than one for a co-badged card). If none is allowed, it holds only the first detected network. It is empty when no card network is detected. To also see detected networks that are not allowed, read `binData.alternatives`. iOS exposes `PrimerCardNetwork` with a `displayName` string property and a `network` (`CardNetwork`) enum whose raw value matches the backend identifier (e.g. `"VISA"`). > > For issuer details, read `session.state.binData`. It is a `PrimerBinData?` that is `nil` until the first detection, with four properties: > > * `preferred: PrimerCardNetwork?` is the first allowed network in your `orderedAllowedCardNetworks` order. It is `nil` when no detected network is allowed or no card number is entered. > * `alternatives: [PrimerCardNetwork]` lists the other detected networks in the same order. > * `status: PrimerBinDataStatus` is `.partial` while the network is detected locally from the card number. This happens with fewer than 8 digits, or when the remote lookup fails. It is `.complete` after the remote BIN lookup. > * `firstDigits: String?` is set for `.complete` results and is `nil` for `.partial` results. > > The `PrimerCardNetwork` entries in `preferred` and `alternatives` carry the issuer details as optional properties. These are `issuerCountryCode`, `issuerName`, `accountFundingType`, `prepaidReloadableIndicator`, `productUsageType`, `productCode`, `productName`, `issuerCurrencyCode`, `regionalRestriction` and `accountNumberType`. They are `nil` for `.partial` results and for any value the lookup does not return. The entries in `availableNetworks` and `selectedNetwork` never carry issuer details. > > ```swift theme={"dark"} > if let bin = session.state.binData, bin.status == .complete { > Text(bin.preferred?.issuerName ?? "") > } > ``` ## Supported card networks | `network` | Web / Android `displayName` | iOS `displayName` | | - | - | - | | `VISA` | Visa | Visa | | `MASTERCARD` | Mastercard | Mastercard | | `AMEX` | American Express | American Express | | `DISCOVER` | Discover | Discover | | `DINERS_CLUB` | Diners Club | Diners | | `JCB` | JCB | JCB | | `MAESTRO` | Maestro | Maestro | | `UNIONPAY` | UnionPay | UnionPay | | `ELO` | Elo | Elo | | `HIPER` | Hiper | Hiper | | `HIPERCARD` | Hipercard | Hiper | | `MIR` | Mir | Mir | | `CARTES_BANCAIRES` | Cartes Bancaires | Cartes Bancaires | | `BANCONTACT` | — | Bancontact | | `DANKORT` | Dankort | — (not in iOS `CardNetwork`) | | `EFTPOS` | Eftpos | EFTPOS | | `OTHER` | Other | Unknown | > [!NOTE] > > On Android, these are values of the `CardNetwork.Type` enum, each with a `displayName` property. On iOS, the `network` raw values map to cases of the `CardNetwork` enum; a few display names and the supported set differ (iOS has no `DANKORT` and adds `BANCONTACT`). See [PrimerCardNetwork](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-card-network) for the authoritative iOS list. ## Variations ### Show a loading indicator Use `primer:bin-data-loading-change` to indicate when BIN data is being fetched: ```javascript theme={"dark"} checkout.addEventListener('primer:bin-data-loading-change', (event) => { const { loading } = event.detail; document.getElementById('card-logo').style.opacity = loading ? '0.5' : '1'; }); ``` ### Display card network name > [tab] Web > > For user-facing text, use `displayName` instead of `network`: > > ```javascript theme={"dark"} > checkout.addEventListener('primer:bin-data-available', (event) => { > const { preferred } = event.detail; > > const networkName = preferred?.displayName || 'Card'; > document.getElementById('card-type-label').textContent = networkName; > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val controller = rememberCardFormController(checkout) > val state by controller.state.collectAsStateWithLifecycle() > > val networkName = state.networkSelection.selectedNetwork?.displayName ?: "Card" > Text(text = "Paying with $networkName") > ``` > [tab] iOS > > ```swift theme={"dark"} > let networkName = session.state.selectedNetwork?.displayName ?? "Card" > Text("Paying with \(networkName)") > ``` ### Show/hide based on detection > [tab] Web > > ```javascript theme={"dark"} > const cardLogo = document.getElementById('card-logo'); > > checkout.addEventListener('primer:bin-data-available', (event) => { > const { preferred } = event.detail; > > if (preferred) { > cardLogo.src = `/images/${preferred.network.toLowerCase()}.svg`; > cardLogo.style.display = 'block'; > } else { > cardLogo.style.display = 'none'; > } > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val controller = rememberCardFormController(checkout) > val state by controller.state.collectAsStateWithLifecycle() > > val detected = state.networkSelection.selectedNetwork > > AnimatedVisibility(visible = detected != null) { > if (detected != null) { > Text(text = detected.displayName) > } > } > ``` > [tab] iOS > > ```swift theme={"dark"} > @ObservedObject var session: PrimerCardFormSession > > var body: some View { > VStack { > if let network = session.state.selectedNetwork { > Text(network.displayName) > .transition(.opacity) > } > CardFormDefaults.cardNumber(session) > } > .animation(.default, value: session.state.selectedNetwork?.network) > } > ``` ### Co-badge network selector > [tab] Web > > Some cards support multiple networks (e.g., Carte Bancaire / Visa). Use `alternatives` to offer a network picker: > > ```javascript theme={"dark"} > checkout.addEventListener('primer:bin-data-available', (event) => { > const { preferred, alternatives } = event.detail; > const cobrandEl = document.getElementById('cobrand-selector'); > > if (preferred) { > document.getElementById('card-logo').src = `/images/${preferred.network.toLowerCase()}.svg`; > } > > const selectableNetworks = [preferred, ...alternatives].filter(n => n?.allowed); > cobrandEl.hidden = selectableNetworks.length <= 1; > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val controller = rememberCardFormController(checkout) > val state by controller.state.collectAsStateWithLifecycle() > val networkSelection = state.networkSelection > > if (networkSelection.isNetworkSelectable && networkSelection.availableNetworks.size > 1) { > NetworkSelector( > networks = networkSelection.availableNetworks, > selected = networkSelection.selectedNetwork, > onSelect = { network -> controller.selectCardNetwork(network) }, > ) > } > ``` > > > [!NOTE] > > > > `PrimerCardForm` renders a dropdown selector for co-badged cards automatically. Use `selectCardNetwork()` only if building a fully custom card form. > [tab] iOS > > When a card supports multiple networks, `session.state.availableNetworks` contains all options. Render your own picker and commit the choice with `session.selectCardNetwork(_:)`. After that call, `session.state.selectedNetwork` holds the user's pick: > > ```swift theme={"dark"} > @ObservedObject var session: PrimerCardFormSession > > var body: some View { > let networks = session.state.availableNetworks > if networks.count > 1 { > HStack { > ForEach(networks, id: \.network) { network in > Button(network.displayName) { > session.selectCardNetwork(network) > } > .buttonStyle(.bordered) > .disabled(!network.allowed) > } > } > } > } > ``` > > > [!NOTE] > > > > `PrimerCardForm` renders a network selector for co-badged cards automatically, inside the card number field. It is a dropdown by default. With `PrimerCardPaymentOptions(networkSelectorStyle: .inline)`, it shows inline badges instead. When a detected network such as EFTPOS does not allow selection, it shows the badges of all detected networks and offers no choice. `CardFormDefaults.cardNumber(session)` keeps this selector when you recompose the fields, so do not add `CardFormDefaults.cardNetwork(session)` next to it. Call `selectCardNetwork(_:)` only when you build your own picker. ### Use icon font or CSS classes ```javascript theme={"dark"} checkout.addEventListener('primer:bin-data-available', (event) => { const { preferred } = event.detail; const iconEl = document.getElementById('card-icon'); if (preferred) { iconEl.classList.add(`card-${preferred.network.toLowerCase()}`); } }); ``` ## See also > [card] [Build a custom card form](/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form) > > Step-by-step guide to building a fully custom card form > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Handle payment lifecycle events > [card] [Use BIN data for Click to Pay](/docs/checkout/primer-checkout/guides-and-recipes/use-bin-data-to-control-click-to-pay) > > Control Click to Pay based on BIN data # Display saved payment methods Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/display-saved-payment-methods Show saved payment methods count and list saved cards. Display the number of saved payment methods or list saved cards for returning customers. ## Recipe: Show saved methods count > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:vault-methods-update', (event) => { > const { vaultedPayments } = event.detail; > const count = vaultedPayments.size(); > > document.getElementById('saved-methods-badge').textContent = > count > 0 ? `${count} saved` : ''; > }); > ``` > [tab] Android > > Use `PrimerVaultedPaymentMethods` to render saved methods: > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController(clientToken) > val vaultedController = rememberVaultedPaymentMethodsController(checkout) > > PrimerVaultedPaymentMethods(controller = vaultedController) > ``` > > This renders a list of saved payment methods with card brand icons, masked card numbers, and expiry dates. The customer can select a saved method to pay with it. > [tab] iOS > > Read the count inside the `header` slot of `PrimerVaultedPaymentMethods`, which hands you the `PrimerSelectionSession`. Custom slot content must be wrapped in `AnyView`: > > ```swift theme={"dark"} > PrimerVaultedPaymentMethods( > header: { session in > let count = session.vaultedPaymentMethods.count > return AnyView(Text(count > 0 ? "\(count) saved" : "")) > } > ) > ``` ## Recipe: List saved cards > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:vault-methods-update', (event) => { > const methods = event.detail.vaultedPayments.toArray(); > const container = document.getElementById('saved-cards'); > > container.innerHTML = methods > .filter((m) => m.paymentMethodType === 'PAYMENT_CARD') > .map((m) => ` >
> ${m.paymentInstrumentData.network} •••• ${m.paymentInstrumentData.last4Digits} >
> `) > .join(''); > }); > ``` > [tab] Android > > For full control over how saved methods are displayed, observe the controller's state directly: > > ```kotlin theme={"dark"} > @Composable > fun CustomVaultedMethods( > checkout: PrimerCheckoutController, > ) { > val vaultedController = rememberVaultedPaymentMethodsController(checkout) > val vaultedState by vaultedController.state.collectAsStateWithLifecycle() > > Column { > vaultedState.paymentMethods.forEach { method -> > Card( > modifier = Modifier > .fillMaxWidth() > .padding(vertical = 4.dp), > onClick = { vaultedController.select(method) }, > ) { > Row( > modifier = Modifier > .fillMaxWidth() > .padding(16.dp), > verticalAlignment = Alignment.CenterVertically, > ) { > Column(Modifier.weight(1f)) { > Text( > text = method.paymentMethodType, > style = MaterialTheme.typography.bodyLarge, > ) > Text( > text = method.description, > style = MaterialTheme.typography.bodySmall, > color = MaterialTheme.colorScheme.onSurfaceVariant, > ) > } > if (vaultedState.selectedMethod == method) { > Icon( > imageVector = Icons.Default.Check, > contentDescription = "Selected", > tint = MaterialTheme.colorScheme.primary, > ) > } > } > } > } > } > } > ``` > [tab] iOS > > Override the `item` slot of `PrimerVaultedPaymentMethods` to render the saved method with custom UI. The view is a one-row shortcut, so the slot is called once — for the selected method, with `isSelected: true`. It receives the method, that flag, and an `onSelect` callback; custom content must be wrapped in `AnyView`: > > ```swift theme={"dark"} > PrimerVaultedPaymentMethods( > item: { method, isSelected, onSelect in > AnyView( > Button(action: onSelect) { > HStack { > VStack(alignment: .leading) { > Text(method.paymentMethodType) > .font(.body) > if method.paymentMethodType == "PAYMENT_CARD" { > Text("Saved card") > .font(.caption) > .foregroundColor(.secondary) > } > } > Spacer() > if isSelected { > Image(systemName: "checkmark.circle.fill") > } > } > .padding(.vertical, 10) > .padding(.horizontal, 16) > } > .buttonStyle(.plain) > ) > } > ) > ``` ## How it works > [tab] Web > > 1. Listen for the `primer:vault-methods-update` DOM event > 2. Access `vaultedPayments` from the event detail > 3. Use `.size()` to get the count or `.toArray()` to iterate over methods > 4. Each method contains `paymentMethodType` and `paymentInstrumentData` with card details > [tab] Android > > 1. Create a vaulted payment methods controller using `rememberVaultedPaymentMethodsController()` > > 2. Use `PrimerVaultedPaymentMethods` for the default rendering, or observe the controller's state for a custom UI > > 3. To save new payment methods, call `cardFormController.setVaultOnSuccess(true)` before payment > > > [!NOTE] > > > > Vaulting requires a `customerId` in your client session. Pass it when creating the session on your server. > [tab] iOS > > 1. Place `PrimerVaultedPaymentMethods` inside a hierarchy that applies the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. The modifier injects a `PrimerSelectionSession` into the environment, which `PrimerVaultedPaymentMethods` resolves internally > > 2. The `header` slot hands your code that `PrimerSelectionSession`. Read `session.vaultedPaymentMethods` for the full list of saved methods, or `session.state` for `selectedVaultedPaymentMethod` and `isVaultPaymentLoading`. The `item` slot receives the method, an `isSelected` flag and an `onSelect` callback. The `submitButton` slot receives `isLoading`, `isEnabled` and an `onSubmit` callback. When a card needs CVV recapture, the SDK raises the CVV recapture screen. Outside the slots, reach the same session as `checkoutSession.selection` > > 3. `PrimerVaultedPaymentMethods()` renders the selected method as a one-row shortcut and hides itself when nothing is saved; its default header links to the SDK's saved-methods screen for switching or deleting. Override the `item` slot to restyle that row, or build your own layout over `vaultedPaymentMethods` if you want every method visible inline > > 4. The view's submit button pays with the selected method > > 5. To save new payment methods, call `try await checkoutSession.cardForm?.setVaultOnSuccess(true)` before payment > > > [!NOTE] > > > > Vaulting requires a `customerId` in your client session. Pass it when creating the session on your server. ## Variations ### Save and display methods > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:vault-methods-update', (event) => { > const methods = event.detail.vaultedPayments.toArray(); > const container = document.getElementById('saved-methods'); > > container.innerHTML = methods > .map((method) => { > if (method.paymentMethodType === 'PAYMENT_CARD') { > const { network, last4Digits } = method.paymentInstrumentData; > return ` >
> ${network} > •••• ${last4Digits} >
> `; > } > return ` >
> ${method.paymentMethodType} > ${method.paymentMethodType} >
> `; > }) > .join(''); > }); > ``` > [tab] Android > > To save a new payment method after a successful payment, call `setVaultOnSuccess()` on the card form controller: > > ```kotlin theme={"dark"} > val cardFormController = rememberCardFormController(checkout) > > LaunchedEffect(cardFormController) { > cardFormController.setVaultOnSuccess(true) > } > ``` > [tab] iOS > > `selectVaulted(_:)` is the pay verb, so call it from your pay button rather than from a row tap. Keep which row looks selected in your own view state: > > ```swift theme={"dark"} > // Pays with the saved method. Returns immediately; the payment runs on. > session.selectVaulted(method) > ``` > > A card that needs CVV recapture raises the CVV recapture screen, and that screen finishes the payment. The outcome arrives through `.primerCheckoutSession(_:theme:onCompletion:)`. > > Before a saved-method payment starts, the SDK calls the `onBeforePaymentCreate` handler you set on `PrimerCheckoutSession`. In that handler, you can abort the payment or supply an idempotency key. An abort arrives as a payment failure. > > `PrimerVaultedPaymentMethods` renders one saved method and a submit button that calls `selectVaulted(_:)` for you. > > To save a new card after a successful payment, call `setVaultOnSuccess(_:)` on the card form session. It updates the client session, which needs a `customerId`. Call it with `false` to stop saving, for example from a customer-facing "Save card" toggle: > > ```swift theme={"dark"} > // `checkoutSession` is the PrimerCheckoutSession you hold as @StateObject > PrimerCardForm() > .task(id: checkoutSession.phase) { > // `cardForm` is nil until the session is ready, so this runs again when `phase` changes > try? await checkoutSession.cardForm?.setVaultOnSuccess(true) > } > ``` ### Inline saved methods with card form > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:vault-methods-update', (event) => { > const methods = event.detail.vaultedPayments.toArray(); > > methods > .filter((m) => m.paymentMethodType === 'PAYMENT_CARD') > .forEach((method) => { > const { network, last4Digits, expirationMonth, expirationYear } = > method.paymentInstrumentData; > > console.log( > `${network} •••• ${last4Digits} - Expires ${expirationMonth}/${expirationYear}`, > ); > }); > }); > ``` > [tab] Android > > This example shows saved methods above the card form, letting the customer choose between a saved method or entering new card details: > > ```kotlin theme={"dark"} > @Composable > fun InlineCheckoutWithVault(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (state) { > is PrimerCheckoutState.Success -> { } > is PrimerCheckoutState.Failure -> { } > else -> Unit > } > } > > when (state) { > is PrimerCheckoutState.Loading -> { > CircularProgressIndicator() > } > is PrimerCheckoutState.Ready -> { > PrimerCheckoutHost( > checkout = checkout, > ) { > val vaultedController = rememberVaultedPaymentMethodsController(checkout) > val cardFormController = rememberCardFormController(checkout) > > LaunchedEffect(cardFormController) { > cardFormController.setVaultOnSuccess(true) > } > > Column(Modifier.padding(16.dp)) { > Text( > text = "Saved payment methods", > style = MaterialTheme.typography.titleMedium, > ) > Spacer(Modifier.height(12.dp)) > > PrimerVaultedPaymentMethods(controller = vaultedController) > > Spacer(Modifier.height(24.dp)) > HorizontalDivider() > Spacer(Modifier.height(24.dp)) > > Text( > text = "Or pay with a new card", > style = MaterialTheme.typography.titleMedium, > ) > Spacer(Modifier.height(12.dp)) > > PrimerCardForm(controller = cardFormController) > } > } > } > } > } > ``` > [tab] iOS > > Compose `PrimerVaultedPaymentMethods` and `PrimerCardForm` under the `.primerCheckoutSession(_:theme:onCompletion:)` modifier, letting the customer choose between a saved method or entering new card details: > > ```swift theme={"dark"} > struct InlineCheckoutWithVault: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject( > wrappedValue: PrimerCheckoutSession(clientToken: clientToken) > ) > } > > var body: some View { > ScrollView { > VStack(spacing: 24) { > Text("Saved payment methods") > .font(.title3.weight(.semibold)) > .frame(maxWidth: .infinity, alignment: .leading) > > PrimerVaultedPaymentMethods() > > Divider() > > Text("Or pay with a new card") > .font(.title3.weight(.semibold)) > .frame(maxWidth: .infinity, alignment: .leading) > > PrimerCardForm() > } > .padding() > } > .primerCheckoutSession(session) { state in > switch state { > case .success(let data): > print("Payment complete: \(data)") > case let .failure(error, _): > print("Payment failed: \(error)") > default: > break > } > } > } > } > ``` ### Conditional UI based on saved methods > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:vault-methods-update', (event) => { > const { vaultedPayments } = event.detail; > const hasSavedMethods = vaultedPayments.size() > 0; > > document.getElementById('saved-methods-section').style.display = hasSavedMethods > ? 'block' > : 'none'; > > document.getElementById('new-payment-section').querySelector('h3').textContent = > hasSavedMethods ? 'Or pay with a new method' : 'Payment method'; > }); > ``` > [tab] Android > > The bottom sheet shows vaulted methods automatically when they are available. No extra configuration is needed beyond providing a `customerId` in the client session: > > ```kotlin theme={"dark"} > @Composable > fun CheckoutWithSavedMethods(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { } > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Failed: ${s.primerError.diagnosticsId}") > } > else -> Unit > } > } > > when (state) { > is PrimerCheckoutState.Loading -> { > CircularProgressIndicator() > } > is PrimerCheckoutState.Ready -> { > PrimerCheckoutSheet( > checkout = checkout, > onDismiss = { }, > ) > } > } > } > ``` > [tab] iOS > > The managed `PrimerCheckout` shows vaulted methods automatically when they are available. No extra configuration is needed beyond providing a `customerId` in the client session: > > ```swift theme={"dark"} > PrimerCheckout(clientToken: clientToken) { state in > // Handle the terminal payment result > } > ``` > > For inline layouts, `PrimerVaultedPaymentMethods` hides itself entirely when the customer has no saved methods, so you do not need to branch on the empty case to keep the section from appearing. > > > [!WARNING] > > > > That also means you cannot render an empty-state message from inside the `header` slot — when there is nothing saved, no slot is called at all. Branch in the layout that *contains* the view instead, reading `vaultedPaymentMethods` from `checkoutSession.selection`. Observe that `PrimerSelectionSession` with `@ObservedObject`. Saved methods load after the session is ready. A view that observes only the checkout session does not update when they load or change: > > > > ```swift theme={"dark"} > > // Pass in the PrimerCheckoutSession you hold as @StateObject > > struct SavedMethodsSection: View { > > @ObservedObject var checkoutSession: PrimerCheckoutSession > > > > var body: some View { > > if let selection = checkoutSession.selection { > > SavedMethodsHeading(selection: selection) > > } > > PrimerVaultedPaymentMethods() > > } > > } > > > > // Observes the selection session, so the heading follows saved methods as they load or are deleted > > struct SavedMethodsHeading: View { > > @ObservedObject var selection: PrimerSelectionSession > > > > var body: some View { > > Text(selection.vaultedPaymentMethods.isEmpty ? "Payment method" : "Or pay with a new method") > > } > > } > > ``` > > To customize the section's own heading, override the `header` slot — it receives the `PrimerSelectionSession`. Keep a "Show all" affordance: it is the route to the SDK screen where a customer deletes a saved method. Custom slot content must be wrapped in `AnyView`: > > ```swift theme={"dark"} > PrimerVaultedPaymentMethods( > header: { session in > AnyView( > HStack { > Text("Pay faster") > Spacer() > Button("Manage") { session.showAll() } > } > ) > } > ) > ``` ## See also > [card] [Vault manager component](/docs/sdk/primer-checkout-web/components/primer-vault-manager) > > SDK reference for saved payment methods > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Handle payment lifecycle events # Express Checkout: shipping in the Apple Pay and Google Pay sheets Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping Supply shipping options and confirm the shopper's choice from inside the Apple Pay and Google Pay sheets. > [!NOTE] > > **New feature.** Express Checkout shipping is available to all merchants. No allowlisting or account setup is required. > > **What it covers today:** Apple Pay and Google Pay on the **Web** SDK ([Primer Checkout](/docs/checkout/primer-checkout/installation)), Google Pay on the **Android** SDK ([Checkout Components](/docs/sdk/android-checkout/v3.0.0-beta/installation)), and Apple Pay on the **iOS** SDK ([Checkout Components](/docs/sdk/ios-checkout/v3.0.0-beta/installation)). > > Because it is new, **test your integration end to end in the [sandbox](/docs/testing/overview) before going live in production.** Apple Pay and Google Pay collect the shopper's shipping address inside the native payment sheet, after checkout has already started. If your shipping rates depend on that address, you need to price them while the sheet is open. Express Checkout shipping does this with two callbacks. Your app or page supplies the shipping options for the address the shopper entered, and your backend confirms the option they pick. Primer then recalculates the order total from the confirmed shipping, so the amount stays authoritative on our side. ## When to use it Use it when shipping cost or availability depends on the destination and cannot be known when the client session is created. For example: * Physical goods priced by weight, zone, or carrier rate. * Free-shipping thresholds that vary by region. * Shipping choices that depend on state held in your app or page, such as a selected store or a delivery window. ## How it works 1. **The shopper enters an address, or the sheet opens.** The SDK asks your code for the shipping options for that address. The sheet stays in a loading state. 2. **Your code returns the options.** This is display only. Primer does not store the list and does not price anything from it. 3. **An option is selected.** The SDK hands you that option. This fires when the shopper picks one, and also for the option the sheet pre-selects, so expect it more than once per sheet session. 4. **Your backend confirms it** by PATCHing `order.shipping` onto the client session, then your code tells the SDK it is done. 5. **Primer re-reads the session**, checks that the confirmation matches the selection, recomputes `order.amount`, and refreshes the sheet total. 6. **The shopper authorizes.** Authorization waits for the confirmation, so a payment can never be created against a shipping option your backend has not priced. > [!NOTE] > > **The two callbacks are a pair.** The address callback is display only and never changes the amount. The option callback is the one that moves money, and it goes through your backend. ## Prerequisites On every platform: * An [API key](/docs/api-reference/get-started/authentication) with `client_tokens:write` for the client session PATCH. * On iOS, a client session with no legacy `SHIPPING` checkout module. There a legacy module takes priority and the handlers are ignored. Web and Android do not read it. > [tab] Web > > * Primer Checkout already integrated. See [First payment](/docs/checkout/primer-checkout/first-payment). > * `@primer-io/primer-js` **1.9.2** or later. Earlier versions do not dispatch these events at all. > * Apple Pay and/or Google Pay configured in the [Dashboard](/docs/connections/payment-methods/apple-pay/overview). > [tab] Android > > * `io.primer:checkout` **3.0.0-beta.8** or later. Earlier versions do not have these handlers. > * Google Pay configured through [`PrimerGooglePayOptions`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-settings#primergooglepayoptions). > * A physical device with Google Play services and a card in Google Wallet. None of this flow can be exercised in the emulator. > > The SDK declares the Google Pay callback service in its own manifest and ships the matching keep rules, so there is nothing to add to your app's manifest or ProGuard configuration. > > The SDK depends on `com.google.android.gms:play-services-wallet` **20.0.0** and exposes it to your app. If your app declares an older version, Gradle resolves to 20.0.0. > [tab] iOS > > * Apple Pay already integrated. See [Apple Pay integration](/docs/sdk/ios-checkout/v3.0.0-beta/guides/apple-pay-integration). > * A physical device with a card in Wallet to test the payment. The iOS Simulator shows the sheet and runs both handlers, but its payment token is not a real one, so the payment itself fails. ## Step 1. Enable shipping in the payment sheet Shipping selection is off by default. Turn it on in the SDK options. > [tab] Web > > ```typescript theme={"dark"} > const checkout = document.querySelector('primer-checkout'); > > checkout.options = { > applePay: { > // Apple Pay nests these under `shippingOptions`. > shippingOptions: { > requireShippingMethod: true, > requiredShippingContactFields: ['postalAddress', 'name', 'email'], > }, > }, > googlePay: { > // Google Pay takes them at the top level. The nesting is not the same > // as Apple Pay, so do not copy the block above. > captureShippingAddress: true, > requireShippingMethod: true, > }, > }; > ``` > > > [!WARNING] > > > > **The two wallets nest these options differently.** Apple Pay reads `applePay.shippingOptions.requireShippingMethod`. Google Pay reads `googlePay.requireShippingMethod`, with no `shippingOptions` object. An option placed at the wrong level is ignored silently, and the sheet opens without a shipping selector. > > | Option | Wallet | Effect | > | - | - | - | > | `applePay.shippingOptions.requireShippingMethod` | Apple Pay | Shows the shipping method selector in the sheet. | > | `applePay.shippingOptions.requiredShippingContactFields` | Apple Pay | Which shipping contact fields the shopper must provide. | > | `googlePay.captureShippingAddress` | Google Pay | Collects a shipping address in the sheet. | > | `googlePay.requireShippingMethod` | Google Pay | Shows the shipping option selector. | > [tab] Android > > On Android the handlers turn shipping on. You do not set any shipping option in `PrimerSettings`: when you register `onShippingAddressChange`, the SDK asks the shopper for a shipping address, and when you also register `onShippingOptionChange`, the sheet shows the shipping options. > > ```kotlin theme={"dark"} > val settings = PrimerSettings( > paymentMethodOptions = PrimerPaymentMethodOptions( > googlePayOptions = PrimerGooglePayOptions( > merchantName = "Example Store", > // Optional: ask for the phone number too. The SDK asks for the address itself. > shippingAddressParameters = PrimerGoogleShippingAddressParameters( > phoneNumberRequired = true, > ), > ), > ), > ) > > val checkout = rememberPrimerCheckoutController(clientToken, settings) > ``` > > | Handlers you register | Effect | > | - | - | > | `onShippingAddressChange` and `onShippingOptionChange` | The sheet asks for an address, shows your options and confirms the selection, as described here. | > | `onShippingAddressChange` only | The sheet asks for an address and shows no options. See below. | > > `shippingAddressParameters` still adds the phone number. `requireShippingMethod` is not needed. > > ### Address updates only > > If you register only `onShippingAddressChange`, the sheet shows no shipping options. The SDK still calls `onShippingAddressChange` for each address and ignores the options it returns. Use it when the total depends on the address, for example for tax. Patch the client session from your backend before you return, and the SDK re-reads the total for the sheet. `onShippingOptionChange` is not called, and authorization does not wait for a confirmation. > [tab] iOS > > On iOS the handlers turn shipping on. You do not set any shipping option in `PrimerSettings`: when you set `onShippingAddressChange`, the SDK asks the shopper for a shipping address, and when you also set `onShippingOptionChange`, the sheet shows the shipping options. > > ```swift theme={"dark"} > let settings = PrimerSettings( > paymentMethodOptions: PrimerPaymentMethodOptions( > applePayOptions: PrimerApplePayOptions( > merchantIdentifier: "merchant.com.example", > merchantName: "Example Store", > // Optional: other shipping contact fields. The SDK adds the postal address itself. > shippingOptions: PrimerApplePayOptions.ShippingOptions( > shippingContactFields: [.name, .emailAddress], > // Required by the initializer. The handlers decide whether the sheet shows options. > requireShippingMethod: false > ) > ) > ) > ) > > let session = PrimerCheckoutSession(clientToken: clientToken, settings: settings) > ``` > > | Handlers you set | Effect | > | - | - | > | `onShippingAddressChange` and `onShippingOptionChange` | The sheet asks for an address, shows your options and confirms the selection, as described here. | > | `onShippingAddressChange` only | The sheet asks for an address and shows no options. See below. | > > `shippingOptions.shippingContactFields` still adds other fields, for example name or email. The `ShippingOptions` initializer requires `requireShippingMethod`, but Checkout Components does not read it. Pass `false`. > > ### Address updates only > > If you set only `onShippingAddressChange`, the sheet shows no shipping options. The SDK still calls `onShippingAddressChange` for each address and ignores the options it returns. Use it when the total depends on the address, for example for tax. Patch the client session from your backend before you return, and the SDK re-reads the total for the sheet. `onShippingOptionChange` is not called, and authorization does not wait for a confirmation. ## Step 2. Supply options for the address Respond to the address callback with the options you want the sheet to show. > [tab] Web > > Listen for `primer:shipping-address-change` and call `setShippingOptions()`. > > > [!WARNING] > > > > **Call `preventDefault()` before any async work.** The SDK treats the event as handled only if your listener calls `preventDefault()`, or calls `setShippingOptions()` synchronously. If you fetch rates from your backend, `setShippingOptions()` runs later, so `preventDefault()` is the only thing telling the SDK to wait. Without it the SDK moves on with no options and no shipping confirmation, no error is raised, and **the shopper is charged the total without shipping.** The same rule applies to `continue()` in Step 3. > > ```typescript theme={"dark"} > checkout.addEventListener('primer:shipping-address-change', (event) => { > // Tell the SDK to wait. Required whenever you respond asynchronously. > event.preventDefault(); > > const { shippingAddress, setShippingOptions } = event.detail; > > (async () => { > const rates = await fetch('/my-backend/shipping-rates', { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > body: JSON.stringify({ shippingAddress }), > }).then((r) => r.json()); > > setShippingOptions(rates); > })(); > }); > ``` > > ### Event payload > > `primer:shipping-address-change` is a [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). Its data is on `event.detail`. > > | Property | Type | Description | > | - | - | - | > | `paymentMethodType` | `'APPLE_PAY' \| 'GOOGLE_PAY'` | Which wallet the shopper is using. | > | `shippingAddress` | `NullableAddress` | The address from the sheet, redacted by the wallet at this stage. Expect city, state, postal code and country. Street address, name, phone and email are not available until after authorization. Any field can be `null`. | > | `setShippingOptions` | `(options: ShippingOption[]) => void` | Call with the options to display. Call it once. Later calls are ignored. | > | `timestamp` | `number` | Unix timestamp in seconds, when the event was dispatched. | > > ### The ShippingOption shape > > ```typescript theme={"dark"} > interface ShippingOption { > id: string; // Stable identifier. Echoed back on selection, and > // must match order.shipping.methodId when you confirm. > name: string; // Display label, e.g. "Standard" > description: string; // Display detail, e.g. "5-7 business days" > amount: number; // Shipping cost in MINOR UNITS, e.g. 500 = £5.00 > } > ``` > [tab] Android > > Register `onShippingAddressChange` on the [`PrimerCheckoutController`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-controller) before the sheet opens and return the options. Registering right after you create the controller is the simplest way to guarantee the ordering. > > ```kotlin theme={"dark"} > LaunchedEffect(checkout) { > checkout.onShippingAddressChange { change -> > myBackend.shippingRates(change.shippingAddress).map { rate -> > PrimerShippingOption( > id = rate.id, > name = rate.name, > description = rate.eta, > amount = rate.amountInMinorUnits, > ) > } > } > } > ``` > > The handler is a `suspend` function. The SDK calls it on the main thread, so suspend for your backend call and do not block. The two handlers never run at the same time, and a handler still running when the 20 seconds expire is cancelled. > > The SDK pre-selects one option and confirms it immediately: the one matching the client session's current `order.shipping.methodId` if there is one, otherwise the first in your list. Your list order is kept. > > ### Payload > > ```kotlin theme={"dark"} > data class PrimerShippingAddressChange( > val paymentMethodType: String, > val shippingAddress: PrimerAddress, > ) > ``` > > | Property | Description | > | - | - | > | `paymentMethodType` | Which wallet the shopper is using. `"GOOGLE_PAY"` today. | > | `shippingAddress` | The address from the sheet, redacted by the wallet at this stage. Expect `countryCode`, `postalCode`, `city` and `state`. Name and street lines are not available until after authorization. Any field can be `null`. | > > ### The option > > ```kotlin theme={"dark"} > data class PrimerShippingOption( > val id: String, // Echoed back on selection. Must match order.shipping.methodId. > val name: String, // Display label, for example "Standard" > val description: String, // Display detail, for example "5-7 business days" > val amount: Int, // Shipping cost in MINOR UNITS, for example 500 = £5.00 > ) > ``` > > The sheet shows `name` and `description`. It does not show `amount` next to the option, so include the price in `name` or `description` if you want the shopper to see it before the total updates. > [tab] iOS > > Set `onShippingAddressChange` on the [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) and return the options. > > ```swift theme={"dark"} > session.onShippingAddressChange = { change in > let rates = try await myBackend.shippingRates(for: change.shippingAddress) > return rates.map { > PrimerShippingOption( > id: $0.id, > name: $0.name, > description: $0.eta, > amount: $0.amountInMinorUnits > ) > } > } > ``` > > The SDK pre-selects one option and confirms it immediately: the one matching the client session's current `order.shipping.methodId` if there is one, otherwise the first in your list. Apple Pay shows the pre-selected option first, so the SDK moves it to the top of the list. > > ### Payload > > ```swift theme={"dark"} > public struct PrimerShippingAddressChange: Sendable { > public let paymentMethodType: String > public let shippingAddress: PrimerAddress > } > ``` > > | Property | Description | > | - | - | > | `paymentMethodType` | Which wallet the shopper is using. `"APPLE_PAY"` today. | > | `shippingAddress` | The address from the sheet, redacted by Apple at this stage. Expect city, state, postal code and country. Street address, name, phone and email are not available until after authorization. Any field can be `nil`. | > > ### The option > > ```swift theme={"dark"} > public struct PrimerShippingOption: Equatable, Sendable { > public let id: String // Echoed back on selection. Must match order.shipping.methodId. > public let name: String // Display label, for example "Standard" > public let description: String // Display detail, for example "5-7 business days" > public let amount: Int // Shipping cost in MINOR UNITS, for example 500 = £5.00 > } > ``` The wallet gives you a partial address on purpose. If you price below postal code granularity, you cannot do it at this stage. Return an empty list to tell the shopper you do not ship to that address. The sheet shows an "address not serviceable" error and they can enter a different one. On Android this needs both handlers: with `onShippingAddressChange` alone the returned list is ignored. ## Step 3. Confirm the selection from your backend When an option is selected, send it to your backend, which PATCHes it onto the client session, then tell the SDK you are done. > [tab] Web > > Listen for `primer:shipping-option-change` and call `continue()` once the PATCH has landed. > > ```typescript theme={"dark"} > checkout.addEventListener('primer:shipping-option-change', (event) => { > event.preventDefault(); > > // `continue` is a reserved word in JavaScript. Alias it when destructuring. > const { selectedShippingOption, continue: confirmShipping } = event.detail; > > (async () => { > const response = await fetch('/my-backend/commit-shipping', { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > // Send the id only. Your backend resolves the price. > body: JSON.stringify({ shippingOptionId: selectedShippingOption.id }), > }); > > if (!response.ok) { > // Do not call continue() here. The PATCH did not land, so the session > // still holds the old shipping. Acknowledging anyway would let the > // shopper reach authorization and fail there, which is harder to > // understand. Log it and let the callback time out instead. > console.error('Shipping PATCH failed, not confirming the selection'); > return; > } > > confirmShipping(); > })(); > }); > ``` > > Your confirm endpoint can be called more than once during a single sheet session, including for the option the sheet pre-selects before the shopper touches anything. Make it idempotent. > > ### Event payload > > | Property | Type | Description | > | - | - | - | > | `paymentMethodType` | `'APPLE_PAY' \| 'GOOGLE_PAY'` | Which wallet the shopper is using. | > | `selectedShippingOption` | `ShippingOption` | The option that was selected, exactly as you supplied it. | > | `continue` | `() => void` | Acknowledge the confirmation. **Reserved word** — give it an alias, as in the example above. | > | `timestamp` | `number` | Unix timestamp in seconds, when the event was dispatched. | > [tab] Android > > Register `onShippingOptionChange` and return once your backend has confirmed. Returning is the acknowledgement. Throw, or let the call fail, if the PATCH did not land. > > ```kotlin theme={"dark"} > LaunchedEffect(checkout) { > checkout.onShippingOptionChange { change -> > // Send the id only. Your backend resolves the price. > myBackend.updateShipping(orderId, change.selectedShippingOption.id) > } > } > ``` > > The handler runs for the pre-selected option as soon as options are supplied, and again each time the shopper picks a different one. Make your confirm endpoint idempotent. > > ### Payload > > ```kotlin theme={"dark"} > data class PrimerShippingOptionChange( > val paymentMethodType: String, > val selectedShippingOption: PrimerShippingOption, > ) > ``` > [tab] iOS > > Set `onShippingOptionChange` and return once your backend has confirmed. Returning is the acknowledgement. Throw if the PATCH did not land. > > ```swift theme={"dark"} > session.onShippingOptionChange = { change in > // Send the id only. Your backend resolves the price. > try await myBackend.commitShipping(optionId: change.selectedShippingOption.id) > } > ``` > > The handler runs for the pre-selected option as soon as options are supplied, and again each time the shopper picks a different one. Make your confirm endpoint idempotent. > > ### Payload > > ```swift theme={"dark"} > public struct PrimerShippingOptionChange: Sendable { > public let paymentMethodType: String > public let selectedShippingOption: PrimerShippingOption > } > ``` > > ### Other entry points > > The handlers are available on all three entry points. On [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) and [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter), pass them at the call site as the last parameters: > > ```swift theme={"dark"} > PrimerCheckout( > clientToken: clientToken, > primerSettings: settings, > onShippingAddressChange: { change in try await myBackend.rates(for: change.shippingAddress) }, > onShippingOptionChange: { change in > try await myBackend.commitShipping(optionId: change.selectedShippingOption.id) > } > ) > ``` ### The PATCH Your backend PATCHes `order.shipping` onto the client session. The SDK never sets the shipping amount itself, so the shopper's device cannot change the amount that is charged: ```bash theme={"dark"} curl -X PATCH https://api.sandbox.primer.io/client-session \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "clientToken": "YOUR_CLIENT_TOKEN", "orderId": "order-123", "order": { "shipping": { "methodId": "standard", "methodName": "Standard", "methodDescription": "5-7 business days", "amount": 500 }, "lineItems": [ { "itemId": "sku-1", "description": "T-shirt", "amount": 2000, "quantity": 1 } ] } }' ``` > [!WARNING] > > **Do not send a top-level `amount`.** It pins the order total and overrides Primer's recalculation. The shopper is charged the total without shipping, and the shipping you just confirmed is dropped silently. ### Tax Primer recomputes the order total as: ``` sum over line items of (quantity x amount + taxAmount - discountAmount) + shipping.amount + any fees ``` If the destination changes the tax due, set `taxAmount` on each line item and re-send the full `lineItems` array in the same PATCH. Two things to watch: * `taxAmount` is added once per line. It is not multiplied by `quantity`. * A top-level `order.taxAmount` is **not** included in the recalculated total. Use per line item tax, or a fee. ## Step 4. Primer verifies and refreshes After you acknowledge, the SDK re-reads the client session and checks that `order.shipping.methodId` and `order.shipping.amount` match the option that was selected. If they match, the sheet total updates and the shopper can authorize. If they do not, the attempt fails with an integration error. On Android, the refreshed session reaches your app as [`PrimerCheckoutState.Ready`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state), like any other client session update, so any state you derive from it picks up the new total. On iOS, a confirmation that does not match does not fail the attempt while the sheet is open. The sheet keeps the option your backend last confirmed. See [When something goes wrong](#when-something-goes-wrong). On Android, a confirmation that does not match shows a recoverable error in the sheet. See [When something goes wrong](#when-something-goes-wrong). ## Lifecycle and edge cases ### Timeouts Each callback has **20 seconds** to respond. Apple and Google also apply their own limit inside the sheet, which we do not control, so treat 20 seconds as a ceiling rather than a budget. Keep rate calls and confirmations fast. > [tab] Web > > | Callback | If you do not respond in time | > | - | - | > | `primer:shipping-address-change` | The sheet shows a recoverable error and stays open. The shopper can try another address. | > | `primer:shipping-option-change` | The sheet shows a recoverable error, and the payment attempt then fails at authorization. The confirmation is not retried. | > [tab] Android > > On Android the 20 seconds cover the whole Google Pay callback. On sheet open that is the address handler, the option handler and the client-session read together, so keep both handlers well inside it. > > | Handler | If you do not return in time, or throw | > | - | - | > | `onShippingAddressChange` | The sheet shows a recoverable error and stays open. The shopper can try another address. This includes confirming the pre-selected option, which runs in the same callback. | > | `onShippingOptionChange` | The confirmation is not recorded and the sheet shows a recoverable error. If the shopper still authorizes, the SDK blocks authorization and nothing is charged. | > [tab] iOS > > | Handler | If you do not return in time, or throw | > | - | - | > | `onShippingAddressChange` | The sheet stays open. The shopper can try another address. This includes confirming the pre-selected option, which runs in the same address update. | > | `onShippingOptionChange` | The confirmation is not recorded. The sheet stays open and shows the option your backend last confirmed, so the shopper can pay for that option or pick again. Nothing is charged for the failed option. | ### When something goes wrong > [tab] Web > > Failures in this flow surface on `primer:payment-failure`, like any other payment failure: > > ```typescript theme={"dark"} > checkout.addEventListener('primer:payment-failure', (event) => { > const { error } = event.detail; > console.error(error.origin, error.code, error.message, error.suggestion); > }); > ``` > > * `error.origin` is `integration` when the fix is on your side, and `primer` when it is on ours. > * `error.code` is `REQUEST_TIMEOUT` when a callback was not answered in time, and `REQUEST_ERROR` when the confirmation did not match the selection. > * `error.suggestion` carries a short, actionable hint. Read it first. > > See [Log errors and debugging](/docs/checkout/primer-checkout/guides-and-recipes/log-errors-debugging) for the wider error model. > [tab] Android > > Failures while the sheet is open are shown inside the sheet, and the shopper can recover without relaunching it: > > * An empty option list shows "We do not ship to this address". The shopper can enter another address. > * When the shopper picks an option and your handler throws, times out, or the confirmation does not match, the sheet shows "Something went wrong. Please try again." The shopper can pick again. > * When the same happens while the sheet opens or after an address change, the error shows on the address and no options are listed, because the pre-selected option could not be confirmed. The shopper can enter another address. > * Authorization with no verified confirmation is blocked and nothing is charged. > > While an address error is showing, the sheet's Pay button stays enabled. If the shopper taps it, Google Pay rejects the payment with its own "Request failed" dialog, and the attempt ends as a failure in your app. Nothing is charged. > > Failures after the sheet closes surface as [`PrimerCheckoutState.Failure`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state), like any other payment failure. > [tab] iOS > > Failures while the sheet is open are handled inside the sheet: > > * An empty option list shows Apple's "address not serviceable" error. The shopper can enter another address. > * An address handler that throws or times out keeps the sheet open. The shopper can try another address. > * When the shopper picks an option and its confirmation fails, the sheet stays open on the option your backend last confirmed. The shopper can pay for that option or pick again. A confirmation fails when the option handler throws or times out, or when the confirmation does not match the option. > * When the pre-selected option fails to confirm after the sheet opens or the address changes, the sheet treats it like an address handler failure. The shopper can try another address. > * Authorization with no verified confirmation fails in the sheet and nothing is charged. The SDK does not confirm the option again at this point. > > Failures after the sheet closes surface as [`PrimerCheckoutState.failure`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state), like any other payment failure. ### No listener or handler responded > [tab] Web > > If nothing responds, either because no listener is registered or because an async listener did not call `preventDefault()`, the SDK logs a console warning and carries on by itself. No options are shown, no shipping is confirmed, and the shopper is charged the total without shipping. > > If the amounts look wrong, check the browser console for a warning about `primer:shipping-address-change` or `primer:shipping-option-change` having no listener. > [tab] Android > > The SDK uses the handlers only when you register `onShippingAddressChange`. Without it, the SDK leaves the sheet alone and `PrimerGooglePayOptions` alone decides what the sheet asks for, as in drop-in. If you register `onShippingOptionChange` without `onShippingAddressChange`, neither runs and the SDK logs a warning. Pass `null` to either method to remove its handler. > > **Registration timing.** The SDK decides whether to use the handlers when it builds the Google Pay request, just before the sheet opens. Register in a `LaunchedEffect` keyed on the controller, or right after `rememberPrimerCheckoutController`, so the handlers are in place before the shopper can tap Google Pay. > > **Repeated callbacks.** Google Pay may call the SDK more than once for the same address, including on sheet open. The SDK collapses these and reuses the options and the confirmation it already has. The address handler runs only when the address differs from the last one it answered. With both handlers registered, the SDK then confirms the pre-selected option again. Treat both as idempotent anyway. > [tab] iOS > > The SDK uses the handlers only when both of these are true: > > * You set `onShippingAddressChange`. > * The client session has no legacy `SHIPPING` checkout module. > > If one of them is false, the SDK leaves the sheet alone and uses the shipping options in the client session. The SDK logs a warning when a legacy `SHIPPING` checkout module overrides your handlers, and when you set `onShippingOptionChange` without `onShippingAddressChange`. > > The SDK checks this when the shopper taps Apple Pay. You can set the handlers on the session at any time before that. ### Retries If a payment fails and the shopper reopens the wallet sheet, the shipping flow starts again from the address change. Options supplied in a previous attempt are not reused. ### Changing the address twice If the shopper edits the address again before the previous confirmation has completed, that earlier confirmation is dropped and the flow restarts from the new address. Your backend can therefore receive a PATCH for an address the shopper has already moved on from. Always price from the address in the request you are handling, never from stored state. ## Troubleshooting > [tab] Web > > | Symptom | Likely cause | > | - | - | > | No shipping selector in the sheet | `requireShippingMethod` is at the wrong nesting level for the wallet, or the client session carries a legacy `SHIPPING` checkout module. | > | Options never appear and no error is raised | Your async listener did not call `preventDefault()`, so the SDK moved on without waiting. Check the console for a "no listener" warning. | > | Authorization fails after the shopper picks an option | Your backend PATCHed a different `methodId` or `amount` than the option the SDK sent, or `continue()` was called before the PATCH landed. | > | The shopper is charged the pre-shipping total | The PATCH included a top-level `amount`, or no listener confirmed the selection. | > [tab] Android > > | Symptom | Likely cause | > | - | - | > | No shipping options in the sheet | `onShippingOptionChange` is not registered, or `onShippingAddressChange` is not registered. | > | The handlers never run | `onShippingAddressChange` is not registered, or it was registered after the sheet opened. If only `onShippingOptionChange` is registered, the log shows a warning. | > | "Something went wrong. Please try again." in the sheet | Your handler threw, took longer than 20 seconds, or your backend PATCHed a different `methodId` or `amount` than the option the SDK sent. | > | Authorization fails after the shopper picks an option | The confirmation for the selected option was never verified. Check the PATCH response and timing on your backend. | > | Google Pay shows "Request failed" \[OR\_BIBED\_06] after an error in the sheet | The shopper tapped Pay while an address error was showing. See [When something goes wrong](#when-something-goes-wrong). Nothing was charged. | > | The shopper is charged the pre-shipping total | The PATCH included a top-level `amount`, which overrides Primer's recalculation. | > | Works in debug, callbacks never arrive in release | The SDK ships consumer keep rules for the callback service. Check that your build does not override them with an aggressive R8 configuration. | > [tab] iOS > > | Symptom | Likely cause | > | - | - | > | No shipping options in the sheet | `onShippingOptionChange` is not set, or one of the conditions in [No listener or handler responded](#no-listener-or-handler-responded) is false. | > | The handlers never run | `onShippingAddressChange` is not set, or the client session carries a legacy `SHIPPING` checkout module. Check the log for a warning. | > | The sheet goes back to the previous option after the shopper picks one | Your handler threw, took longer than 20 seconds, or your backend PATCHed a different `methodId` or `amount` than the option the SDK sent. | > | Authorization fails after the shopper picks an option | The confirmation for the selected option was never verified. Check the PATCH response and timing on your backend. | > | The shopper is charged the pre-shipping total | The PATCH included a top-level `amount`, which overrides Primer's recalculation. | ## See also > [card] [Events reference](/docs/sdk/primer-checkout-web/events-reference) > > Full reference for the shipping events and every other checkout event > [card] [PrimerCheckoutController](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-controller) > > Where the two Android handlers live > [card] [Apple Pay](/docs/connections/payment-methods/apple-pay/overview) > > Configure Apple Pay, including merchant identity and domain verification > [card] [Google Pay](/docs/connections/payment-methods/google-pay/overview) > > Configure Google Pay > [card] [Update client session](/docs/api-reference/v2.4/api-reference/client-session-api/update-client-session) > > API reference for the PATCH used to commit shipping > [card] [PrimerSettings](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-settings) > > Optional Android Google Pay settings, such as asking for the phone number > [card] [PrimerCheckoutSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) > > Where the two iOS handlers live > [card] [iOS Apple Pay integration](/docs/sdk/ios-checkout/v3.0.0-beta/guides/apple-pay-integration) > > Where the iOS Apple Pay shipping options live # External submit button Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/external-submit-button Trigger card form submission from a button outside the checkout. Use your own submit button to trigger payment. On Web, place your button outside the `` component and dispatch a custom event. On Android, override the `submitButton` slot in `PrimerCardForm` with a custom Composable. On iOS, override the `submitButton` slot in `PrimerCardForm` with a custom SwiftUI view. ## Recipe > [tab] Web > > ```html theme={"dark"} > > > > > > > > ``` > > ```javascript theme={"dark"} > document.getElementById('my-pay-button').addEventListener('click', () => { > document.dispatchEvent( > new CustomEvent('primer:card-submit', { > bubbles: true, > composed: true, > }), > ); > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { /* navigate */ } > is PrimerCheckoutState.Failure -> { /* log error */ } > else -> Unit > } > } > > when (state) { > is PrimerCheckoutState.Loading -> CircularProgressIndicator() > is PrimerCheckoutState.Ready -> { > PrimerCheckoutSheet( > checkout = checkout, > cardForm = { > val cardFormController = rememberCardFormController(checkout) > val formState by cardFormController.state.collectAsStateWithLifecycle() > > PrimerCardForm( > controller = cardFormController, > submitButton = { > BrandedPayButton( > isEnabled = formState.isFormValid && !formState.isLoading, > isLoading = formState.isLoading, > onClick = { cardFormController.submit() }, > ) > }, > ) > }, > ) > } > } > } > ``` > [tab] iOS > > ```swift theme={"dark"} > struct CheckoutView: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject( > wrappedValue: PrimerCheckoutSession(clientToken: clientToken) > ) > } > > var body: some View { > ScrollView { > PrimerCardForm(submitButton: { formSession in > BrandedPayButton(session: formSession) > }) > .padding() > } > .primerCheckoutSession(session) { state in > switch state { > case .success: break // navigate > case .failure: break // log error > default: break > } > } > } > } > > struct BrandedPayButton: View { > @ObservedObject var session: PrimerCardFormSession > > var body: some View { > Button(action: { session.submit() }) { > Text(session.state.isLoading ? "Processing..." : "Complete payment") > .frame(maxWidth: .infinity, minHeight: 50) > } > .buttonStyle(.borderedProminent) > .disabled(!session.state.isValid || session.state.isLoading) > } > } > ``` ## How it works > [tab] Web > > 1. Place your custom button outside the `` component > > 2. Listen for click events on your button > > 3. Dispatch the `primer:card-submit` custom event to trigger form submission > > 4. The event bubbles up to the card form and initiates the payment > > > [!NOTE] > > > > The `bubbles: true` and `composed: true` options are required so the event can cross shadow DOM boundaries and reach the card form component. > [tab] Android > > 1. Create a `PrimerCardFormController` to access form state > 2. Pass a custom `submitButton` to `PrimerCardForm` > 3. Use `formState.isFormValid` to control the enabled state and `formState.isLoading` for a loading indicator > 4. Call `controller.submit()` to trigger payment > [tab] iOS > > 1. Pass a custom `submitButton` slot to `PrimerCardForm`; the other slots keep their default rendering > 2. The slot receives the active `PrimerCardFormSession`; observe it with `@ObservedObject` > 3. Call `session.submit()` from your custom button to trigger payment > 4. Read `session.state.isValid` and `session.state.isLoading` to control the enabled state and loading indicator ## Variations ### Button with loading state > [tab] Web > > ```javascript theme={"dark"} > const payButton = document.getElementById('my-pay-button'); > const checkout = document.querySelector('primer-checkout'); > > payButton.addEventListener('click', () => { > document.dispatchEvent( > new CustomEvent('primer:card-submit', { > bubbles: true, > composed: true, > }), > ); > }); > > // Update button state during processing > checkout.addEventListener('primer:state-change', (event) => { > const { isProcessing } = event.detail; > payButton.disabled = isProcessing; > payButton.textContent = isProcessing ? 'Processing...' : 'Pay Now'; > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > @Composable > fun BrandedPayButton( > isEnabled: Boolean, > isLoading: Boolean, > onClick: () -> Unit, > ) { > Button( > onClick = onClick, > enabled = isEnabled, > modifier = Modifier > .fillMaxWidth() > .height(52.dp), > shape = RoundedCornerShape(12.dp), > colors = ButtonDefaults.buttonColors( > containerColor = Color(0xFF6C5CE7), > disabledContainerColor = Color(0xFF6C5CE7).copy(alpha = 0.4f), > ), > ) { > if (isLoading) { > CircularProgressIndicator( > modifier = Modifier.size(20.dp), > color = Color.White, > strokeWidth = 2.dp, > ) > } else { > Icon( > imageVector = Icons.Default.Lock, > contentDescription = null, > modifier = Modifier.size(18.dp), > ) > Spacer(Modifier.width(8.dp)) > Text( > text = "Complete Purchase", > style = MaterialTheme.typography.titleMedium, > ) > } > } > } > ``` > [tab] iOS > > ```swift theme={"dark"} > struct BrandedPayButton: View { > @ObservedObject var session: PrimerCardFormSession > > var body: some View { > Button(action: { session.submit() }) { > HStack { > if session.state.isLoading { > ProgressView() > .tint(.white) > } > Text(session.state.isLoading ? "Processing..." : "Complete purchase") > } > .frame(maxWidth: .infinity, minHeight: 52) > } > .buttonStyle(.borderedProminent) > .tint(.purple) > .disabled(!session.state.isValid || session.state.isLoading) > } > } > ``` > > Pass it to the `submitButton` slot, leaving the card fields at their defaults: > > ```swift theme={"dark"} > PrimerCardForm(submitButton: { session in > BrandedPayButton(session: session) > }) > ``` ### Programmatic submission with amount > [tab] Web > > Alternatively, you can call the submit method directly on the card form: > > ```javascript theme={"dark"} > const cardForm = document.querySelector('primer-card-form'); > const payButton = document.getElementById('my-pay-button'); > > payButton.addEventListener('click', async () => { > try { > await cardForm.submit(); > } catch (error) { > console.error('Submission failed:', error); > } > }); > ``` > [tab] Android > > Access the client session from the checkout state to show the amount on your button: > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > when (state) { > is PrimerCheckoutState.Loading -> CircularProgressIndicator() > is PrimerCheckoutState.Ready -> { > val clientSession = (state as PrimerCheckoutState.Ready).clientSession > val formattedAmount = checkout.formatAmount(clientSession.totalAmount ?: 0) > > PrimerCheckoutSheet( > checkout = checkout, > cardForm = { > val controller = rememberCardFormController(checkout) > val formState by controller.state.collectAsStateWithLifecycle() > > PrimerCardForm( > controller = controller, > submitButton = { > Button( > onClick = { controller.submit() }, > enabled = formState.isFormValid && !formState.isLoading, > modifier = Modifier.fillMaxWidth(), > ) { > Text("Pay $formattedAmount") > } > }, > ) > }, > ) > } > } > } > ``` > [tab] iOS > > Show the amount on your button. Read `session.clientSession?.totalAmount`, add the card surcharge from `formSession.state.surchargeAmountRaw`, and pass the sum to `session.formatAmount(_:)`. Render the label through the `submitButton` slot: > > ```swift theme={"dark"} > struct CheckoutView: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject( > wrappedValue: PrimerCheckoutSession(clientToken: clientToken) > ) > } > > var body: some View { > ScrollView { > PrimerCardForm(submitButton: { formSession in > Button(action: { formSession.submit() }) { > Text(amountLabel(formSession)) > .frame(maxWidth: .infinity, minHeight: 50) > } > .buttonStyle(.borderedProminent) > .disabled(!formSession.state.isValid || formSession.state.isLoading) > }) > .padding() > } > .primerCheckoutSession(session) { state in > switch state { > case .success: break // navigate > case .failure: break // log error > default: break > } > } > } > > private func amountLabel(_ formSession: PrimerCardFormSession) -> String { > guard let total = session.clientSession?.totalAmount, > let formatted = session.formatAmount(total + (formSession.state.surchargeAmountRaw ?? 0)) > else { return "Pay" } > return "Pay \(formatted)" > } > } > ``` > > > [!NOTE] > > > > `totalAmount` is the amount you set when you created the client session, in minor units, for example `1000` for \$10.00. `formatAmount(_:)` uses the currency's own decimal digits, so it is also correct for currencies such as JPY. `clientSession` is `nil` until the session is ready, so the button reads "Pay" until then. `clientSession` is a snapshot from when the checkout became ready, and its `totalAmount` does not include the card surcharge. `formSession.state.surchargeAmountRaw` holds the surcharge for the detected card network in minor units. It is `nil` when no surcharge applies, so the button shows the plain total until the shopper enters a card number that has one. ## See also > [card] [Disable buttons during payment](/docs/checkout/primer-checkout/guides-and-recipes/disable-buttons-during-payment) > > Prevent double submission during payment processing > [card] [Build a custom card form](/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form) > > Step-by-step guide to building a fully custom card form # Log errors for debugging Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/log-errors-debugging Capture and log payment errors for debugging and support. Log payment errors with diagnostic information to help debug issues and work with Primer support. ## Recipe > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > > primer.onPaymentFailure = ({ error }) => { > console.error('Payment failed:', { > code: error.code, > message: error.message, > diagnosticsId: error.diagnosticsId, // Share with Primer support > }); > }; > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Failure -> { > val error = s.primerError > Log.e("Checkout", "Payment failed: ${error.description}") > Log.e("Checkout", "Error code: ${error.errorCode}") > Log.e("Checkout", "Diagnostics ID: ${error.diagnosticsId}") > Log.e("Checkout", "Recovery: ${error.recoverySuggestion}") > } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > ``` > [tab] iOS > > ```swift theme={"dark"} > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > if case let .failure(error, checkoutData) = state { > print("[Primer] Error ID: \(error.errorId)") > print("[Primer] Description: \(error.errorDescription ?? "N/A")") > print("[Primer] Diagnostics: \(error.diagnosticsId)") > print("[Primer] Recovery: \(error.recoverySuggestion ?? "N/A")") > print("[Primer] Payment ID: \(checkoutData?.payment?.id ?? "none")") > print("[Primer] Order ID: \(checkoutData?.payment?.orderId ?? "none")") > } > } > ) > ``` ## How it works > [tab] Web > > 1. Listen for the `primer:ready` event to access the Primer SDK instance > 2. Set the `onPaymentFailure` callback > 3. Log the error details including `diagnosticsId` which helps Primer support investigate issues > [tab] Android > > 1. Observe `checkout.state` with `collectAsStateWithLifecycle()` and react in a `LaunchedEffect` > 2. Handle `PrimerCheckoutState.Failure` to access the `PrimerError` > 3. Log the error details including `diagnosticsId` which helps Primer support investigate issues > > Every `PrimerError` includes these properties: > > | Property | Type | Description | > | - | - | - | > | `errorId` | `String` | Unique error identifier | > | `description` | `String` | Human-readable error message | > | `errorCode` | `String?` | Error code (e.g., `"card_declined"`) | > | `diagnosticsId` | `String` | Reference ID for Primer support | > | `recoverySuggestion` | `String?` | Suggested recovery action for the user | > [tab] iOS > > 1. Receive `PrimerCheckoutState` through the `onCompletion` closure on `PrimerCheckout` or the `.primerCheckoutSession(_:theme:onCompletion:)` modifier, and match `.failure` > 2. Access `PrimerError` properties for debugging details > 3. Log the `diagnosticsId` which helps Primer support investigate issues > > Every `PrimerError` includes these properties: > > | Property | Type | Description | > | - | - | - | > | `errorId` | `String` | Stable identifier for the error category | > | `errorDescription` | `String?` | Human-readable error message for logging | > | `diagnosticsId` | `String` | Reference ID for Primer support | > | `recoverySuggestion` | `String?` | Developer-facing hint on how to fix the cause. `nil` for most payment failures, such as `payment-failed` | > > `.failure` also carries `checkoutData`. When the payment was created before it failed (for example a decline), `checkoutData?.payment` holds the payment ID and order ID. Log them so you can look up the payment on your backend. `checkoutData` is `nil` when the failure happened before a payment existed (initialization, tokenization, connectivity). > > `.failure` arrives once per failed payment attempt. With the SDK error screen on (the default), the checkout stays open for a retry. Don't treat `.failure` as the end of the session. `.success` or `.dismissed` arrives once and ends the session. > > If loading fails, `PrimerCheckout` delivers `.failure`. With the SDK error screen on (the default), the checkout stays open for a retry. With `isErrorScreenEnabled: false`, the checkout shows nothing and you build your own retry UI. The `.primerCheckoutSession` modifier delivers a load failure once and ends the session. > [!TIP] > > The `diagnosticsId` is a unique identifier for the error. When contacting Primer support, always include this ID to help them quickly locate and diagnose the issue. ## Variations ### Send errors to logging service > [tab] Web > > ```javascript theme={"dark"} > primer.onPaymentFailure = ({ error, paymentMethodType }) => { > // Send to your logging service (Sentry, LogRocket, etc.) > Sentry.captureException(new Error(error.message), { > extra: { > code: error.code, > diagnosticsId: error.diagnosticsId, > paymentMethod: paymentMethodType, > }, > }); > }; > ``` > [tab] Android > > ```kotlin theme={"dark"} > is PrimerCheckoutState.Failure -> { > val error = s.primerError > Sentry.captureException(Exception(error.description)) { scope -> > scope.setExtra("error_code", error.errorCode.orEmpty()) > scope.setExtra("diagnostics_id", error.diagnosticsId) > } > } > ``` > [tab] iOS > > ```swift theme={"dark"} > if case let .failure(error, _) = state { > ErrorLogger.log( > errorId: error.errorId, > description: error.errorDescription ?? "Unknown error", > diagnosticsId: error.diagnosticsId > ) > } > ``` ### Custom error display > [tab] Web > > ```javascript theme={"dark"} > const primerEvents = [ > 'primer:ready', > 'primer:state-change', > 'primer:methods-update', > 'primer:payment-start', > 'primer:payment-success', > 'primer:payment-failure', > 'primer:card-success', > 'primer:card-error', > 'primer:bin-data-available', > 'primer:vault-methods-update', > ]; > > primerEvents.forEach((eventName) => { > document.addEventListener(eventName, (event) => { > console.log(`[${eventName}]`, event.detail); > }); > }); > ``` > [tab] Android > > Override the error slot in `PrimerCheckoutSheet` to display a custom error screen. Observe `checkout.state` separately to log diagnostics: > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Diagnostics: ${s.primerError.diagnosticsId}") > } > else -> Unit > } > } > > PrimerCheckoutSheet( > checkout = checkout, > error = { primerError, _ -> > Column( > modifier = Modifier > .fillMaxWidth() > .padding(24.dp), > horizontalAlignment = Alignment.CenterHorizontally, > ) { > Icon( > imageVector = Icons.Default.Warning, > contentDescription = null, > tint = MaterialTheme.colorScheme.error, > modifier = Modifier.size(48.dp), > ) > Spacer(Modifier.height(16.dp)) > Text( > text = "Something went wrong", > style = MaterialTheme.typography.titleLarge, > ) > Spacer(Modifier.height(8.dp)) > Text( > text = primerError.description, > style = MaterialTheme.typography.bodyMedium, > textAlign = TextAlign.Center, > color = MaterialTheme.colorScheme.onSurfaceVariant, > ) > if (primerError.recoverySuggestion != null) { > Spacer(Modifier.height(4.dp)) > Text( > text = primerError.recoverySuggestion!!, > style = MaterialTheme.typography.bodySmall, > color = MaterialTheme.colorScheme.onSurfaceVariant, > textAlign = TextAlign.Center, > ) > } > Spacer(Modifier.height(24.dp)) > Button( > onClick = { checkout.refresh() }, > modifier = Modifier.fillMaxWidth(), > ) { > Text("Try again") > } > Spacer(Modifier.height(8.dp)) > OutlinedButton( > onClick = { checkout.dismiss() }, > modifier = Modifier.fillMaxWidth(), > ) { > Text("Use a different method") > } > } > }, > onDismiss = { }, > ) > ``` > [tab] iOS > > Compose the checkout with `PrimerCheckoutSession`. Turn off the SDK error screen with `PrimerUIOptions(isErrorScreenEnabled: false)`. Then use each `.failure` from the `.primerCheckoutSession` modifier's `onCompletion` to drive your own error screen. If you leave the SDK error screen on (the default), it opens in a sheet over your view on every failed payment. Your error view appears only after the shopper dismisses that sheet. > > ```swift theme={"dark"} > struct CheckoutView: View { > @StateObject private var session: PrimerCheckoutSession > @State private var paymentError: PrimerError? > > init(clientToken: String) { > let settings = PrimerSettings(uiOptions: PrimerUIOptions(isErrorScreenEnabled: false)) > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken, settings: settings)) > } > > var body: some View { > ScrollView { > if paymentError != nil { > VStack(spacing: 16) { > Image(systemName: "exclamationmark.triangle.fill") > .font(.largeTitle) > .foregroundColor(.red) > Text("Something went wrong") > .font(.title2) > Text("Please try a different payment method.") > .multilineTextAlignment(.center) > .foregroundColor(.secondary) > Button("Try again") { > paymentError = nil > Task { > if session.phase == .ready { > await session.refresh() > } else { > session.cancel() > await session.start() > } > } > } > .buttonStyle(.borderedProminent) > } > .padding(24) > } else { > PrimerPaymentMethods() > PrimerCardForm() > } > } > .primerCheckoutSession(session) { state in > if case let .failure(error, checkoutData) = state { > print("[Primer] Error: \(error.errorDescription ?? "N/A")") > print("[Primer] Diagnostics: \(error.diagnosticsId)") > print("[Primer] Payment ID: \(checkoutData?.payment?.id ?? "none")") > paymentError = error > } > } > } > } > ``` > > `refresh()` only reloads a session that has finished loading. If loading failed, "Try again" calls `cancel()` and then `start()` to rebuild the session. ### Inline error handling > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:methods-update', (event) => { > const methods = event.detail.toArray(); > console.table(methods.map((m) => ({ type: m.type, id: m.id }))); > }); > ``` > [tab] Android > > For `PrimerCheckoutHost`, observe `checkout.state` and display your own UI: > > ```kotlin theme={"dark"} > @Composable > fun InlineCheckoutWithErrors(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > var paymentError by remember { mutableStateOf(null) } > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Failure -> { > paymentError = s.primerError > } > is PrimerCheckoutState.Success -> { > paymentError = null > } > else -> Unit > } > } > > when (state) { > is PrimerCheckoutState.Loading -> { > CircularProgressIndicator() > } > is PrimerCheckoutState.Ready -> { > PrimerCheckoutHost(checkout = checkout) { > val cardFormController = rememberCardFormController(checkout) > > Column(Modifier.padding(16.dp)) { > PrimerCardForm(controller = cardFormController) > > paymentError?.let { error -> > Spacer(Modifier.height(16.dp)) > Card( > colors = CardDefaults.cardColors( > containerColor = MaterialTheme.colorScheme.errorContainer, > ), > modifier = Modifier.fillMaxWidth(), > ) { > Row( > modifier = Modifier.padding(16.dp), > verticalAlignment = Alignment.CenterVertically, > ) { > Icon( > imageVector = Icons.Default.Warning, > contentDescription = null, > tint = MaterialTheme.colorScheme.error, > ) > Spacer(Modifier.width(12.dp)) > Column(Modifier.weight(1f)) { > Text( > text = error.description, > style = MaterialTheme.typography.bodyMedium, > ) > if (error.recoverySuggestion != null) { > Text( > text = error.recoverySuggestion!!, > style = MaterialTheme.typography.bodySmall, > ) > } > } > } > } > } > } > } > } > } > } > ``` > [tab] iOS > > Read per-field validation errors from `PrimerCardFormSession.state.fieldErrors` inside a `PrimerCardForm` slot, and handle each failed payment attempt in `onCompletion`: > > ```swift theme={"dark"} > struct InlineCheckoutWithErrors: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > PrimerCardForm( > cardDetails: { cardSession in > CardDetails(session: cardSession) > } > ) > .padding() > } > .primerCheckoutSession(session) { state in > if case let .failure(error, _) = state { > print("[Primer] Payment error: \(error.errorDescription ?? "N/A")") > } > } > } > } > > struct CardDetails: View { > @ObservedObject var session: PrimerCardFormSession > > var body: some View { > VStack(alignment: .leading, spacing: 8) { > CardFormDefaults.cardDetails(session) > ForEach(session.state.fieldErrors) { fieldError in > Text("\(fieldError.fieldType): \(fieldError.message)") > .font(.caption) > .foregroundColor(.red) > } > } > } > } > ``` ## See also > [card] [Track payment in analytics](/docs/checkout/primer-checkout/guides-and-recipes/track-payment-analytics) > > Send payment events to your analytics platform > [card] [Error handling](/docs/checkout/primer-checkout/build-your-ui/error-handling) > > Handle payment failures and display error messages # Manual payment approval Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/manual-payment-approval Approve or abort each payment from your backend before Primer creates it. > [!NOTE] > > **New feature.** Manual payment approval is available to all merchants; no allowlisting or account setup is required. Because it's new, **test your integration end to end in the [sandbox](/docs/testing/overview) before going live in production.** Available on the **Web** SDK ([Primer Checkout](/docs/checkout/primer-checkout/installation)) today; iOS and Android are coming. By default, Primer Checkout creates and processes a payment automatically as soon as the customer submits their details. With **manual payment approval**, Primer pauses after tokenization and waits for your backend to explicitly approve (or abort) the payment before it is created. Once you approve, Primer resumes control and manages the rest of the process, including 3DS, redirects, retries, and webhooks. Manual payment approval gives your backend a decision point between tokenization and payment creation, without handing it the full payment lifecycle. ## When to use it Use manual payment approval when a server-side decision must happen *after* the customer enters their payment details but *before* the payment is created. For example: * Running a fraud or risk check against the card BIN or network. * Confirming stock or inventory at the last moment. * Applying business rules that decide whether the payment should proceed at all. If you don't need a decision point in the middle of the flow, use the [default automatic flow](/docs/checkout/primer-checkout/first-payment) instead. ## How it works The flow is approval-based and payment-method agnostic, and the same sequence works for cards and APMs. ![Manual payment approval sequence diagram](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/primer-checkout/guides-and-recipes/manual-payment-approval-diagram.png) Manual payment approval flow 1. **Your server creates a client session** with `approvalMode: "MANUAL"`. 2. **The customer submits** their payment details. Primer tokenizes the payment method and prepares a *payment attempt*, but does **not** create the payment yet. 3. **The checkout emits `primer:payment-approval-required`** with the `paymentAttemptId`. The SDK maintains a loading state. 4. **Your backend decides** and calls either `/approve` (create the payment) or `/abort` (cancel it). 5. **Your frontend calls `continueFlow()`**. Primer fetches the result and resolves the checkout UI, including any 3DS challenge, automatically. > [!NOTE] > > Approval is scoped to a single **payment attempt**, not the whole session. If a payment is declined, the customer can retry within the same session, which creates a new attempt. See [Retries](#retries-after-a-failed-payment). ## Prerequisites * Primer Checkout already integrated (see [First payment](/docs/checkout/primer-checkout/first-payment)). * An [API key](/docs/api-reference/get-started/authentication) with the following scopes: * `client_tokens:write` for creating the client session. * `transactions:authorize` for approving a payment attempt. * `transactions:cancel` for aborting a payment attempt. ## Step 1. Create a client session in MANUAL mode Create the [client session](/docs/checkout/client-session) on your server and set `approvalMode` to `MANUAL`. This is set at creation only and is immutable; it cannot be changed with `PATCH /client-session`. ```bash theme={"dark"} curl -X POST https://api.primer.io/client-session \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "orderId": "order-123", "currencyCode": "USD", "amount": 1000, "approvalMode": "MANUAL" }' ``` Pass the returned `clientToken` to your frontend and render the checkout: ```html theme={"dark"} ``` ## Step 2. Listen for the approval event When the customer confirms their intention to pay, the checkout dispatches `primer:payment-approval-required` instead of creating the payment. Register a listener on the checkout element: ```javascript theme={"dark"} const checkout = document.querySelector('primer-checkout'); checkout.addEventListener('primer:payment-approval-required', async (event) => { const { clientSessionId, paymentAttemptId, paymentMethodToken, continueFlow } = event.detail; // Send the attempt to your backend, which decides whether to approve or abort. // Your frontend does not need to know which was called. await fetch('/my-backend/handle-payment-approval', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientSessionId, paymentAttemptId }), }); // Resume the SDK once your backend has responded. await continueFlow(); }); ``` ### Event payload `primer:payment-approval-required` is a [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent); its data is on `event.detail`. | Property | Type | Description | | - | - | - | | `clientSessionId` | `string` | The client session identifier. | | `paymentAttemptId` | `string` | Identifies the specific attempt. **Required** when calling `/approve` or `/abort`. | | `paymentMethodToken` | `PaymentMethodToken` | The tokenized payment method, including `paymentInstrumentType` and `paymentInstrumentData` (e.g. card `network`, `last4Digits`, `cardholderName`). Use it to run fraud or risk checks. | | `continueFlow` | `() => Promise` | Call after your backend has approved or aborted. Resolves once the checkout shows the result screen. | | `timestamp` | `number` | Unix timestamp (seconds) when the event was dispatched. | > [!WARNING] > > If the customer refreshes the page while an attempt is still awaiting approval, the SDK **re-emits** `primer:payment-approval-required`. > > Use `paymentAttemptId` to deduplicate on your backend. If you've already approved that attempt, skip the second approval and just call `continueFlow()`. ## Step 3. Approve or abort from your backend Your backend uses the `paymentAttemptId` from the event to either approve or abort the attempt. ### Approve Approving triggers payment creation. Primer creates the payment, runs any required action (such as 3DS), and processes it. ```bash theme={"dark"} curl -X POST https://api.primer.io/payment-attempts/{paymentAttemptId}/approve \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" ``` The request does not accept any properties in the body; the attempt is identified by the path. A `200 OK` confirms the approval was accepted and Primer has resumed control: ```json theme={"dark"} { "paymentAttemptId": "6c5d3a30-3c2e-4f55-9d8e-5b3d5e3a5c7f", "paymentId": "IHQlakKC" } ``` Use `paymentId` to look the payment up later via the [Payments API](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment). The `200` confirms approval only; it does **not** convey the payment outcome (success, decline, or 3DS required). The SDK resolves the outcome after you call `continueFlow()`. > [!WARNING] > > To update the session before approving (for example to attach an invoice ID to `metadata`), call [`PATCH /client-session`](/docs/api-reference/v2.4/api-reference/client-session-api/update-client-session) *before* `/approve`; the approve endpoint does not accept session updates. > > Sending `metadata` in a `PATCH` **replaces the entire `metadata` object; it does not merge.** Sending only your new key wipes any keys already on the session, so send the full `metadata` object with the existing keys plus the new one. > > Note that the client session shown in the dashboard is the one captured during tokenization, so if the session is patched before approval, the client session that is shown is not the one used for the payment. ### Abort Aborting cancels the attempt. No payment is created and the tokenized payment method is invalidated. ```bash theme={"dark"} curl -X POST https://api.primer.io/payment-attempts/{paymentAttemptId}/abort \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "reason": "fraud-check-failed" }' ``` The `reason` field is optional free text; do not include cardholder data. Primer stores it for internal observability only: it is not currently shown in the Dashboard or retrievable via the API. A `200 OK` returns `{ "paymentAttemptId": "..." }`. ### Error responses | Status | `errorId` | Meaning | | - | - | - | | `404` | `PaymentAttemptNotFound` | The attempt does not exist or belongs to another account. | | `409` | `ClientSessionNotManual` | The session is not in `MANUAL` approval mode. | | `409` | `InvalidPaymentAttemptTransition` | The attempt is not the current attempt for its session, or is already in a terminal state. | | `409` | `PaymentAttemptSessionConflict` | The attempt cannot be approved, as client session updates have been made to disallowed fields since attempt creation | | `409` | `IdempotencyKeyAlreadyExists` | A concurrent or duplicate approve already created a payment for this attempt. (`/approve` only.) | | `410` | `PaymentAttemptExpired` | The attempt expired (see [Timeout](#timeout)) and can no longer be approved or aborted. | > [!NOTE] > > `paymentAttemptId` acts as the idempotency key, so a duplicate or retried `/approve` never creates a second payment. > > A replay does **not** return the original `200`. Instead it returns `409 IdempotencyKeyAlreadyExists`, which confirms the payment was already created for that attempt (for example, if your first call succeeded but its response timed out). > > Treat that `409` as "already approved": look the payment up via the [Payments API](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) or the webhooks below, and don't create a new attempt. ## Step 4. Resume the checkout After your backend responds, call `continueFlow()` from the event handler. The SDK fetches the client session and the resulting payment and resolves the UI on its own; you don't route payment results back to the SDK. * **Approved and successful** → the checkout shows its success screen. * **Approved and requires 3DS** → the SDK presents the 3DS challenge, then resolves to success or failure automatically. * **Approved but declined, or aborted** → the checkout unlocks the payment method form and shows a message that the payment could not be completed. The customer can retry with the same or a different payment method, which starts a new attempt. The final result is delivered through the **same events as the automatic flow**. Listen for `primer:payment-success` and `primer:payment-failure` to react to the outcome. You don't need any approval-specific result handling. ```javascript theme={"dark"} checkout.addEventListener('primer:payment-success', (event) => { const { payment } = event.detail; window.location.href = `/confirmation?order=${payment.orderId}`; }); checkout.addEventListener('primer:payment-failure', (event) => { const { error } = event.detail; console.error('Payment failed:', error.diagnosticsId); }); ``` > [!NOTE] > > These events update the customer-facing UI. The source of truth for your **backend** is webhooks; a backend-driven integration shouldn't rely on the browser to confirm a payment. > > Once you approve, the payment follows the normal Primer payment lifecycle, so your server receives the standard [`PAYMENT.STATUS`](/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-status-update) webhook as the payment moves to `AUTHORIZED`, `DECLINED`, or a failed state, exactly as in the automatic flow. > > Use those webhooks to fulfill the order and reconcile. See [Configure webhooks](/docs/api-reference/get-started/configure-webhooks). > [!NOTE] > > `continueFlow()` is the primary signal, but as a safety net the SDK also polls automatically after a few seconds if `continueFlow()` is never called (for example after a frontend crash). You should still always call it for the best experience. ## Full example ```javascript theme={"dark"} const checkout = document.querySelector('primer-checkout'); checkout.addEventListener('primer:payment-approval-required', async (event) => { const { clientSessionId, paymentAttemptId, paymentMethodToken, continueFlow } = event.detail; try { // Your backend decides whether to approve or abort, using paymentAttemptId. const response = await fetch('/my-backend/handle-payment-approval', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientSessionId, paymentAttemptId, network: paymentMethodToken.paymentInstrumentData?.network, }), }); if (!response.ok) { console.error('Approval decision failed'); } } finally { // Always resume the SDK so the customer is never stuck on a spinner. await continueFlow(); } }); ``` On your backend, approve or abort the attempt: ```javascript theme={"dark"} // POST /my-backend/handle-payment-approval app.post('/my-backend/handle-payment-approval', async (req, res) => { const { paymentAttemptId } = req.body; const fraudOk = await runFraudCheck(req.body); const endpoint = fraudOk ? 'approve' : 'abort'; const primerResponse = await fetch( `https://api.primer.io/payment-attempts/${paymentAttemptId}/${endpoint}`, { method: 'POST', headers: { 'X-Api-Key': process.env.PRIMER_API_KEY, 'X-Api-Version': '2.4', 'Content-Type': 'application/json', }, body: fraudOk ? undefined : JSON.stringify({ reason: 'fraud-check-failed' }), }, ); res.status(primerResponse.ok ? 200 : 502).json(await primerResponse.json()); }); ``` ## Lifecycle and edge cases ### While awaiting approval Between the `primer:payment-approval-required` event and your `continueFlow()` call, the checkout is locked: it shows a loading state and the customer cannot change payment method or submit again. This prevents a race between a new tokenization and an in-flight `/approve`. The checkout reports this through `primer:state-change` as `isProcessing: true`. Once you call `continueFlow()` and the attempt resolves, the checkout unlocks, showing the result on success, or returning the customer to the payment form to retry after a decline. ### Retries after a failed payment A payment decline (card declined, 3DS failure, abandonment) is a payment-level outcome; it does not reopen the attempt. To retry, the customer selects a payment method and re-enters their details, which tokenizes a new attempt within the same session and emits a fresh `primer:payment-approval-required` event. You don't need a new client session. Only one attempt can be active at a time. A new attempt can only start once the previous one is in a terminal state (declined, aborted, or expired). Retries are bounded by the session's lifetime (24 hours). ### 3DS 3DS is handled automatically after approval; you don't write any 3DS code. When the customer abandons or fails a 3DS challenge, Primer treats it as a payment decline and the standard retry path applies. ### Timeout While your backend decides, the customer waits on a loading state and the checkout is locked (see [While awaiting approval](#while-awaiting-approval)), so make the decision quickly. If your backend calls neither `/approve` nor `/abort` within **90 seconds**, the attempt expires automatically. No payment is created and the tokenized payment method is invalidated. The checkout unlocks the payment method form with a message that the payment could not be completed, and the customer can retry. The 90-second window is fixed and is not configurable. A subsequent `/approve` or `/abort` on an expired attempt returns `410 PaymentAttemptExpired`. > [!WARNING] > > Respond well within the 90-second window. If the attempt expires, it's lost: the customer has to re-enter their payment details to start a new attempt, which hurts conversion. Keep the approve/abort decision fast (fraud and risk checks at this point typically complete in a few seconds) and move any slow or non-blocking work to an asynchronous process *after* you've responded. ### Browser refresh If the customer refreshes mid-flow, the SDK re-reads the session state and resumes accordingly: | Attempt state on refresh | What the customer sees | | - | - | | No attempt yet | Payment method form (normal checkout) | | Awaiting approval | Loading state; `primer:payment-approval-required` is re-emitted | | Approved, processing | Loading state, then resolves to the result | | Approved, succeeded | Success screen | | Approved but declined, aborted, or expired | The payment method form unlocks with a message that the payment could not be completed; the customer can retry | ## See also > [card] [Events reference](/docs/sdk/primer-checkout-web/events-reference) > > Full reference for primer:payment-approval-required and all other events > [card] [Approve a payment attempt](/docs/api-reference/v2.4/api-reference/payment-attempts-api/approve-a-payment-attempt) > > API reference for the approve endpoint > [card] [Abort a payment attempt](/docs/api-reference/v2.4/api-reference/payment-attempts-api/abort-a-payment-attempt) > > API reference for the abort endpoint > [card] [Client session](/docs/checkout/client-session) > > Create and configure a client session > [card] [Migrating from the legacy flow](/docs/checkout/primer-checkout/migration/manual-flow) > > Move an existing manual payment creation integration to this flow # Guides and recipes Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/overview Browse what can be customized in Primer Checkout – payment flow, user experience, custom controls and vault – with links to the guide or recipe for each task. Primer Checkout recipes are short, focused how-to guides that walk you through completing a specific task. Recipes are a great way to add new features or customize behavior in your checkout by following step-by-step instructions. Each guide includes platform-specific code examples for **Web**, **Android**, and **iOS**. ## Guides In-depth tutorials that cover larger topics from start to finish. > [card] [Build a custom card form](/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form) > > Create and customize your own card payment form with full control over layout, styling, and behavior ## Recipes Quick solutions for common tasks. Each recipe shows you how to accomplish one specific thing. ### Payment flow > [card] [Redirect after payment](/docs/checkout/primer-checkout/guides-and-recipes/redirect-after-payment) > > Navigate users to a confirmation page after completing payment > [card] [Show success message](/docs/checkout/primer-checkout/guides-and-recipes/show-success-message) > > Display a custom success message or modal after payment > [card] [Track in analytics](/docs/checkout/primer-checkout/guides-and-recipes/track-payment-analytics) > > Send payment events to your analytics platform > [card] [Log errors](/docs/checkout/primer-checkout/guides-and-recipes/log-errors-debugging) > > Capture and log payment errors for debugging > [card] [Prevent duplicate payments](/docs/checkout/primer-checkout/guides-and-recipes/use-idempotency-keys) > > Prevent duplicate payments by attaching an idempotency key > [card] [Manual payment approval](/docs/checkout/primer-checkout/guides-and-recipes/manual-payment-approval) > > Approve or abort each payment from your backend before Primer creates it > [card] [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping) > > Price and confirm shipping options inside the Apple Pay and Google Pay sheets > [card] [BIN data and click to pay](/docs/checkout/primer-checkout/guides-and-recipes/use-bin-data-to-control-click-to-pay) > > Use BIN Data to Control Click to Pay ### User experience > [card] [Pre-fill cardholder name](/docs/checkout/primer-checkout/guides-and-recipes/prefill-cardholder-name) > > Automatically fill in the cardholder name from user profile > [card] [Show loading indicator](/docs/checkout/primer-checkout/guides-and-recipes/show-loading-indicator) > > Display a loading state while payment is processing > [card] [Disable buttons during payment](/docs/checkout/primer-checkout/guides-and-recipes/disable-buttons-during-payment) > > Disable external buttons while payment is processing ### Custom controls > [card] [External submit button](/docs/checkout/primer-checkout/guides-and-recipes/external-submit-button) > > Trigger card form submission from a button outside the checkout > [card] [Display card network](/docs/checkout/primer-checkout/guides-and-recipes/display-card-network) > > Show the card brand logo as users type their card number ### Vault > [card] [Display saved payment methods](/docs/checkout/primer-checkout/guides-and-recipes/display-saved-payment-methods) > > Show saved payment methods count and list saved cards # Pre-fill cardholder name Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/prefill-cardholder-name Automatically fill in the cardholder name from user profile data. Pre-populate the cardholder name field with data from your user's profile to reduce friction at checkout. ## Recipe > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > > const user = getAuthenticatedUser(); > if (user?.fullName) { > primer.setCardholderName(user.fullName); > } > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController(clientToken) > val cardFormController = rememberCardFormController(checkout) > > LaunchedEffect(cardFormController) { > cardFormController.updateCardholderName(userProfile.fullName) > } > ``` > [tab] iOS > > ```swift theme={"dark"} > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > PrimerCardForm() > } > .primerCheckoutSession(session) { state in > // Handle .success and .dismissed. After .ready, a .failure ends one attempt and the customer can retry. > } > .onChange(of: session.phase) { phase in > guard phase == .ready, let cardForm = session.cardForm else { return } > > // The client session already carries the customer you attached on your backend. > let customer = session.clientSession?.customer > let name = [customer?.firstName, customer?.lastName] > .compactMap { $0 } > .joined(separator: " ") > > if !name.isEmpty { > cardForm.updateCardholderName(name) > } > } > } > ``` ## How it works > [tab] Web > > 1. Listen for the `primer:ready` event to access the Primer SDK instance > > 2. Retrieve the user's name from your authentication system or profile data > > 3. Call `primer.setCardholderName()` with the name value > > > [!NOTE] > > > > When using `setCardholderName()`, you don't need to include the `` component in your form if you don't want users to edit the name. > [tab] Android > > 1. Create a `PrimerCardFormController` using `rememberCardFormController()` > > 2. Call `updateCardholderName()` with the user's name inside a `LaunchedEffect` > > 3. The field will display the prefilled name and the user can edit it if needed > > > [!NOTE] > > > > `updateCardholderName()` sets the field value programmatically. The customer can still edit the prefilled name. The same approach works for other fields -- use `updateCardNumber()`, `updateExpiryDate()`, or `updateCvv()` as needed. > [tab] iOS > > 1. Hold a `PrimerCheckoutSession` as a `@StateObject` and apply the `.primerCheckoutSession(_:theme:onCompletion:)` modifier > 2. Once the session reaches `.ready`, read the customer from [`session.clientSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state#primerclientsession) -- these are the details you attached when you created the client session, so there is nothing to pass in from your own screen > 3. The `cardForm` sub-session (a [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session)) is available at the same point -- call `updateCardholderName()` on it > 4. The field shows the name, the customer can still edit it, and the form counts the field as filled, so the submit button is not held back > > Every property on the client session is optional, so build the name defensively -- a session created > without a customer leaves the field untouched rather than writing an empty string. > > > [!NOTE] > > > > The other setters on `PrimerCardFormSession` work the same way: `updateCardNumber()`, > > `updateExpiryDate()`, `updateCvv()`, `updateFirstName()`, `updateLastName()`, > > `updateAddressLine1()`, `updateAddressLine2()`, `updateCity()`, `updateState()`, > > `updatePostalCode()`, `updatePhoneNumber()` and `updateCountryCode()`. Each one changes what its > > field shows and counts the field as filled. `updateCountryCode()` takes a country code such as `"GB"`. If the > > SDK does not recognize the code, the country field stays as it was. A write that lands while the > > customer is typing in a text field does not override their keystrokes. > > > > The values you read back are redacted: `cardForm.state` carries the card number masked to its BIN and > > last four digits, and never carries the CVV. ## Variations ### Pre-fill from shipping address > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > > // Get name from shipping form > const shippingName = document.getElementById('shipping-name').value; > if (shippingName) { > primer.setCardholderName(shippingName); > } > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > LaunchedEffect(cardFormController) { > cardFormController.updateCardholderName(shippingAddress.fullName) > } > ``` > [tab] iOS > > ```swift theme={"dark"} > .onChange(of: session.phase) { phase in > guard phase == .ready, let cardForm = session.cardForm else { return } > > let shipping = session.clientSession?.customer?.shippingAddress > let name = [shipping?.firstName, shipping?.lastName] > .compactMap { $0 } > .joined(separator: " ") > > if !name.isEmpty { > cardForm.updateCardholderName(name) > } > } > ``` ### Pre-fill with editable field If you want to pre-fill but still allow editing, include the cardholder name input and set an initial value: > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > const user = getAuthenticatedUser(); > > if (user?.fullName) { > // Pre-fill the value > primer.setCardholderName(user.fullName); > > // The component will show this value > // and users can still edit it > } > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (state) { > is PrimerCheckoutState.Success -> { } > is PrimerCheckoutState.Failure -> { } > else -> Unit > } > } > > PrimerCheckoutHost( > checkout = checkout, > ) { > val cardFormController = rememberCardFormController(checkout) > > LaunchedEffect(cardFormController) { > cardFormController.updateCardholderName(userProfile.fullName) > } > > PrimerCardForm( > controller = cardFormController, > cardDetails = { > Column { > CardFormDefaults.CardholderField(cardFormController) > Spacer(Modifier.height(8.dp)) > CardFormDefaults.CardNumberField(cardFormController) > Spacer(Modifier.height(8.dp)) > Row(Modifier.fillMaxWidth()) { > CardFormDefaults.ExpiryField( > cardFormController, > Modifier.weight(1f), > ) > Spacer(Modifier.width(8.dp)) > CardFormDefaults.CvvField( > cardFormController, > Modifier.weight(1f), > ) > } > } > }, > ) > } > ``` > [tab] iOS > > The prefilled field is always editable. Recomposing the `cardDetails` slot is how you decide where > the name sits -- here it leads the form, so the customer sees what was filled in for them first: > > ```swift theme={"dark"} > struct PrefilledCardFormScreen: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > PrimerCardForm(cardDetails: { formSession in > VStack(spacing: 16) { > CardFormDefaults.cardholderName(formSession) > CardFormDefaults.cardNumber(formSession) > HStack(spacing: 12) { > CardFormDefaults.expiryDate(formSession) > CardFormDefaults.cvv(formSession) > } > CardFormDefaults.cardNetwork(formSession) > } > .padding() > }) > } > .primerCheckoutSession(session) { state in > // Handle .success and .dismissed. After .ready, a .failure ends one attempt and the customer can retry. > } > .onChange(of: session.phase) { phase in > guard phase == .ready, let cardForm = session.cardForm else { return } > > let customer = session.clientSession?.customer > let name = [customer?.firstName, customer?.lastName] > .compactMap { $0 } > .joined(separator: " ") > > if !name.isEmpty { > cardForm.updateCardholderName(name) > } > } > } > } > ``` > > > [!NOTE] > > > > When you recompose the individual card fields, add `CardFormDefaults.cardNetwork(formSession)` so co-badged cards still get a network selector -- the built-in one is suppressed once you replace the default `cardDetails` section. ## See also > [card] [Build a custom card form](/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form) > > Step-by-step guide to building a fully custom card form > [card] [SDK options](/docs/checkout/primer-checkout/configuration/sdk-options) > > All available SDK configuration options # Redirect after successful payment Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/redirect-after-payment Navigate users to a confirmation page after completing payment. Redirect users to a confirmation or thank you page after a successful payment. ## Recipe > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-success', (event) => { > const { payment } = event.detail; > window.location.href = `/order/confirmation?id=${payment.orderId}`; > }); > ``` > [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 > navController.navigate("confirmation/${payment.orderId}") { > popUpTo("checkout") { inclusive = true } > } > } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > ``` > [tab] iOS > > ```swift theme={"dark"} > struct CheckoutView: View { > let clientToken: String > @State private var paymentResult: PaymentResult? > @State private var paymentCompleted = false > > var body: some View { > if paymentCompleted, let result = paymentResult { > ConfirmationView(result: result) > } else { > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > if case .success(let result) = state { > paymentResult = result > paymentCompleted = true > } > } > ) > } > } > } > ``` ## How it works > [tab] Web > > 1. Listen for the `primer:payment-success` event on the checkout element > 2. Extract the `payment` object from `event.detail` > 3. Use `window.location.href` to redirect to your confirmation page > 4. Pass the `orderId` as a query parameter so your confirmation page can display order details > [tab] Android > > 1. Observe `checkout.state` with `collectAsStateWithLifecycle()` and react in a `LaunchedEffect` > 2. Handle `PrimerCheckoutState.Success` to access `checkoutData.payment` > 3. Navigate to your confirmation screen using `navController` or your preferred navigation approach > 4. Use `popUpTo` to remove the checkout screen from the back stack > > | Property | Type | Description | > | - | - | - | > | `payment.id` | `String` | The Primer payment ID | > | `payment.orderId` | `String` | Your order ID | > [tab] iOS > > 1. Use the `onCompletion` callback on `PrimerCheckout` > > 2. Match on `.success` to extract the `PaymentResult` > > 3. Update SwiftUI state to navigate to your confirmation view > > 4. Pass `result.paymentId` to your confirmation view. `result.paymentMethodType` tells you which method was used. `result.amount` and `result.currencyCode` are optional and are `nil` for card payments, so take the amount and currency for your receipt from your own order. > > > [!NOTE] > > > > By default, `PrimerCheckout` shows its own success screen and calls `onCompletion` with `.success` when that screen auto-dismisses after 3 seconds. To redirect as soon as the payment succeeds, turn off the SDK screen with `PrimerSettings(uiOptions: PrimerUIOptions(isSuccessScreenEnabled: false))` and pass it as `primerSettings`. > > | Property | Type | Description | > | - | - | - | > | `paymentId` | `String` | The Primer payment ID | > | `paymentMethodType` | `String?` | The payment method type used (e.g. `"PAYMENT_CARD"`) | ## Variations ### Redirect with payment ID > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-success', (event) => { > const { payment } = event.detail; > window.location.href = `/order/confirmation?paymentId=${payment.id}`; > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > is PrimerCheckoutState.Success -> { > val paymentId = s.checkoutData.payment.id > navController.navigate("confirmation/$paymentId") > } > ``` > [tab] iOS > > Pass the payment ID to your confirmation view: > > ```swift theme={"dark"} > struct CheckoutView: View { > let clientToken: String > @State private var paymentId: String? > > var body: some View { > if let paymentId { > ConfirmationView(paymentId: paymentId) > } else { > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > if case .success(let result) = state { > paymentId = result.paymentId > } > } > ) > } > } > } > ``` ### Redirect to different pages based on payment method > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-success', (event) => { > const { payment, paymentMethodType } = event.detail; > > const redirectUrls = { > PAYMENT_CARD: '/confirmation/card', > PAYPAL: '/confirmation/paypal', > default: '/confirmation', > }; > > const url = redirectUrls[paymentMethodType] || redirectUrls.default; > window.location.href = `${url}?id=${payment.orderId}`; > }); > ``` > [tab] Android > > > [!NOTE] > > > > Payment method type is not available on `PrimerCheckoutState.Success`. The SDK manages payment method routing internally. Use the `payment.orderId` to redirect to a single confirmation screen. > [tab] iOS > > > [!NOTE] > > > > The completion result exposes `result.paymentMethodType` (e.g. `"PAYMENT_CARD"`), so you can branch your redirect on it. Pass `result.paymentId` along to your confirmation screen. ## See also > [card] [Show custom success message](/docs/checkout/primer-checkout/guides-and-recipes/show-success-message) > > Display a branded success state after payment > [card] [Track payment in analytics](/docs/checkout/primer-checkout/guides-and-recipes/track-payment-analytics) > > Send payment events to your analytics platform # Show loading indicator Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/show-loading-indicator Display a loading state while payment is processing. Show a loading overlay or spinner while the payment is being processed to provide feedback to users. ## Recipe > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:state-change', (event) => { > const { isProcessing } = event.detail; > > if (isProcessing) { > document.getElementById('loading-overlay').style.display = 'block'; > } else { > document.getElementById('loading-overlay').style.display = 'none'; > } > }); > ``` > [tab] Android > > ### Loading during initialization > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > when (state) { > is PrimerCheckoutState.Loading -> { > Box( > modifier = Modifier.fillMaxSize(), > contentAlignment = Alignment.Center, > ) { > CircularProgressIndicator() > } > } > is PrimerCheckoutState.Ready -> { > PrimerCheckoutSheet(checkout = checkout) > } > } > ``` > > ### Loading during form submission > > ```kotlin theme={"dark"} > val cardFormController = rememberCardFormController(checkout) > val formState by cardFormController.state.collectAsStateWithLifecycle() > > Button( > onClick = { cardFormController.submit() }, > enabled = formState.isFormValid && !formState.isLoading, > modifier = Modifier.fillMaxWidth(), > ) { > if (formState.isLoading) { > CircularProgressIndicator( > modifier = Modifier.size(20.dp), > color = Color.White, > strokeWidth = 2.dp, > ) > } else { > Text("Pay") > } > } > ``` > [tab] iOS > > ### Loading during initialization > > `PrimerCheckout` renders Primer's managed loading screen while it initializes. For a custom inline layout, observe the `PrimerCheckoutSession`'s `phase` and show your own loading UI until it becomes `.ready`: > > ```swift theme={"dark"} > @StateObject private var session: PrimerCheckoutSession > > var body: some View { > ScrollView { > if session.phase == .initializing { > VStack(spacing: 16) { > ProgressView() > .scaleEffect(1.5) > Text("Loading payment methods...") > .font(.subheadline) > .foregroundColor(.secondary) > } > .frame(maxWidth: .infinity, maxHeight: .infinity) > } else { > PrimerCardForm() > } > } > .primerCheckoutSession(session) { state in > handle(state) > } > } > ``` > > ### Loading during form submission > > Drive the submit button from the `PrimerCardFormSession` injected into the slot, using `state.isLoading` and `state.isValid`: > > ```swift theme={"dark"} > PrimerCardForm(submitButton: { session in > Button(action: { session.submit() }) { > if session.state.isLoading { > ProgressView() > .tint(.white) > } else { > Text("Pay") > } > } > .frame(maxWidth: .infinity, minHeight: 48) > .buttonStyle(.borderedProminent) > .disabled(!session.state.isValid || session.state.isLoading) > }) > ``` ## How it works > [tab] Web > > 1. Listen for the `primer:state-change` event > 2. Check the `isProcessing` property from the event detail > 3. Show your loading UI when `isProcessing` is `true` > 4. Hide it when `isProcessing` is `false` > [tab] Android > > The SDK provides two loading states: > > | State Source | Property | When It's True | > | - | - | - | > | `PrimerCheckoutController.state` | `PrimerCheckoutState.Loading` | SDK initializing, fetching configuration | > | `PrimerCardFormController.state` | `isLoading` | Payment is being processed after submit | > [tab] iOS > > The SDK provides two loading states: > > | State Source | Property | When It's Active | > | - | - | - | > | `PrimerCheckoutSession` | `phase == .initializing` | SDK initializing, fetching configuration | > | `PrimerCardFormSession.state` | `isLoading` | From submit until the payment result, including while `onBeforePaymentCreate` waits for your decision | ## Variations ### Custom loading screen > [tab] Web > > ```javascript theme={"dark"} > const overlay = document.getElementById('loading-overlay'); > > checkout.addEventListener('primer:state-change', (event) => { > overlay.classList.toggle('visible', event.detail.isProcessing); > }); > ``` > > ```css theme={"dark"} > .loading-overlay { > opacity: 0; > visibility: hidden; > transition: opacity 0.2s, visibility 0.2s; > } > > .loading-overlay.visible { > opacity: 1; > visibility: visible; > } > ``` > [tab] Android > > Override the `loading` slot in `PrimerCheckoutSheet` to replace the default loading screen: > > ```kotlin theme={"dark"} > PrimerCheckoutSheet( > checkout = checkout, > loading = { > Column( > modifier = Modifier > .fillMaxWidth() > .padding(48.dp), > horizontalAlignment = Alignment.CenterHorizontally, > ) { > CircularProgressIndicator( > color = MaterialTheme.colorScheme.primary, > ) > Spacer(Modifier.height(16.dp)) > Text( > text = "Preparing your checkout...", > style = MaterialTheme.typography.bodyMedium, > color = MaterialTheme.colorScheme.onSurfaceVariant, > ) > } > }, > onDismiss = { }, > ) > ``` > [tab] iOS > > The managed `PrimerCheckout` renders its own loading screen. To show a branded loading view, compose your UI inline with a `PrimerCheckoutSession` and render your view while `phase` is `.initializing`: > > ```swift theme={"dark"} > @StateObject private var session: PrimerCheckoutSession > > var body: some View { > ScrollView { > if session.phase == .initializing { > VStack(spacing: 16) { > ProgressView() > .controlSize(.large) > .tint(.accentColor) > Text("Preparing your checkout...") > .font(.body) > .foregroundColor(.secondary) > } > .frame(maxWidth: .infinity, maxHeight: .infinity) > .background(.ultraThinMaterial) > } else { > PrimerCardForm() > } > } > .primerCheckoutSession(session) { state in > handle(state) > } > } > ``` ### Inline loading overlay > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:state-change', (event) => { > const { isProcessing } = event.detail; > > // Disable all inputs on the page during processing > document.querySelectorAll('input, button, select').forEach((el) => { > el.disabled = isProcessing; > }); > }); > ``` > [tab] Android > > For inline integrations, you manage the loading UI yourself. This example shows a semi-transparent overlay during form submission: > > ```kotlin theme={"dark"} > @Composable > fun InlineCheckoutWithLoading(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (state) { > is PrimerCheckoutState.Success -> { } > is PrimerCheckoutState.Failure -> { } > else -> Unit > } > } > > when (state) { > is PrimerCheckoutState.Loading -> { > Box( > modifier = Modifier.fillMaxSize(), > contentAlignment = Alignment.Center, > ) { > Column(horizontalAlignment = Alignment.CenterHorizontally) { > CircularProgressIndicator() > Spacer(Modifier.height(12.dp)) > Text("Loading payment methods...") > } > } > } > is PrimerCheckoutState.Ready -> { > PrimerCheckoutHost( > checkout = checkout, > ) { > val cardFormController = rememberCardFormController(checkout) > val formState by cardFormController.state.collectAsStateWithLifecycle() > > Box { > Column(Modifier.padding(16.dp)) { > PrimerCardForm( > controller = cardFormController, > submitButton = { > Button( > onClick = { cardFormController.submit() }, > enabled = formState.isFormValid && !formState.isLoading, > modifier = Modifier.fillMaxWidth(), > ) { > if (formState.isLoading) { > CircularProgressIndicator( > modifier = Modifier.size(20.dp), > color = Color.White, > strokeWidth = 2.dp, > ) > } else { > Text("Pay") > } > } > }, > ) > } > > if (formState.isLoading) { > Box( > modifier = Modifier > .matchParentSize() > .background(Color.Black.copy(alpha = 0.3f)), > contentAlignment = Alignment.Center, > ) { > Card( > modifier = Modifier.padding(32.dp), > ) { > Column( > modifier = Modifier.padding(24.dp), > horizontalAlignment = Alignment.CenterHorizontally, > ) { > CircularProgressIndicator() > Spacer(Modifier.height(12.dp)) > Text("Processing payment...") > } > } > } > } > } > } > } > } > } > ``` > [tab] iOS > > For inline integrations, once the payment starts, the SDK shows its own processing screen in a sheet above your layout. The sheet then shows the success or error screen. To hide the success and error screens, pass `PrimerSettings(uiOptions: PrimerUIOptions(isSuccessScreenEnabled: false, isErrorScreenEnabled: false))` as the `settings` of `PrimerCheckoutSession`. The processing screen always shows while a payment runs. The shopper cannot swipe that sheet away while the payment processes. > > `isLoading` on the `PrimerCardFormSession` turns `true` as soon as the shopper submits. It stays `true` while `onBeforePaymentCreate` waits for your decision. Use it to dim the form, disable your controls, or show a loading card until the SDK sheet appears, as this example does: > > ```swift theme={"dark"} > struct InlineCheckoutWithLoading: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > PrimerCardForm( > cardDetails: { session in > VStack(spacing: 16) { > CardFormDefaults.cardNumber(session) > HStack(spacing: 12) { > CardFormDefaults.expiryDate(session) > CardFormDefaults.cvv(session) > } > } > }, > submitButton: { session in > SubmitWithOverlay(session: session) > } > ) > .padding() > } > .primerCheckoutSession(session) { state in > // Handle the terminal PrimerCheckoutState. > } > } > } > > struct SubmitWithOverlay: View { > @ObservedObject var session: PrimerCardFormSession > > var body: some View { > ZStack { > Button(action: { session.submit() }) { > Text("Pay") > .frame(maxWidth: .infinity, minHeight: 48) > } > .buttonStyle(.borderedProminent) > .disabled(!session.state.isValid || session.state.isLoading) > > if session.state.isLoading { > Color.black.opacity(0.3) > .ignoresSafeArea() > VStack(spacing: 12) { > ProgressView() > Text("Processing payment...") > .font(.subheadline) > } > .padding(24) > .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12)) > } > } > } > } > ``` ### Show processing message > [tab] Web > > ```javascript theme={"dark"} > checkout.addEventListener('primer:state-change', (event) => { > const statusEl = document.getElementById('status-message'); > > if (event.detail.isProcessing) { > statusEl.textContent = 'Processing your payment...'; > statusEl.className = 'status processing'; > } else if (event.detail.isSuccessful) { > statusEl.textContent = 'Payment successful!'; > statusEl.className = 'status success'; > } else { > statusEl.textContent = ''; > statusEl.className = 'status'; > } > }); > ``` > [tab] Android > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > val cardFormController = rememberCardFormController(checkout) > val formState by cardFormController.state.collectAsStateWithLifecycle() > > when { > state is PrimerCheckoutState.Loading -> Text("Loading payment methods...") > formState.isLoading -> Text("Processing payment...") > } > ``` > [tab] iOS > > Observe the session `phase` and the card form session's `state.isLoading` to drive a status message. Observe the `PrimerCardFormSession` in its own view, because `PrimerCheckoutSession` does not publish card form changes: > > ```swift theme={"dark"} > struct StatusMessage: View { > @ObservedObject var session: PrimerCheckoutSession > > var body: some View { > if session.phase == .initializing { > Text("Loading payment methods...") > } else if let cardForm = session.cardForm { > CardFormStatus(cardForm: cardForm) > } > } > } > > struct CardFormStatus: View { > @ObservedObject var cardForm: PrimerCardFormSession > > var body: some View { > if cardForm.state.isLoading { > Text("Processing payment...") > } > } > } > ``` ## See also > [card] [Disable external buttons](/docs/checkout/primer-checkout/guides-and-recipes/disable-buttons-during-payment) > > Prevent double submission during payment processing > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Handle payment lifecycle events # Show custom success message Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/show-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) > } > } > } > } > ``` ## 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. ## Variations ### Custom success with payment details > [tab] Web > > ```javascript theme={"dark"} > primer.onPaymentSuccess = ({ payment }) => { > document.getElementById('success-container').innerHTML = ` >

Thank you for your order!

>

Order ID: ${payment.orderId}

>

Amount: ${formatCurrency(payment.amount, payment.currencyCode)}

> `; > }; > ``` > [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 > } > } > ) > ``` ### 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 > } > } > ) > ``` ## See also > [card] [Redirect after payment](/docs/checkout/primer-checkout/guides-and-recipes/redirect-after-payment) > > Navigate to a confirmation page after payment > [card] [Error handling](/docs/checkout/primer-checkout/build-your-ui/error-handling) > > Handle payment failures and display error messages # Track payment in analytics Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/track-payment-analytics Send payment events to your analytics platform. Track payment success and failure events in your analytics platform (Google Analytics, Segment, etc.). ## Recipe > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:payment-success', (event) => { > const { paymentSummary, paymentMethodType } = event.detail; > > analytics.track('Payment Completed', { > paymentId: paymentSummary.id, > orderId: paymentSummary.orderId, > method: paymentMethodType, > last4: paymentSummary.paymentMethodData?.last4Digits, > }); > }); > > document.addEventListener('primer:payment-failure', (event) => { > const { error, paymentMethodType } = event.detail; > > analytics.track('Payment Failed', { > errorCode: error.code, > method: paymentMethodType, > diagnosticsId: error.diagnosticsId, > }); > }); > ``` > [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 > trackPaymentSuccess(payment.id, payment.orderId) > } > is PrimerCheckoutState.Failure -> { > val error = s.primerError > trackPaymentFailure(error.errorCode, error.diagnosticsId) > } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > ``` > [tab] iOS > > ```swift theme={"dark"} > PrimerCheckout(clientToken: clientToken) { state in > switch state { > case let .success(result): > Analytics.track("payment_success", properties: [ > "payment_id": result.paymentId > ]) > case let .failure(error, _): > Analytics.track("payment_failure", properties: [ > "error_id": error.errorId, > "diagnostics_id": error.diagnosticsId > ]) > default: > break > } > } > ``` ## How it works > [tab] Web > > 1. Listen for `primer:payment-success` and `primer:payment-failure` DOM events > 2. Extract relevant data from `event.detail` > 3. Send to your analytics platform with meaningful event names and properties > [tab] Android > > 1. Observe `checkout.state` with `collectAsStateWithLifecycle()` and react in a `LaunchedEffect` > 2. Map `PrimerCheckoutState` terminal cases to analytics events > 3. Extract relevant data from each state and send to your analytics platform > > | Checkout State | Analytics Event | Key Properties | > | - | - | - | > | `Success` | `purchase_completed` | `payment_id`, `order_id` | > | `Failure` | `purchase_failed` | `error_code`, `diagnostics_id` | > [tab] iOS > > 1. Pass an `onCompletion` closure to `PrimerCheckout` (or to the `.primerCheckoutSession(_:theme:onCompletion:)` modifier when composing views inline). It receives `.failure` once for each failed attempt, while the checkout stays open for the shopper to retry. It then receives `.success` or `.dismissed` exactly once. > 2. Map `PrimerCheckoutState` cases to analytics events > 3. Extract relevant data from each state and send to your analytics platform > > | Checkout State | Analytics Event | Key Properties | > | - | - | - | > | `.success(result)` | `payment_success` | `payment_id` | > | `.failure(error, checkoutData)` | `payment_failure` | `error_id`, `diagnostics_id`, plus `payment_id` and `order_id` from `checkoutData?.payment` | > | `.dismissed` | `checkout_dismissed` | — | > > If no payment was created before the failure, `checkoutData` is `nil`. This happens for initialization, tokenization and connectivity failures. > > `.initializing` and `.ready` are never delivered. With `PrimerCheckout`, a failed initialization arrives as `.failure`. The error screen then offers a retry. With the inline modifier, a failed initialization is the last outcome delivered. > > `.failure` can arrive more than once in one checkout, one per failed attempt. A `payment_failure` count is therefore per attempt, not per checkout. ## Variations ### Google Analytics 4 / Firebase Analytics > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:payment-success', (event) => { > const { paymentSummary, paymentMethodType } = event.detail; > > gtag('event', 'purchase', { > transaction_id: paymentSummary.orderId, > value: paymentSummary.amount / 100, // Convert from cents > currency: paymentSummary.currencyCode, > payment_type: paymentMethodType, > }); > }); > ``` > [tab] Android > > Add the Firebase Analytics dependency: > > ```kotlin theme={"dark"} > // build.gradle.kts > implementation(platform("com.google.firebase:firebase-bom:33.0.0")) > implementation("com.google.firebase:firebase-analytics") > ``` > > Create an analytics tracker: > > ```kotlin theme={"dark"} > class CheckoutAnalytics( > private val firebaseAnalytics: FirebaseAnalytics, > ) { > fun trackPaymentSuccess(paymentId: String, orderId: String?) { > firebaseAnalytics.logEvent("purchase_completed") { > param("payment_id", paymentId) > param("order_id", orderId.orEmpty()) > } > } > > fun trackPaymentFailure(errorCode: String?, diagnosticsId: String) { > firebaseAnalytics.logEvent("purchase_failed") { > param("error_code", errorCode.orEmpty()) > param("diagnostics_id", diagnosticsId) > } > } > > fun trackPaymentMethodSelected(methodType: String) { > firebaseAnalytics.logEvent("payment_method_selected") { > param("payment_method_type", methodType) > } > } > } > ``` > > Wire it into your checkout: > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen( > clientToken: String, > analytics: CheckoutAnalytics, > ) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { > val payment = s.checkoutData.payment > analytics.trackPaymentSuccess(payment.id, payment.orderId) > } > is PrimerCheckoutState.Failure -> { > analytics.trackPaymentFailure( > s.primerError.errorCode, > s.primerError.diagnosticsId, > ) > } > else -> Unit > } > } > > when (state) { > is PrimerCheckoutState.Loading -> CircularProgressIndicator() > is PrimerCheckoutState.Ready -> { > PrimerCheckoutSheet(checkout = checkout) > } > } > } > ``` > [tab] iOS > > Add the Firebase Analytics dependency via SPM or CocoaPods, then create a tracker: > > ```swift theme={"dark"} > class CheckoutAnalytics { > let firebaseAnalytics: Analytics.Type = Analytics.self > > func trackState(_ state: PrimerCheckoutState) { > switch state { > case let .success(result): > firebaseAnalytics.logEvent("purchase_completed", parameters: [ > "payment_id": result.paymentId > ]) > case let .failure(error, _): > firebaseAnalytics.logEvent("purchase_failed", parameters: [ > "error_id": error.errorId, > "diagnostics_id": error.diagnosticsId > ]) > default: > break > } > } > } > ``` > > > [!NOTE] > > > > `PaymentResult.amount` and `currencyCode` are optional and are `nil` for card and saved-method payments. Take the purchase value and currency from your own order. > > Wire it into your checkout. `PrimerCheckout` calls `onCompletion` with `.failure` for each failed attempt, then once with `.success` or `.dismissed`: > > ```swift theme={"dark"} > struct CheckoutView: View { > let clientToken: String > let analytics = CheckoutAnalytics() > > var body: some View { > PrimerCheckout(clientToken: clientToken) { state in > analytics.trackState(state) > } > } > } > ``` ### Segment / Reusable analytics wrapper > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:payment-success', (event) => { > const { paymentSummary, paymentMethodType } = event.detail; > > analytics.track('Order Completed', { > order_id: paymentSummary.orderId, > total: paymentSummary.amount / 100, > currency: paymentSummary.currencyCode, > payment_method: paymentMethodType, > }); > }); > ``` > [tab] Android > > For apps that use multiple analytics providers, create an interface that decouples checkout tracking from any specific SDK: > > ```kotlin theme={"dark"} > interface CheckoutTracker { > fun onPaymentSuccess(paymentId: String, orderId: String?) > fun onPaymentFailure(errorCode: String?, diagnosticsId: String) > fun onPaymentMethodSelected(methodType: String) > } > > class CompositeCheckoutTracker( > private val trackers: List, > ) : CheckoutTracker { > override fun onPaymentSuccess(paymentId: String, orderId: String?) { > trackers.forEach { it.onPaymentSuccess(paymentId, orderId) } > } > > override fun onPaymentFailure(errorCode: String?, diagnosticsId: String) { > trackers.forEach { it.onPaymentFailure(errorCode, diagnosticsId) } > } > > override fun onPaymentMethodSelected(methodType: String) { > trackers.forEach { it.onPaymentMethodSelected(methodType) } > } > } > ``` > > Usage: > > ```kotlin theme={"dark"} > fun handleState(state: PrimerCheckoutState, tracker: CheckoutTracker) { > when (state) { > is PrimerCheckoutState.Success -> { > val payment = state.checkoutData.payment > tracker.onPaymentSuccess(payment.id, payment.orderId) > } > is PrimerCheckoutState.Failure -> { > tracker.onPaymentFailure(state.primerError.errorCode, state.primerError.diagnosticsId) > } > else -> Unit > } > } > ``` > [tab] iOS > > For apps with multiple analytics providers, create a protocol that decouples checkout tracking: > > ```swift theme={"dark"} > protocol CheckoutTracker { > func onPaymentSuccess(paymentId: String) > func onPaymentFailure(errorId: String) > } > > class CompositeCheckoutTracker: CheckoutTracker { > let trackers: [CheckoutTracker] > > init(trackers: [CheckoutTracker]) { self.trackers = trackers } > > func onPaymentSuccess(paymentId: String) { > trackers.forEach { $0.onPaymentSuccess(paymentId: paymentId) } > } > > func onPaymentFailure(errorId: String) { > trackers.forEach { $0.onPaymentFailure(errorId: errorId) } > } > } > ``` > > Usage: > > ```swift theme={"dark"} > func handleState(_ state: PrimerCheckoutState, tracker: CheckoutTracker) { > switch state { > case let .success(result): > tracker.onPaymentSuccess(paymentId: result.paymentId) > case let .failure(error, _): > tracker.onPaymentFailure(errorId: error.errorId) > default: > break > } > } > ``` ### Track payment method selection > [tab] Web > > ```javascript theme={"dark"} > document.addEventListener('primer:payment-start', (event) => { > const { paymentMethodType } = event.detail; > > analytics.track('Payment Method Selected', { > method: paymentMethodType, > }); > }); > ``` > [tab] Android > > > [!NOTE] > > > > Payment method selection tracking is not available through `PrimerCheckoutState`. The SDK manages payment method selection internally within its UI components. > [tab] iOS > > `PrimerPaymentMethods` passes each row's `CheckoutPaymentMethod` (with `type` and `name`) and an `onSelect` action to its `method` slot. Wrap `PaymentMethodsDefaults.method` and track the tap before calling `onSelect`. `PrimerPaymentMethods` is a composable view, so place it inside `.primerCheckoutSession(_:theme:onCompletion:)`. The managed `PrimerCheckout` modal has no selection callback. > > ```swift theme={"dark"} > struct TrackedPaymentMethods: View { > var body: some View { > PrimerPaymentMethods(method: { method, onSelect in > PaymentMethodsDefaults.method(method) { > Analytics.track("payment_method_selected", properties: [ > "type": method.type, > "name": method.name > ]) > onSelect() > } > }) > } > } > ``` ## See also > [card] [Log errors for debugging](/docs/checkout/primer-checkout/guides-and-recipes/log-errors-debugging) > > Capture and surface errors during development > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Handle payment lifecycle events # Use BIN Data to Control Click to Pay Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/use-bin-data-to-control-click-to-pay Disable Click to Pay when BIN data shows a prepaid card. When a customer starts typing their card number, Primer can surface enriched BIN data in the frontend. This includes network details, issuer information such as the country or the bank, or funding type like DEBIT, CREDIT, PREPAID, or DEFERRED\_DEBIT. You can use this information to adapt your checkout UI early, before a payment is created. In this guide, you will build a concrete example: block Click to Pay when the selected card network is prepaid, while handling co-badged cards correctly. ## What you build You will implement this behavior: * While BIN data is loading, disable Click to Pay and show a short message * When BIN data is complete, enable Click to Pay unless the selected network is PREPAID ## Events you need ### Event `primer:bin-data-loading-change` Use this event to handle the loading state. | Property | Type | Description | | - | - | - | | `loading` | boolean | `true` when BIN lookup starts, `false` when it completes | ```javascript theme={"dark"} const checkout = document.querySelector('primer-checkout'); checkout.addEventListener('primer:bin-data-loading-change', (event) => { const { loading } = event.detail; // Use loading to disable buttons or show a loader }); ``` ### Event `primer:bin-data-available` Use this event to read BIN data once it is available. | Property | Type | Description | | - | - | - | | `preferred` | `BinDataDetails \| undefined` | Recommended network | | `alternatives` | `BinDataDetails[]` | Other detected networks | | `status` | `"partial" \| "complete"` | Data completeness | | `firstDigits` | `string \| undefined` | BIN prefix | > [!NOTE] > > `status = "partial"` means local detection only.\ > `status = "complete"` means enriched BIN data is available, typically after 8 digits.\ > Only make decisions when `status === "complete"`. ```javascript theme={"dark"} checkout.addEventListener('primer:bin-data-available', (event) => { const { preferred, alternatives, status, firstDigits } = event.detail; }); ``` ## Recipe: block Click to Pay for prepaid cards This example is framework agnostic. You only need to wire `setClickToPayDisabled` to your own Click to Pay button. ```javascript theme={"dark"} function setClickToPayDisabled(disabled, message) { const btn = document.querySelector('#click-to-pay'); const helper = document.querySelector('#bin-message'); if (btn) btn.disabled = disabled; if (helper) helper.textContent = message || ''; } const checkout = document.querySelector('primer-checkout'); checkout.addEventListener('primer:bin-data-loading-change', (event) => { if (event.detail.loading) { setClickToPayDisabled(true, 'Checking card type...'); } }); checkout.addEventListener('primer:bin-data-available', (event) => { const { status, preferred, alternatives } = event.detail; if (status !== 'complete') return; const selectedNetworkFundingType = preferred?.accountFundingType || alternatives?.[0]?.accountFundingType; if (selectedNetworkFundingType === 'PREPAID') { setClickToPayDisabled(true, 'Prepaid cards are not supported with Click to Pay'); return; } setClickToPayDisabled(false, ''); }); ``` ## Co-badged cards On co-badged cards, BIN data can include multiple networks for the same card. Each network can have its own `accountFundingType`. That means: * Funding type is network specific * You should evaluate the funding type for the network you will actually use ### Example BIN data for a co-badged card Here is an example payload you may see in the frontend for a co-badged card: ```json theme={"dark"} { "preferred": { "network": "VISA", "displayName": "Visa", "issuerCountryCode": "FR", "issuerName": "SOCIETE GENERALE S.A.", "accountFundingType": "DEBIT", "prepaidReloadableIndicator": "NOT_APPLICABLE", "productUsageType": "CONSUMER", "productCode": "F", "productName": "Visa Classic", "issuerCurrencyCode": "EUR", "regionalRestriction": "UNKNOWN", "accountNumberType": "PRIMARY_ACCOUNT_NUMBER", "allowed": true }, "alternatives": [ { "network": "CARTES_BANCAIRES", "displayName": "Cartes Bancaires", "issuerCountryCode": "FR", "issuerName": "SOCIETE GENERALE", "accountFundingType": "DEBIT", "prepaidReloadableIndicator": "UNKNOWN", "productUsageType": "CONSUMER", "productCode": "C", "productName": "CB Cobadgé - Classic", "issuerCurrencyCode": "EUR", "regionalRestriction": "UNKNOWN", "accountNumberType": "PRIMARY_ACCOUNT_NUMBER", "allowed": true } ], "status": "complete", "firstDigits": "497355" } ``` ## How to pick the right funding type ### If Primer selects the network automatically Use the `preferred` network from the event payload: ```javascript theme={"dark"} const fundingType = preferred?.accountFundingType; ``` ### If the customer can select a network Evaluate funding type for the selected network: ```javascript theme={"dark"} function getFundingTypeForNetwork(network, preferred, alternatives) { const allNetworks = [preferred, ...(alternatives || [])]; return allNetworks.find((n) => n?.network === network)?.accountFundingType; } ``` > [!WARNING] > > Do not block the entire card just because one of the networks is PREPAID.\ > Block only the network where `accountFundingType === "PREPAID"`, and keep other valid networks available. ## See also > [card] [Events reference](/docs/sdk/primer-checkout-web/events-reference) > > Full reference for BIN data events and payload types > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > When, why, and how to use events in your integration # Prevent duplicate payments with idempotency keys Source: https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/use-idempotency-keys Pass an idempotency key in Auto flow to prevent duplicate payment creation, and learn when to reuse vs rotate it. Pass an idempotency key when creating payments to ensure the same payment is never created twice. For background on how idempotency keys work at the API level, see **Idempotency Key**. ## Rule of thumb * **Same idempotency key = same payment attempt** (safe retries, no duplicates) * **New idempotency key = new payment attempt** (creates a new payment) If you reuse a key for a new attempt, it will trigger a failure with error code `IDEMPOTENCY_KEY_ALREADY_EXISTS`. On iOS, this failure arrives as a generic error without that code. ## How it works In Auto flow, the SDK creates the payment by calling the Payments API internally. > [tab] Web > > When you provide an idempotency key via `continuePaymentCreation({ idempotencyKey })` in the `primer:payment-start` event, the SDK includes it as the `X-Idempotency-Key` header on: > > * `POST /payments` (create payment) > > If the same request is retried with the same key: > > * The API will not create a second payment. > * It will fail with a `409 Conflict` response. > [tab] Android > > When you provide an idempotency key via `handler.continuePaymentCreation(idempotencyKey)` in the `beforePaymentCreate` gate, the SDK includes it as the `X-Idempotency-Key` header on: > > * `POST /payments` (create payment) > > The key is passed per attempt from the payment-creation gate — it is no longer a parameter on `rememberPrimerCheckoutController`. > > If the same request is retried with the same key: > > * The API will not create a second payment. > * It will fail with a `409 Conflict` response. > [tab] iOS > > When you provide an idempotency key via `decisionHandler(.continuePaymentCreation(withIdempotencyKey:))` in your `PrimerCheckoutSession`'s `onBeforePaymentCreate` handler, the SDK includes it as the `X-Idempotency-Key` header on: > > * `POST /payments` (create payment) > > The SDK asks for the key once per payment attempt, through `onBeforePaymentCreate` or the `idempotencyKey` provider. > > * A key you pass to `.continuePaymentCreation(withIdempotencyKey:)` takes precedence over the provider. > * The provider supplies the key when there is no handler, or when the handler continues without a key. > * The SDK sends the key only on the create-payment request and clears it when that request returns, whether it succeeds or fails. > * Resume requests, for example after 3DS or a redirect, do not carry the key. > * To retry the same attempt with the same key, return that key again when the SDK asks for it. > > If the same request is retried with the same key: > > * The API will not create a second payment. > * It will fail with a `409 Conflict` response. ### Why key rotation matters For redirect and 3DS flows, the payment is created **before** the user completes the external step. If the user abandons the redirect or retries after a failed authentication, this becomes a **new payment attempt**, and the key must be rotated. If you do not rotate the key, the retry will fail with an error code `IDEMPOTENCY_KEY_ALREADY_EXISTS`. On iOS, the retry fails with a generic error. ## When to reuse vs rotate ### Reuse the same key Reuse the current key when you are retrying the **same attempt**, for example: * transient network retry * the SDK retries the same request * resume of the same attempt ### Rotate the key Rotate to a new key when the user starts a **new attempt**, for example: * user abandons a redirect, popup, or external app flow and tries again * user cancels the payment and tries again * failed 3DS and the user retries as a new attempt * user switches payment method (optional but recommended) ## Recipe > [tab] Web > > In this recipe we: > > 1. Intercept payment creation with `primer:payment-start` > 2. Provide an `idempotencyKey` per attempt > 3. Rotate the attempt when the user abandons a redirect flow using `primer:payment-cancel` > 4. Handle duplicate key errors explicitly > > ```js theme={"dark"} > let attempt = 1; > let currentIdempotencyKey = null; > > // Optional: track whether we should rotate on the next attempt > let shouldRotateOnNextStart = false; > > // You can generate locally (UUID) or fetch from your backend. > // Backend is recommended if you want stronger guarantees across refresh/outages. > async function getIdempotencyKeyForAttempt(attemptNumber) { > // Example 1: local generation > // return crypto.randomUUID(); > > // Example 2: backend generation (recommended) > const res = await fetch(`/api/idempotency-key?attempt=${attemptNumber}`, { method: 'POST' }); > const data = await res.json(); > return data.idempotencyKey; > } > > // 1) Inject the key when the payment starts > checkout.addEventListener('primer:payment-start', async (event) => { > event.preventDefault(); > > // If we detected a new attempt boundary, rotate attempt counter > if (shouldRotateOnNextStart) { > attempt += 1; > currentIdempotencyKey = null; > shouldRotateOnNextStart = false; > } > > // Create the key once per attempt and reuse it for retries of the same attempt > if (!currentIdempotencyKey) { > currentIdempotencyKey = await getIdempotencyKeyForAttempt(attempt); > } > > event.detail.continuePaymentCreation({ idempotencyKey: currentIdempotencyKey }); > }); > > // 2) Detect the user abandoning a redirect or popup based flow > // This event is the key signal to know the next click is a new attempt. > checkout.addEventListener('primer:payment-cancel', () => { > shouldRotateOnNextStart = true; > }); > > // 3) Handle the duplicate key error explicitly > checkout.addEventListener('primer:payment-failure', (event) => { > const { error } = event.detail; > > if (error?.code === 'IDEMPOTENCY_KEY_ALREADY_EXISTS') { > // This means either: > // - The cancel event was not handled (and the key was not rotated), or > // - A payment was already successfully created with this key. > > // Suggested UX: > // - Check the payment status server-side to see if a previous attempt succeeded. > // If so, redirect the user to a completion/confirmation page. > // - Otherwise, tell the user to retry (after rotating the key). > > // Ensure the next attempt uses a new key. > shouldRotateOnNextStart = true; > } > }); > ``` > [tab] Android > > In this recipe we: > > 1. Intercept payment creation with the `beforePaymentCreate` gate > 2. Provide an idempotency key per attempt > 3. Rotate the key on success, dismissal, or a duplicate-key failure > 4. Handle duplicate key errors explicitly > > ```kotlin theme={"dark"} > @Composable > fun CheckoutView(clientToken: String) { > val checkout = rememberPrimerCheckoutController(clientToken) > val state by checkout.state.collectAsStateWithLifecycle() > > // Create the key once per attempt and reuse it for retries of the same attempt > var currentIdempotencyKey by remember { mutableStateOf(null) } > > fun rotateKey() { > currentIdempotencyKey = null > } > > LaunchedEffect(state) { > when (val s = state) { > // 2) Payment succeeded — rotate key for any future attempt > is PrimerCheckoutState.Success -> rotateKey() > // 3) Handle the duplicate key error explicitly > is PrimerCheckoutState.Failure -> { > if (s.primerError.errorCode == "IDEMPOTENCY_KEY_ALREADY_EXISTS") { > rotateKey() > } > } > else -> Unit > } > } > > PrimerCheckoutSheet( > checkout = checkout, > // 1) Inject the key when the payment starts > beforePaymentCreate = { handler -> > LaunchedEffect(Unit) { > val key = currentIdempotencyKey > ?: UUID.randomUUID().toString().also { currentIdempotencyKey = it } > handler.continuePaymentCreation(key) > } > }, > // 4) User dismissed checkout — rotate key for next attempt > onDismiss = { rotateKey() }, > ) > } > ``` > [tab] iOS > > Hold a [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) and supply the key through its `onBeforePaymentCreate` decision handler. In this recipe we: > > 1. Intercept payment creation with `onBeforePaymentCreate` > 2. Provide an idempotency key per attempt > 3. Rotate the key when the payment succeeds, fails or the checkout is dismissed > > ```swift theme={"dark"} > import SwiftUI > import PrimerSDK > > // Holds the mutable key in a reference type so the @Sendable > // onBeforePaymentCreate closure can capture it safely (capturing a > // View-local @State var from that escaping @Sendable closure is a > // Swift 6 concurrency error and would not reliably drive the value). > @available(iOS 15.0, *) > @MainActor > final class IdempotencyKeyStore: ObservableObject { > @Published private(set) var attempt = 1 > private var currentKey: String? > > // Create the key once per attempt and reuse it until the attempt ends. > func keyForCurrentAttempt() -> String { > if let key = currentKey { return key } > let key = UUID().uuidString > currentKey = key > return key > } > > func rotate() { > currentKey = nil > attempt += 1 > } > } > > @available(iOS 15.0, *) > struct CheckoutView: View { > @StateObject private var session: PrimerCheckoutSession > @StateObject private var keys = IdempotencyKeyStore() > > init(clientToken: String) { > let store = IdempotencyKeyStore() > let session = PrimerCheckoutSession(clientToken: clientToken) > // 1) Inject the key when the payment is about to be created. > // `store` is a reference type, so this @Sendable closure > // captures it safely. > session.onBeforePaymentCreate = { _, decisionHandler in > Task { @MainActor in > decisionHandler(.continuePaymentCreation(withIdempotencyKey: store.keyForCurrentAttempt())) > } > } > _session = StateObject(wrappedValue: session) > _keys = StateObject(wrappedValue: store) > } > > var body: some View { > ScrollView { > VStack(spacing: 24) { > PrimerPaymentMethods() > PrimerCardForm() > } > .padding() > } > .primerCheckoutSession(session) { state in > switch state { > // 2) Payment succeeded: rotate the key for any future attempt > case .success: > keys.rotate() > // 3) The attempt failed. The checkout stays open, so the user's > // retry is a new attempt and needs a new key. > case .failure: > keys.rotate() > // 4) User dismissed checkout: rotate the key for the next attempt > case .dismissed: > keys.rotate() > default: > break > } > } > } > } > ``` > > > [!NOTE] > > > > The `.primerCheckoutSession` closure receives `.failure` for each failed attempt, and the checkout stays open so the user can retry. A duplicate-key rejection has no dedicated `errorId`. It arrives as a generic `.failure` whose `errorId` is `"unknown"`, and `error.underlyingErrorCode` is `nil`. You cannot branch on it, so rotate the key on every `.failure`, as the recipe does. If the network drops after the request was sent, the payment may already exist. Check its status on your server before you let the user pay again. If the user abandons a web redirect, the checkout returns to the method list and the closure receives nothing. The next attempt then reuses the key and fails once, and that `.failure` rotates the key. > > > [!TIP] > > > > If you only need a fresh key per attempt without custom logic, skip `onBeforePaymentCreate` and pass the declarative `idempotencyKey` provider when you construct the session: `PrimerCheckoutSession(clientToken: token, idempotencyKey: { UUID().uuidString })`. It is invoked once per payment attempt. ## Handling network loss and state recovery Idempotency prevents duplicate charges, but it does **not** fully manage recovery when the client loses state. > [tab] Web > > If the network drops or the page refreshes right after `createPayment` is sent: > > * The payment may have been created on the server, even if the client never received a response. > * Retrying with the **same idempotency key** is the safest client-side action for the same attempt. > * If the client lost state (e.g., after a page refresh), it cannot reliably know if the payment succeeded, is pending, or failed. > > If you need bulletproof recovery (across refresh or outages), you should: > > * Keep a server-side order state, and/or > * Listen to webhooks, and/or > * Use manual payment flow for full lifecycle control. > [tab] Android > > If the app is backgrounded, the process is terminated, or the network drops right after payment creation is initiated: > > * The payment may have been created on the server, even if the app never received a response. > * If the user re-opens the app and triggers a new payment, using the **same idempotency key** prevents a duplicate charge. > * The client cannot reliably know if the previous payment succeeded, is pending, or failed. > > If you need bulletproof recovery (across app termination or outages), you should: > > * Persist the idempotency key and attempt counter (e.g., in `DataStore` or a local database) > * Keep a server-side order state, and/or > * Listen to webhooks > [tab] iOS > > If the app is backgrounded, the process is terminated, or the network drops right after payment creation is initiated: > > * The payment may have been created on the server, even if the app never received a response. > * If the user re-opens the app and triggers a new payment, using the **same idempotency key** prevents a duplicate charge. > * The client cannot reliably know if the previous payment succeeded, is pending, or failed. > > If you need bulletproof recovery (across app termination or outages), you should: > > * Persist the idempotency key and attempt counter (e.g., in `UserDefaults` or a local database) > * Keep a server-side order state, and/or > * Listen to webhooks *** ## Common pitfalls ### Rotating the key on every click If you generate a new key every time, you reduce the protection against true request retries. ### Reusing the same key after abandon If the user cancels a redirect flow and tries again with the same key, the API will fail with a `409`. ### Treating idempotency errors as generic failures `IDEMPOTENCY_KEY_ALREADY_EXISTS` is often expected behavior.\ Handle it explicitly and guide the user instead of showing a generic error. On iOS, the SDK does not expose this code, so rotate the key on every `.failure`. *** ## See also > [card] [Idempotency Key](/docs/api-reference/get-started/idempotency-key) > > How idempotency keys work at the API level > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Platform-specific events and interception patterns > [card] [Redirect after payment](/docs/checkout/primer-checkout/guides-and-recipes/redirect-after-payment) > > Navigate to a confirmation page after payment > [card] [Log errors for debugging](/docs/checkout/primer-checkout/guides-and-recipes/log-errors-debugging) > > Capture and log payment errors for debugging # Install Primer Checkout Source: https://primer.io/docs/checkout/primer-checkout/installation Package managers, browser requirements and initial setup for Web, iOS and Android. ## Prerequisites You'll need your `clientToken` to initialize Primer Checkout. See our [Client Session guide](/docs/checkout/client-session) on how to create a client session and retrieve a `clientToken` first. ## Environment Requirements Before diving into the implementation, ensure your environment meets these requirements: | Requirement | Details | | - | - | | **Node.js** | Current LTS version recommended | | **Browsers** | Modern browsers with ES2020 support (see below) | | **Not Supported** | Internet Explorer 11, Classic Edge (legacy) | ### Minimum Browser Versions The SDK requires ES2020 support. Minimum supported browser versions: | Browser | Minimum Version | | - | - | | Chrome | 80+ | | Edge | 80+ | | Firefox | 79+ | | Safari | 14+ | | iOS Safari | 14+ | | Opera | 67+ | | Samsung Internet | 13.0+ | > [!NOTE] > > Legacy browsers like Internet Explorer 11 aren't officially supported due to their non-standard DOM behavior and lack of support for modern Web Component features and ES2020 syntax that this SDK is built on. ## Install the SDK > [tab] Web > > Install the Primer SDK using your preferred package manager: > > > [!NOTE] > > > > `@primer-io/primer-js` is installed via a package manager. Pick whichever you use. npm, yarn, and pnpm are all supported. > > > [tab] npm > > > > ```bash theme={"dark"} > > npm install @primer-io/primer-js > > ``` > > > [tab] yarn > > > > ```bash theme={"dark"} > > yarn add @primer-io/primer-js > > ``` > > > [tab] pnpm > > > > ```bash theme={"dark"} > > pnpm add @primer-io/primer-js > > ``` > [tab] Android > > Add the Primer BOM and the Primer Checkout SDK to your module-level `build.gradle.kts`. The BOM keeps the SDK and the 3DS, Klarna and Stripe ACH wrappers on the same version: > > ```kotlin theme={"dark"} > dependencies { > implementation(platform("io.primer:bom:3.0.0-beta.8")) > implementation("io.primer:checkout") > } > ``` > > Or without the BOM: > > ```kotlin theme={"dark"} > dependencies { > implementation("io.primer:checkout:3.0.0-beta.8") > } > ``` > > To add the wrappers, see [Payment method dependencies](/docs/sdk/android-checkout/v3.0.0-beta/installation#payment-method-dependencies). > > Ensure Jetpack Compose is enabled in your module-level `build.gradle.kts`: > > ```kotlin theme={"dark"} > android { > buildFeatures { > compose = true > } > composeOptions { > kotlinCompilerExtensionVersion = "1.5.8" > } > } > > dependencies { > implementation(platform("androidx.compose:compose-bom:2025.12.00")) > implementation("androidx.compose.ui:ui") > implementation("androidx.compose.material3:material3") > implementation("androidx.lifecycle:lifecycle-runtime-compose:2.7.0") > } > ``` > > > [!WARNING] > > > > **This is a beta SDK.** The API may change before the stable release. > > Contact [Primer support](https://primer.io/docs/support) before using in production. > [tab] iOS > > Install the Primer SDK using your preferred package manager: > > > [tab] Swift Package Manager > > > > 1. In Xcode, go to **File > Add Package Dependencies** > > 2. Enter the repository URL: > > > > ``` > > https://github.com/primer-io/primer-sdk-ios.git > > ``` > > > > 3. Under **Dependency Rule**, choose **Exact Version** and enter the beta tag `3.0.0-beta.8` > > 4. Add `PrimerSDK` to your target > > > [tab] CocoaPods > > > > Add the following to your `Podfile`: > > > > ```ruby theme={"dark"} > > pod 'PrimerSDK', '3.0.0-beta.8' > > ``` > > > > Then run: > > > > ```bash theme={"dark"} > > pod install > > ``` > > Your app must target **iOS 15.0** or later. > > > [!WARNING] > > > > **This is a beta SDK.** The API may change before the stable release. > > Contact [Primer support](https://primer.io/docs/support) before using in production. ## Load and initialize > [tab] Web > > Import and initialize Primer in your application: > > ```javascript theme={"dark"} > import { loadPrimer } from '@primer-io/primer-js'; > loadPrimer(); > ``` > [tab] Android > > The SDK initializes automatically when you create a checkout controller. Use `rememberPrimerCheckoutController` in your Composable: > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > ) > ``` > > The SDK starts loading configuration immediately upon creation. > [tab] iOS > > The SDK initializes automatically when you create a `PrimerCheckout` view. Import PrimerSDK and add it to your SwiftUI view: > > ```swift theme={"dark"} > import SwiftUI > import PrimerSDK > > struct CheckoutView: View { > let clientToken: String > > var body: some View { > PrimerCheckout(clientToken: clientToken) > } > } > ``` > > The SDK starts loading configuration immediately when the view appears. ## Add the checkout component > [tab] Web > > Create a basic checkout by adding the `primer-checkout` component to your page: > > ```html theme={"dark"} > > ``` > > | Property | Description | > | - | - | > | `client-token` | A token retrieved from the [Client Session endpoint](/docs/checkout/client-session). Authenticates the checkout session and contains configuration for available payment methods. | > [tab] Android > > Add the checkout to your Composable: > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen(clientToken: String) { > val checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > ) > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (state) { > is PrimerCheckoutState.Success -> { /* Navigate to confirmation */ } > is PrimerCheckoutState.Failure -> { /* Error is shown in the UI */ } > else -> Unit > } > } > > PrimerCheckoutSheet(checkout = checkout) > } > ``` > [tab] iOS > > Add the checkout view to your screen with a `clientToken` and an `onCompletion` callback: > > ```swift theme={"dark"} > struct CheckoutView: View { > let clientToken: String > > var body: some View { > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > switch state { > case .success(let result): > print("Payment succeeded: \(result.paymentId)") > case let .failure(error, _): > print("Payment failed: \(error.errorId)") > case .dismissed: > print("Checkout dismissed") > default: > break > } > } > ) > } > } > ``` > > | Parameter | Type | Description | > | - | - | - | > | `clientToken` | `String` | A token retrieved from the [Client Session endpoint](/docs/checkout/client-session). Authenticates the checkout session and contains configuration for available payment methods. | > | `onCompletion` | `((PrimerCheckoutState) -> Void)?` | Optional, defaults to `nil`. Receives `.failure` once per failed attempt, including a failed initialization. If the SDK error screen is on, the checkout stays open for a retry. Receives `.success` or `.dismissed` exactly once. | ## Verify installation > [tab] Web > > Check that components are registered correctly in your browser console: > > ```javascript theme={"dark"} > console.log(customElements.get('primer-checkout')); > ``` > [tab] Android > > Build your project to confirm the SDK is resolved correctly: > > ```bash theme={"dark"} > ./gradlew assembleDebug > ``` > > The SDK includes its own ProGuard rules — no additional configuration is needed for release builds. > [tab] iOS > > Build and run your app. If the SDK is installed correctly, you should see the checkout UI with payment methods configured in your Primer Dashboard. > > > [!WARNING] > > > > If the checkout shows an error screen instead of payment methods, or `onCompletion` receives `.failure`, verify that: > > > > * Your `clientToken` is valid and not expired > > * Payment methods are configured in your [Primer Dashboard](https://dashboard.primer.io) > > > > If you turn off the SDK error screen with `PrimerSettings(uiOptions: PrimerUIOptions(isErrorScreenEnabled: false))`, the checkout shows nothing when it fails. The `.failure` in `onCompletion` is then your only signal. ## Framework-specific setup > [tab] Web > > | Framework | Additional Steps | > | - | - | > | React 18/19 | See [React Integration Guide](/docs/checkout/primer-checkout/frameworks/react-integration-guide) for stable reference patterns | > | Next.js | See [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) for client-side loading | > | Nuxt.js | See [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) for `onMounted` pattern | > | SvelteKit | See [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) for `onMount` pattern | > | Vue.js (client-only) | No additional setup needed | > | Vanilla JS | No additional setup needed | > > > [!WARNING] > > > > **Server-Side Rendering** > > > > If you're using Next.js, Nuxt, SvelteKit, or any SSR framework, you must load Primer only on the client side. The Web Components API doesn't exist in Node.js. > > > > ```javascript theme={"dark"} > > useEffect(() => { > > if (typeof window !== 'undefined') { > > loadPrimer(); > > } > > }, []); > > ``` > > > > See the [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) for complete patterns. > [tab] Android > > No framework-specific setup is needed. The SDK integrates directly with Jetpack Compose. > [tab] iOS > > No framework-specific setup is needed. `PrimerCheckout` integrates directly with SwiftUI. > > For UIKit apps, use [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/guides/uikit-integration) to present the checkout from a `UIViewController`. ## See also > [card] [First Payment](/docs/checkout/primer-checkout/first-payment) > > Accept your first payment > [card] [Styling](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Customize the appearance > [card] [Layout](/docs/checkout/primer-checkout/build-your-ui/layout-customization) > > Control component arrangement > [card] [Core Concepts](/docs/checkout/primer-checkout/core-concepts) > > Understand the architecture # Framework-Specific Migration Guide Source: https://primer.io/docs/checkout/primer-checkout/migration/frameworks Migrate to the new Primer Checkout Web SDK with patterns specific to your JavaScript framework — Vanilla JS, React (18/19), Vue 3, Svelte, and Angular. Primer Checkout is built with [Lit](https://lit.dev/) Web Components. Each JavaScript framework handles Web Components differently — especially around setting properties, passing objects, and handling events. This guide provides the correct migration patterns for each framework. > [!NOTE] > > This guide is for **Web only**. iOS and Android use native UI frameworks (SwiftUI/UIKit and Jetpack Compose respectively) and do not require framework-specific migration steps. See the [Migration Guide](/docs/checkout/primer-checkout/migration/overview) for platform-specific migration instructions. > [!NOTE] > > This guide covers **framework-specific** patterns. For the complete list of Web API and configuration changes (callbacks, payment method options, event payloads, vault methods), see the [Migration Guide](/docs/checkout/primer-checkout/migration/overview). *** ## Quick comparison | Task | Vanilla JS | React 18 | React 19 | Vue 3 | | - | - | - | - | - | | Set `client-token` | `setAttribute()` | `client-token={val}` | `client-token={val}` | `:client-token="val"` | | Set `options` object | `el.options = obj` | ref + `useEffect` | JSX prop directly | `.options="obj"` or ref | | Set `custom-styles` | `setAttribute()` + JSON | `custom-styles={json}` | `custom-styles={json}` | `:custom-styles="json"` | | Listen to events | `addEventListener()` | ref + `useEffect` | ref + `useEffect` | `@primer:payment-success` or ref | | Handle payment result | `primer:payment-success` event | Event in `useEffect` | Event in `useEffect` | Event listener | *** ## Vanilla JavaScript Vanilla JS has the most straightforward integration. The `` element behaves like any other DOM element. ### Property types Primer Checkout uses two types of configuration. The distinction matters: | Type | How to set | Examples | | - | - | - | | **Component properties** (strings) | `setAttribute()` or HTML attribute | `client-token`, `custom-styles`, `loader-disabled` | | **SDK options** (objects) | Direct property assignment | `options` | > [!WARNING] > > Don't mix these up. Component properties must use `setAttribute()`. The `options` object must be assigned directly. Using `setAttribute('options', ...)` will not work. ### Migration example ```javascript theme={"dark"} import { loadPrimer } from '@primer-io/primer-js'; // Load the SDK loadPrimer(); const checkout = document.querySelector('primer-checkout'); // ✅ Component properties — use setAttribute() checkout.setAttribute('client-token', clientToken); checkout.setAttribute('custom-styles', JSON.stringify({ primerColorBrand: '#4a6cf7', })); // ✅ SDK options — assign directly checkout.options = { locale: 'en-GB', card: { cardholderName: { required: true, visible: true }, }, }; // ✅ Payment events checkout.addEventListener('primer:payment-success', (event) => { const { payment, paymentMethodType } = event.detail; console.log('Last 4:', payment.last4Digits); window.location.href = `/confirmation`; }); checkout.addEventListener('primer:payment-failure', (event) => { const { error } = event.detail; console.error('Failed:', error.message, error.diagnosticsId); }); ``` > [!NOTE] > > **Direct property assignment also works in vanilla JS.** Because `` is a Lit element, you can use `checkout.clientToken = '...'` — Lit's `@property` decorator maps between the JS property and the HTML attribute. However, the SDK documentation uses `setAttribute()` for string properties, and we recommend following that convention for consistency. ### Intercepting payments To run validation before payment creation, listen for `primer:payment-start` and use `preventDefault()`: ```javascript theme={"dark"} checkout.addEventListener('primer:payment-start', (event) => { const { continuePaymentCreation, abortPaymentCreation } = event.detail; event.preventDefault(); // Stop automatic continuation if (!document.getElementById('terms-checkbox').checked) { alert('Please accept the terms'); abortPaymentCreation(); } else { continuePaymentCreation(); } }); ``` *** ## React React's handling of Web Components differs significantly between React 18 and React 19, particularly for object properties. ### Why React needs special handling React assumes all JSX props map to HTML attributes — it has no built-in mechanism to set DOM properties on custom elements. This creates two problems: 1. **CamelCase props are lowercased.** Writing `` sets the attribute `clienttoken` (all lowercase), which the component doesn't recognize. 2. **Objects are stringified.** In React 18, passing an object prop like `options={{ locale: 'en-GB' }}` results in the attribute `options="[object Object]"`. React 19 added native support for custom element properties, which resolves the object problem but not the attribute naming issue. | What you write in React JSX | What React does | Result | | - | - | - | | `clientToken="..."` | Sets attribute `clienttoken` (lowercased) | ❌ Wrong attribute name | | `client-token="..."` | Sets attribute `client-token` | ✅ Works | | `ref.current.clientToken = value` | Sets JS property directly | ✅ Works | | `options={{ locale: 'en-GB' }}` (React 18) | Sets attribute `options="[object Object]"` | ❌ Fails | | `options={{ locale: 'en-GB' }}` (React 19) | Sets property directly | ✅ Works | ### React 19 React 19 can pass objects directly as properties to custom elements. ```tsx theme={"dark"} import { useEffect, useRef } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; // Define options outside component for stable reference const SDK_OPTIONS = { locale: 'en-GB' }; export function Checkout({ clientToken }: { clientToken: string }) { const checkoutRef = useRef(null); useEffect(() => { loadPrimer(); }, []); // Set up event handlers useEffect(() => { const checkout = checkoutRef.current; if (!checkout) return; const handleSuccess = (event: PrimerEvents['primer:payment-success']) => { const { payment } = event.detail; window.location.href = `/confirmation`; }; const handleFailure = (event: PrimerEvents['primer:payment-failure']) => { const { error } = event.detail; console.error('Payment failed:', error.message); }; checkout.addEventListener('primer:payment-success', handleSuccess); checkout.addEventListener('primer:payment-failure', handleFailure); return () => { checkout.removeEventListener('primer:payment-success', handleSuccess); checkout.removeEventListener('primer:payment-failure', handleFailure); }; }, []); return ( ); } ``` ### React 18 React 18 cannot pass objects via JSX props — they become `[object Object]` strings. Use a ref to set the `options` property imperatively. ```tsx theme={"dark"} import { useEffect, useRef } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; const SDK_OPTIONS = { locale: 'en-GB' }; export function Checkout({ clientToken }: { clientToken: string }) { const checkoutRef = useRef(null); useEffect(() => { loadPrimer(); }, []); useEffect(() => { const checkout = checkoutRef.current; if (!checkout) return; // React 18: Must set object properties via ref checkout.options = SDK_OPTIONS; const handleSuccess = (event: PrimerEvents['primer:payment-success']) => { const { payment } = event.detail; window.location.href = `/confirmation`; }; const handleFailure = (event: PrimerEvents['primer:payment-failure']) => { const { error } = event.detail; console.error('Payment failed:', error.message); }; checkout.addEventListener('primer:payment-success', handleSuccess); checkout.addEventListener('primer:payment-failure', handleFailure); return () => { checkout.removeEventListener('primer:payment-success', handleSuccess); checkout.removeEventListener('primer:payment-failure', handleFailure); }; }, []); return ( ); } ``` ### Custom styling in React The `custom-styles` attribute accepts a JSON string. Pass it as a kebab-case attribute: ```tsx theme={"dark"} const stylesJson = JSON.stringify({ primerColorBrand: '#4a6cf7', primerRadiusMedium: '12px', }); // Both React 18 and 19 — string attributes work the same ``` Alternatively, use CSS variables directly in your stylesheet (no `custom-styles` attribute needed): ```css theme={"dark"} primer-checkout { --primer-color-brand: #4a6cf7; --primer-radius-medium: 12px; } ``` ### TypeScript setup TypeScript doesn't recognize custom element tags. Add a declaration: ```typescript theme={"dark"} // src/types/primer.d.ts import type { CheckoutElement } from '@primer-io/primer-js'; declare global { namespace JSX { interface IntrinsicElements { 'primer-checkout': CheckoutElement; } } } ``` ### React + SSR (Next.js) Primer requires browser APIs. In Next.js, load it client-side only: ```tsx theme={"dark"} 'use client'; import { useEffect } from 'react'; import { loadPrimer } from '@primer-io/primer-js'; export default function CheckoutPage() { useEffect(() => { loadPrimer(); }, []); return ( ); } ``` → See the [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) and [React Integration Guide](/docs/checkout/primer-checkout/frameworks/react-integration-guide) for complete patterns. *** ## Vue 3 Vue has excellent Web Component support — it [scores 100%](https://custom-elements-everywhere.com/libraries/vue/results/results.html) on the Custom Elements Everywhere tests. Vue 3 automatically detects DOM properties using the `in` operator and sets them correctly, so passing objects works naturally. ### Compiler configuration Vue attempts to resolve any tag with a dash as a Vue component first. Tell the compiler to treat `primer-*` tags as custom elements: > [tab] Vite (vite.config.js) > > ```javascript theme={"dark"} > import vue from '@vitejs/plugin-vue'; > > export default { > plugins: [ > vue({ > template: { > compilerOptions: { > isCustomElement: (tag) => tag.startsWith('primer-') > } > } > }) > ] > }; > ``` > [tab] Vue CLI (vue.config.js) > > ```javascript theme={"dark"} > module.exports = { > chainWebpack: (config) => { > config.module > .rule('vue') > .use('vue-loader') > .tap((options) => ({ > ...options, > compilerOptions: { > isCustomElement: (tag) => tag.startsWith('primer-') > } > })); > } > }; > ``` > [tab] In-Browser > > ```javascript theme={"dark"} > // Only for in-browser compilation > app.config.compilerOptions.isCustomElement = (tag) => tag.startsWith('primer-'); > ``` Without this configuration, Vue will emit "failed to resolve component" warnings for `` and other Primer elements. ### Basic integration ```vue theme={"dark"} ``` ### Passing properties — Vue's `in` operator check Vue 3 automatically checks whether a key exists as a DOM property using the `in` operator. If it does, Vue sets it as a property (not an attribute). This means objects like `options` work correctly in most cases. However, if the `in` check fails (the property isn't defined when Vue first renders), you can force property binding with the `.prop` modifier: ```vue theme={"dark"} ``` > [!NOTE] > > The `.prop` modifier (or its shorthand `.`) explicitly tells Vue to set a DOM property rather than an attribute. This is rarely needed for Primer components since Lit defines its properties upfront, but it's a useful escape hatch. ### Custom styling in Vue ```vue theme={"dark"} ``` Or use CSS variables in a style block (preferred): ```vue theme={"dark"} ``` ### Vue 3 + SSR (Nuxt 3) Primer requires browser APIs. In Nuxt 3, load it client-side only: ```vue theme={"dark"} ``` You'll also need to register Primer elements as custom elements in `nuxt.config.ts`: ```typescript theme={"dark"} // nuxt.config.ts export default defineNuxtConfig({ vue: { compilerOptions: { isCustomElement: (tag) => tag.startsWith('primer-') } } }); ``` → See the [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) for more Nuxt patterns. *** ## Other frameworks ### Svelte Svelte treats custom elements natively — no special configuration is needed. ```svelte theme={"dark"} ``` ### Angular Angular supports custom elements through `CUSTOM_ELEMENTS_SCHEMA`: ```typescript theme={"dark"} // app.module.ts import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core'; @NgModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class AppModule {} ``` ```typescript theme={"dark"} // checkout.component.ts import { Component, ElementRef, Input, OnInit, ViewChild, OnDestroy } from '@angular/core'; import { loadPrimer } from '@primer-io/primer-js'; @Component({ selector: 'app-checkout', template: ` ` }) export class CheckoutComponent implements OnInit, OnDestroy { @Input() clientToken!: string; @ViewChild('checkoutRef') checkoutRef!: ElementRef; private successHandler = (event: PrimerEvents['primer:payment-success']) => { const { payment } = event.detail; // handle success }; private failureHandler = (event: PrimerEvents['primer:payment-failure']) => { const { error } = event.detail; // handle failure }; ngOnInit() { loadPrimer(); const checkout = this.checkoutRef.nativeElement; checkout.options = { locale: 'en-GB' }; checkout.addEventListener('primer:payment-success', this.successHandler); checkout.addEventListener('primer:payment-failure', this.failureHandler); } ngOnDestroy() { const checkout = this.checkoutRef?.nativeElement; if (checkout) { checkout.removeEventListener('primer:payment-success', this.successHandler); checkout.removeEventListener('primer:payment-failure', this.failureHandler); } } } ``` *** ## Migration checklist Use this checklist to verify your migration is complete: * **Updated `client-token` setting** — Using `setAttribute()` (vanilla JS), kebab-case attribute (React/Vue), or framework-appropriate binding * **Updated `options` setting** — Using direct property assignment, not `setAttribute()` * **Updated `custom-styles`** — Passing a JSON string via attribute, or using CSS variables instead * **Updated event handlers** — Listening for `primer:payment-success` and `primer:payment-failure` events * **Configured compiler** (Vue only) — Added `isCustomElement` for `primer-*` tags * **SSR handled** (if applicable) — Loading Primer client-side only *** ## Next steps > [card] [General Migration Guide](/docs/checkout/primer-checkout/migration/overview) > > API changes, payment method options, and event payloads > [card] [React Integration](/docs/checkout/primer-checkout/frameworks/react-integration-guide) > > React 18/19 patterns in depth > [card] [SSR Guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) > > Next.js, Nuxt, and SvelteKit > [card] [SDK Options Reference](/docs/sdk/primer-checkout-web/sdk-options-reference) > > Complete configuration reference # Migrate the manual flow Source: https://primer.io/docs/checkout/primer-checkout/migration/manual-flow Replace `paymentHandling: MANUAL` and the tokenize/resume callbacks with `approvalMode` on the client session and a single approve-or-abort decision. > [!NOTE] > > **New feature.** Manual payment approval is available to all merchants; no allowlisting or account setup is required. Because it's new, **test your integration end to end in the [sandbox](/docs/testing/overview) before going live in production.** Available on the **Web** SDK today; iOS and Android are coming. If your legacy integration uses the **manual payment creation** flow (`paymentHandling: 'MANUAL'` with `onTokenizeSuccess` / `onResumeSuccess` callbacks), this guide covers the changes needed to move to the equivalent flow on Primer Checkout: **[manual payment approval](/docs/checkout/primer-checkout/guides-and-recipes/manual-payment-approval)**. > [!NOTE] > > This is a focused companion to the main [Migration Guide](/docs/checkout/primer-checkout/migration/overview). Start there for the SDK-wide changes (package, initialization, events, styling); this page covers only what's specific to the manual flow. ## What changes The core shift: in the legacy flow your backend **owned the payment lifecycle**: it created the payment, inspected `requiredAction`, and routed each step (3DS, resume) back to the SDK. In the new flow your backend makes a single **approve-or-abort decision**, and Primer owns everything after that. | Concern | Legacy manual flow | New manual approval flow | | - | - | - | | Enabling the flow | `paymentHandling: 'MANUAL'` (SDK setting) | `approvalMode: 'MANUAL'` (client session field) | | Trigger | `onTokenizeSuccess(token, handler)` callback | `primer:payment-approval-required` event | | Your backend call | `POST /payments` (then `POST /payments/{id}/resume`) | `POST /payment-attempts/{id}/approve` (or `/abort`) | | Creating the payment | You create it with the `paymentMethodToken` | Primer creates it when you approve | | 3DS / required actions | You route `requiredAction.clientToken` back via `handler.continueWithNewClientToken()` | Primer handles 3DS and resume automatically | | Resuming | `onResumeSuccess(resumeToken, handler)` + `POST /payments/{id}/resume` | Removed (no resume step) | | Resolving the UI | `handler.handleSuccess()` / `handler.handleFailure()` | `continueFlow()` (the SDK resolves the UI itself) | | Outcome | Returned from your `POST /payments` call | `primer:payment-success` / `primer:payment-failure` events | The result is far less code: there is no payment creation request, no resume request, and no required-action routing on your side. ## Step 1. Enable the flow on the client session, not the SDK Move the manual switch from an SDK setting to a client session field. **Legacy** (set on the SDK): ```javascript theme={"dark"} Primer.showUniversalCheckout(clientToken, { paymentHandling: 'MANUAL', // ... }); ``` **New** (set on the client session when you create it server-side): ```bash theme={"dark"} curl -X POST https://api.primer.io/client-session \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "orderId": "order-123", "currencyCode": "USD", "amount": 1000, "approvalMode": "MANUAL" }' ``` The SDK is initialized the same way as any Primer Checkout integration (see the [Migration Guide](/docs/checkout/primer-checkout/migration/overview#initialization)); there is no `paymentHandling` option. ## Step 2. Replace the tokenize/resume callbacks with the approval event The two callbacks collapse into a single event. **Legacy** (create the payment and route required actions yourself): ```javascript theme={"dark"} Primer.showUniversalCheckout(clientToken, { paymentHandling: 'MANUAL', async onTokenizeSuccess(paymentMethodTokenData, handler) { const response = await createPayment(paymentMethodTokenData.token); // POST /payments if (!response) return handler.handleFailure('Payment failed.'); if (response.requiredAction?.clientToken) { return handler.continueWithNewClientToken(response.requiredAction.clientToken); } return handler.handleSuccess(); }, async onResumeSuccess(resumeTokenData, handler) { const response = await resumePayment(resumeTokenData.resumeToken); // POST /payments/{id}/resume if (!response) return handler.handleFailure('Payment failed.'); if (response.requiredAction?.clientToken) { return handler.continueWithNewClientToken(response.requiredAction.clientToken); } return handler.handleSuccess(); }, }); ``` **New** (decide, then resume): ```javascript theme={"dark"} const checkout = document.querySelector('primer-checkout'); checkout.addEventListener('primer:payment-approval-required', async (event) => { const { paymentAttemptId, continueFlow } = event.detail; // Your backend calls /approve or /abort (Step 3) await fetch('/my-backend/handle-payment-approval', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paymentAttemptId }), }); await continueFlow(); }); ``` Note what disappears: no `POST /payments`, no `requiredAction` inspection, no `continueWithNewClientToken`, and no `onResumeSuccess` / resume call. Primer creates and orchestrates the payment after you approve. ## Step 3. Swap payment creation for approve / abort Your backend endpoint changes from creating (and resuming) a payment to approving or aborting the attempt. **Legacy:** ```javascript theme={"dark"} // Create the payment with the tokenized method await fetch('https://api.primer.io/payments', { method: 'POST', headers: { 'X-Api-Key': KEY, 'X-Api-Version': '2.4', 'Content-Type': 'application/json' }, body: JSON.stringify({ paymentMethodToken }), }); ``` **New:** ```javascript theme={"dark"} // Approve the attempt; Primer creates and processes the payment await fetch(`https://api.primer.io/payment-attempts/${paymentAttemptId}/approve`, { method: 'POST', headers: { 'X-Api-Key': KEY, 'X-Api-Version': '2.4' }, }); // Or abort it; no payment is created await fetch(`https://api.primer.io/payment-attempts/${paymentAttemptId}/abort`, { method: 'POST', headers: { 'X-Api-Key': KEY, 'X-Api-Version': '2.4', 'Content-Type': 'application/json' }, body: JSON.stringify({ reason: 'fraud-check-failed' }), }); ``` The legacy flow had no first-class way to *decline* after tokenization other than failing the payment. The new flow gives you `/abort` as an explicit, payment-free cancellation. ## Step 4. Read the outcome from events The payment result is no longer the return value of your `POST /payments` call. Listen for the standard payment events instead, the same ones every Primer Checkout integration uses: ```javascript theme={"dark"} checkout.addEventListener('primer:payment-success', (event) => { const { payment } = event.detail; window.location.href = `/confirmation?order=${payment.orderId}`; }); checkout.addEventListener('primer:payment-failure', (event) => { const { error } = event.detail; console.error('Payment failed:', error.diagnosticsId); }); ``` ## Behavior differences to be aware of * **3DS is automatic.** You no longer route `requiredAction.clientToken` back to the SDK. After you approve, Primer stages and resolves 3DS itself. * **Retries create a new attempt.** On a decline the checkout unlocks the payment form and the customer can retry in the same session; re-tokenizing creates a new `paymentAttemptId`. You don't create a new client session. * **There's a 90-second approval window.** If your backend calls neither `/approve` nor `/abort` within 90 seconds, the attempt expires. The legacy flow had no such window. * **`paymentAttemptId` is the idempotency key.** Duplicate or concurrent approves for the same attempt converge on one payment. See the [Manual payment approval](/docs/checkout/primer-checkout/guides-and-recipes/manual-payment-approval) guide for the full lifecycle, error matrix, and browser-refresh recovery. ## Migration checklist * **Moved the switch**: replaced `paymentHandling: 'MANUAL'` (SDK) with `approvalMode: 'MANUAL'` (client session) * **Replaced callbacks**: swapped `onTokenizeSuccess` / `onResumeSuccess` for the `primer:payment-approval-required` event + `continueFlow()` * **Replaced backend calls**: swapped `POST /payments` (and `/resume`) for `POST /payment-attempts/{id}/approve` (or `/abort`) * **Removed required-action routing**: deleted `continueWithNewClientToken` and resume handling (Primer handles 3DS) * **Read outcomes from events**: using `primer:payment-success` / `primer:payment-failure` * **Handled abort and the 90s timeout**: see the manual payment approval guide ## Next steps > [card] [Manual payment approval](/docs/checkout/primer-checkout/guides-and-recipes/manual-payment-approval) > > The full guide for the new flow > [card] [Migration Guide](/docs/checkout/primer-checkout/migration/overview) > > SDK-wide changes for moving to Primer Checkout > [card] [Events Reference](/docs/sdk/primer-checkout-web/events-reference) > > primer:payment-approval-required and all events > [card] [Client session](/docs/checkout/client-session) > > Create a session with approvalMode # Migrate from Drop-in or Headless Source: https://primer.io/docs/checkout/primer-checkout/migration/overview Complete SDK migration for Web, iOS and Android: package changes, the new initialization pattern, callbacks replaced by events, and CSS-based theming. This guide covers the key changes when migrating from the legacy SDK to the new Primer Checkout Components. Select your platform to see platform-specific migration steps. > [!NOTE] > > Not every section will apply — skip sections for features you don't use. *** ## Package and imports > [tab] Web > > For Web-specific framework patterns (React, Vue, Svelte, Angular), see the [Framework Migration Guide](/docs/checkout/primer-checkout/migration/frameworks). > > ### Installation > > ```bash theme={"dark"} > # Remove legacy package > npm uninstall @primer-io/checkout-web > > # Install new package > npm install @primer-io/primer-js > ``` > > ### Import changes > > **Legacy:** > > ```javascript theme={"dark"} > import { Primer as PrimerSDK } from '@primer-io/checkout-web'; > ``` > > **New:** > > ```javascript theme={"dark"} > import { loadPrimer } from '@primer-io/primer-js'; > ``` > > ### Type imports > > If you use TypeScript, the type names have changed: > > ```typescript theme={"dark"} > import type { > CheckoutElement, > PrimerCheckoutOptions, > PrimerJS, > } from '@primer-io/primer-js'; > ``` > > | Legacy type | New type | Purpose | > | - | - | - | > | `PrimerCheckout` | `PrimerJS` | Main SDK instance | > | `UniversalCheckoutOptions` | `PrimerCheckoutOptions` | Checkout configuration | > | N/A | `CheckoutElement` | Web component element type | > [tab] Android > > > [!WARNING] > > > > The Android SDK is currently in **beta** (v3.0.0-beta.8). The API is subject to change before stable release. > > ### No dependency changes required > > Primer Checkout Components is part of the same SDK. No BOM or artifact changes are needed. > > ### Jetpack Compose requirement > > If your project doesn't already use Jetpack Compose, enable it in your module-level `build.gradle.kts`: > > ```kotlin theme={"dark"} > android { > buildFeatures { > compose = true > } > composeOptions { > kotlinCompilerExtensionVersion = "1.5.8" > } > } > > dependencies { > implementation(platform("androidx.compose:compose-bom:2025.12.00")) > implementation("androidx.compose.ui:ui") > implementation("androidx.compose.material3:material3") > implementation("androidx.lifecycle:lifecycle-runtime-compose:2.7.0") > } > ``` > > ### Import > > ```kotlin theme={"dark"} > import io.primer.android.checkout.* > ``` > [tab] iOS > > > [!WARNING] > > > > The iOS SDK is currently in **beta** (v3.0.0-beta.8). The API is subject to change before stable release. > > ### Update the dependency version > > Primer Checkout is part of the same `PrimerSDK` package, but only in the 3.0 beta line. Pin the dependency to `3.0.0-beta.8`: > > * **CocoaPods**: `pod 'PrimerSDK', '3.0.0-beta.8'` > * **Swift Package Manager**: set the dependency rule to **Exact Version** `3.0.0-beta.8` > > ### Minimum deployment target > > Update your minimum deployment target from iOS 13.0 to **iOS 15.0**: > > * **Xcode**: Target > General > Minimum Deployments > iOS 15.0 > * **Podfile**: `platform :ios, '15.0'` > * **Package.swift**: `.iOS(.v15)` > > The whole `PrimerSDK` package requires iOS 15.0, through both CocoaPods and Swift Package Manager. This includes Drop-In and Headless, so an app that uses them alongside Primer Checkout cannot keep a lower deployment target. > > ### Import > > The import stays the same: > > ```swift theme={"dark"} > import PrimerSDK > ``` *** ## Initialization > [tab] Web > > The initialization pattern changes from a single function call to a multi-step process involving a Web Component and event listeners. > > ### Legacy pattern > > ```javascript theme={"dark"} > import { Primer as PrimerSDK } from '@primer-io/checkout-web'; > > const checkout = await PrimerSDK.showUniversalCheckout(clientToken, { > container: '#checkout-container', > onCheckoutComplete: (data) => { /* ... */ }, > onCheckoutFail: (error, data, handler) => { /* ... */ }, > }); > ``` > > ### New pattern > > ```javascript theme={"dark"} > import { loadPrimer } from '@primer-io/primer-js'; > > // 1. Load the SDK (registers the web component) > loadPrimer(); > > // 2. Get or create the checkout element > const checkout = document.querySelector('primer-checkout'); > > // 3. Set the client token (component property — use setAttribute) > checkout.setAttribute('client-token', clientToken); > > // 4. Set SDK options (object — assign directly) > checkout.options = { > locale: 'en-GB', > }; > > // 5. Listen for payment events > checkout.addEventListener('primer:payment-success', (event) => { > const { payment, paymentMethodType } = event.detail; > window.location.href = `/confirmation?order=${payment.orderId}`; > }); > > checkout.addEventListener('primer:payment-failure', (event) => { > const { error } = event.detail; > console.error('Payment failed:', error.message); > }); > ``` > > Or declare the element in HTML: > > ```html theme={"dark"} > > ``` > > ### Key differences > > | Aspect | Legacy | New | > | - | - | - | > | Entry point | `PrimerSDK.showUniversalCheckout()` | `loadPrimer()` + `` element | > | Container | `container: '#checkout-container'` (CSS selector) | The `` element *is* the container | > | Configuration | Single options object passed to function | Two types: component properties (`setAttribute`) and SDK `options` (direct assignment) | > | Payment handling | Callbacks in options object | DOM events (`primer:payment-success`, `primer:payment-failure`) | > > > [!WARNING] > > > > **Component properties vs SDK options** — these are different and cannot be mixed. > > > > * **Component properties** (`client-token`, `custom-styles`, `loader-disabled`): Use `setAttribute()`. > > * **SDK options** (`locale`, `card`, `vault`, `applePay`, etc.): Assign directly to `.options`. > > > > Using `setAttribute('options', ...)` will not work. See the [SDK Options guide](/docs/checkout/primer-checkout/configuration/sdk-options) for details. > [tab] Android > > The initialization changes from configuring a singleton to creating a Compose-based controller and rendering a checkout sheet. > > ### Legacy pattern (Drop-In) > > ```kotlin theme={"dark"} > // Configure singleton + set listener > Primer.instance.configure( > settings = PrimerSettings(), > listener = checkoutListener, > ) > > // Present checkout > Primer.instance.showUniversalCheckout(context, clientToken) > ``` > > ### New pattern > > ```kotlin theme={"dark"} > @Composable > fun CheckoutScreen(clientToken: String) { > // 1. Create checkout controller > val checkout = rememberPrimerCheckoutController( > clientToken = clientToken, > settings = PrimerSettings(), > ) > > // 2. Observe outcomes via checkout.state > val state by checkout.state.collectAsStateWithLifecycle() > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { > val paymentId = s.checkoutData.payment.id > navigateToConfirmation(paymentId) > } > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Failed: ${s.primerError.description}") > } > else -> Unit > } > } > > // 3. Render checkout sheet > PrimerCheckoutSheet( > checkout = checkout, > onDismiss = { navigateBack() }, > ) > } > ``` > > For inline layouts instead of a modal sheet, use `PrimerCheckoutHost`: > > ```kotlin theme={"dark"} > PrimerCheckoutHost(checkout = checkout) { > // Your custom Compose layout > } > ``` > > ### Key differences > > | Aspect | Drop-In | CheckoutComponents | > | - | - | - | > | Entry point | `Primer.instance.showUniversalCheckout()` | `rememberPrimerCheckoutController()` + `PrimerCheckoutSheet()` | > | Configuration | `Primer.instance.configure(settings, listener)` | `PrimerSettings` param on controller | > | Result handling | `PrimerCheckoutListener` callbacks | `PrimerCheckoutState.Success` / `.Failure` via `checkout.state` | > | UI framework | Android Views | Jetpack Compose | > | Presentation | Automatic (Activity) | `PrimerCheckoutSheet` (modal) or `PrimerCheckoutHost` (inline) | > | State | Listener callbacks | `StateFlow` | > | Dismiss | `Primer.instance.dismiss()` | `checkout.dismiss()` | > [tab] iOS > > The initialization changes from configuring a singleton to creating a view (SwiftUI) or calling a static presenter method (UIKit). Configuration, delegate, and presentation are combined into a single step. > > ### Legacy pattern (Drop-In) > > ```swift theme={"dark"} > // Configure singleton + set delegate > Primer.shared.configure(settings: settings, delegate: self) > > // Present checkout > Primer.shared.showUniversalCheckout(clientToken: clientToken) > ``` > > ### New pattern — UIKit > > For UIKit apps, `PrimerCheckoutPresenter` provides the most direct migration path. It wraps the SwiftUI checkout in a `UIHostingController` and handles presentation. > > ```swift theme={"dark"} > // Set delegate > PrimerCheckoutPresenter.shared.delegate = self > > // Present checkout — minimal > PrimerCheckoutPresenter.presentCheckout(clientToken: clientToken, from: self) > > // Or with settings > PrimerCheckoutPresenter.presentCheckout( > clientToken: clientToken, > from: self, > primerSettings: PrimerSettings(paymentHandling: .auto) > ) > > // Or with settings and theme > PrimerCheckoutPresenter.presentCheckout( > clientToken: clientToken, > from: self, > primerSettings: PrimerSettings(paymentHandling: .auto), > primerTheme: PrimerCheckoutTheme() > ) > ``` > > `PrimerCheckoutPresenter` also provides: > > * `PrimerCheckoutPresenter.isPresenting` — check if checkout is currently visible > * `PrimerCheckoutPresenter.dismiss()` — programmatically dismiss the checkout > > ### New pattern — SwiftUI > > For SwiftUI apps, use the managed `PrimerCheckout` view directly. It renders Primer's default screens end to end and reports the outcome through `onCompletion`: > > ```swift theme={"dark"} > PrimerCheckout( > clientToken: clientToken, > primerSettings: PrimerSettings(paymentHandling: .auto), > primerTheme: PrimerCheckoutTheme(), > onCompletion: { state in > switch state { > case .success(let result): > print("Payment succeeded: \(result.paymentId)") > case let .failure(error, _): > print("Payment failed: \(error.errorId)") > case .dismissed: > print("Dismissed") > default: > break > } > } > ) > ``` > > To build a custom layout instead of the managed screens, hold a `PrimerCheckoutSession` as a `@StateObject`, place the composable views (`PrimerCardForm`, `PrimerPaymentMethods`) in your hierarchy, and attach the `.primerCheckoutSession(_:theme:onCompletion:)` modifier: > > ```swift theme={"dark"} > struct CustomCheckoutView: View { > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > PrimerPaymentMethods() > PrimerCardForm() > } > .primerCheckoutSession(session) { state in > if case .success(let result) = state { > print("Payment succeeded: \(result.paymentId)") > } > } > } > } > ``` > > ### Key differences > > | Aspect | Drop-In | CheckoutComponents (UIKit) | CheckoutComponents (SwiftUI) | > | - | - | - | - | > | Entry point | `Primer.shared.showUniversalCheckout()` | `PrimerCheckoutPresenter.presentCheckout()` | `PrimerCheckout()` view (managed) or `PrimerCheckoutSession` + `.primerCheckoutSession` (custom) | > | Configuration | `Primer.shared.configure(settings:delegate:)` | Parameters on `presentCheckout()` | Parameters on initializer | > | Delegate | `PrimerDelegate` | `PrimerCheckoutPresenterDelegate` | `onCompletion` closure | > | Payment handling | `.auto` or `.manual` | `.auto` only | `.auto` only | > | Min iOS | 13.0 (v2.x) | 15.0 | 15.0 | > | UI framework | UIKit | UIKit (wraps SwiftUI internally) | SwiftUI | > | Dismiss | `Primer.shared.dismiss()` | `PrimerCheckoutPresenter.dismiss()` | View lifecycle | > > > [!WARNING] > > > > Primer Checkout creates the payment itself. If your Drop-In or Headless integration uses `PrimerSettings(paymentHandling: .manual)` and creates payments from your backend, switch to `.auto`. A checkout started with `.manual` fails immediately with a `PrimerError` whose `errorId` is `invalid-value`. Use `onBeforePaymentCreate` on [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) to pass an idempotency key or to abort a payment before the SDK creates it. Backend-driven manual approval is available on Web today and is coming to iOS, see [Migrate the manual flow](/docs/checkout/primer-checkout/migration/manual-flow). *** ## Accessing the SDK > [tab] Web > > Some SDK methods require access to the `PrimerJS` instance. This instance is provided via the `primer:ready` event, which fires when the checkout is fully initialized. > > ### Getting the instance > > ```javascript theme={"dark"} > const checkout = document.querySelector('primer-checkout'); > > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > > // Now you can call SDK methods > await primer.refreshSession(); > }); > ``` > > ### Storing for later use > > If you need to call SDK methods outside of the event handler (e.g., in response to user actions or after a session expires), store the reference: > > ```javascript theme={"dark"} > let primer; > > checkout.addEventListener('primer:ready', (event) => { > primer = event.detail; > }); > > // Later, when needed > async function handleSessionRefresh() { > if (primer) { > await primer.refreshSession(); > } > } > ``` > > ### Available methods > > The `PrimerJS` instance provides: > > | Method | Description | > | - | - | > | `refreshSession()` | Sync the SDK with server-side session changes. Returns `Promise`. | > | `getPaymentMethods()` | Returns the list of available payment methods. | > | `setCardholderName(name)` | Programmatically set the cardholder name field. | > | `vault.startPayment(id, options?)` | Start payment with a vaulted method. | > | `vault.createCvvInput(options)` | Create a CVV input for re-capture. | > | `vault.delete(id)` | Delete a vaulted payment method. | > > > [!NOTE] > > > > Most integrations don't need to access the `PrimerJS` instance directly. The primary use cases are session refresh, programmatic cardholder name updates, and headless vault implementations. > [tab] Android > > In Primer Checkout Components, checkout state is available via `PrimerCheckoutController.state`, a `StateFlow` you can collect in your composables: > > ```kotlin theme={"dark"} > val checkout = rememberPrimerCheckoutController(clientToken, PrimerSettings()) > val state by checkout.state.collectAsStateWithLifecycle() > > when (state) { > is PrimerCheckoutState.Loading -> CircularProgressIndicator() > is PrimerCheckoutState.Ready -> { /* Render checkout */ } > is PrimerCheckoutState.Success -> { /* Payment completed */ } > is PrimerCheckoutState.Failure -> { /* Show error */ } > else -> Unit > } > ``` > > The controller also provides: > > * `checkout.refresh()` — reinitialize the checkout session > * `checkout.dismiss()` — programmatically dismiss the checkout UI > > See the [PrimerCheckoutController reference](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-controller) for the full API. > [tab] iOS > > In Primer Checkout Components, outcomes are delivered as `PrimerCheckoutState` values in your `onCompletion` closure. `.failure` arrives once for each failed payment attempt, and the checkout stays usable for a retry. Then `.success` or `.dismissed` arrives exactly once. A failed initialization is the exception. It arrives once as `.failure` and ends a custom-layout session. The composable views own their interactive state through observable sessions. > > For custom layouts, hold a `PrimerCheckoutSession` and attach the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. The composable views (`PrimerCardForm`, `PrimerPaymentMethods`) resolve their per-feature session — `PrimerCardFormSession`, `PrimerSelectionSession` — from the environment, and you observe those sessions inside your slot closures: > > ```swift theme={"dark"} > @StateObject private var session: PrimerCheckoutSession > > init(clientToken: String) { > _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) > } > > var body: some View { > ScrollView { > // Observe the card form session inside its slots > PrimerCardForm( > submitButton: { cardForm in > Button("Pay") { cardForm.submit() } > .disabled(!cardForm.state.isValid || cardForm.state.isLoading) > } > ) > } > .primerCheckoutSession(session) { state in > // .failure for each failed attempt, then .success or .dismissed once > } > } > ``` > > `PrimerCheckoutSession` also provides: > > * `await session.refresh()` — re-fetch configuration and payment methods after a client-session update > * `session.cancel()` — tear the session down (the modifier wires this to `onDisappear`) > > A failed refresh reports `.failure` through `onCompletion`, and the session stays usable. > > See the [PrimerCheckoutSession reference](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) for the full session API. *** ## Result handling > [tab] Web > > The new SDK uses DOM events as the primary API for payment lifecycle handling. This replaces the callback-based approach from the legacy SDK. > > ### Migration table > > | Legacy callback | New event | Notes | > | - | - | - | > | `onCheckoutComplete(data)` | `primer:payment-success` | Unified `payment` property | > | `onCheckoutFail(error, data, handler)` | `primer:payment-failure` | Simplified — no handler | > | `onBeforePaymentCreate(data, handler)` | `primer:payment-start` | Use `preventDefault()` + handlers in `event.detail` | > | `onPaymentCreationStart()` | `primer:payment-start` | Same event, check `paymentMethodType` | > | `onClientSessionUpdate(session)` | Call `primer.refreshSession()` | Now a method, not event | > | `submitButton.onDisable(disabled)` | `primer:state-change` | Check `isProcessing` / `isLoading` | > > ### Payment success > > **Legacy:** > > ```javascript theme={"dark"} > onCheckoutComplete: (data) => { > console.log('Payment ID:', data.payment.id); > console.log('Customer email:', data.customer.email); > } > ``` > > **New:** > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-success', (event) => { > const { payment, paymentMethodType, timestamp } = event.detail; > > // payment is a PaymentSummary — contains partial card data > console.log('Last 4:', payment.last4Digits); > console.log('Network:', payment.network); > console.log('Method:', paymentMethodType); > > window.location.href = '/confirmation'; > }); > ``` > > The `PaymentSummary` contains partial card data (last 4 digits, network, cardholder name) but not full PII like customer email or full card number. Use server-side webhooks for complete payment data. > > ### Payment failure > > **Legacy:** > > ```javascript theme={"dark"} > onCheckoutFail: (error, data, handler) => { > handler.showErrorMessage('Your card was declined'); > } > ``` > > **New:** > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-failure', (event) => { > const { error, payment, paymentMethodType, timestamp } = event.detail; > > // error has: code, message, diagnosticsId, data > console.error('Failed:', error.message, error.diagnosticsId); > > // The SDK shows the error in the UI automatically. > // Use this event for logging, analytics, or retry logic. > }); > ``` > > ### Pre-payment validation (intercepting payments) > > The legacy `onBeforePaymentCreate` callback is replaced by the `primer:payment-start` event. Use `event.preventDefault()` to intercept the payment flow, then call `continuePaymentCreation()` or `abortPaymentCreation()` from `event.detail`. > > **Legacy:** > > ```javascript theme={"dark"} > onBeforePaymentCreate: (data, handler) => { > if (!termsAccepted) { > handler.showErrorMessage('Please accept the terms'); > handler.abort(); > } else { > handler.continuePaymentCreation(); > } > } > ``` > > **New:** > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-start', (event) => { > const { paymentMethodType, continuePaymentCreation, abortPaymentCreation } = event.detail; > > // Prevent automatic continuation > event.preventDefault(); > > if (!document.getElementById('terms-checkbox').checked) { > // Show your own error UI > alert('Please accept the terms'); > abortPaymentCreation(); > } else { > // Optionally pass an idempotency key > continuePaymentCreation({ idempotencyKey: 'your-key' }); > } > }); > ``` > > > [!NOTE] > > > > If you don't call `event.preventDefault()`, the payment continues automatically. Only use `preventDefault()` when you need to run validation or async checks before payment creation. > > ### Session refresh > > This is no longer a callback. It's a method you call when you need to sync the SDK with server-side session changes. > > **Legacy:** > > ```javascript theme={"dark"} > onClientSessionUpdate: (session) => { > console.log('Session updated:', session); > } > > checkout.updateClientSession(newClientToken); > ``` > > **New:** > > ```javascript theme={"dark"} > // Update the client token, then call refreshSession() > checkout.setAttribute('client-token', newClientToken); > > checkout.addEventListener('primer:ready', (event) => { > const primer = event.detail; > await primer.refreshSession(); > }); > ``` > [tab] Android > > The callback-based `PrimerCheckoutListener` is replaced by `StateFlow`. Payment outcomes are terminal cases of that single state flow — observe `checkout.state` and match on `PrimerCheckoutState.Success` / `.Failure`. > > ### Callback migration > > | Legacy (`PrimerCheckoutListener`) | New (CheckoutComponents) | > | - | - | > | `onCheckoutCompleted(checkoutData)` | `PrimerCheckoutState.Success` (via `checkout.state`) | > | `onFailed(error, checkoutData, errorHandler)` | `PrimerCheckoutState.Failure` (via `checkout.state`) | > | Listener callbacks | `StateFlow` | > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > > LaunchedEffect(state) { > when (val s = state) { > is PrimerCheckoutState.Success -> { > val paymentId = s.checkoutData.payment.id > navigateToConfirmation(paymentId) > } > is PrimerCheckoutState.Failure -> { > Log.e("Checkout", "Error: ${s.primerError.description}") > } > else -> Unit > } > } > > PrimerCheckoutSheet( > checkout = checkout, > onDismiss = { > navigateBack() > }, > ) > ``` > > ### State observation > > ```kotlin theme={"dark"} > val state by checkout.state.collectAsStateWithLifecycle() > > when (state) { > is PrimerCheckoutState.Loading -> { /* Show loading */ } > is PrimerCheckoutState.Ready -> { /* Checkout is interactive */ } > is PrimerCheckoutState.Success -> { /* Payment completed */ } > is PrimerCheckoutState.Failure -> { /* Handle error */ } > else -> Unit > } > ``` > > See [PrimerCheckoutState](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state) for the complete state reference, including the `Success` and `Failure` outcome cases. > [tab] iOS > > The callback-based `PrimerDelegate` is replaced by either `PrimerCheckoutPresenterDelegate` (UIKit) or `onCompletion` + state observation (SwiftUI). > > ### UIKit — PrimerCheckoutPresenterDelegate > > | Legacy (`PrimerDelegate`) | New (`PrimerCheckoutPresenterDelegate`) | > | - | - | > | `primerDidCompleteCheckoutWithData(_:)` | `primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult)` | > | `primerDidFailWithError(_:data:decisionHandler:)` | `primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?)` | > | `primerDidDismiss()` | `primerCheckoutPresenterDidDismiss()` | > > `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` fires once for each failed payment attempt, including a failed initialization. > > * While the SDK error screen is shown, the sheet stays open so the shopper can retry or, when available, choose another payment method. Don't dismiss the sheet or navigate away in this callback. > * If the shopper closes the sheet on the error screen, the delegate receives `primerCheckoutPresenterDidDismiss()`. A successful retry reaches `primerCheckoutPresenterDidCompleteWithSuccess(_:)`. > * When `uiOptions.isErrorScreenEnabled` is `false`, the sheet closes on failure. > * When the payment exists, `checkoutData?.payment` carries the payment ID and order ID. When the failure happens before a payment exists, for example during initialization, `checkoutData` is `nil`. > > ```swift theme={"dark"} > class CheckoutViewController: UIViewController, PrimerCheckoutPresenterDelegate { > > func showCheckout() { > PrimerCheckoutPresenter.shared.delegate = self > PrimerCheckoutPresenter.presentCheckout( > clientToken: clientToken, > from: self, > primerSettings: PrimerSettings(paymentHandling: .auto) > ) > } > > func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) { > let confirmationVC = ConfirmationViewController(paymentId: result.paymentId) > navigationController?.pushViewController(confirmationVC, animated: true) > } > > func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) { > print("Payment failed: \(error.errorId)") > } > > func primerCheckoutPresenterDidDismiss() { > print("Checkout dismissed") > } > } > ``` > > A failed 3DS challenge reaches `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` like any other failed payment. > > ### SwiftUI — onCompletion + state observation > > | Legacy (`PrimerDelegate`) | New (CheckoutComponents) | > | - | - | > | `primerDidCompleteCheckoutWithData(_:)` | `onCompletion: .success(PaymentResult)` | > | `primerDidFailWithError(_:data:decisionHandler:)` | `onCompletion: .failure(PrimerError, checkoutData: PrimerCheckoutData?)` | > | `primerDidDismiss()` | `onCompletion: .dismissed` | > | `primerWillCreatePaymentWithData(_:decisionHandler:)` | `PrimerCheckoutSession.onBeforePaymentCreate` handler | > > The managed `PrimerCheckout` view reports outcomes through `onCompletion`. It delivers `.failure` once for each failed attempt, including a failed initialization, while the checkout stays open for a retry. Then it delivers `.success` or `.dismissed` exactly once. Switch over the case to route your UI: > > ```swift theme={"dark"} > PrimerCheckout( > clientToken: clientToken, > onCompletion: { state in > switch state { > case .success(let result): > navigateToConfirmation(paymentId: result.paymentId) > case let .failure(error, _): > logError(error) > case .dismissed: > navigateBack() > default: > break > } > } > ) > ``` > > For custom layouts, the `.primerCheckoutSession(_:theme:onCompletion:)` modifier delivers `.failure` once for each failed payment attempt, then `.success` or `.dismissed` exactly once. A failed initialization is delivered once as `.failure` and ends the session. To observe interactive state during the flow, read the `@Published state` on the per-feature session injected into each slot — for example `PrimerCardFormSession.state` inside a `PrimerCardForm` slot. > > > [!NOTE] > > > > `PaymentResult` replaces `PrimerCheckoutData` as the success type. It contains `paymentId`, `status`, `token`, `redirectUrl`, `errorMessage`, `amount`, `currencyCode`, and `paymentMethodType`. A failure carries `PrimerCheckoutData` as `checkoutData`. > > See [PrimerCheckoutState](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) for the complete state lifecycle documentation. *** ## Configuration and theming > [tab] Web > > ### Options changes > > #### Options that work the same > > These options are identical in both SDKs: > > * `locale` — Language/region code (e.g., `'en-GB'`). Falls back to `en-GB` if the locale is not supported. > * `merchantDomain` — Your website domain (used for Apple Pay validation). > * `submitButton.useBuiltInButton` — Show or hide the built-in submit button. > * `submitButton.amountVisible` — Display the payment amount on the button. > > #### Options that changed > > | Legacy option | New option | Notes | > | - | - | - | > | `container` | Removed | The `` element *is* the container | > | `vault.visible` | `vault.enabled` | Renamed — same purpose | > | `form.inputLabelsVisible` | Removed | Labels are always visible for accessibility | > | `successScreen.visible` | Removed | Handle success UI in your application | > | `successScreen.message` | Removed | Use `primer:payment-success` event or the `checkout-complete` slot | > | `apiVersion` | `sdkCore` | `sdkCore` defaults to `true`; set to `false` only for legacy compatibility | > > #### New options > > | Option | Description | > | - | - | > | `vault.headless` | Hide default vault UI for custom implementations | > | `vault.showEmptyState` | Show a message when no saved payment methods exist | > > #### Success screen replacement > > The legacy SDK had a built-in success screen. The new SDK gives you two options: > > **Option 1: Use the `checkout-complete` slot** (declarative) > > ```html theme={"dark"} > > >
>

Thank you for your order!

>

Your payment was processed successfully.

>
>
>
> ``` > > **Option 2: Handle via event** (imperative) > > ```javascript theme={"dark"} > checkout.addEventListener('primer:payment-success', (event) => { > const { payment } = event.detail; > window.location.href = `/confirmation?order=${payment.orderId}`; > }); > ``` > > ### Styling changes > > The styling system has fundamentally changed from JavaScript objects to CSS custom properties. > > #### Legacy: CSS-in-JS objects > > ```javascript theme={"dark"} > PrimerSDK.showUniversalCheckout(clientToken, { > style: { > input: { > base: { fontSize: 16, color: '#000000' }, > invalid: { color: '#DC3545', borderColor: '#DC3545' } > }, > button: { > base: { backgroundColor: '#007BFF', color: '#FFFFFF' } > } > } > }); > ``` > > #### New: CSS custom properties > > **Option 1: CSS stylesheet** (recommended) > > ```css theme={"dark"} > primer-checkout { > --primer-color-brand: #007BFF; > --primer-color-text-primary: #333333; > --primer-typography-brand: 'Inter', sans-serif; > --primer-radius-medium: 8px; > } > ``` > > **Option 2: `custom-styles` attribute** (JSON string with camelCase keys) > > ```javascript theme={"dark"} > checkout.setAttribute('custom-styles', JSON.stringify({ > primerColorBrand: '#007BFF', > primerColorTextPrimary: '#333333', > primerTypographyBrand: 'Inter, sans-serif', > primerRadiusMedium: '8px', > })); > ``` > > The conversion rule for the `custom-styles` attribute: `--primer-color-brand` → `primerColorBrand` (remove `--`, convert kebab-case to camelCase). > > **Option 3: Inline CSS** > > ```javascript theme={"dark"} > checkout.style.setProperty('--primer-color-brand', '#007BFF'); > ``` > > #### Key differences > > | Aspect | Legacy | New | > | - | - | - | > | Location | JavaScript options object | CSS stylesheet, `custom-styles` attribute, or inline styles | > | Syntax | Nested JS objects | CSS variables with `--primer-` prefix | > | Theming | Manual recreation for dark mode | Built-in dark theme via `class="primer-dark-theme"` | > | Debugging | Difficult to inspect | Live editing in browser DevTools | > | Performance | Runtime style injection | Native CSS cascade | > > #### Design token categories > > The new SDK organizes styling into token categories: > > * **Colors** — `--primer-color-brand`, `--primer-color-text-primary`, `--primer-color-background-primary`, and more > > * **Typography** — `--primer-typography-brand` (font family), `--primer-typography-body-medium-size`, etc. > > * **Spacing** — `--primer-space-xxsmall` (2px) through `--primer-space-xlarge` (20px) > > * **Border radius** — `--primer-radius-xsmall` (2px) through `--primer-radius-large` (12px) > > * **Sizing** — `--primer-size-small` through `--primer-size-xxxlarge` > > * **Animation** — `--primer-animation-duration`, `--primer-animation-easing` > > * **Border width** — `--primer-width-default` and state variants > > > See the [Styling Variables Reference](/docs/sdk/primer-checkout-web/styling-variables) for the complete list of available tokens. > > > [!NOTE] > > > > **Don't attempt a 1:1 mapping** from your legacy CSS-in-JS styles. Instead, start with your brand color (`--primer-color-brand`) and font (`--primer-typography-brand`), then use browser DevTools to inspect which tokens affect which elements and adjust from there. > [tab] Android > > ### Settings > > `PrimerSettings` is now passed to `rememberPrimerCheckoutController()` instead of `Primer.instance.configure()`. > > | Legacy | New | Notes | > | - | - | - | > | `Primer.instance.configure(settings)` | `PrimerSettings` param on controller | Same pattern | > | Theme via `PrimerSettings.uiOptions` | `PrimerTheme` data class on composables | Separate from settings | > | Screen flags | Composable slot parameters | Custom screens via composition | > > ### Theming > > The legacy theme settings are replaced by `PrimerTheme`, a data class with design token overrides: > > ```kotlin theme={"dark"} > PrimerCheckoutSheet( > checkout = checkout, > theme = PrimerTheme( > lightColorTokens = object : LightColorTokens() { > override val primerColorBrand: Color = Color(0xFF007BFF) > }, > radiusTokens = RadiusTokens( > medium = 12.dp, > ), > ), > ) > ``` > > Token categories: `LightColorTokens`/`DarkColorTokens`, `RadiusTokens`, `SpacingTokens`, `TypographyTokens`, `WidthTokens`, and `SizeTokens`. > > ### Layout customization > > In Drop-In, customization was limited to settings. In CheckoutComponents, every screen is a composable slot you can override: > > ```kotlin theme={"dark"} > PrimerCheckoutSheet( > checkout = checkout, > splash = { MyCustomSplash() }, > loading = { MyCustomLoading() }, > success = { data -> MyCustomSuccess(data) }, > error = { primerError, _ -> MyCustomError(primerError) }, > ) > ``` > > ### Payment method configuration > > Payment method behavior is configured server-side through the [client session API](/docs/checkout/client-session). No client-side payment method option migration is needed. > > See [SDK Options](/docs/checkout/primer-checkout/configuration/sdk-options), [Styling customization](/docs/checkout/primer-checkout/build-your-ui/styling-customization), and [Layout customization](/docs/checkout/primer-checkout/build-your-ui/layout-customization) for details. > [tab] iOS > > ### Settings > > `PrimerSettings` is now passed directly to `PrimerCheckout` or `PrimerCheckoutPresenter.presentCheckout()` instead of `Primer.shared.configure()`. > > | Legacy | New | Notes | > | - | - | - | > | `Primer.shared.configure(settings:)` | `PrimerSettings` param on view/presenter/session | Same type, different delivery | > | `PrimerTheme` (UIKit color/font overrides) | `PrimerCheckoutTheme` (design tokens) | New token-based system | > | `PrimerUIOptions` screen flags | `PrimerUIOptions` in `PrimerSettings` | Scope varies by option, see below. For layout, use `@ViewBuilder` slots | > > `isSuccessScreenEnabled`, `isErrorScreenEnabled` and `appearanceMode` apply to `PrimerCheckout`, `PrimerCheckoutPresenter` and the composable views. `isInitScreenEnabled` applies only to `PrimerCheckout` and `PrimerCheckoutPresenter`, because the composable views never show an init screen. `dismissalMechanism` shows the close button on most SDK screens when it contains `.closeButton`. The BLIK, MB Way and country picker screens always show one. Only the `PrimerCheckoutPresenter` sheet enforces swipe-to-dismiss (`.gestures`). > > ### Theming > > The legacy `PrimerTheme` (colors and fonts) is replaced by `PrimerCheckoutTheme`, which uses a design token system with optional override structs. Every override is optional — set only the tokens you want to change and the SDK fills in the rest: > > ```swift theme={"dark"} > PrimerCheckoutTheme( > colors: ColorOverrides( > primerColorBrand: Color(red: 0.91, green: 0.51, blue: 0.47), > primerColorTextPrimary: Color(white: 0.1) > ), > radius: RadiusOverrides( > primerRadiusMedium: 12 > ), > typography: TypographyOverrides( > bodyMedium: TypographyOverrides.TypographyStyle( > font: "Inter", > weight: .semibold, > size: 16, > lineHeight: 20 > ) > ) > ) > ``` > > Token categories: colors, radius, spacing, sizes, typography, and border widths. `colors` themes light mode only. To theme dark mode, also pass `darkColors`. Any color you leave out of `darkColors` uses Primer's dark default, not your `colors` value. > > ### Layout customization > > In Drop-In, customization was limited to theme properties. The managed `PrimerCheckout` view renders Primer's default screens. For full control, compose the views under `PrimerCheckoutSession` and customize them through their `@ViewBuilder` slots — for example the `PrimerCardForm` slots (`cardDetails`, `billingAddress`, `submitButton`), each of which receives a `PrimerCardFormSession`: > > ```swift theme={"dark"} > ScrollView { > PrimerCardForm( > submitButton: { cardForm in > Button("Pay now") { cardForm.submit() } > .disabled(!cardForm.state.isValid || cardForm.state.isLoading) > } > ) > PrimerPaymentMethods() > } > .primerCheckoutSession(session) { state in > // Receives .failure per failed attempt, then .success or .dismissed once. > } > ``` > > Use `CardFormDefaults` (and `PaymentMethodsDefaults`) building blocks inside slots when you want Primer's prebuilt field views with a custom arrangement. Which fields appear is Dashboard-driven via `CardFormConfiguration`; visual styling is theme-driven through `PrimerCheckoutTheme` design tokens. > > ### Payment method configuration > > Payment method behavior (Apple Pay, Klarna, etc.) is configured server-side through the [client session API](/docs/checkout/client-session). No client-side payment method option migration is needed. > > See [SDK Options](/docs/checkout/primer-checkout/configuration/sdk-options), [Styling customization](/docs/checkout/primer-checkout/build-your-ui/styling-customization), and [Layout customization](/docs/checkout/primer-checkout/build-your-ui/layout-customization) for details. *** ## Web-specific details > [!NOTE] > > The following sections apply to **Web only**. iOS and Android handle these concerns through the composable views and slots described above. ### Payment method options #### Card form The card form options have been simplified. The legacy `requireCvv` and `requireCardholderName` top-level options no longer exist. Use the `cardholderName` sub-object instead. **Legacy:** ```javascript theme={"dark"} card: { requireCvv: true, requireCardholderName: true, } ``` **New:** ```javascript theme={"dark"} card: { cardholderName: { required: true, visible: true, defaultValue: 'John Doe', // Optional: pre-fill the field } } ``` CVV is always required by the card form — there is no option to disable it. For runtime updates to the cardholder name after initialization, use `primer.setCardholderName('name')` instead of updating the options. #### Apple Pay The Apple Pay options have been restructured. The legacy `merchantId` and `merchantName` are handled server-side, not in client options. **Legacy:** ```javascript theme={"dark"} applePay: { merchantId: 'merchant.com.example', merchantName: 'Example Store', captureBillingAddress: true, } ``` **New:** ```javascript theme={"dark"} applePay: { buttonOptions: { type: 'buy', buttonStyle: 'black', }, billingOptions: { requiredBillingContactFields: ['postalAddress'], }, shippingOptions: { requiredShippingContactFields: ['postalAddress', 'name', 'phone', 'email'], requireShippingMethod: true, }, } ``` Key changes: * `merchantId` and `merchantName` — removed from client options (configured server-side). * `captureBillingAddress` — deprecated. Use `billingOptions.requiredBillingContactFields` instead. The only supported billing field is `'postalAddress'`. * **Shipping fields** — use `'phone'` (not `'phoneNumber'`) and `'email'` (not `'emailAddress'`). * **Button styling** — new `buttonOptions` object with `type` and `buttonStyle`. > See the [Apple Pay reference](/docs/sdk/primer-checkout-web/apple-pay) for all button types and complete configuration. #### Google Pay Google Pay options are largely the same with some additions. **Legacy:** ```javascript theme={"dark"} googlePay: { merchantId: 'merchant-id-from-google', merchantName: 'Example Store', buttonType: 'buy', buttonColor: 'black', } ``` **New:** ```javascript theme={"dark"} googlePay: { buttonType: 'buy', buttonColor: 'black', buttonSizeMode: 'fill', buttonRadius: 4, buttonLocale: 'en', captureBillingAddress: true, captureShippingAddress: true, emailRequired: true, requireShippingMethod: true, shippingAddressParameters: { allowedCountryCodes: ['US', 'CA'], phoneNumberRequired: true, }, } ``` Key changes: * `merchantId` and `merchantName` — removed from client options (configured server-side). * New button options: `buttonSizeMode`, `buttonRadius`, `buttonLocale`. * New address capture: `captureBillingAddress`, `captureShippingAddress`, `emailRequired`. * New shipping: `requireShippingMethod`, `shippingAddressParameters`. > See the [Google Pay reference](/docs/sdk/primer-checkout-web/google-pay) for complete configuration. #### Klarna The Klarna configuration has changed significantly from the legacy SDK. There is no `klarna.locale` option — the Klarna locale is derived from the top-level `locale` option. **Legacy:** ```javascript theme={"dark"} klarna: { locale: 'en-GB', } ``` **New:** ```javascript theme={"dark"} klarna: { paymentFlow: 'DEFAULT', // 'DEFAULT' or 'PREFER_VAULT' allowedPaymentCategories: ['pay_now', 'pay_later', 'pay_over_time'], recurringPaymentDescription: '...', // Required for recurring payments buttonOptions: { text: 'Pay with Klarna', }, } ``` Set the locale at the top level instead: ```javascript theme={"dark"} checkout.options = { locale: 'en-GB', klarna: { paymentFlow: 'DEFAULT', }, }; ``` > See the [SDK Options Reference](/docs/sdk/primer-checkout-web/sdk-options-reference#klarna-options) for all Klarna options. #### PayPal PayPal options have been restructured with a `style` sub-object. **Legacy:** ```javascript theme={"dark"} paypal: { buttonColor: 'blue', buttonShape: 'rect', buttonHeight: 45, buttonLabel: 'pay', buttonTagline: false, paymentFlow: 'PREFER_VAULT', } ``` **New:** ```javascript theme={"dark"} paypal: { style: { color: 'gold', // Default is 'gold', not 'blue' shape: 'rect', height: 45, label: 'pay', tagline: false, layout: 'vertical', borderRadius: 4, }, vault: true, // Replaces paymentFlow: 'PREFER_VAULT' } ``` Key changes: * Button properties moved into `style` sub-object and shortened (`buttonColor` → `style.color`). * Default color is `'gold'`, not `'blue'`. * `buttonSize` removed — use `style.height` with a pixel value. * `paymentFlow: 'PREFER_VAULT'` → `vault: true`. > See the [PayPal reference](/docs/sdk/primer-checkout-web/paypal) for all options. ### Vault changes #### Configuration **Legacy:** ```javascript theme={"dark"} vault: { visible: true, deletionDisabled: false, } ``` **New:** ```javascript theme={"dark"} vault: { enabled: true, // Required — must be true to use vault headless: false, // New: hide default UI for custom implementations showEmptyState: true, // New: show message when no saved methods } ``` Key changes: * `visible` → `enabled` (renamed, required). * `deletionDisabled` — no longer a client-side option. Deletion capability is managed through the vault UI or programmatically via `primer.vault.delete()`. * **New:** `headless` mode for building fully custom vault UIs. * **New:** `showEmptyState` to show a message when the user has no saved methods. #### Vault API methods The new SDK provides programmatic vault management: ```javascript theme={"dark"} checkout.addEventListener('primer:ready', async (event) => { const primer = event.detail; // Create CVV input for re-capture const cvvInput = await primer.vault.createCvvInput({ cardNetwork: 'VISA', // Card network, not paymentMethodId container: '#cvv-container', placeholder: 'CVV', }); // Start payment with a saved method await primer.vault.startPayment(paymentMethodId); // Or with CVV for cards requiring re-capture await primer.vault.startPayment(paymentMethodId, { cvv: '123' }); // Delete a saved method await primer.vault.delete(paymentMethodId); }); ``` > [!WARNING] > > `vault.createCvvInput()` takes a `cardNetwork` string (e.g., `'VISA'`, `'MASTERCARD'`), not a `paymentMethodId`. It returns a `Promise` — always use `await`. #### Vault events | Event | Payload | Description | | - | - | - | | `primer:vault-methods-update` | `{ vaultedPayments, cvvRecapture, timestamp }` | Vaulted methods loaded or changed | | `primer:vault-selection-change` | `{ paymentMethodId, timestamp }` | User selected or deselected a saved method | | `primer:vault-submit` | `{ source? }` | Dispatch this to trigger vault payment submission | The `vaultedPayments` payload is an array of `VaultedPaymentMethodSummary` objects. ```javascript theme={"dark"} checkout.addEventListener('primer:vault-methods-update', (event) => { const { vaultedPayments, cvvRecapture, timestamp } = event.detail; // vaultedPayments is already an array console.log(`${vaultedPayments.length} saved methods`); vaultedPayments.forEach(method => { console.log(method.paymentInstrumentData?.last4Digits); }); if (cvvRecapture) { // CVV re-entry is required for vaulted card payments } }); ``` #### Headless vault mode Build a completely custom vault UI while retaining full vault functionality: ```javascript theme={"dark"} checkout.options = { vault: { enabled: true, headless: true, }, }; checkout.addEventListener('primer:vault-methods-update', async (event) => { const { vaultedPayments, cvvRecapture } = event.detail; // Render your custom vault UI vaultedPayments.forEach(method => { if (method.paymentInstrumentType === 'PAYMENT_CARD') { const { network, last4Digits } = method.paymentInstrumentData; // Render: Visa •••• 4242 } }); // Create CVV input if re-capture is required if (cvvRecapture) { const primer = /* get from primer:ready */; const cvvInput = await primer.vault.createCvvInput({ cardNetwork: vaultedPayments[0].paymentInstrumentData.network, container: '#cvv-container', }); } }); ``` > See the [Vault Manager component reference](/docs/sdk/primer-checkout-web/components/primer-vault-manager) for the complete headless vault implementation guide. ### Custom submit button The mechanism for triggering payment submission from an external button has changed from an imperative method call to a dispatched event. #### Card form submission **Legacy:** ```javascript theme={"dark"} document.getElementById('my-button').addEventListener('click', () => { checkout.submit(); }); ``` **New:** ```javascript theme={"dark"} document.getElementById('my-button').addEventListener('click', () => { document.dispatchEvent(new CustomEvent('primer:card-submit', { bubbles: true, composed: true, })); }); ``` #### Vault payment submission For vault payments, dispatch `primer:vault-submit` instead: ```javascript theme={"dark"} document.getElementById('vault-pay-button').addEventListener('click', () => { document.dispatchEvent(new CustomEvent('primer:vault-submit', { bubbles: true, composed: true, })); }); ``` > [!NOTE] > > An alternative approach for card form submission: you can call `cardForm.submit()` directly on the `` element if you have a reference to it. > > ```javascript theme={"dark"} > const cardForm = document.querySelector('primer-card-form'); > await cardForm.submit(); > ``` #### Button state management Monitor the `primer:state-change` event to enable/disable your custom button: ```javascript theme={"dark"} checkout.addEventListener('primer:state-change', (event) => { const { isProcessing, isLoading } = event.detail; document.getElementById('my-button').disabled = isProcessing || isLoading; }); ``` For card form validation state, listen to `primer:card-success` and `primer:card-error`: ```javascript theme={"dark"} checkout.addEventListener('primer:card-success', () => { // Card form is valid — enable submit }); checkout.addEventListener('primer:card-error', (event) => { // Card form has validation errors console.log('Errors:', event.detail.errors); }); ``` > See the [External Submit Button recipe](/docs/checkout/primer-checkout/guides-and-recipes/external-submit-button) for a complete example. ### Events The new SDK uses a comprehensive DOM event system as the primary API for payment lifecycle handling. #### Complete event reference ##### Lifecycle events | Event | Payload | Description | | - | - | - | | `primer:ready` | `PrimerJS` instance | SDK initialized and ready | | `primer:state-change` | `{ isProcessing, isLoading, isSuccessful, primerJsError, paymentFailure }` | State changes during payment lifecycle | | `primer:methods-update` | `InitializedPaymentMethod[]` | Available payment methods loaded or changed | ##### Payment events | Event | Payload | Description | | - | - | - | | `primer:payment-start` | `{ paymentMethodType, abortPaymentCreation, continuePaymentCreation, timestamp }` | Payment creation begins — use `preventDefault()` to intercept | | `primer:payment-success` | `{ payment, paymentMethodType, timestamp }` | Payment completed successfully | | `primer:payment-failure` | `{ error, payment?, paymentMethodType, timestamp }` | Payment failed | ##### Card form events | Event | Payload | Description | | - | - | - | | `primer:card-network-change` | `CardNetworksContextType` | Card network detected from user input | | `primer:card-success` | `{ result }` | Card form validation succeeded | | `primer:card-error` | `{ errors }` | Card form has validation errors | ##### Vault events | Event | Payload | Description | | - | - | - | | `primer:vault-methods-update` | `{ vaultedPayments, cvvRecapture, timestamp }` | Vaulted methods loaded or changed | | `primer:vault-selection-change` | `{ paymentMethodId, timestamp }` | User selected a saved method | | `primer:show-other-payments-toggle` | `{ action?, source? }` | Dispatch to toggle the "other payments" section | | `primer:show-other-payments-toggled` | `{ expanded }` | "Other payments" toggle state changed | ##### Triggerable events You can dispatch these to control the SDK. Both require `bubbles: true` and `composed: true`. | Event | Purpose | | - | - | | `primer:card-submit` | Trigger card form submission | | `primer:vault-submit` | Trigger vault payment submission | | `primer:show-other-payments-toggle` | Toggle the "other payment methods" section | > See the [Events Reference](/docs/sdk/primer-checkout-web/events-reference) for full payload types and usage examples. *** ## Migration checklist > [tab] Web > > Verify your migration is complete: > > * **Replaced package** — Uninstalled `@primer-io/checkout-web`, installed `@primer-io/primer-js` > * **Updated imports** — Using `loadPrimer` and new type names > * **Updated initialization** — Using `` element with `setAttribute('client-token', ...)` and `.options = {}` > * **Updated to events** — Using `primer:payment-success`, `primer:payment-failure` events > * **Updated pre-payment validation** — Using `primer:payment-start` with `preventDefault()` > * **Updated styling** — Replaced CSS-in-JS objects with `--primer-*` CSS custom properties > * **Updated payment method config** — Corrected Apple Pay, PayPal, Klarna options > * **Updated vault config** — Using `vault.enabled` and vault events > * **Updated custom submit** — Dispatching `primer:card-submit` / `primer:vault-submit` events > * **Tested in your framework** — See [Framework Migration Guide](/docs/checkout/primer-checkout/migration/frameworks) > [tab] Android > > Verify your migration is complete: > > * **Added Jetpack Compose** — `buildFeatures { compose = true }` in build config (if not already present) > * **Replaced entry point** — Using `rememberPrimerCheckoutController()` + `PrimerCheckoutSheet()` instead of `Primer.instance.showUniversalCheckout()` > * **Replaced listener** — Observing `PrimerCheckoutState.Success` / `.Failure` on `checkout.state` instead of `PrimerCheckoutListener` > * **Updated theming** — Using `PrimerTheme` data class instead of `PrimerSettings.uiOptions` (if customizing) > * **Tested state observation** — Collecting `StateFlow` with `collectAsStateWithLifecycle()` > * **No server-side changes** — Backend integration remains the same > * **No dependency changes** — Same SDK BOM > [tab] iOS > > Verify your migration is complete: > > * **Updated minimum deployment target** — iOS 15.0 > > * **UIKit**: Replaced `Primer.shared.showUniversalCheckout()` with `PrimerCheckoutPresenter.presentCheckout()` > > * **UIKit**: Replaced `PrimerDelegate` with `PrimerCheckoutPresenterDelegate` > > * **SwiftUI**: Using `PrimerCheckout` view with `onCompletion` callback > > * **Updated result handling** — Using `PaymentResult` instead of `PrimerCheckoutData` for success > > * **Payment handling** — `PrimerSettings` uses the default `.auto`. `.manual` is not supported and fails the checkout at start > > * **Updated theming** — Using `PrimerCheckoutTheme` instead of `PrimerTheme` (if customizing) > > * **Tested 3DS flows** — A failed 3DS challenge arrives as a normal failure (`primerCheckoutPresenterDidFailWithError(_:checkoutData:)` or `onCompletion: .failure`) > > * **No server-side changes** — Backend integration remains the same > > * **Updated the dependency** — `PrimerSDK` pinned to `3.0.0-beta.8` > > > [accordion] Known behavior changes from v2.x > > > > These changes may affect existing integrations that also use v2.x Drop-In or Headless: > > > > * **`PrimerLocaleData` region code**: When providing only `languageCode` (e.g., `PrimerLocaleData(languageCode: "de")`), the `regionCode` now defaults to `nil` instead of the device region. This produces locale code `"de"` instead of `"de-US"`. To preserve v2.x behavior, explicitly pass `regionCode`. > > * **Mastercard number formatting**: Card number display changed from groups of 4-6-6 (`5555 550000 4444`) to standard 4-4-4-4 (`5555 5500 0044 44`), matching industry standard and other platforms. > > * **`PrimerPaymentMethodType` is now public**: All payment method type cases are part of the public API. Merchants can use these for conditional logic (e.g., `if type == .paymentCard`). *** ## Next steps > [tab] Web > > > [card] [Framework Migration](/docs/checkout/primer-checkout/migration/frameworks) > > > > React, Vue, Svelte, and Angular patterns > > > [card] [SDK Options Reference](/docs/sdk/primer-checkout-web/sdk-options-reference) > > > > Complete configuration reference > > > [card] [Events Reference](/docs/sdk/primer-checkout-web/events-reference) > > > > Full event payloads and types > > > [card] [Styling Variables](/docs/sdk/primer-checkout-web/styling-variables) > > > > Complete design token reference > [tab] Android > > > [card] [PrimerCheckoutSheet](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-sheet) > > > > Modal checkout composable > > > [card] [PrimerCheckoutController](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-controller) > > > > Session controller API > > > [card] [PrimerCheckoutState](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state) > > > > Checkout state and payment outcomes > > > [card] [Theming](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/primer-theme) > > > > Design token system > [tab] iOS > > > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > > > SwiftUI view API reference > > > [card] [UIKit Integration](/docs/sdk/ios-checkout/v3.0.0-beta/guides/uikit-integration) > > > > PrimerCheckoutPresenter guide > > > [card] [PrimerCheckoutState](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) > > > > Checkout state lifecycle > > > [card] [API Overview](/docs/sdk/ios-checkout/v3.0.0-beta/api/overview) > > > > Composable views and sessions # Primer Checkout overview Source: https://primer.io/docs/checkout/primer-checkout/product-overview What Primer Checkout supports out of the box, and platform availability across Web, iOS and Android. Primer Checkout is a drop-in payment UI that handles the complexity of accepting payments while giving you full control over the experience. Add it to your app in minutes, customize it to match your brand, and scale to new payment methods without rewriting your integration. ![Primer Documentation showcase of primer checkout components visual](https://goat-assets.production.core.primer.io/marketing/checkout/external-docs/primer-checkout/primer-checkout-card.png) ## What you can do * Accept any payment methods through a single integration * Use a prebuilt, conversion-optimized UI or customize every component * Handle security and compliance without extra work * Add or remove payment methods without changing your frontend code ## Key capabilities | Capability | What It Means | | - | - | | **Single integration** | Add any payment method without writing payment-specific code | | **Prebuilt UI** | Conversion-optimized components that work out of the box | | **Full customization** | Control styling, layout, and behavior through configuration | | **Security built-in** | PCI compliance handled for you with secure hosted inputs | | **Multi-platform** | Web (any framework), Android (Jetpack Compose), iOS (SwiftUI) | ## Design principles ### Works out of the box Drop in a checkout component and you have a working payment form. No configuration required for the default experience. Primer handles validation, error display, 3DS challenges, redirects, and loading states automatically. ### Customizable without complexity Change the look and feel through styling tokens. Rearrange components with layout customization. Add event handlers when you need custom behavior. Each layer of customization is optional — use only what you need. ### Stable integration Your integration interacts with a stable public API. Internal changes stay internal — your code won't break when you update the SDK. ### Payment logic stays with Primer You focus on the user experience. Primer handles the payment method logic, processor communication, and edge cases. Add new payment methods from the Dashboard without touching your frontend code. ### Platform availability Primer Checkout is available on Web, iOS, and Android. * The Web SDK is production-ready. * iOS and Android are currently in beta (v3.0.0-beta) — reach out to your Primer contact before integrating. * React Native is supported via the existing SDK. Support for the new Primer Checkout experience is planned for later in 2026. ## How it works 1. Install the Primer Checkout SDK for your platform 2. Configure your checkout and payment methods 3. Embed the checkout in your application and start accepting payments [Primer Checkout Overview](https://www.youtube.com/embed/fafXux4KPxo) ## Explore StackBlitz examples The examples below are for the Web SDK. iOS and Android examples are available in the platform-specific docs. Try Primer Checkout directly in your browser with these interactive, editable examples:
Example Description
**Basic checkout** Get started with a minimal checkout implementation using default styling [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/primer-io/examples/tree/main/examples/primer-checkout-basic)
**Custom form layout** Build a custom payment form layout with reordered components and custom styling [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/primer-io/examples/tree/main/examples/primer-checkout-custom-form)
**Custom sectioned layout** Organize payment methods into sections (Card, Quick Checkout, Alternative Methods) [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/primer-io/examples/tree/main/examples/primer-checkout-custom-layout)
**Themed checkout** Explore different visual themes using CSS variables [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/primer-io/examples/tree/main/examples/primer-checkout-themes)
**Vaulted payment methods** Save and reuse payment methods with Primer's vaulting functionality [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/primer-io/examples/tree/main/examples/primer-checkout-vaulted)
## Prerequisites Before you start, ensure you have completed these prerequisites: 1. You're [ready to process payments](/docs/get-started/overview) 2. [Checkout is configured](/docs/checkout/checkout-builder) in your Primer Dashboard ## See also > [card] [Installation](/docs/checkout/primer-checkout/installation) > > Add Primer Checkout to your project > [card] [First Payment](/docs/checkout/primer-checkout/first-payment) > > Accept your first payment > [card] [Core Concepts](/docs/checkout/primer-checkout/core-concepts) > > Understand how components work together > [card] [Customization](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Match the checkout to your brand # Use AI coding assistants with Primer Checkout Source: https://primer.io/docs/checkout/primer-checkout/resources/build-with-ai Install Primer's Claude Code skills or the Context7 MCP server so your assistant works from accurate documentation. ## Introduction This guide explains how to effectively use our documentation with Large Language Models (LLMs) and AI coding assistants like Claude Code, ChatGPT, GitHub Copilot, and Cursor. We provide two complementary approaches for accessing our documentation with AI: 1. **Claude Code Skills** - Offline, comprehensive reference for IDE-integrated AI assistants 2. **Context7** - Live, always-up-to-date documentation for web-based and MCP-enabled AI tools Both approaches have their strengths, and you can use them together for the best experience. ## Option 1: Claude Code Skill (Recommended for IDEs) For developers using AI coding assistants in their IDE, we provide comprehensive Claude Code skills that package our complete documentation, integration patterns, and best practices into easily installable formats. ### What is a Claude Code Skill? A Claude Code skill is a packaged knowledge base that your AI coding assistant can reference while you work. It provides instant access to documentation, code patterns, and troubleshooting guidance without requiring internet access. ### Available Skills We offer platform-specific skills so your AI assistant has the most relevant context for your development environment: > [tab] Web > > **Skill name:** `primer-web-components` > > * **Complete Component Reference** - All web component APIs, props, events, and methods > * **React Integration Patterns** - React 18 & 19 specific guidance with hooks and patterns > * **Critical Best Practices** - Common mistakes and how to avoid them (like object reference stability) > * **SSR Support** - Server-side rendering with Next.js and SvelteKit > * **CSS Theming Guide** - Custom styling and theme customization > * **Troubleshooting** - Solutions to common integration issues > [tab] Android > > **Skill name:** `primer-android-checkout` > > * **Complete Composable Reference** - All composable APIs, controllers, state types, and slot parameters > * **Compose Integration Patterns** - PrimerCheckoutSheet and PrimerCheckoutHost patterns > * **Controller Pattern** - remember\*Controller functions, StateFlow observation, and action methods > * **Material 3 Theming** - PrimerTheme with automatic Material 3 color integration > * **Critical Best Practices** - Recomposition handling, state collection, and lifecycle awareness > * **Troubleshooting** - Solutions to common CheckoutComponents issues > [tab] iOS > > **Skill name:** `primer-ios-checkout` > > * **Complete View & Session Reference** - All composable views, sessions, state types, and slot parameters > * **SwiftUI Integration Patterns** - PrimerCheckout and PrimerCheckoutSession with NavigationStack, sheets, full-screen covers, and dismissal handling > * **UIKit Support** - PrimerCheckoutPresenter and PrimerCheckoutPresenterDelegate for UIKit-based applications > * **Design Token Theming** - PrimerCheckoutTheme with color, typography, spacing, and radius overrides > * **Critical Best Practices** - Session observation, stable references, @ViewBuilder slot handling > * **Troubleshooting** - Solutions to common CheckoutComponents issues ### Installation Instructions Installation differs by platform. Choose your platform and AI assistant: > [tab] Web > > #### For Claude Code (claude.ai/code) > > **Via Marketplace (Recommended):** > > ```bash theme={"dark"} > # Add Primer marketplace > /plugin marketplace add primer-io/examples > > # Install the skill > /plugin install primer-web-components@primer-skills > ``` > > Restart Claude Code, and the skill activates automatically when working with Primer components. > > **Manual Installation:** > > ```bash theme={"dark"} > cd ~/.claude/skills > git clone --depth 1 https://github.com/primer-io/examples.git temp > mv temp/claude-code-skills/primer-web-components ./ > rm -rf temp > ``` > > Or download from [GitHub](https://github.com/primer-io/examples/tree/main/claude-code-skills/primer-web-components) and copy to `~/.claude/skills/primer-web-components/` > > #### For Cursor > > Use the same manual installation method as above, but copy to `~/.cursor/skills/` instead. > [tab] Android > > #### For Claude Code (claude.ai/code) > > **Via Marketplace (Recommended):** > > ```bash theme={"dark"} > # Add Primer marketplace > /plugin marketplace add primer-io/examples > > # Install the skill > /plugin install primer-android-checkout@primer-skills > ``` > > Restart Claude Code, and the skill activates automatically when working with Primer Checkout for Android. > > **Manual Installation:** > > ```bash theme={"dark"} > cd ~/.claude/skills > git clone --depth 1 https://github.com/primer-io/examples.git temp > mv temp/claude-code-skills/primer-android-checkout ./ > rm -rf temp > ``` > > Or download from [GitHub](https://github.com/primer-io/examples/tree/main/claude-code-skills/primer-android-checkout) and copy to `~/.claude/skills/primer-android-checkout/` > > #### For Cursor > > Use the same manual installation method as above, but copy to `~/.cursor/skills/` instead. > [tab] iOS > > #### For Claude Code (claude.ai/code) > > **Via Marketplace (Recommended):** > > ```bash theme={"dark"} > # Add Primer marketplace > /plugin marketplace add primer-io/examples > > # Install the skill > /plugin install primer-ios-checkout@primer-skills > ``` > > Restart Claude Code, and the skill activates automatically when working with Primer Checkout for iOS. > > **Manual Installation:** > > ```bash theme={"dark"} > cd ~/.claude/skills > git clone --depth 1 https://github.com/primer-io/examples.git temp > mv temp/claude-code-skills/primer-ios-checkout ./ > rm -rf temp > ``` > > Or download from [GitHub](https://github.com/primer-io/examples/tree/main/claude-code-skills/primer-ios-checkout) and copy to `~/.claude/skills/primer-ios-checkout/` > > #### For Cursor > > Use the same manual installation method as above, but copy to `~/.cursor/skills/` instead. #### For Other AI Assistants Most AI coding assistants support directory-based skills. Check your tool's documentation for the skills directory location and use the manual installation method above. ### Verifying Installation Ask your AI assistant: > [tab] Web > > ``` > Do you have access to the Primer web components skill? > ``` > [tab] Android > > ``` > Do you have access to the Primer Android checkout skill? > ``` > [tab] iOS > > ``` > Do you have access to the Primer iOS checkout skill? > ``` The assistant should confirm it has loaded the skill documentation. ### When to Use the Claude Code Skill * Working in your IDE with integrated AI assistance * Need offline access to documentation * Want best practices and common pitfalls highlighted automatically * Focused on implementation and debugging * **Web**: Working with React, Next.js, or SvelteKit integrations * **iOS**: Working with SwiftUI or UIKit and the @ViewBuilder slot API * **Android**: Working with Jetpack Compose and the controller pattern ## Option 2: Using Context7 for Live Documentation We've partnered with Context7 to provide LLM-friendly versions of our documentation that are always up-to-date and optimized for AI consumption. ### What is Context7? Context7 is a service that pulls up-to-date, version-specific documentation and code examples directly from the source, making it easier for LLMs to provide accurate assistance with our SDK. ### Benefits of Using Context7 for Our Documentation * **Always up-to-date**: Documentation stays in sync with the latest version of our components * **No hallucinations**: LLMs receive accurate API information, reducing incorrect code suggestions * **Context-aware**: The LLM understands the full context of our component library * **Improved code examples**: Get working code snippets that follow our best practices * **Reduced token usage**: Optimized documentation that focuses on what matters ### When to Use Context7 * Using web-based LLMs (ChatGPT, Claude.ai web interface) * Need to verify against the absolute latest documentation * Researching new features or recent API changes * Working with tools that support MCP (Model Context Protocol) * Want dynamic documentation fetching during conversations ### How to Access Context7 Documentation You can access our Context7 documentation in several ways: #### Method 1: Reference the Raw Link in Your Prompt You can directly ask an LLM to retrieve and analyze our documentation by providing the Context7 link: ``` Please analyze the Primer Checkout documentation at https://context7.com/primer-io/examples/llms.txt ``` #### Method 2: Copy the Documentation Text Browse our LLM-friendly documentation versions at: [https://context7.com/primer-io/examples](https://context7.com/primer-io/examples) Then copy the relevant sections and paste them into your conversation with the LLM. #### Method 3: Use the Context7 MCP Server For an even better experience, you can use the Context7 MCP server with compatible AI tools. This allows the AI to automatically pull the latest documentation without you needing to copy/paste anything. ##### Compatible Applications * Cursor * Windsurf * VS Code (with MCP Support extension) * Zed * Claude Desktop * Claude (claude.ai/code) * BoltAI ## Combining Both Approaches For the best experience, use both the Claude Code skill and Context7 together: * **Claude Code skill** provides immediate access to patterns and best practices while coding * **Context7** ensures you're working with the latest API documentation when needed The skill documentation is comprehensive but static (updated with new versions), while Context7 is always current but requires an active connection. Together, they provide both convenience and accuracy. ## Example Prompts Here are some effective prompt examples for using our documentation with LLMs: ### With Claude Code Skill (in your IDE) > [tab] Web > > ``` > Using the Primer web components skill, create a React component that implements > the checkout flow with PayPal as the primary payment method and CardForm as a fallback. > ``` > > ``` > Show me how to properly handle onPaymentSuccess and onPaymentFailure events in React > while avoiding the stable object reference issue mentioned in the skill documentation. > ``` > > ``` > I'm getting a "Cannot read property of undefined" error with primer-checkout. > Help me debug this using the troubleshooting section of the Primer skill. > ``` > [tab] Android > > ``` > Using the Primer Android checkout skill, create a Compose screen with > PrimerCheckoutSheet that handles Success and Failure events and navigates > to a confirmation screen. > ``` > > ``` > Show me how to build a custom card form layout using CardFormDefaults > field composables, rearranging the field order and adding a custom submit button. > ``` > > ``` > My checkout stays in Loading state and never shows payment methods. > Help me debug this using the troubleshooting section of the Primer Android skill. > ``` > [tab] iOS > > ``` > Using the Primer iOS checkout skill, create a SwiftUI view that presents PrimerCheckout > in a sheet and handles payment completion via its onCompletion closure by navigating > to a confirmation view. > ``` > > ``` > Show me how to build a custom card form layout using PrimerCardForm with CardFormDefaults > field building blocks, rearranging the field order and replacing the submit button with > a custom view that observes the session state. > ``` > > ``` > My checkout stays in the initializing state and never shows payment methods. > Help me debug this using the troubleshooting section of the Primer iOS skill. > ``` ### Using Context7 Raw Link ``` Please visit https://context7.com/primer-io/examples/llms.txt and use the documentation to implement a checkout flow with Primer's components that includes PayPal as the first payment method and CardForm as the second. ``` ### Using Context7 MCP Server ``` use context7 Create a basic implementation of Primer's Checkout components using TypeScript. Customize the payment method order to place PayPal on top, CardForm second, and then let the other methods follow. ``` ### General Documentation Request ``` Based on Primer's documentation, show me how to implement error handling in the checkout flow. Use context7 to get the most up-to-date information. ``` ### Combining Both > [tab] Web > > ``` > Using the Primer skill for patterns and Context7 for the latest API, > implement a Next.js 14 App Router page with server-side rendering support > for Primer Checkout. > ``` > [tab] Android > > ``` > Using the Primer Android skill for patterns and Context7 for the latest API, > implement a checkout screen with PrimerCheckoutHost, custom card form, > and Google Pay using Jetpack Compose. > ``` > [tab] iOS > > ``` > Using the Primer iOS skill for patterns and Context7 for the latest API, > implement a checkout flow with custom theming, Apple Pay integration, > and proper error handling in SwiftUI. > ``` ## Installing the Context7 MCP Server The Context7 MCP server can be integrated with various development environments to provide seamless documentation access. ### Installation Instructions The Context7 MCP server is available on GitHub at: [https://github.com/upstash/context7](https://github.com/upstash/context7) Each client requires slightly different configuration: #### For Cursor Add this to your `~/.cursor/mcp.json` file: ```json theme={"dark"} { "mcpServers": { "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp@latest"] } } } ``` #### For Claude Desktop Add this to your `claude_desktop_config.json` file: ```json theme={"dark"} { "mcpServers": { "Context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp@latest"] } } } ``` #### For Claude.ai/Code Run this command: ```bash theme={"dark"} claude mcp add context7 -- npx -y @upstash/context7-mcp@latest ``` For installation instructions with other tools and troubleshooting guidance, please refer to the [Context7 GitHub repository](https://github.com/upstash/context7). ## Best Practices for Using LLMs with Our Documentation 1. **Be specific**: Clearly state which components you want to use and what functionality you need 2. **Provide context**: Mention your framework (React, SwiftUI, Jetpack Compose, etc.) and any specific requirements 3. **Ask for step-by-step explanations**: Request that the LLM explain how the code works 4. **Validate the output**: Always verify generated code against our official documentation 5. **Iterate**: If the initial response isn't quite right, refine your prompt with more details By following this guide, you can efficiently leverage LLMs to build with our component library while ensuring accuracy and best practices. # Troubleshooting — Android Source: https://primer.io/docs/checkout/primer-checkout/troubleshooting-android Fix Compose compiler version conflicts, checkout stuck in Loading, re-initialization on recomposition without `rememberPrimerCheckoutController`, and 3DS broken by configuration changes. ## Quick diagnosis | Symptom | Likely Cause | Solution | | - | - | - | | Compose version conflict | Compiler version mismatch | Align `kotlinCompilerExtensionVersion` | | Checkout stays in Loading | Invalid/expired client token | Check Logcat for errors, regenerate token | | Payment methods empty | Dashboard misconfiguration | Verify Dashboard settings and client session fields | | Recomposition causes re-init | Controller created outside `remember` | Use `rememberPrimerCheckoutController()` | | State not updating in UI | Not using lifecycle-aware collect | Use `collectAsStateWithLifecycle()` | ## Installation issues ### Compose version conflict **Cause:** Build fails with Compose compiler version mismatch. **Solution:** Ensure your Compose compiler version is compatible: ```kotlin theme={"dark"} android { composeOptions { kotlinCompilerExtensionVersion = "1.5.8" } } ``` ## Runtime issues ### Checkout stays in Loading state **Cause:** `PrimerCheckoutState.Loading` never transitions to `Ready`. **Possible causes:** * Invalid or expired client token * Network connectivity issues * Incorrect API key in client session creation **Solution:** Check Logcat for error messages from the SDK. Ensure your client token is fresh and generated correctly. ### Payment methods not showing **Cause:** `PrimerPaymentMethods` shows an empty list. **Possible causes:** * No payment methods configured in Primer Dashboard * Client session missing required fields * Payment methods not enabled for the currency/country **Solution:** Verify your [Primer Dashboard](https://dashboard.primer.io) configuration and ensure your client session includes the correct `currencyCode` and `countryCode`. ### 3DS challenge not completing **Cause:** Payment gets stuck during 3DS authentication. **Solution:** Ensure your Activity has `android:configChanges="orientation|screenSize"` to prevent the WebView from being destroyed during configuration changes. ## Compose-specific issues ### Recomposition causes re-initialization **Cause:** Checkout reinitializes on every recomposition. **Solution:** Use `rememberPrimerCheckoutController()` which survives recomposition: ```kotlin theme={"dark"} // Correct val checkout = rememberPrimerCheckoutController(clientToken) // Incorrect - creates new controller on recomposition val checkout = PrimerCheckoutController(clientToken) ``` ### State not updating in UI **Cause:** UI doesn't reflect state changes from the SDK. **Solution:** Use `collectAsStateWithLifecycle()`: ```kotlin theme={"dark"} val state by checkout.state.collectAsStateWithLifecycle() ``` ## Validation vs payment errors Understanding the difference helps with proper error handling: | Error Type | When It Occurs | How It's Handled | | - | - | - | | **Validation errors** | During input (invalid format, missing fields) | Handled automatically by input components; prevents form submission | | **Payment failures** | After form submission (declined card, network issues) | Requires explicit handling with error container or custom code | > [!WARNING] > > Don't confuse these two error types. Validation errors prevent form submission and are shown inline. Payment failures occur after the form is submitted and require explicit handling. ## Debugging tips ### Log checkout state changes ```kotlin theme={"dark"} LaunchedEffect(checkout) { checkout.state.collect { state -> Log.d("PrimerCheckout", "State: $state") } } ``` ### Log all checkout state changes ```kotlin theme={"dark"} val state by checkout.state.collectAsStateWithLifecycle() LaunchedEffect(state) { Log.d("PrimerCheckout", "State: $state") when (val s = state) { is PrimerCheckoutState.Success -> { } is PrimerCheckoutState.Failure -> { Log.e("PrimerCheckout", "diagnosticsId: ${s.primerError.diagnosticsId}") } else -> Unit } } ``` ## Getting help When contacting Primer support, include: 1. The `diagnosticsId` from any `PrimerCheckoutState.Failure` 2. Your Android API level, Compose version, and SDK version 3. Steps to reproduce the issue ```kotlin theme={"dark"} val state by checkout.state.collectAsStateWithLifecycle() LaunchedEffect(state) { val s = state if (s is PrimerCheckoutState.Failure) { Log.e("Checkout", "diagnosticsId: ${s.primerError.diagnosticsId}") } } ``` ## See also > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Event handling patterns # Troubleshooting — iOS Source: https://primer.io/docs/checkout/primer-checkout/troubleshooting-ios Fix blank composable views (missing `.primerCheckoutSession`), sessions re-initializing without `@StateObject`, silent UIKit delegate callbacks, and Apple Pay not appearing. ## Quick diagnosis | Symptom | Likely Cause | Solution | | - | - | - | | Error screen with retry button (`PrimerCheckout`, UIKit), or empty composable views and a `.failure` in `onCompletion` | Invalid or expired client token | Generate a fresh `clientToken` from your server for each session | | Some payment methods missing, or an error with `misconfigured-payment-methods` / `missing-configuration` | Dashboard misconfiguration, unsupported currency/country, or methods the SDK does not support | Verify Dashboard settings and `currencyCode`/`countryCode` in client session | | Composable views render nothing | `.primerCheckoutSession` modifier missing above them, or session not yet `.ready` | Apply `.primerCheckoutSession(_:theme:onCompletion:)` around the views; they bind once the session reaches `.ready` | | Composable views go empty after a view update | A new `PrimerCheckoutSession` is built whenever SwiftUI re-evaluates the enclosing `body` (stored in a `let` or computed property) | Hold the session as a `@StateObject` | | Theme or settings not applied | `PrimerCheckoutTheme`/`PrimerSettings` created inside view `body` | Define as constants outside the view body | | Delegate callbacks never fire (UIKit) | `PrimerCheckoutPresenterDelegate` not set or deallocated | Set `delegate` on `.shared` before calling `presentCheckout` and retain the delegate | | Apple Pay missing from the list, or an "Apple Pay Unavailable" screen | Apple Pay not enabled for this session on the Dashboard; device without Apple Pay or without a supported card in Wallet; or, when paying, a missing or wrong merchant ID (`invalid-merchant-identifier`, `unable-to-present-apple-pay`) | Enable Apple Pay on the Dashboard; test on a real device with cards in Wallet; verify Apple Developer & Dashboard config | | Card form shows invalid despite filled fields | One of the four card fields is invalid or empty: card number, expiry, CVV or cardholder name (for example a field left out of a custom `cardDetails` slot) | Inspect `fieldErrors` on the `PrimerCardFormSession` handed to your card-form slot | | Payment fails after submission | Declined card, network issue, or processor error | Handle the `.failure(PrimerError, checkoutData)` state and log `diagnosticsId` | | Build error on iOS 14 | Minimum deployment target not met | Set deployment target to iOS 15.0+ | ## Configuration and initialization ### Error screen after initialization **Cause:** Invalid, expired, or malformed client token. `PrimerCheckout` and `PrimerCheckoutPresenter` show an error screen with a **Retry** button, not a blank screen. If you pass `PrimerSettings(uiOptions: PrimerUIOptions(isErrorScreenEnabled: false))`, `PrimerCheckout` shows nothing and only delivers `.failure` to `onCompletion`. `PrimerCheckoutPresenter` then closes the sheet and reports the failure to `primerCheckoutPresenterDidFailWithError`. In the composable flow (`.primerCheckoutSession`), the SDK never shows an error screen for a failed initialization, regardless of `isErrorScreenEnabled`. `onCompletion` receives one `.failure`, `session.phase` stays `.initializing`, and the composable views stay empty. **Solution:** Generate a fresh `clientToken` from your server for each checkout session. Client tokens are single-use and expire. ```swift theme={"dark"} PrimerCheckout( clientToken: freshClientToken, // Always fetch from your server onCompletion: { state in if case let .failure(error, _) = state { print("[Primer] Error: \(error.errorId)") print("[Primer] Description: \(error.errorDescription ?? "N/A")") print("[Primer] Diagnostics: \(error.diagnosticsId)") } } ) ``` > [!NOTE] > > If you see `invalid-client-token` in the error, your token is malformed or has expired. Generate a new one from your server. ### Payment methods not showing **Cause:** If no payment method is left to show, the checkout does not show an empty list. The session never reaches `.ready`. It reports `.failure` through `onCompletion`, or through `primerCheckoutPresenterDidFailWithError` in UIKit. The `errorId` tells you why: * `misconfigured-payment-methods`: the configuration loaded for this client token lists no payment methods, because none are enabled in the Dashboard for this session * `missing-configuration`: the SDK supports none of the configured methods, or the session configuration could not be loaded With `PrimerCheckout` and `PrimerCheckoutPresenter`, the shopper sees the error screen. It has no **Retry** button because no payment was attempted. Missing individual methods have multiple possible causes: * No payment methods configured in the [Primer Dashboard](https://dashboard.primer.io) for the given currency/country * The SDK only renders payment methods it supports — unsupported types are silently filtered out * Klarna appears only when `PrimerKlarnaSDK` is linked into your app. With CocoaPods, add `pod 'PrimerKlarnaSDK'` next to `PrimerSDK` in your `Podfile`. Without it, Klarna is filtered out of the list, and the debug log shows `Filtering out unregistered payment method: KLARNA`. * Client session missing required `currencyCode` or `countryCode` fields **Solution:** The SDK logs nothing by default. In a Debug build, turn on SDK debug logging before you create the checkout: `PrimerLogging.shared.logger = DefaultLogger(logLevel: .debug)`. Then check the Xcode console for messages like `Filtering out unregistered payment method: TYPE`. Verify your Dashboard configuration matches the currency and country in your client session. When using the composable [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) view, read the available methods from `session.selection?.state.paymentMethods`. ## SwiftUI integration ### Composable views render nothing **Cause:** The composable views — [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form), [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods), and [`PrimerVaultedPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) — resolve their session from the SwiftUI environment. Without the [`.primerCheckoutSession(_:theme:onCompletion:)`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session#view-modifier) modifier above them, they have no session to bind to. They also stay empty until the session reaches `.ready`. If initialization fails, for example because of an invalid client token or no supported payment methods, the session never reaches `.ready`. The modifier's `onCompletion` receives a single `.failure`, `session.phase` stays `.initializing`, and the views stay empty with no error screen. To find the reason, match `.failure(error, _)` in `onCompletion` and read `error.errorId`. [Error screen after initialization](#error-screen-after-initialization) shows the pattern. > [!WARNING] > > A composable view without `.primerCheckoutSession` above it in the hierarchy cannot resolve a session and will not function. This is the most common cause of "nothing renders" issues. **Solution:** Hold a [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) as a `@StateObject` and attach the modifier once around your composable views. The modifier injects the session, the derived `PrimerCardFormSession`, and the `PrimerSelectionSession` into the environment, calls `start()` on appear, and tears the session down on disappear: ```swift theme={"dark"} struct CheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject( wrappedValue: PrimerCheckoutSession(clientToken: clientToken) ) } var body: some View { ScrollView { VStack(spacing: 24) { PrimerPaymentMethods() PrimerCardForm() } } .primerCheckoutSession(session) { state in // Receives the outcome PrimerCheckoutState. } } } ``` If you only need the prebuilt screens, use the managed [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) view instead. It builds its own checkout, so it needs no `PrimerCheckoutSession` and no modifier. ### Session re-initializes unexpectedly **Cause:** A `let` or computed property builds a new `PrimerCheckoutSession` whenever SwiftUI re-evaluates the enclosing `body`. The modifier starts a session only when the view appears. The new session never starts, so the composable views stay empty. Nothing uses the original session anymore. **Solution:** Own the session as a `@StateObject` so SwiftUI keeps a single instance for the lifetime of the view: ```swift theme={"dark"} // WRONG: a new session on every body evaluation, and the modifier never starts it struct CheckoutView: View { let session = PrimerCheckoutSession(clientToken: clientToken) var body: some View { ... } } // CORRECT: one session for the lifetime of the view struct CheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject( wrappedValue: PrimerCheckoutSession(clientToken: clientToken) ) } var body: some View { ... } } ``` The modifier also tears the session down whenever the views under it disappear. This includes transient cases such as switching tabs, pushing another screen, or presenting the parent sheet again. When the views reappear, the session initializes again from the client token. Attach `.primerCheckoutSession` to a view that stays on screen for the whole checkout. The `.primerCheckoutSession` modifier drives the lifecycle for you — you normally never call `start()` or `cancel()` yourself. Call `session.refresh()` only when you need to reload after a client-session update (for example, an amount or currency change). ### Theme or settings not applied **Cause:** Creating `PrimerCheckoutTheme()` or `PrimerSettings()` inside the SwiftUI `body` property. SwiftUI re-evaluates `body` frequently, creating new objects each time. **Solution:** Define configuration as constants outside the view body: ```swift theme={"dark"} private let primerTheme = PrimerCheckoutTheme( colors: ColorOverrides(primerColorBrand: .blue) ) private let primerSettings = PrimerSettings(paymentHandling: .auto) struct CheckoutView: View { let clientToken: String var body: some View { PrimerCheckout( clientToken: clientToken, primerSettings: primerSettings, primerTheme: primerTheme ) } } ``` See [Best Practices](/docs/checkout/primer-checkout/configuration/best-practices) for more SwiftUI performance tips. ## UIKit integration ### Delegate callbacks never fire **Cause:** `PrimerCheckoutPresenterDelegate` not set on `PrimerCheckoutPresenter.shared` before calling `presentCheckout`, or the delegate object was deallocated. > [!WARNING] > > The delegate is a `weak` reference. Ensure the delegate object (typically your view controller) is retained for the lifetime of the checkout presentation. If the delegate is deallocated, callbacks silently stop. **Solution:** Set the delegate before presenting and implement all required methods: ```swift theme={"dark"} class CheckoutViewController: UIViewController, PrimerCheckoutPresenterDelegate { func showCheckout() { // Set delegate BEFORE presenting PrimerCheckoutPresenter.shared.delegate = self PrimerCheckoutPresenter.presentCheckout( clientToken: clientToken, from: self ) } // Required delegate methods func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) { // Handle successful payment } func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) { print("Payment failed: \(error.errorId)") } func primerCheckoutPresenterDidDismiss() { // Handle checkout dismissed } } ``` ### Checkout not presented **Cause:** Calling `presentCheckout` while a checkout is already on screen or still animating in. The SDK skips a second call only while the sheet is animating in. After that, a second call replaces the presenter's reference to the checkout on screen. **Solution:** Check `PrimerCheckoutPresenter.isPresenting` before calling. It is `true` from the start of the presentation until the checkout is dismissed or completes: ```swift theme={"dark"} guard !PrimerCheckoutPresenter.isPresenting else { print("Checkout already visible") return } PrimerCheckoutPresenter.presentCheckout(clientToken: clientToken, from: self) ``` ## Card form ### Form shows invalid despite all visible fields being filled **Cause:** `state.isValid` is `true` only when the card number, expiry date, CVV and cardholder name are all valid and non-empty. Billing address fields do not affect it. A field you left out of a custom `cardDetails` slot stays empty, so the form never becomes valid. **Solution:** Inspect `state.fieldErrors` on the [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) to identify which specific fields are failing validation. The session is handed to each [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) slot, and `PrimerCardForm` already observes it, so the slot re-renders on every state change: ```swift theme={"dark"} PrimerCardForm(cardDetails: { session in VStack(alignment: .leading) { CardFormDefaults.cardDetails(session) ForEach(session.state.fieldErrors) { error in Text("\(String(describing: error.fieldType)): \(error.message)") .foregroundColor(.red) .font(.caption) } } }) ``` `fieldErrors` lists only fields that the shopper filled in and that failed validation. A field that was never filled in or never shown has no entry. If `fieldErrors` is empty but `isValid` is `false`, check `session.state.data` for the four card fields. Use `session.state.isValid` to gate the submit button and `session.state.errorMessage(for:)` to display a per-field message. ## Apple Pay ### Apple Pay not available **Cause:** Multiple possible causes: * Apple Pay is not enabled in the Primer Dashboard for this client session, so it is not in the payment method list * The device cannot make Apple Pay payments, or Wallet has no card for the supported networks. Apple Pay still appears in the list. Selecting it opens an "Apple Pay Unavailable" screen. The text under the title is the error description, for example `[apple-pay-device-not-supported] Device does not support Apple Pay (diagnosticsId: ...)` or `[apple-pay-no-cards-in-wallet] Apple Pay has no cards in wallet (diagnosticsId: ...)`. When the shopper came from the payment method list, the screen has a **Choose Another Payment Method** button. * No merchant identifier: the payment fails with `invalid-merchant-identifier` because `PrimerSettings` has no `PrimerApplePayOptions`. * Wrong merchant identifier: the identifier does not match the Apple Developer portal and the Primer Dashboard. Apple rejects the request. If the Apple Pay sheet cannot open, the payment fails with `unable-to-present-apple-pay`. **Solution:** Test on a physical device with a card added to Wallet. Verify Apple Pay configuration in both the Apple Developer portal and Primer Dashboard. There is no separate Apple Pay view or scope. Apple Pay appears whenever the Dashboard enables it for the session. It shows as a `CheckoutPaymentMethod` (with `type == "APPLE_PAY"`) in [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods), or as a managed screen in [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout). To pay, pass your merchant identifier through [`PrimerSettings(paymentMethodOptions:)`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings) with `PrimerApplePayOptions(merchantIdentifier: "merchant.com.myapp", merchantName: nil)`. `merchantName` has no default value, so you must pass it. If Apple Pay never appears, confirm the method is present in `session.selection?.state.paymentMethods` and check the Dashboard. See the [Apple Pay integration guide](/docs/sdk/ios-checkout/v3.0.0-beta/guides/apple-pay-integration). ## Installation ### SPM package not found **Cause:** Build fails with "No such module 'PrimerSDK'". **Solution:** Re-add the SPM package: 1. In Xcode, go to **File > Add Package Dependencies** 2. Enter `https://github.com/primer-io/primer-sdk-ios` 3. Set the dependency rule to **Exact Version** `3.0.0-beta.8`, then add the `PrimerSDK` product to your target ### CocoaPods installation fails **Cause:** `pod install` fails or doesn't include the Primer SDK. **Solution:** Verify that your Podfile pins the beta version, then reinstall. Without a version, CocoaPods resolves the latest stable 2.x release, which does not include Primer Checkout. ```ruby theme={"dark"} # Podfile pod 'PrimerSDK', '3.0.0-beta.8' ``` ```bash theme={"dark"} pod install --repo-update ``` ### Minimum deployment target **Cause:** Your app's deployment target (or the Podfile's `platform :ios`) is below iOS 15.0. The build or install fails before the app runs. Depending on how you integrate, you see one of these errors: * Swift Package Manager: `The package product 'PrimerSDK' requires minimum platform version 15.0 for the iOS platform, but this target supports 14.0` * Xcode build: `compiling for iOS 14.0, but module 'PrimerSDK' has a minimum deployment target of iOS 15.0` * `pod install`: a CocoaPods message that the matching PrimerSDK spec requires a higher minimum deployment target **Solution:** The Primer Checkout iOS SDK requires iOS 15.0 or later. Update your deployment target: ``` // In Xcode: General > Deployment Info > iOS 15.0 ``` ## Validation vs payment errors Understanding the difference helps with proper error handling: | Error Type | When It Occurs | How It's Handled | | - | - | - | | **Validation errors** | During input (invalid format, missing fields) | Handled automatically by input components; prevents form submission | | **Payment failures** | After form submission (declined card, network issues) | Shown on the SDK error screen (unless `uiOptions.isErrorScreenEnabled` is `false`) and delivered as `.failure(error, checkoutData)` to `onCompletion`, or to `primerCheckoutPresenterDidFailWithError` in UIKit | > [!WARNING] > > Don't confuse these two error types. Validation errors prevent form submission and are shown inline. Payment failures occur after the form is submitted and require explicit handling. ## Debugging tips ### Log the outcome state The `onCompletion` closure on [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) or the `.primerCheckoutSession(_:theme:onCompletion:)` modifier receives the outcome [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state). Expect it more than once when a payment attempt fails and the customer retries. `.success` and `.dismissed` end the session. In the composable flow, a failed initialization also ends it: the modifier delivers that one `.failure` and nothing after it. ```swift theme={"dark"} PrimerCheckout(clientToken: clientToken) { state in print("[Primer] Terminal state: \(state)") } ``` For the composable flow, log it from the modifier instead: ```swift theme={"dark"} .primerCheckoutSession(session) { state in print("[Primer] Terminal state: \(state)") } ``` ### Inspect available payment methods Read the available methods from the [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) once the session is `.ready`: ```swift theme={"dark"} if let methods = session.selection?.state.paymentMethods { for method in methods { print("[Primer] Available: \(method.type) (\(method.name))") } } ``` ### Check session readiness The composable views bind only once the session reaches `.ready`. Observe `session.phase` to confirm initialization completed and the child sessions resolved: ```swift theme={"dark"} print("[Primer] Phase: \(session.phase)") print("[Primer] Card form ready: \(session.cardForm != nil)") print("[Primer] Selection ready: \(session.selection != nil)") ``` `phase` has no failed value. If it stays `.initializing`, the session is either still loading or initialization failed, so check the `onCompletion` closure for a `.failure`. ### Log card form validation errors Read `fieldErrors` from the [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) handed to a `PrimerCardForm` slot: ```swift theme={"dark"} PrimerCardForm(submitButton: { session in let _ = session.state.fieldErrors.forEach { error in print("[Primer] Field error - \(error.fieldType): \(error.message)") } return CardFormDefaults.submitButton(session) }) ``` ### Extract diagnostics for support ```swift theme={"dark"} if case let .failure(error, _) = state { print("[Primer] Error ID: \(error.errorId)") print("[Primer] Description: \(error.errorDescription ?? "N/A")") print("[Primer] Diagnostics ID: \(error.diagnosticsId)") print("[Primer] Recovery: \(error.recoverySuggestion ?? "N/A")") } ``` ## Getting help When contacting Primer support, include: 1. The `diagnosticsId` from any error callbacks 2. Your iOS version, Xcode version, and SDK version 3. Steps to reproduce the issue ```swift theme={"dark"} if case let .failure(error, _) = state { print("Include in support request:") print(" Error ID: \(error.errorId)") print(" Description: \(error.errorDescription ?? "N/A")") print(" Diagnostics ID: \(error.diagnosticsId)") print(" Recovery: \(error.recoverySuggestion ?? "N/A")") } ``` ## See also > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Event handling patterns > [card] [Build a custom card form](/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form) > > Card form tutorial > [card] [Best practices](/docs/checkout/primer-checkout/configuration/best-practices) > > SwiftUI performance tips # Troubleshooting — Web Source: https://primer.io/docs/checkout/primer-checkout/troubleshooting-web Fix `customElements is not defined`, duplicate card forms, React 18 property assignment, Shadow DOM styling and unstyled-element flashes. ## Quick diagnosis | Symptom | Likely Cause | Solution | | - | - | - | | Components don't render | `loadPrimer()` not called | Call `loadPrimer()` before using components | | `customElements is not defined` | Code running on server | Load SDK only on client side | | `window is not defined` | Code running on server | Add `typeof window !== 'undefined'` check | | Two card forms appear | Using both custom form and payment method | Choose one approach | | Card inputs don't work | Inputs outside `` | Wrap inputs in card form component | | Options not applied (React) | New object reference each render | Use stable references with `useMemo` or constants | | Styles not applying | Trying to style shadow DOM | Use CSS variables instead | | Slotted content flashes unstyled | Slotted content renders before `loadPrimer()` runs | Add a `:not(:defined)` CSS guard | ## Server-side rendering errors ### Error: "customElements is not defined" **Cause:** Primer code is running on the server where Web Components API doesn't exist. **Solution:** Ensure `loadPrimer()` is called only in client-side lifecycle methods. > [tab] Next.js / React > > ```javascript theme={"dark"} > import { useEffect } from 'react'; > import { loadPrimer } from '@primer-io/primer-js'; > > function MyCheckoutComponent() { > useEffect(() => { > if (typeof window !== 'undefined') { > loadPrimer(); > } > }, []); > > return ( > > {/* Checkout content */} > > ); > } > ``` > [tab] Nuxt 3 > > ```javascript theme={"dark"} > > ``` > [tab] SvelteKit > > ```javascript theme={"dark"} > > ``` ### Error: "window is not defined" **Cause:** Code is accessing browser globals during server-side rendering. **Solution:** Add environment checks before accessing browser APIs: ```javascript theme={"dark"} if (typeof window !== 'undefined') { // Browser-only code here } ``` ## Card form issues ### Duplicate card forms **Cause:** Using both `` and `` in the same layout. **Why this happens:** `` internally creates its own ``. When you also add a custom card form, you end up with two card forms on the page. **Solution:** Choose one approach: ```html theme={"dark"}
``` ### Card inputs not working **Cause:** Card input components placed outside ``. **Solution:** All card inputs must be descendants of the card form: ```html theme={"dark"}
``` ### Dynamic rendering creates duplicates **Cause:** When dynamically rendering payment methods, `PAYMENT_CARD` is included while also using a custom card form. **Solution:** Filter out `PAYMENT_CARD` when using a custom card form: ```javascript theme={"dark"} checkout.addEventListener('primer:methods-update', (event) => { const availableMethods = event.detail .toArray() // Filter out PAYMENT_CARD if you're using a custom card form .filter((method) => method.type !== 'PAYMENT_CARD'); availableMethods.forEach((method) => { const element = document.createElement('primer-payment-method'); element.setAttribute('type', method.type); container.appendChild(element); }); }); ``` ## React-specific issues ### Options not being applied **Cause:** Creating new object references on every render forces unnecessary comparisons. > [!NOTE] > > The Primer SDK implements deep comparison for the `options` property. This means unstable references won't cause re-initialization, but they still add comparison overhead on every render. **Solution:** Use stable references: ```javascript theme={"dark"} // SUBOPTIMAL: New object every render function CheckoutPage() { return ; } // OPTIMAL: Stable reference const SDK_OPTIONS = { locale: 'en-GB' }; function CheckoutPage() { return ; } // OPTIMAL: Use useMemo for dynamic options function CheckoutPage({ userLocale }) { const options = useMemo(() => ({ locale: userLocale, }), [userLocale]); return ; } ``` ### Calling methods before ready **Cause:** Calling SDK methods before the checkout is initialized. **Solution:** Wait for the `primer:ready` event: ```javascript theme={"dark"} // WRONG: May fail if checkout isn't ready const checkout = document.querySelector('primer-checkout'); const primerJS = checkout.primerJS; // May be undefined primerJS.setCardholderName('John Doe'); // Error! // CORRECT: Wait for the ready event checkout.addEventListener('primer:ready', (event) => { const primerJS = event.detail; primerJS.setCardholderName('John Doe'); // Works correctly }); ``` ### React 18 vs React 19 property assignment **Cause:** React 18 converts object props to `[object Object]` strings for web components. **Solution:** Use the appropriate pattern for your React version: > [tab] React 18 > > ```javascript theme={"dark"} > const SDK_OPTIONS = { locale: 'en-GB' }; > > function CheckoutPage() { > const checkoutRef = useRef(null); > > useEffect(() => { > if (checkoutRef.current) { > checkoutRef.current.options = SDK_OPTIONS; > } > }, []); > > return ; > } > ``` > [tab] React 19 > > ```javascript theme={"dark"} > const SDK_OPTIONS = { locale: 'en-GB' }; > > function CheckoutPage() { > return ; > } > ``` ## Styling issues ### CSS not applying to components **Cause:** Trying to style internal elements with CSS selectors. Shadow DOM prevents external CSS from reaching internal elements. **Solution:** Use CSS variables instead: ```css theme={"dark"} /* WRONG: Won't work with Shadow DOM */ primer-checkout input { border-color: blue; } /* CORRECT: Use CSS variables */ primer-checkout { --primer-color-border-input-default: blue; } ``` ### Flash of Unstyled Custom Elements **Cause:** `` is a custom element. Until the browser has registered it (which happens when `loadPrimer()` actually runs), it has no shadow DOM and no styling of its own. Any content you've slotted into it renders as plain, unstyled HTML in the meantime. This is only a visible problem when **both** of these are true: * You've slotted your own content into the `main` slot — for example the [custom content during loading](/docs/sdk/primer-checkout-web/components/primer-checkout#custom-content-during-loading) pattern, where a `
` wraps your own markup alongside `` * `loadPrimer()` runs after the page has already painted — for example inside a `useEffect`, behind a dynamic `import()`, or after other startup work If you haven't slotted anything, there's nothing to flash. If `loadPrimer()` runs immediately, the window is too short to notice. It's the combination that causes a visible flash. **Solution:** Add a CSS rule to your page — inline in ``, not dependent on the SDK's script having loaded — that targets the element until it's actually defined: ```css theme={"dark"} primer-checkout:not(:defined) { visibility: hidden; } ``` `:not(:defined)` is true the instant the browser parses an unrecognized custom element — it needs no JavaScript and doesn't depend on `loadPrimer()` having run, so it closes the gap regardless of how late the SDK loads. The rule above is just one example — `display: none` on the same selector works too. What matters is targeting `:not(:defined)`, not which specific property you use to hide the content. > [!TIP] > > Also call `loadPrimer()` as early as your framework allows (e.g. before your first render) rather than inside a post-mount effect, to keep the window as short as possible. ## Validation vs payment errors Understanding the difference helps with proper error handling: | Error Type | When It Occurs | How It's Handled | | - | - | - | | **Validation errors** | During input (invalid format, missing fields) | Handled automatically by input components; prevents form submission | | **Payment failures** | After form submission (declined card, network issues) | Requires explicit handling with error container or custom code | > [!WARNING] > > Don't confuse these two error types. Validation errors prevent form submission and are shown inline. Payment failures occur after the form is submitted and require explicit handling. ## Debugging tips ### Log all Primer events ```javascript theme={"dark"} const primerEvents = [ 'primer:ready', 'primer:state-change', 'primer:methods-update', 'primer:payment-success', 'primer:payment-failure', 'primer:card-error', 'primer:card-network-change', ]; primerEvents.forEach((eventName) => { document.addEventListener(eventName, (event) => { console.log(`[${eventName}]`, event.detail); }); }); ``` ### Verify component registration ```javascript theme={"dark"} // Should return a constructor, not undefined console.log(customElements.get('primer-checkout')); ``` ### Check available payment methods ```javascript theme={"dark"} checkout.addEventListener('primer:methods-update', (event) => { const methods = event.detail.toArray(); console.table(methods.map((m) => ({ type: m.type, id: m.id }))); }); ``` ## Getting help When contacting Primer support, include: 1. The `diagnosticsId` from any error callbacks 2. Your browser, OS version, and framework version 3. Steps to reproduce the issue ```javascript theme={"dark"} primer.onPaymentFailure = ({ error }) => { console.error('Payment failed:', { code: error.code, message: error.message, diagnosticsId: error.diagnosticsId, }); }; ``` ## See also > [card] [SSR guide](/docs/checkout/primer-checkout/frameworks/ssr-guide) > > Server-side rendering patterns > [card] [React integration](/docs/checkout/primer-checkout/frameworks/react-integration-guide) > > React-specific guidance > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Event handling patterns > [card] [Build a custom card form](/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form) > > Card form tutorial # Advised actions Source: https://primer.io/docs/concepts/advised-actions ## What are advised actions and advice codes? When you create a payment via Primer, the request is sent to your chosen processor based on your payment workflows. If the payment is not successful, some processors surface the advice code from the underlying payment method or card networks (e.g. Mastercard's Merchant Advice Code), enabling you to identify the best course of action for this transaction. Where possible, Primer exposes this underlying advice code, and maps it to a unified advice action so that you can reason about them in a single way across all your payments. ### Why are advised actions important? The advised actions and underlying advice codes can be used to determine: * **Whether the payment can be safely retried** \ *Some card networks such as Visa/Mastercard charges additional fees whenever the retry limit is exceeded* * **The best course of action to maximize the chances of recovery** \ *e.g. Retry now, retry later, or use another payment method* ## Primer's unified advised action Whenever possible, Primer exposes the unified advised action through this field: | Field | Description | Payment Object fields | | - | - | - | | Primer advised action | Indicates how this declined payment should be handled | `statusReason.advisedAction` `transactions[x].processorStatusReason.advisedAction` | Here are all the valid values for the unified advised action: | Primer advised action | Description | Example | | - | - | - | | `RETRY_LATER` | The payment was likely declined due to a temporary issue (e.g. Insufficient funds). The payment can be retried immediately or at a later date. | **Recurring payment declined due to insufficient funds** Retry the payment later. | | `UPDATE_DATA` | The payment was likely declined because critical data was missing or out-of-date. Please ensure you use the most up-to-date payment information and customer details before retrying the payment. | **Recurring payment declined due to an expired card** Use [Network Tokens](/docs/payment-services/network-tokenization) to have the latest card, or ask the customer to save a new payment method. | | `DO_NOT_RETRY` | The payment was declined and should not be retried. You can still charge this payment method for future orders or installments. | **The transaction is not permitted by the issuer** Do not retry this payment. The customer should contact their bank to understand the restriction. | | `STOP_ALL_PAYMENTS` | The processor or payment method explicitly informs you to stop making any payment requests with this payment method. Please use another payment method to charge this customer. | **The customer blocked all payments initiated by you** Do not charge this card again. Ask the customer to save a new payment method. | These fields are returned in the output of the Payments App in Workflows, as well as the API response and the payment status webhook. For example: ```json JSON theme={"dark"} { "id": "oWSlcuulG", "date": "2023-11-01T13:04:15.704780", "status": "DECLINED", ... "statusReason": { "type": "ISSUER_DECLINED", "declineType": "SOFT_DECLINE", "code": "ISSUER_TEMPORARILY_UNAVAILABLE", "message": "Processor Network Unavailable - Try Again", "advisedAction": "RETRY_LATER" }, "transactions": [ { "date": "2023-10-25T12:23:20.568943", ... "processorStatus": "DECLINED", "processorStatusReason": { "type": "ISSUER_DECLINED", "declineType": "SOFT_DECLINE", "code": "ISSUER_TEMPORARILY_UNAVAILABLE", "message": "Processor Network Unavailable - Try Again", "advisedAction": "RETRY_LATER" } } ] } ``` ## Payment method advice code Where possible, Primer also exposes the advice code and message from the payment method or card network. These are unified across all processors to facilitate analysis on all your payments. | Field | Description | Payment Object fields | | - | - | - | | Payment method advice code | The raw advice code from the payment method or card network (e.g. Mastercard MAC), unified across all processors | `statusReason.paymentMethodAdviceCode` `transactions[x].processorStatusReason.paymentMethodAdviceCode` | | Payment method advice message | Human-readable version of the advice code, unified across all processors | `statusReason.paymentMethodAdviceMessage` `transactions[x].processorStatusReason.paymentMethodAdviceMessage` | These fields are returned in the output of the Payments App in Workflows, as well as the API response and the payment status webhook. For example: ```json JSON theme={"dark"} { "id": "oWSlcuulG", "date": "2023-11-01T13:04:15.704780", "status": "DECLINED", ... "statusReason": { "type": "ISSUER_DECLINED", "declineType": "SOFT_DECLINE", "code": "ISSUER_TEMPORARILY_UNAVAILABLE", "message": "Processor Network Unavailable - Try Again", "paymentMethodAdviceCode": "24", // MAC 24 "paymentMethodAdviceMessage: " "advisedAction": "RETRY_LATER", }, "transactions": [ { "date": "2023-10-25T12:23:20.568943", ... "processorStatus": "DECLINED", "processorStatusReason": { "type": "ISSUER_DECLINED", "declineType": "SOFT_DECLINE", "code": "ISSUER_TEMPORARILY_UNAVAILABLE", "message": "Processor Network Unavailable - Try Again", "advisedAction": "RETRY_LATER" } } ] } ``` ## Supported card networks and processors The unified advised action and raw advice code are available for the following card networks: * **Mastercard** - using the [Merchant Advice Code (MAC)](#mastercard-merchant-advice-code-mac) * **Visa** - using the [Visa decline category code](#visa-decline-category-codes) And for the following processors: * Stripe * Braintree * Adyen > [!NOTE] > > Please reach out to us directly via our [Service Desk](https://portal.support.primer.io/servicedesk/customer/portal/11) if you need support for additional card networks, payment methods, or processors. ## Card network advice codes ### Mastercard Merchant Advice Code (MAC) Merchant Advice Codes (MACs) were introduced by Mastercard to recommend the best course of action to take for each declined payment. Here is the list of MACs, with how they map to Primer's advised action: | Merchant Advice Code (MAC) | Message | Primer advised action | | - | - | - | | 01 | Updated information needed | `UPDATE_DATA` | | 02 | Cannot be approved now, try again later | `RETRY_LATER` | | 03 | Do not try again | `DO_NOT_RETRY` | | 04 | Token requirements not fulfilled for this token type | `UPDATE_DATA` | | 21 | Stop recurring payment requests | `STOP_ALL_PAYMENTS` | | 22 | Merchant does not qualify for product code | `DO_NOT_RETRY` | | 24 | Retry after 1 hour | `RETRY_LATER` | | 25 | Retry after 24 hours | `RETRY_LATER` | | 26 | Retry after 2 days | `RETRY_LATER` | | 27 | Retry after 4 days | `RETRY_LATER` | | 28 | Retry after 6 days | `RETRY_LATER` | | 29 | Retry after 8 days | `RETRY_LATER` | | 30 | Retry after 10 days | `RETRY_LATER` | | 40 | Non-reloadable prepaid card | `RETRY_LATER` | | 41 | Single-use virtual card number | `RETRY_LATER` | | 42 | Sanction score exceeds applicable threshold value | `RETRY_LATER` | | 43 | Multi-use virtual card | `RETRY_LATER` | > [!WARNING] > > Mastercard charges Transaction Processing Excellence (TPA) fees: > > * If the number of authorization attempts on a single card exceed 10 in 24 hours and 35 in 30 days > * Whenever a merchant retries a payment declined with the MAC `03: Do not try again` or `21: Stop recurring payment requests` within a 30-day period ### Visa decline category codes Unlike Mastercard and their MAC, Visa does not expose a dedicated advice code. Instead, Visa categorizes their decline code into four categories, each with their overarching advice. Primer exposes the category code (`"1"` to `"4"`) as the advice code. | Category code | Message | Primer Advised Action | | - | - | - | | 1 | Issuer will never approve | `DO_NOT_RETRY` or `STOP_ALL_PAYMENTS` | | 2 | Issuer cannot approve at this time | `RETRY_LATER` | | 3 | Issuer cannot approve with these details | `UPDATE_DATA` | | 4 | Generic response | `RETRY_LATER` | #### Category 1 - Issuer will never approve The issuer declined the payment and will never approve a retry. This happens, for instance, when the card number is invalid, or the account is closed. > [!WARNING] > > **You are not allowed to retry the payment:** > > * Visa charges Excessive Retry Fees > for each retry. > > * Visa charges an additional Stop Payment Service > (SPS) fee of €1 per retry after receiving a revocation of authorization (R0, > R1, or R3). | Raw decline code | Raw decline message | Primer Advised Action | | - | - | - | | 04 | Pickup card (no fraud) | `DO_NOT_RETRY` | | 07 | Pickup card, special condition (fraud account) | `DO_NOT_RETRY` | | 12 | Invalid transaction | `DO_NOT_RETRY` | | 14 | Invalid account number (no such number) | `DO_NOT_RETRY` | | 15 | No such issuer | `DO_NOT_RETRY` | | 41 | Lost card, pick up (fraud account) | `DO_NOT_RETRY` | | 43 | Stolen card, pick up (fraud account) | `DO_NOT_RETRY` | | 44 | Lost/stolen card | `DO_NOT_RETRY` | | 46 | Closed account | `DO_NOT_RETRY` | | 57 | Transaction not permitted to issuer/cardholder | `DO_NOT_RETRY` | | R0 | Stop payment order | `STOP_ALL_PAYMENTS` | | R1 | Revocation of authorization order | `STOP_ALL_PAYMENTS` | | R3 | Revocation of all authorizations order | `STOP_ALL_PAYMENTS` | #### Category 2 - Issuer cannot approve at this time The issuer declined the payment but may approve it at a later date. This happens, for instance, when the card has insufficient funds or is temporarily restricted. > [!WARNING] > > **You can retry the payment up to 15 times in a 30-day window:** > > * Once the limit is exceeded, Visa charges Excessive Retry Fees for each subsequent attempt. | Raw decline code | Raw decline message | Primer advised action | | - | - | - | | 03 | Invalid merchant | `RETRY_LATER` | | 19 | Re-enter transaction | `RETRY_LATER` | | 51 | Insufficient funds / Over credit limit | `RETRY_LATER` | | 59 | Suspected fraud | `RETRY_LATER` | | 60 | Exceeds approval amount limit | `RETRY_LATER` | | 61 | Exceeds approval amount limit | `RETRY_LATER` | | 62 | Restricted card (card invalid in region or country) | `RETRY_LATER` | | 65 | Exceeds withdrawal frequency limit | `RETRY_LATER` | | 75 | Allowable number of PIN entry tries exceeded | `RETRY_LATER` | | 78 | “Blocked, first used” - Transaction from new cardholder, and card not properly unblocked | `RETRY_LATER` | | 86 | Cannot verify PIN | `RETRY_LATER` | | 91 | Issuer unavailable or switch inoperative | `RETRY_LATER` | | 93 | Transaction cannot be completed; violation of law | `RETRY_LATER` | | N3 | Cash service not available | `RETRY_LATER` | | N4 | Cash request exceeds issuer limit | `RETRY_LATER` | | 9G | Blocked by cardholder/contact cardholder | `RETRY_LATER` | #### Category 3 - Issuer cannot approve with these details The issuer declined the payment because the card details were missing or out-of-date. This happens, for instance, when the card's CVV or expiry date is missing. > [!WARNING] > > **You can retry the payment up to 15 times in a 30-day window:** > > * Once the limit is exceeded, Visa charges Excessive Retry Fees for each subsequent attempt. > > * Visa also charges Data Quality Fee if the number of attempts exceed 25,000 transactions. | Raw decline code | Raw decline message | Primer advised action | | - | - | - | | 54 | Expired card or expiration date is missing | `UPDATE_DATA` | | 55 | Incorrect PIN or PIN missing | `UPDATE_DATA` | | 70 | PIN data required | `UPDATE_DATA` | | 82 | Negative Online CAM, dCVV, iCVV, or CVV results | `UPDATE_DATA` | | N7 | Decline for CVV2 failure | `UPDATE_DATA` | | 1A | Additional customer authentication required (Europe only) | `UPDATE_DATA` | #### Category 4 - Generic response codes This issuer declined the payment, but the decline reason does not belong to any other category. > [!WARNING] > > **You can retry the payment up to 15 times in a 30-day window:** > > * Once the limit is exceeded, Visa charges Excessive Retry Fees for each subsequent attempt. | Raw decline code | Raw decline message | Primer advised action | | - | - | - | | 01 | Refer to card issuer | `RETRY_LATER` | | 02 | Refer to card issuer’s special conditions | `RETRY_LATER` | | 05 | Do not honor | `RETRY_LATER` | | 06 | Error | `RETRY_LATER` | | 13 | Invalid amount or currency conversion field overflow | `RETRY_LATER` | | 30 | Format error | `RETRY_LATER` | | 31 | Bank not supported by switch | `RETRY_LATER` | | 34 | Suspected fraud | `RETRY_LATER` | | 36 | Restricted card | `RETRY_LATER` | | 39 | No credit account | `RETRY_LATER` | | 40 | Requested function not supported | `RETRY_LATER` | | 42 | Invalid account | `RETRY_LATER` | | 52 | No checking account | `RETRY_LATER` | | 53 | No savings account | `RETRY_LATER` | | 76 | Unsolicited reversal | `RETRY_LATER` | | 81 | Cryptographic error found in PIN | `RETRY_LATER` | | 89 | Ineligible to receive financial position information (GIV) | `RETRY_LATER` | | 92 | Financial institution or intermediate network facility cannot be found for routing | `RETRY_LATER` | | 94 | Request is identified as a duplicate | `RETRY_LATER` | | 96 | System malfunction | `RETRY_LATER` | | 5C | Transaction not supported/blocked by issuer | `RETRY_LATER` | | 6P | Verification data failed | `RETRY_LATER` | # Currencies Source: https://primer.io/docs/concepts/currencies ## Primer's currency policy The `amount` field in the Primer APIs is in minor units i.e. the smallest unit of a currency. A currency can either have 0, 2 or 3 minor units. For example: * JPY has 0 minor units, so to create a payment for 1000 JPY, `amount` should equal `1000` * USD has 2 minor units, so to create a payment for 10.00 USD, `amount` should equal `1000` * IQD has 3 minor units, so to create a payment for 1.000 IQD, `amount` should equal `1000` ## Supported currencies > [!WARNING] > > **The following currencies are disabled by default and require your Primer account to be "*gated in*" in order to use them:** > > BHD, BIF, CLP, CVE, GNF, HUF, IDR, INR, ISK, KHR, KMF, MMK, PYG, RWF, SAR, UGX, VED, VES, VND, XOF, XPF > > If you try to use one of these currencies without being gated in, you will receive the following API validation error message: > > ```json JSON theme={"dark"} > { > "error": { > "errorId": "DisabledCurrencyError", > "description": "HUF is a disabled currency", > "recoverySuggestion": "To enable, please speak to your Customer Success Manager or our Service Desk https://portal.support.primer.io/servicedesk/customer/portal/11.", > "diagnosticsId": "9942005157443145021" > } > } > ``` > > To be gated in, speak to your Customer Success Manager or raise a ticket on our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11).  If you don’t have access, please contact your account administrator for assistance. > [!WARNING] > > **The following currencies have been retired and are no longer accepted for new payment or client session creation:** > > BGN, ZWL, ANG > > They remain listed in the table below because they can still appear on historical or existing payment data. If you try to use one of these currencies for a new payment or client session, you will receive the following API validation error message: > > ```json JSON theme={"dark"} > { > "error": { > "errorId": "DeprecatedCurrencyError", > "description": "BGN is no longer a supported currency", > "recoverySuggestion": "Please use a currently supported currency.", > "diagnosticsId": "9942005157443145021" > } > } > ``` See below for the supported currencies and the number of minor units supported per currency. | Code | Name | Number of minor units | | :- | - | - | | AED | UAE Dirham | 2 | | AFN | Afghani | 2 | | ALL | Lek | 2 | | AMD | Armenian Dram | 2 | | ANG | Netherlands Antillean Guilder | 2 | | AOA | Kwanza | 2 | | ARS | Argentine Peso | 2 | | AUD | Australian Dollar | 2 | | AWG | Aruban Florin | 2 | | AZN | Azerbaijanian Manat | 2 | | BAM | Convertible Mark | 2 | | BBD | Barbados Dollar | 2 | | BDT | Taka | 2 | | BGN | Bulgarian Lev | 2 | | BHD | Bahraini Dinar | 3 | | BIF | Burundi Franc | 0 | | BMD | Bermudian Dollar | 2 | | BND | Brunei Dollar | 2 | | BOB | Boliviano | 2 | | BOV | Mvdol | 2 | | BRL | Brazilian Real | 2 | | BSD | Bahamian Dollar | 2 | | BTN | Ngultrum | 2 | | BWP | Pula | 2 | | BYN | Belarusian Ruble | 2 | | BZD | Belize Dollar | 2 | | CAD | Canadian Dollar | 2 | | CDF | Congolese Franc | 2 | | CHE | WIR Euro | 2 | | CHF | Swiss Franc | 2 | | CHW | WIR Franc | 2 | | CLP | Chilean Peso | 0 | | CNY | Yuan Renminbi | 2 | | COP | Colombian Peso | 2 | | COU | Unidad de Valor Real | 2 | | CRC | Costa Rican Colon | 2 | | CUC | Peso Convertible | 2 | | CUP | Cuban Peso | 2 | | CVE | Cape Verde Escudo | 2 | | CZK | Czech Koruna | 2 | | DJF | Djibouti Franc | 0 | | DKK | Danish Krone | 2 | | DOP | Dominican Peso | 2 | | DZD | Algerian Dinar | 2 | | EGP | Egyptian Pound | 2 | | ERN | Nakfa | 2 | | ETB | Ethiopian Birr | 2 | | EUR | Euro | 2 | | FJD | Fiji Dollar | 2 | | FKP | Falkland Islands Pound | 2 | | GBP | Pound Sterling | 2 | | GEL | Lari | 2 | | GHS | Ghana Cedi | 2 | | GIP | Gibraltar Pound | 2 | | GMD | Dalasi | 2 | | GNF | Guinea Franc | 0 | | GTQ | Quetzal | 2 | | GYD | Guyana Dollar | 2 | | HKD | Hong Kong Dollar | 2 | | HNL | Lempira | 2 | | HRK | Croatian Kuna | 2 | | HTG | Gourde | 2 | | HUF | Forint | 2 | | IDR | Rupiah | 2 | | ILS | New Israeli Sheqel | 2 | | INR | Indian Rupee | 2 | | IQD | Iraqi Dinar | 3 | | IRR | Iranian Rial | 2 | | ISK | Iceland Krona | 0 | | JMD | Jamaican Dollar | 2 | | JOD | Jordanian Dinar | 3 | | JPY | Yen | 0 | | KES | Kenyan Shilling | 2 | | KGS | Som | 2 | | KHR | Riel | 2 | | KMF | Comoro Franc | 0 | | KPW | North Korean Won | 2 | | KRW | Won | 0 | | KWD | Kuwaiti Dinar | 3 | | KYD | Cayman Islands Dollar | 2 | | KZT | Tenge | 2 | | LAK | Kip | 2 | | LBP | Lebanese Pound | 2 | | LKR | Sri Lanka Rupee | 2 | | LRD | Liberian Dollar | 2 | | LSL | Loti | 2 | | LYD | Libyan Dinar | 3 | | MAD | Moroccan Dirham | 2 | | MDL | Moldovan Leu | 2 | | MKD | Denar | 2 | | MMK | Kyat | 2 | | MNT | Tugrik | 2 | | MOP | Pataca | 2 | | MUR | Mauritius Rupee | 2 | | MVR | Rufiyaa | 2 | | MWK | Kwacha | 2 | | MXN | Mexican Peso | 2 | | MXV | Mexican Unidad de Inversion (UDI) | 2 | | MYR | Malaysian Ringgit | 2 | | MZN | Mozambique Metical | 2 | | NAD | Namibia Dollar | 2 | | NGN | Naira | 2 | | NIO | Cordoba Oro | 2 | | NOK | Norwegian Krone | 2 | | NPR | Nepalese Rupee | 2 | | NZD | New Zealand Dollar | 2 | | OMR | Rial Omani | 3 | | PAB | Balboa | 2 | | PEN | Nuevo Sol | 2 | | PGK | Kina | 2 | | PHP | Philippine Peso | 2 | | PKR | Pakistan Rupee | 2 | | PLN | Zloty | 2 | | PYG | Guarani | 0 | | QAR | Qatari Rial | 2 | | RON | New Romanian Leu | 2 | | RSD | Serbian Dinar | 2 | | RUB | Russian Ruble | 2 | | RWF | Rwanda Franc | 0 | | SAR | Saudi Riyal | 2 | | SBD | Solomon Islands Dollar | 2 | | SCR | Seychelles Rupee | 2 | | SDG | Sudanese Pound | 2 | | SEK | Swedish Krona | 2 | | SGD | Singapore Dollar | 2 | | SHP | Saint Helena Pound | 2 | | SLE | Leone | 2 | | SOS | Somali Shilling | 2 | | SRD | Surinam Dollar | 2 | | SSP | South Sudanese Pound | 2 | | STN | Dobra | 2 | | SVC | El Salvador Colon | 2 | | SYP | Syrian Pound | 2 | | SZL | Lilangeni | 2 | | THB | Baht | 2 | | TJS | Somoni | 2 | | TMT | Turkmenistan New Manat | 2 | | TND | Tunisian Dinar | 3 | | TOP | Pa’anga | 2 | | TRY | Turkish Lira | 2 | | TTD | Trinidad and Tobago Dollar | 2 | | TWD | New Taiwan Dollar | 2 | | TZS | Tanzanian Shilling | 2 | | UAH | Hryvnia | 2 | | UGX | Uganda Shilling | 0 | | USD | US Dollar | 2 | | UYU | Peso Uruguayo | 2 | | UZS | Uzbekistan Sum | 2 | | VED | Digital Bolivar | 2 | | VES | Sovereign Bolivar | 2 | | VND | Dong | 0 | | VUV | Vatu | 0 | | WST | Tala | 2 | | XAF | CFA Franc BEAC | 0 | | XCD | East Caribbean Dollar | 2 | | XCG | Caribbean Guilder | 2 | | XFU | UIC-Franc | 2 | | XOF | CFA Franc BCEAO | 0 | | XPF | CFP Franc | 0 | | YER | Yemeni Rial | 2 | | ZAR | Rand | 2 | | ZMW | Zambian Kwacha | 2 | | ZWG | Zimbabwe Gold | 2 | | ZWL | Zimbabwe Dollar | 2 | # Primer's Unified Mapping Standard Source: https://primer.io/docs/concepts/decline-codes/mapping-standard We unify the decline codes across all processors and payment methods we integrate with so you only have to understand them in one way. This guide will outline how we map issuer decline reasons. > [!NOTE] > > [See here for an overview of what decline codes are and how they're defined on Primer.](/docs/concepts/decline-codes/overview) ### How does Primer approach this? Where possible, we map our decline reasons to the raw response codes that the issuers provide that are defined by the card networks (e.g. Visa and Mastercard). If the raw response code isn’t returned by the processor, we use the processor response code. > [!NOTE] > > Primer exposes the underlying decline codes for selected payment methods, card networks, and processors to enable you to analyze them in a unified way. > > Head over to the [Payment method decline codes](/docs/concepts/decline-codes/payment-method-decline-codes) guide to learn more. ### Mapping Standard *Only showing for Mastercard & Visa.* | Raw response code | Card Network(s) | Decline Type | Decline Reason | | :- | :- | :- | :- | | 01: Refer to card issuer | Mastercard | `SOFT_DECLINE` | `REFER_TO_CARD_ISSUER` | | 03: Invalid merchant | Mastercard Visa | `HARD_DECLINE` | `ERROR` | | 04: Pickup card (no fraud) \[Visa] / Capture card \[Mastercard] | Mastercard Visa | `HARD_DECLINE` | `LOST_OR_STOLEN_CARD` | | 05: Do not honor | Mastercard Visa | `SOFT_DECLINE` | `DO_NOT_HONOR` | | 07: Pickup card, special conditions | Visa | `HARD_DECLINE` | `LOST_OR_STOLEN_CARD` | | 12: Invalid transaction | Mastercard Visa | `HARD_DECLINE` | `ERROR` | | 13: Invalid amount | Mastercard | `HARD_DECLINE` | `ERROR` | | 14: Invalid card number | Mastercard Visa | `HARD_DECLINE` | `INVALID_CARD_NUMBER` | | 15: No such issuer | Mastercard Visa | `HARD_DECLINE` | `ERROR` | | 19: Re-enter transaction | Visa | `SOFT_DECLINE` | `ISSUER_TEMPORARILY_UNAVAILABLE` | | 30: Format error | Mastercard | `SOFT_DECLINE` | `DECLINED` | | 41: (Pickup card) lost card | Mastercard Visa | `HARD_DECLINE` | `LOST_OR_STOLEN_CARD` | | 43: (Pickup card) stolen card | Mastercard Visa | `HARD_DECLINE` | `LOST_OR_STOLEN_CARD` | | 46: Closed Account | Visa | `HARD_DECLINE` | `ERROR` | | 51: Insufficient funds / Not Sufficient Funds | Mastercard Visa | `SOFT_DECLINE` | `INSUFFICIENT_FUNDS` | | 54: Expired card / Expiration date missing | Mastercard Visa | `HARD_DECLINE` | `EXPIRED_CARD` | | 57: Transaction not permitted to issuer/cardholder | Mastercard Visa | `HARD_DECLINE` | `ERROR` | | 58: Transaction not permitted to acquirer | Mastercard | `HARD_DECLINE` | `ERROR` | | 59: Suspected fraud | Visa | `HARD_DECLINE` | `SUSPECTED_FRAUD` | | 61: Exceeds withdrawal amount limit(s) / Exceeds approval amount limit | Mastercard Visa | `SOFT_DECLINE` | `WITHDRAWAL_LIMIT_EXCEEDED` | | 62: Restricted card | Mastercard Visa | `HARD_DECLINE` | `ERROR` | | 63: Security violation | Mastercard | `SOFT_DECLINE` | `REFER_TO_CARD_ISSUER` | | 65: Exceeds Withdrawal Frequency Limit | Mastercard Visa | `SOFT_DECLINE` | `WITHDRAWAL_LIMIT_EXCEEDED` | | 65: Authentication required | Mastercard | `SOFT_DECLINE` | `AUTHENTICATION_REQUIRED` | | 70: Contact card issuer | Mastercard | `SOFT_DECLINE` | `REFER_TO_CARD_ISSUER` | | 76: Invalid/non-existent “To Account” specified | Mastercard | `HARD_DECLINE` | `ERROR` | | 77: Invalid/non-existent “From Account” specified | Mastercard | `HARD_DECLINE` | `ERROR` | | 78: Invalid/nonexistent account specified (general) | Mastercard | `HARD_DECLINE` | `ERROR` | | 78: Blocked, first used | Visa | `SOFT_DECLINE` | `REFER_TO_CARD_ISSUER` | | 79: Lifecycle | Mastercard | `HARD_DECLINE` | `ERROR` | | 82: Policy | Mastercard | `HARD_DECLINE` | `ERROR` | | 83: Fraud / Security | Mastercard | `HARD_DECLINE` | `SUSPECTED_FRAUD` | | 84: Invalid Authorization Lifecycle | Mastercard | `HARD_DECLINE` | `ERROR` | | 88: Cryptographic failure | Mastercard | `HARD_DECLINE` | `ERROR` | | 91: Issuer unavailable or switch inoperative | Mastercard Visa | `SOFT_DECLINE` | `ISSUER_TEMPORARILY_UNAVAILABLE` | | 92: Unable to route transaction | Mastercard | `SOFT_DECLINE` | `DECLINED` | | 93: Transaction cannot be completed; violation of law | Visa | `HARD_DECLINE` | `ERROR` | | 96: System malfunction | Mastercard Visa | `SOFT_DECLINE` | `ISSUER_TEMPORARILY_UNAVAILABLE` | | R0: Stop Payment Order | Visa | `HARD_DECLINE` | `ERROR` | | R1: Revocation of Authorization Order | Visa | `HARD_DECLINE` | `ERROR` | | R3: Revocation of all authorization orders | Visa | `HARD_DECLINE` | `ERROR` | | N7: Decline for CVV2 Failure | Visa | `HARD_DECLINE` | `ERROR` | | 1A: Additional Customer Authentication Required (Europe only) | Visa | `SOFT_DECLINE` | `AUTHENTICATION_REQUIRED` | # Overview Source: https://primer.io/docs/concepts/decline-codes/overview ## What are decline codes? When you create a payment via Primer, the request is sent to your chosen processor based on your payment workflows. > [!NOTE] > > [See here for how to process payments on Primer](/docs/get-started/connect-a-processor). If the payment is not successful, the processor will return decline fields outlining why the payment was unsuccessful. There are different reasons for payments being declined, such as: * Technical issues with the processor or payment method * Processor rejects the payment (typically due to fraud prevention rules) * Issuing bank declines the payment Each processor has a very different way of responding and handling decline codes, which is where Primer comes in. We abstract this complexity and unify all the different decline code mappings into a single, standardized way of reasoning about declined payments. > [!NOTE] > > [See here for Primer’s unified decline mapping standard and how we map from raw response codes.](./mapping-standard) ### Why are decline codes important? Understanding why a payment is not authorized is crucial, serving as a key communication tool between payment systems, issuers, merchants and end customers. They offer clarity and guidance when your payments encounter issues, enabling you to devise a strategy to achieve: * **Enhanced customer experience** - understanding the specific reason can help cardholders take appropriate action * **Improved fraud prevention** - help protect cardholders from unauthorized charges and your business from chargeback fees * **Boost payment success** - optimize your authorization rates by analyzing decline reasons and identifying areas of improvement ## Decline codes on Primer Below are the fields you need to consider when evaluating why a payment wasn’t successful: | Field | Description | Payment Object fields | | :- | :- | :- | | Payment Status | The status of the payment | `status` `transactions[x].processorStatus` | | Decision Type | The decision behind why the payment was not successful | `statusReason.type` `transactions[x].processorStatusReason.type` | | Decline Type | Determines if the payment had a soft or hard decline when the decision type is `ISSUER_DECLINED` | `statusReason.declineType` `transactions[x].processorStatusReason.declineType` | | Decline Reason | The decline reason if the decision type is `ISSUER_DECLINED` | `statusReason.code` `transactions[x].processorStatusReason.code` | | Error Message | The error message provided by the processor | `statusReason.message` `transactions[x].processorStatusReason.message` | > [!NOTE] > > **What is the difference between the payment and transaction fields?** > > A Primer payment can have multiple processor transactions. > > * The payment fields represent the latest/final values > * The transaction fields represent the values for that specific processor transaction These fields are returned in the API response, as well as being included in the payment status webhook. For example: ```json JSON theme={"dark"} { "id": "oWSlcuulG", "date": "2023-11-01T13:04:15.704780", "status": "DECLINED", ... "statusReason": { "type": "ISSUER_DECLINED", "declineType": "SOFT_DECLINE", "code": "ISSUER_TEMPORARILY_UNAVAILABLE", "message": "Processor Network Unavailable - Try Again" }, "transactions": [ { "date": "2023-10-25T12:23:20.568943", ... "processorStatus": "DECLINED", "processorStatusReason": { "type": "ISSUER_DECLINED", "declineType": "SOFT_DECLINE", "code": "ISSUER_TEMPORARILY_UNAVAILABLE", "message": "Processor Network Unavailable - Try Again" } } ] } ``` ### Payment Status There are three possible payment statuses for unsuccessful payments: | Status | Description | | :- | :- | | FAILED | There is a technical problem that prevents the payment from being processed. | | DECLINED | The payment was processed and declined by one of the parties in the chain, such as the processor or card issuer. | | CANCELLED | The payment was canceled by the end customer. This is only used for some APMs. *Otherwise, CANCELLED is used when you choose to cancel an authorized payment.* | > [!NOTE] > > [See here for a detailed breakdown of all of Primer’s payment statuses and how the state machine works](/docs/concepts/payment-lifecycle). ### Decision Type There are four possible decision types behind why a payment is unsuccessful: | Decision Type | Description | | :- | :- | | `APPLICATION_ERROR` | There is a technical problem that prevents the payment from being processed. | | `GATEWAY_TIMEOUT` | The processor returned a timeout error or did not respond within our maximum timeout allowance. | | `GATEWAY_REJECTED` | The processor has rejected the payment and has not sent it downstream to be processed. | | `ISSUER_DECLINED` | The processor sent the payment to be processed but the card issuer has declined the payment. | ### Decline Reason This should only populated when decision type is `ISSUER_DECLINED`. Below are the decline reasons for **hard declines**: | Decline Reason | Description | Merchant Recommended Action | | :- | :- | :- | | `INVALID_CARD_NUMBER` | The issuer does not recognize the card number that it’s received. Perhaps, the account number was never issued or has been permanently blocked/closed | Evaluate for potential fraud and/or revalidate account number for accuracy | | `EXPIRED_CARD` | The card is expired or the expiration date is invalid | Validate the expiration date prior to reattempt and monitor reattempts for potential fraud | | `LOST_OR_STOLEN_CARD` | The cardholder has reported the card stolen or lost, and as a result, the account is either fraud-compromised or closed | Request alternate payment method from cardholder and/or advise the cardholder to contact their issuer | | `SUSPECTED_FRAUD` | The transaction does not pass risk monitoring detection systems or controls | Advise the cardholder to contact their issuer | | `ERROR` | Generic hard decline reason that groups a range of declines | Check the error message for more information | | `UNKNOWN` | The fallback decline reason if the decline code is not mapped. We conduct regular audits of this bucket of payments and update our mappings accordingly | Check the error message for more information | Below are the decline reasons for **soft declines**: | Decline Reason | Description | Merchant Recommended Action | | :- | :- | :- | | `REFER_TO_CARD_ISSUER` | The card issuer has indicated an issue with this card and requests contact from the customer | The shopper can try again after they resolved the issue with their bank/issuer | | `INSUFFICIENT_FUNDS` | Transaction amount exceeds the cardholder’s available balance | May reattempt for a lesser amount or at a later date to allow the customer to fund their debit account or pay down their credit account | | `WITHDRAWAL_LIMIT_EXCEEDED` | The amount and/or count activity limit for the account has been exceeded | Do not reattempt the transaction the same day to allow limits to reset | | `ISSUER_TEMPORARILY_UNAVAILABLE` | The issuer’s system is unable to perform the authorization due to system malfunction or critical message failure | Reattempts can occur within the same day | | `AUTHENTICATION_REQUIRED` | 3DS is required for this payment | Trigger 3DS flow for this payment | | `DO_NOT_HONOR` | This is a generic refusal that card issuers provide that has several possible causes | Check the error message for more information | | `DECLINED` | Generic soft decline reason that groups a range of declines | Check the error message for more information | ### Decline Types There are two types of issuer declines: | Decline Type | Description | | :- | :- | | `SOFT_DECLINE` | These payments can be retried under certain conditions | | `HARD_DECLINE` | These payments should never be retried | > [!WARNING] > > This logic is now superseeded by Primer's [unified advised action](/docs/concepts/advised-actions), which gives you a finer understanding of how to handle each payment. ### Error Message This is the error message provided by the processor so this does not have a predefined set of possible values. This can give extra information that’s useful when determining what’s the best action to pursue. ### Underlying decline codes Primer exposes the underlying decline codes for selected payment methods, card networks, and processors to enable you to analyze them in a unified way. Head over to the [Payment method decline codes](/docs/concepts/decline-codes/payment-method-decline-codes) guide to learn more. ### Advised actions If the payment is not successful, some processors surface the advice code from the underlying payment method or card networks (e.g. Mastercard's Merchant Advice Code), enabling you to identify the best course of action for this transaction. Where possible, Primer exposes this underlying advice code, and maps it to a unified advice action so that you can reason about them in a single way across all your payments. Head over to the [Advised actions](/docs/concepts/advised-actions) guide to learn more. ## How decline codes are used within Primer’s ecosystem Decline codes can be used in different ways to drive your payments strategy: * Create automated flows in Workflows to handle these scenarios, such as sending an automated email to the customer for every decline due to insufficient funds - [*learn more here*](/docs/get-started/create-workflow) * View aggregated data insights on all your declines in Observability to help identify broader trends and areas of improvement/focus - [*learn more here*](/docs/observability/overview) * Our Fallbacks feature is only triggered for certain decline scenarios - [*learn more here*](/docs/payment-services/fallbacks) * Our Adaptive 3DS feature is only triggered for certain decline scenarios - [*learn more here*](/docs/payment-services/3d-secure/overview#adaptive-3ds) * Create Monitors on Primer to track decline reasons, so you’re always alerted to changes in processor responses - [*learn more here*](/docs/monitors/overview) > [!NOTE] > > [See here for Primer’s unified decline mapping standard and how we map from raw response codes.](/docs/concepts/decline-codes/mapping-standard) # Payment method decline codes Source: https://primer.io/docs/concepts/decline-codes/payment-method-decline-codes ## What are payment method decline codes? If a payment is rejected, some processors surface the decline reason of the underlying card network or payment method. Where possible, Primer maps these decline reasons to our [unified mapping standard](/docs/concepts/decline-codes/mapping-standard). Additionally, to facilitate precise decline analysis across your payment stack, Primer exposes the underlying decline code in a unified way across all supported processors. ## Payment method decline codes Below are the fields we expose on the Payments API when a payment is not successful: | Field | Description | Payment Object fields | | :- | :- | :- | | Payment Method Result Code | The result code from the payment method or card network, unified across all processors | `statusReason.paymentMethodResultCode` `transactions[x].processorStatusReason.paymentMethodResultCode` | | Payment Method Result Message | Human-readable version of the result code, unified across all processors | `statusReason.paymentMethodResultMessage` `transactions[x].processorStatusReason.paymentMethodResultMessage` | These fields are returned in the output of the Payments App in Workflows, as well as the API response and the payment status webhook. For example: ```json JSON theme={"dark"} { "status": "DECLINED", ... "statusReason": { // Payment method results (here, for Visa) "paymentMethodResultCode": "91", "paymentMethodResultMessage": "Issuer unavailable or switch inoperative", // Primer decline code mapping "type": "ISSUER_DECLINED", "declineType": "SOFT_DECLINE", "code": "ISSUER_TEMPORARILY_UNAVAILABLE" }, "transactions": [ { "processorStatus": "DECLINED", ... "processorStatusReason": { // Payment method results (here, for Visa) "paymentMethodResultCode": "91", "paymentMethodResultMessage": "Issuer unavailable or switch inoperative", // Primer decline code mapping "type": "ISSUER_DECLINED", "declineType": "SOFT_DECLINE", "code": "ISSUER_TEMPORARILY_UNAVAILABLE" } } ] } ``` > [!NOTE] > > **What is the difference between the payment and transaction fields?** > > A Primer payment can have multiple processor transactions. > > * The payment fields represent the latest/final values > * The transaction fields represent the values for that specific processor transaction > > *For example, if a payment is first declined on Stripe then successfully authorized on Adyen using fallback, the payment level reflects the final successful transaction, while the transaction fields shows all attempts.* These fields are also available in the output of the Payments App in Workflows, enabling you to run specific actions based on the underlying decline reasons. ## Supported processors and card networks The result codes are exposed for payments made with Visa and Mastercard on the following processors: * Stripe * Braintree * Adyen > [!NOTE] > > Please reach out to us directly via our [Service Desk](https://portal.support.primer.io/servicedesk/customer/portal/11) if you need support for additional processors. ## Card network decline codes ### Mastercard | Code | Message | | - | - | | 01 | Refer to card issuer | | 03 | Invalid merchant | | 04 | Capture card | | 05 | Do not honor | | 08 | Honor with ID | | 12 | Invalid transaction | | 13 | Invalid amount | | 14 | Invalid card number | | 15 | Invalid issuer | | 30 | Format error | | 41 | Lost card | | 43 | Stolen card | | 46 | Closed account | | 51 | Insufficient funds/over credit limit | | 54 | Expired card | | 55 | Invalid PIN | | 57 | Transaction not permitted to issuer/cardholder | | 58 | Transaction not permitted to acquirer/terminal | | 61 | Exceeds withdrawal amount limit | | 62 | Restricted card | | 63 | Security violation | | 65 | Exceeds withdrawal count limit | | 70 | Contact Card Issuer | | 71 | PIN Not Changed | | 72 | Account not yet activated | | 75 | Allowable number of PIN tries exceeded | | 76 | Invalid/nonexistent “To Account” specified | | 77 | Invalid/nonexistent “From Account” specified | | 78 | Invalid/nonexistent account specified (general) | | 79 | Life cycle (Mastercard use only) | | 80 | System not available | | 81 | Domestic Debit Transaction Not Allowed (Regional use only) | | 82 | Policy (Mastercard use only) | | 83 | Fraud/Security (Mastercard use only) | | 84 | Invalid Authorization Life Cycle | | 86 | PIN Validation not possible | | 87 | Purchase Amount Only, No Cash Back Allowed | | 88 | Cryptographic failure | | 89 | Unacceptable PIN—Transaction Declined—Retry | | 90 | Cutoff is in progress | | 91 | Authorization System or issuer system inoperative | | 92 | Unable to route transaction | | 94 | Duplication transaction detected | | 96 | System error | | 1Z | Authorization System or issuer system inoperative | | R0 | Stop payment order | | R1 | Revocation of authorization order | | R3 | Revocation of all authorizations order | ### Visa | Code | Message | | - | - | | 01 | Refer to card issuer | | 02 | Refer to card issuer’s special conditions | | 03 | Invalid merchant | | 04 | Pickup card (no fraud) | | 05 | Do not honor | | 06 | Error | | 07 | Pickup card, special condition (fraud account) | | 12 | Invalid transaction | | 13 | Invalid amount or currency conversion field overflow | | 14 | Invalid account number (no such number) | | 15 | No such issuer | | 19 | Re-enter transaction | | 30 | Format error | | 31 | Bank not supported by switch | | 34 | Suspected fraud | | 36 | Restricted card | | 39 | No credit account | | 40 | Requested function not supported | | 41 | Lost card, pick up (fraud account) | | 42 | Invalid account | | 43 | Stolen card, pick up (fraud account) | | 44 | Lost/stolen card | | 46 | Closed account | | 51 | Insufficient funds / Over credit limit | | 52 | No checking account | | 53 | No savings account | | 54 | Expired card or expiration date is missing | | 55 | Incorrect PIN or PIN missing | | 57 | Transaction not permitted to issuer/cardholder | | 58 | Transaction not permitted to acquirer | | 59 | Suspected fraud | | 60 | Exceeds approval amount limit | | 61 | Exceeds approval amount limit | | 62 | Restricted card (card invalid in region or country) | | 63 | Security violation (source is not correct issuer) | | 65 | Exceeds withdrawal frequency limit | | 70 | PIN data required | | 75 | Allowable number of PIN entry tries exceeded | | 76 | Unsolicited reversal | | 78 | “Blocked, first used” - Transaction from new cardholder, and card not properly unblocked | | 79 | Already reversed (by Switch) | | 81 | Cryptographic error found in PIN | | 82 | Negative Online CAM, dCVV, iCVV, or CVV results | | 86 | Cannot verify PIN | | 89 | Ineligible to receive financial position information (GIV) | | 91 | Issuer unavailable or switch inoperative | | 92 | Financial institution or intermediate network facility cannot be found for routing | | 93 | Transaction cannot be completed; violation of law | | 94 | Request is identified as a duplicate | | 96 | System malfunction | | 1A | Additional customer authentication required (Europe only) | | 5C | Transaction not supported/blocked by issuer | | 6P | Verification data failed | | 9G | Blocked by cardholder/contact cardholder | | N3 | Cash service not available | | N4 | Cash request exceeds issuer limit | | N7 | Decline for CVV2 failure | | P5 | Denied PIN unblock - PIN change or unblock request declined by issuer | | Q1 | Card authentication failed | | R0 | Stop payment order | | R1 | Revocation of authorization order | | R3 | Revocation of all authorizations order | # Timeouts Source: https://primer.io/docs/concepts/decline-codes/timeouts A timeout can occur when: 1. A [payment processor](/docs/get-started/connect-a-processor#what-is-a-processor%3F) takes too long to respond to a request. 2. A general request timeout occurs due to technical or unknown reasons within Primer's infrastructure. In API ≤v2.3 processor timeouts were included within a more general error decision type of `Application Error`. This included processor timeouts, processor errors and on rare occasions, internal Primer timeouts. Starting from API 2.4, processor timeouts will be split into their own error decision type of `Gateway Timeout`, and `Application Error` now only includes processor errors and on rare occasions, internal Primer timeouts. | | **Status** | **Error Decision Type** | **Error Decline Type** | **Error Decline Reason** | | - | - | - | - | - | | **Payment Processor Timeout** | As per the last status of the payment | `Gateway Timeout` | N/A | N/A | | **Payment Processor Errors & Primer Timeouts** | As per the last status of the payment | `Application Error` | N/A | N/A | > [!NOTE] > > To benefit from this change, ensure to [upgrade to API v2.4](/docs/changelogs/api-changelog#api-v2-4) and [update your Primer Payments App](/docs/workflows/apps/overview#managing-updates). ### Timeout Length Starting from API v2.4, our Payments API has a maximum timeout value of 90 seconds. Previously, when using API ≤v2.3, it was 25 seconds. **Why 90 Seconds?** 90 seconds allows sufficient time for external processors with long response times to handle requests. For context, most processors have a maximum timeout allowance between 60 and 70 seconds. The additional buffer accommodates any internal Primer operations, minimizing synchronization issues when external processor timeouts occur. If a request to a processor times out, the payment will retain its latest status. This means an authorization will remain PENDING, a capture request will stay AUTHORIZED, a refund request on a captured payment will stay SETTLED, and so on. This is to allow any potential recovery or updates, as a FAILED payment cannot be recovered. ### How You Should Handle Processor Timeouts 1. **Processor Timeouts (`Gateway Timeout`)** A `Gateway Timeout` indicates that the processor did not respond in time. In this case, you may verify the status of the authorization directly with the processor (via their dashboard or API). Some processors provide search endpoints to check the status of an authorization using your reference IDs. *Note: This behavior varies by processor. For instance, Stripe notes that processor timeouts rarely result in actual authorizations, but this is not guaranteed across all providers.* 2. **General Request Timeouts (`Application Error`)** Timeouts internal to Primer can theoretically occur at any point in the payment flow. They are however **very rare**, and the vast majority of payments with an `Application Error` will be due to an issue on the payment processors side. In this situation you can review the processor `Error Message` for details on what has occurred. ### What Happens Beyond 90 Seconds? When a payment takes longer than 90 seconds to process, the request is terminated, and the result is considered a timeout. At this point: * For processor timeouts, you can attempt to reconcile manually by checking the processor's system for the status of the authorization. # Filters & Dimensions Source: https://primer.io/docs/concepts/filters-and-dimensions ## What are filters and dimensions? A dimension provides a structured way to categorize and group payment data, facilitating comprehensive analysis and reporting, such as grouping payments by processor or payment method, to better understand trends and patterns in payment processes. When used as a filter, the dimension refines and narrows down payment data, allowing users to focus on specific aspects or criteria, such as payment methods or regions, to gain deeper insights and make informed decisions. ## Filters and dimensions ### General | Name | Description | | - | - | | Account Funding Type | The funding type of payment card used. Applicable for card, Apple Pay and Google Pay payment methods | | Account Usage Type | The usage type of payment card used. Applicable for card, Apple Pay and Google Pay payment methods | | Amount | The amount of the payment | | Bank Identification Number (BIN) | The first 6 digits of the payment card used. Applicable for card, Apple Pay and Google Pay payment methods | | Currency Code | The three letter ISO code for the currency of the payment | | Customer ID | The customer ID passed in with the payment | | Decision Type | Grouping for the type of error received for unsuccessful payments. Applicable where payment status is declined or failed | | Decline Reason | Additional information on the reason for declined payments. Applicable where decision type is issuer declined | | E-commerce Indicator (ECI) | The value returned during 3D Secure authentication indicating the outcome of the authentication request. Applicable for card, Apple Pay and Google Pay payment methods | | Issuer | The issuing bank for the payment card. Applicable for card, Apple Pay and Google Pay payment methods | | Issuer Country Code | The two letter ISO code for the country of issuance of the payment card. Applicable for card, Apple Pay and Google Pay payment methods | | MIT/CIT Payment | Indicates whether a payment was initiated by a customer directly (CIT), or by the merchant on behalf of the customer (MIT). Applicable where a payment type is passed in with a payment | | Merchant ID (MID) | The merchant account the payment originated from | | Metadata | The metadata passed in with the payment. Applicable where a metadata was passed in with the payment | | Network | The card network of the payment card. Applicable for card, Apple Pay and Google Pay payment methods | | Order Country Code | The two letter ISO code for the country passed in with the payment request. Applicable where an order country code was passed in with the payment | | Order ID | The order ID passed in with the payment | | Payment Method | The payment method used for the payment | | Payment Type | The transaction type associated with the payment, used to indicate if a payment was part of a recurring schedule | | Processor | The processor used for the payment. Applicable where a request to a processor was made | | Refunded | Indicates whether there is a refund associated with the payment | | Status | The status of the payment | ### 3DS | Name | Description | | - | - | | 3DS Challenge Issued | Indicates whether the cardholder was presented with a 3D Secure challenge screen | | 3DS Error Code | The error code returned during 3D Secure authentication. Applicable where 3D Secure authentication encountered an error. | | 3DS Initiator | Where the 3DS request was initiated from | | 3DS Protocol Version | The protocol version used for 3D Secure authentication. Applicable where 3D Secure authentication was included with the payment | | 3DS Reason Code | Description of the error experienced during 3D Secure authentication. Applicable where the 3D Secure response is auth failed or skipped | | 3DS Response Code | The 3D Secure authentication status of the payment | | 3DS Transaction Status | The transaction status of 3D Secure authentication. Applicable where 3D Secure authentication was included with the payment | | 3DS Transaction Status Reason | The descriptive reason for unsuccessful 3D Secure transaction statuses. Applicable where 3D Secure authentication was unsuccessful | ### Fallbacks | Name | Description | | - | - | | Fallback Processor | The fallback processor that was used for the payment | | Fallback Processor MID | The fallback processor MID that was used in the payment | | Fallback Processor Used | Indicates whether a fallback was attempted as part of the payment | | Fallback previous processor | The processor used initially that resulted in a fallback attempt | | Fallback previous processor MID | The processor MID used initially that resulted in a fallback attempt | # Metrics Source: https://primer.io/docs/concepts/metrics ## What is a Metric? A metric is a key performance indicator that provides essential data for evaluating and optimizing payment processes. Primer includes 20 metrics within our Dashboards and Monitors, and we're adding new data all the time. ## Metrics | Metric Name | Definition | | - | - | | Authorization rate | Main indicator of the performance of your payment flow. Calculated as the count of payments that reached the status SETTLED PARTIALLY\_SETTLED SETTLING or AUTHORIZED divided by the total number of payments that reached a processor.This metric ignores payments where
  • the status is PENDING FAILED or CANCELLED
  • the status is set to DECLINED before being sent to a processor (i.e. the declined payments that have [`processor.name`](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment#response-processor) set to `null`)
| | Sales count | The total number of settled sales | | Sales value (can be converted to any currency) | The total value of settled sales in the currency set in the Dashboard | | Refunds count | The total number of refunds | | Refunds value | The total value of refunds in the currency set in the Dashboard | | Refunds (% of sales value) | The refund value as a % of sales value. Calculated on date of sale created | | Average order value | The average value of settled sales | | Average refund value | The average value of settled refunds | | Payments count | The total number of payments created | | Payments count (authorized) | The total number of authorized payments | | Payments count (declined) | The total number of declined payments | | Payments count (failed) | The total number of failed payments | | Decline rate | Rate of declined vs successful payments | | 3DS authentication count | The total number of payments that had a 3DS request | | 3DS authentication count (failed) | The total number of payments that had a failed 3DS request | | 3DS authentication rate | The number of successful 3DS attempts divided by the total number of 3DS attempts. Excludes processor 3DS | | Recovered sales value | The total combined value of sales recovered by fallbacks & adaptive 3DS | | Recovered sales value (adaptive 3DS) | The total value of sales recovered by adaptive 3DS | | Recovered sales value (fallbacks) | The total value of sales recovered by fallbacks | | Fallbacks count | The total number of payments where a fallback was attempted | # Overview Source: https://primer.io/docs/concepts/overview ## Understand the foundations of Primer Learn how payments flow through Primer and explore the key concepts that power our platform. ![Understand the foundations of Primer](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/concepts/banner/light.png) ## Learn about Primer > [card] [Primer Payment](/docs/concepts/primer-payment) > > Learn about Primer's payment model and creation process > [card] [Payment Lifecycle](/docs/concepts/payment-lifecycle) > > Understand how payments flow through the Primer system > [card] [Currencies](/docs/concepts/currencies) > > Learn about currency handling in Primer > [card] [Payment Timeline](/docs/concepts/payment-timeline) > > Track the chronological events in a payment's lifecycle > [card] [Payment Method Token](/docs/concepts/payment-method-token) > > Understand how payment methods are tokenized and stored > [card] [Decline Codes](/docs/concepts/decline-codes/overview) > > Explore payment decline reasons and timeout scenarios > [card] [Metrics](/docs/concepts/metrics) > > Understand key payment metrics and analytics > [card] [Filters & Dimensions](/docs/concepts/filters-and-dimensions) > > Learn how to analyze and segment your payment data # Payment lifecycle Source: https://primer.io/docs/concepts/payment-lifecycle All Primer payments conform to a unified payment lifecycle, which makes them work the same way regardless of the payment services you need. A payment always has a **payment status**. Each payment will progress through some combination of the statuses listed below on their way through your workflow. A newly-created payment is assigned the status PENDING. ![payment lifecycle](https://goat-assets.production.core.primer.io/marketing/external-docs/concepts/payment-lifecycle/payment-lifecycle.png) Payment lifecycle > [card] > > PENDING > > The payment is awaiting a subsequent action or callback. This usually occurs with asynchronous processors. Prepare for this contingency by [setting up Webhooks](/docs/api-reference/get-started/configure-webhooks). > [card] > > AUTHORIZED > > The processor has authorized the payment and no further status-altering actions > have been defined in your Workflow. > [card] > > SETTLED > > PARTIALLY\_SETTLED > > The processor has settled funds in your account. If the entirety of the payment amount has been settled, the payment will have the status SETTLED. > > Some processors allow for the [capture of only a part of the authorized amount](/docs/api-reference/v2.4/api-reference/payments-api/capture-a-payment#body-amount). If you leverage this capability, the payment status will be set to PARTIALLY\_SETTLED. > [card] > > DECLINED > > The processor has declined the payment and no further status-altering actions have > been defined in your Workflow. You may want to consider retrying certain declined > payments. > [card] > > FAILED > > This usually occurs when there is a processor gateway issue, such as a service > disruption. Set up retries and [fallbacks](/docs/payment-services/fallbacks) to mitigate > failures. > [card] > > CANCELLED > > The payment was canceled prior to it being settled. > [card] > > SETTLING > > The payment has been submitted for settlement and funds will be settled later. > This usually occurs with asynchronous processors. Prepare for this contingency > by [setting up Webhooks](/docs/api-reference/get-started/configure-webhooks). ### Enforcing the payments lifecycle The [Payments API](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) enforces our payments lifecycle state machine and returns a validation error if an API call is attempted where the payment status doesn't support that action. > [!NOTE] > > The error status code returned is `400` with `errorId` = `InvalidPaymentStatus` See below for the breakdown of the API requests and what's supported for each payment status (table scrolls horizontally): | API Request | PENDING | AUTHORIZED | SETTLING | SETTLED | PARTIALLY\_SETTLED | CANCELLED | DECLINED | FAILED | | :- | - | - | - | - | - | - | - | - | | `POST /authorize` | Allow | Block | Block | Block | Block | Block | Allow | Allow | | `POST /cancel` | Allow | Allow | Allow | Block | Block | Block | Block | Block | | `POST /capture` | Block | Allow | Allow | Block | Allow | Block | Block | Block | | `POST /decline` | Allow | Block | Block | Block | Block | Block | Block | Block | | `POST /refund` | Block | Block | Block | Allow | Allow | Block | Block | Block | > [!WARNING] > > Processors may not support all the actions for each payment status outlined in the above table e.g. some processors may support cancelling a SETTLING payment, whilst others may not. # Payment method token Source: https://primer.io/docs/concepts/payment-method-token A payment method token is a string representing sensitive payment method credentials and customer data. Primer provides [Universal Checkout](/docs/checkout/checkout-builder), our all-in-one Checkout SDK, to securely capture payment method data while fully embedded on your site or in your app. By communicating directly with Primer's PCI-L1 tokenization service, Universal Checkout transforms sensitive customer data into a secure uniform string called a **payment method token**. Universal Checkout generates a payment method token regardless of the customer's chosen payment method. This enables you to reason about your checkout flow in a unified way. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/concepts/payment-creation/payment-creation.png) Payment creation > [!NOTE] > > Our agnostic tokenization service and centralized vault enable you to handle [recurring payments](/docs/get-started/recurring-payments), fallbacks, and retries across processors without compromising UX. > > No more PSP-specific tokens — now **you** own your payment data. ## Get a payment method token The Payments API requires a payment method token to create a payment. You can get a payment method token from: * Universal Checkout (see [Manual Payment Creation](/docs/checkout/advanced/manual-payment-creation)) * Primer’s unified vault (see [Save payment methods](/docs/payment-services/save-payment-methods)) # Payment timeline Source: https://primer.io/docs/concepts/payment-timeline Available for every payment in the Dashboard, the payment timeline is the best representation of a payment on Primer. It displays all attributes of the payment, as well as the entire series of events that have taken place throughout its lifecycle. ## How to find the payment timeline Navigate, search and filter your payments with an easy-to-use interface in the [Payments](https://dashboard.primer.io/payments) section of the Primer Dashboard. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/concepts/payment-timeline/payments-timeline.png) Payments timeline Select a payment to see its detailed timeline of events. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/concepts/payment-timeline/payment-timeline-view.png) Payment timeline view **Primer is not a black box, but rather your payments infrastructure**. Select a specific event to see the requests and responses, providing full transparency into everything that’s happened to your payment throughout its journey. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/concepts/payment-timeline/payment-details.png) Payment details # Primer Payment Source: https://primer.io/docs/concepts/primer-payment A **Payment** is a first-class object that unifies the representation of a user payment across all your processors or payment methods. A Primer payment is made of: * a **payment status** that conforms to a unified payment lifecycle * **payment method information** such as card details * **order details** such as line items and currency * **customer details** such as contact information, shipping, and billing address * a **timeline** of events created throughout the lifecycle of the payment ![](https://goat-assets.production.core.primer.io/marketing/external-docs/concepts/what-is-a-payment/what-is-a-payment.png) What is a Payment? > [!NOTE] > > You may be familiar with the **transaction** concept used by many payment processors. Because a single Primer payment can go through multiple processors via fallbacks, retries or split routing, it can contain multiple transactions, all of which are clearly displayed on the payment's timeline. Payments are created automatically by Universal Checkout - our unified client-side SDK - or manually by sending a request to the Payments API. In both cases, the following data is required to create a payment: * An **order ID** * An **amount** (or a list of **line items**), and a **currency code** * A **payment method token** ### Order ID The Order ID offers a simple way for you to tie one or multiple payments to an order in your system. > [!NOTE] > > You can reuse the same order ID for multiple payments. This is handy to link multiple payments together. ### Line items and currency They describe the total amount and the currency that will be sent to the processor to authorize and capture the payment. # Connect a processor Source: https://primer.io/docs/get-started/connect-a-processor ## What is a processor? A payment processor (or "PSP") facilitates electronic payments between merchants and customers. Payment processors provide a variety of services, including the ability to accept and process credit and debit card payments as well as enabling other types of payment methods. Payment processors handle the technical aspects of processing payments, including communicating with the various financial networks and banks involved in the transaction. Primer has integrated with many processors, including Stripe, Braintree, and Adyen. Through Primer, you can simply connect to any processor with no-code and begin routing payments to them based on your needs and requirements. > [!NOTE] > > You need at least one processor connected to begin processing payments through Primer. ## How to add a processor Simply set up the connection by following the steps below to enable Primer to communicate with the processor on your behalf: 1. Select the processor you want to add via the Primer Dashboard 2. Give Primer access to your processor account 3. Choose which payment methods you wish to enable for the processor ### 1. Select the processor you want to add via the Primer Dashboard Navigate to the [Integrations](https://dashboard.primer.io/integrations?status=active) section on the Primer Dashboard. You will see your existing connected processors and the ability to add a new integration via the *' + New integration'* button in the top right corner. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/connect-a-processor/integrations-home.png) Integrations Section > [!NOTE] > > In Primer's Sandbox, you will have the Primer test processor automatically configured so you can begin testing your integration straightaway! Once you select *' + New integration'*, you can browse the available processors and find your processor of choice. Find more details about the processor by selecting *'More Info'* and when you're ready, continue to add the integration. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/connect-a-processor/integrations-marketplace.png) Integrations Marketplace ### 2. Give Primer access to your processor account Depending on the processor, you will now either have to enter your account credentials or you will be redirected to the processor to log in and connect your account. As this varies per processor, there are instructions on how to obtain the credentials, so it's recommended to follow these. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/connect-a-processor/adyen-credentials-guide.png) Example of guide to obtaining credentials There may be some additional setup steps required based on the functionality you want and the way the processor works. These are also clearly presented and easy to follow. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/connect-a-processor/adyen-setup-instructions.png) Example of setup instructions You will then need to add your merchant account(s) for the processor. > [!NOTE] > > Depending on the processor, sometimes this step is done for you. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/connect-a-processor/adyen-integration-home.png) Connected integration page ### 3. Choose which payment methods you wish to enable for the processor Activate any non-card payment methods supported by the processor for each merchant account. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/connect-a-processor/adyen-add-merchant-account.png) Example of adding a merchant account Once turned on, you can configure when these payment methods should be shown to your customer in the [Checkout](https://dashboard.primer.io/checkout) section of the Dashboard. > [!NOTE] > > Some payment methods have specific requirements when adding them to your checkout flow. Make sure to check the [Connections section](/docs/connections/payment-methods/overview) for all requirements. # Create a Workflow Source: https://primer.io/docs/get-started/create-workflow ## What is a workflow? When a payment is created, you need to determine where to route the payment - this is where [Workflows](/docs/workflows/overview) comes in. Workflows enable you to build end-to-end payment automation flows without writing any code. A workflow is necessary to dynamically process payments created via Primer. Primer gives you all the building blocks to create and manage your workflows based on your own business logic and requirements. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/workflow-preview.png) Workflow Example ## How to create a workflow [https://www.loom.com/embed/49eb7bc205af45b3bbac17589f2bca9f](https://www.loom.com/embed/49eb7bc205af45b3bbac17589f2bca9f) Head to the Workflows section of the Dashboard to create your first workflow. ### Start from a template When creating a new workflow, you can browse all available [templates](/docs/workflows/templates) that Primer has made available for a wide array of use cases, such as Payment Orchestration and Operational Efficiency. A template, same as a workflow, consists of a [Trigger](#select-a-trigger) and multiple blocks ([Utilities](/docs/workflows/utilities/workflow-utilities/), or [actions](#add-actions) with Inputs already set up). Each template covers a very specific use case but you can always tailor the workflow according to your requirements once you have added it to your account. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/templates-list.png) Templates List ### Start with a blank workflow If you do not want to use an existing template but start from scratch, you can also build a workflow on your own by choosing an [app's](/docs/workflows/apps/native-apps/overview) trigger. #### Select a Trigger Creating a workflow from scratch always starts with the selection of an app and one of its Triggers. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/trigger-list.png) List of Apps and Triggers Choosing this Trigger is critical: your workflow will start executing every time an app emits an event matching that Trigger. For example, you can start a workflow when: * a payment is created via the Payments app * a payment status is updated via the Payments app * a monitor event is created via the Monitors app * a dispute status is updated via the Disputes app * an Onfido KYC result is received via the Onfido app ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/create-workflow.png) Create workflow In our example, we want to run our workflow each time a payment is created. The "Payment created" Trigger from the [Payments App](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) is perfect for this. Once the Trigger has been selected, your workflow will be in draft mode. This workflow will not be live until you publish it. The Trigger will produce a set of output values that you can use in the next workflow block to build upon. With only a Trigger on the canvas, the workflow is not actively doing anything just yet. Now we can start adding some actions. ### Add actions Actions can be added to a workflow to perform tasks, such as: * sending a message to Slack * creating a task on Asana * authorizing a Payment using the [Payments App](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) with a payment processor Add an action after a trigger, or after any block in the workflow. You can add more than one action to build flows with multiple blocks. Click on the action that you want to use and drag it onto the canvas, you will see placeholders where you can drop an action. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/drag-drop-new.gif) Drag and drop Each action has to be configured with a set of input values. These values are critical for the action to successfully complete its task. For instance: * “Send a message to Slack“ needs to know what message to send, and to which Slack channel * “Create a task on Asana” needs to know under which project to create the task, as well as its title and description. * “Authorize a payment” needs to know which payment to authorize, and which processor to use ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/add-action.png) Add action These input values can come from different places: * From a Trigger: e.g. the ”Authorize payment” action can use the payment ID from the “Payment created” Trigger * From a previous action: e.g. the ”Send a message to Slack” action can use the task URL provided by the “Create a task on Asana” task * Set up manually: e.g. you can specify the slack channel for the ”Send a message to Slack” action Actions are automatically executed when the previous action or trigger is successfully completed. Similarly to Triggers, an action produces output values that are available downstream. This enables you to chain multiple actions together, each being able to make use of outputs of previous blocks. ### Publish your workflow To process a payment, you will need at least one workflow that is made of the following blocks: 1. ["Payment created" trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) 2. ["Authorize payment" action](/docs/workflows/apps/native-apps/primer-payments-app/authorize-payment-action) You can also set up other payment actions in the workflow, including ["Capture"](/docs/workflows/apps/native-apps/primer-payments-app/capture-payment-action), ["Refund"](/docs/workflows/apps/native-apps/primer-payments-app/refund-payment-action) and ["Cancel"](/docs/workflows/apps/native-apps/primer-payments-app/cancel-payment-action). See the [Payments App](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) section to learn more. Before you publish your workflow, we validate that all blocks are properly configured. Any incomplete blocks are highlighted so that you can apply the necessary fixes. Learn more about [validation](/docs/workflows/workflow-validation). ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/validation-steps.png) Workflow validation Once all blocks are correctly configured, the "Publish" button becomes enabled and you can proceed with publishing your workflow. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/publish-workflow.png) Publish workflow If everything is in order... congratulations, you have just created and published your first workflow. From now on, your workflow will be executed whenever an app emits an event matching that trigger. In the case of this workflow, the payment will be authorized every time a payment is created. If anything doesn't work as intended, check our [monitor workflows](/docs/workflows/monitor-workflows/overview) guide to learn how to troubleshoot your workflows. On the Workflows overview page you can see all your published workflows, as well as draft and archived workflows. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/workflows-overview.png) Workflows overview Once published, you can still edit your workflow. The changes will be saved as a draft first, but you can always promote your draft by publishing again. You also have the option to archive a workflow to prevent any new executions. Workflows that have never been published can even be deleted, as no runs are associated with them. ## Use Utilities The workflow we just created is very simple as it runs linearly from left to right. [Utilities](/docs/workflows/utilities/workflow-utilities/) help you create more complex workflows, like using the [Conditions](/docs/workflows/utilities/conditions-block) or [Split](/docs/workflows/utilities/split) Utility to branch a workflow into multiple routes. Conditions exist on two levels: either on the Trigger itself (**"Trigger Conditions"**) or as a Utility within your workflow route. ### Workflow Conditions Conditions within the workflow allow you to create multiple routes. For example to run a different set of actions depending on the country of the payment: ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/multi-conditions.png) Multi conditions > [!WARNING] > > Only one route is executed at a time. If multiple routes have their conditions met, only the top-most route will be executed. Be mindful that this only applies to conditions within the workflow. ### Trigger Conditions Trigger Conditions enable you to set conditions for when to actually start a workflow. For example executing a “Payment created” Trigger only for Ecommerce payments, or split payment workflows by payment method, or have different workflows depending on specific shipping updates. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/create-workflow/trigger-condition.png) Trigger Condition > [!WARNING] > > Be mindful when setting up the conditions when to start a workflow, as otherwise you are risking starting more than one workflow if the set-up is not explicit enough, or no workflows at all if the set-up is too restrictive. Learn more about [Utilities](/docs/workflows/utilities/workflow-utilities/) or learn about recommendations for granular flows in our [best practices guide](/docs/workflows/best-practices). ## Start automating You are now able to supercharge your payment stack with the power of Workflows. To build more powerful workflows, we encourage you to: * Learn about the [Payments App](/docs/workflows/apps/native-apps/primer-payments-app) * Check our guide to [monitor workflows](/docs/workflows/monitor-workflows) * Learn more about Workflows [best practices](/docs/workflows/best-practices) # Explore your payments Source: https://primer.io/docs/get-started/explore-your-payments There are two ways you can get visibility of your payments, regardless of which state they are in: > [card] Payment timeline in the Primer Dashboard > > Easy-to-use UI to browse and review the details of all your payments. > [card] Payments API > > Retrieve details of your payments programmatically via API. ### Payment timeline Access all your Primer payments from the payments list in the Primer Dashboard, where you can navigate, search and filter your payments with an easy-to-use interface. Each payment has a [payment timeline](/docs/concepts/payment-timeline), which shows a detailed view of all events, providing full transparency into everything that's happened to your payment. ### Payments API To retrieve your payments programmatically, you can either: * retrieve a single payment using the Primer payment ID - see the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) for more. * search and retrieve a list of payments - see the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/search-&-list-payments) and [specific guide](/docs/manage-payments/search-payments) for more. # Welcome to Primer Source: https://primer.io/docs/get-started/overview This guide will walk you through everything you need to know to integrate and optimize your payment infrastructure. From setting up workflows and connecting processors to implementing your checkout and managing recurring payments, you’ll find comprehensive resources to help you build a robust payment system. ![AI coding assistants](https://mintcdn.com/primer-cc826789/8hPDq8yMulNB9g_E/images/getting-started/build-with-ai.png?fit=max\&auto=format\&n=8hPDq8yMulNB9g_E\&q=85\&s=bfc838a667b4397d87157d928e1f6e0c) ## [AI coding assistants](/docs/checkout/primer-checkout/resources/build-with-ai) Install Primer's Claude Code skills or the Context7 MCP server so your assistant works from accurate documentation. ## Quickstart guide > [card] [1. Connect a processor](/docs/get-started/connect-a-processor) > > Choose and connect your preferred payment provider in just a few clicks. > [card] [2. Create a workflow](/docs/get-started/create-workflow) > > Build automation to route payments, handle errors, and trigger downstream actions. > [card] [3. Set up universal checkout](/docs/get-started/set-up-a-checkout) > > Customize and launch a flexible checkout that works across devices and regions. > [card] [4. Set up payment updates](/docs/get-started/payment-updates) > > Keep your systems in sync with real-time status updates via workflows or webhooks. > [card] [5. Explore your payments](/docs/get-started/explore-your-payments) > > Get full visibility into the journey of each payment, so you can easily see what's going on. > [card] [6. Recurring payments](/docs/get-started/recurring-payments) > > Manage your recurring payments seamlessly with our Payments API. ## Roll out new payment methods as your business expands [Explore connections →](/docs/connections/payment-methods/overview) ![Start testing](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/testing/banner/light.png) ## [Start testing](/docs/testing/overview) Primer brings together all your preferred payment services in a single, easy-to-implement integration. # Set up payment updates Source: https://primer.io/docs/get-started/payment-updates Payments have a lifecycle. Primer has simplified learning payments and standardized the payment lifecycle for all processors. This way, you only need to rationalize about payments once. You can learn more about Primer's payment lifecycle [here](/docs/concepts/payment-lifecycle). ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/payment-updates/payment-lifecycle.png) Primer's payment lifecycle As the payment is processed and goes through its lifecycle, you can get updates on the payment's state in two ways: > [card] [Universal Checkout events](#universal-checkout-events) > > Update your frontend UI with callbacks via the Primer SDK. > [card] [Payment webhooks](#payment-webhooks) > > Receive payment notification events directly to your server. ## Universal Checkout events The [Primer SDK](/docs/sdk/web/v2.x.x/installation) has various event callbacks you can listen to. These callbacks include `onCheckoutComplete()` and `onPaymentMethodAction()`. These are useful for updating the UI of your application, for example, to show loading indicators, success screens or failure screens. However, as these are client-side, it's not the best practice to rely on these callbacks as the single source of truth. For this, it's recommended to rely on payment webhooks. ## Payment webhooks Primer can also send [webhook](/docs/api-reference/get-started/configure-webhooks) notification events to your server. These should be used to update the status of the payment on your server. See more details about the expected webhook payloads in our [API reference](/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-status-update). ### Handle the Payment's Lifecycle All Primer payments conform to a [unified payment lifecycle](/docs/concepts/payment-lifecycle). Each payment will progress through some combination of the [payment statuses](/docs/concepts/payment-lifecycle) on their way through your workflow. # Recurring payments Source: https://primer.io/docs/get-started/recurring-payments Primer supports merchant-initiated payments (MITs) for recurring and subscription business models. You can use Primer's Payments API to create these payments. > [!NOTE] > > Working out which `paymentType` to send? **One-off payments** have no dedicated payment type. See [Choose the right payment type](#choose-the-right-payment-type). ## Before you start Before you start, make sure you are ready to [process a payment](/docs/get-started/connect-a-processor). ## Generate an API key Ensure you have [an API key configured](/docs/api-reference/get-started/authentication). Make sure to set the following scopes for your API Key: * `client_tokens:write` * `transactions:authorize` ## Get a payment method token The Payments API requires a [payment method token](/docs/concepts/payment-method-token#get-a-payment-method-token) to create a payment, so make sure you [save the payment method](/docs/payment-services/save-payment-methods) on the first payment so you have a vaulted token for MITs. ## Choose the right token type Primer uses two token types, one for each point in the payment lifecycle: * A **single-use token** is generated by Universal Checkout each time a customer enters their details. It's short-lived and authorizes one payment — use it for the customer's **first** payment. See [Payment method token](/docs/concepts/payment-method-token). * A **multi-use token** (also called a *vaulted token*) represents a payment method stored in [Primer's Vault](/docs/payment-services/save-payment-methods). It's long-lived and reusable — use it for **subsequent** merchant-initiated payments. > [!NOTE] > > You don't have to vault a card yourself before the first payment. Pass a single-use token with `paymentMethod.vaultOnSuccess` (or `vaultOn3DS`) set to `true`, and Primer vaults the card for you as part of that first payment, returning a multi-use token you can reuse later. See [Save payment methods](/docs/payment-services/save-payment-methods). ### Valid combinations Match the token type to the [payment type](#payment-types) you are sending: | Payment type | Initiation | Token type to use | | - | - | - | | Omitted (one-off) | Customer-initiated (CIT) | Single-use token | | `FIRST_PAYMENT` | Customer-initiated (CIT) | Single-use token | | `ECOMMERCE` | Customer-initiated (CIT) | Single-use token for a one-off, multi-use (vaulted) token for a saved payment method | | `SUBSCRIPTION` | Merchant-initiated (MIT) | Multi-use (vaulted) token | | `UNSCHEDULED` | Merchant-initiated (MIT) | Multi-use (vaulted) token | > [!WARNING] > > Always use a **single-use token** for `FIRST_PAYMENT`. > > `FIRST_PAYMENT` tells Primer to store the credential and capture the scheme data (such as the `Network Transaction ID`) that optimizes every later payment. Sending it with an already-vaulted token is contradictory — the credential is already stored — and prevents Primer from applying the correct stored-credential logic, which can cause processing issues. To store a card during the first payment, use a single-use token with `vaultOnSuccess` instead of vaulting up front. ### Recommended flow The correct end-to-end flow for storing a card on the first payment and reusing it later: 1. **First payment** — capture the card with Universal Checkout to get a **single-use token**, then create the payment with `paymentType: FIRST_PAYMENT` and `vaultOnSuccess: true` (optionally set [`firstPaymentReason`](#payment-types) to match your intent — `Recurring`, `Unscheduled`, or `CardOnFile`). Primer authorizes the payment and, on success, vaults the card and returns a **multi-use token**. 2. **Subsequent payments** — reuse the **multi-use token** for later merchant-initiated payments, sending `paymentType: SUBSCRIPTION` (fixed schedule and amount) or `UNSCHEDULED` (no fixed schedule or amount). ```bash theme={"dark"} # 1. First payment — single-use token, vault on success curl --location --request \ POST 'https://api.sandbox.primer.io/payments' \ --header 'X-Api-Key: ' \ --header 'X-Api-Version: 2.4' \ --header 'X-Idempotency-Key: ' \ --data '{ "orderId": "", "amount": 800, "currencyCode": "GBP", "paymentMethodToken": "", "paymentMethod": { "paymentType": "FIRST_PAYMENT", "firstPaymentReason": "Recurring", "vaultOnSuccess": true } }' ``` ```bash theme={"dark"} # 2. Subsequent payment — reuse the multi-use (vaulted) token curl --location --request \ POST 'https://api.sandbox.primer.io/payments' \ --header 'X-Api-Key: ' \ --header 'X-Api-Version: 2.4' \ --header 'X-Idempotency-Key: ' \ --data '{ "orderId": "", "amount": 800, "currencyCode": "GBP", "paymentMethodToken": "", "paymentMethod": { "paymentType": "SUBSCRIPTION" } }' ``` ## Send a payment request > [!NOTE] > > See our [API Reference](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment) for more details Below is a minimal payment request example: ```bash theme={"dark"} curl --location --request \ POST 'https://api.sandbox.primer.io/payments' \ --header 'X-Api-Key: ' \ --header 'X-Api-Version: 2.4' \ --header 'X-Idempotency-Key: ' \ --data '{ "orderId": "", "amount": 800, "currencyCode": "GBP", "paymentMethodToken": "", }' ``` > [!NOTE] > > See [Optimize for recurring payments](#optimize-for-recurring-payments) below for more information When you create a payment, it will start your workflow with a ["Payment created" trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger). Learn more about processing payments [here](/docs/get-started/connect-a-processor). Any change in the payment's status (e.g. once it is AUTHORIZED) will trigger a `PAYMENT.STATUS` webhook notification event. Learn more about webhooks [here](/docs/api-reference/get-started/configure-webhooks). ### Recover declined or failed payments A declined transaction doesn't necessarily have to mean the end of the road for your payment. When authorization is declined by the card issuer or processor gateway, a [`statusReason`](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment#response-status-reason) object is returned in response to your payment request, providing a decline `code` and processor `message` (if available) with further information that can help you recover the payment. You can also see this information on the payment's [`Timeline`](/docs/concepts/payment-timeline) in the Dashboard. * **Hard declines** include reasons like invalid information, a closed account, or because the card owner reported the card lost or stolen. These cannot be retried with the existing `paymentMethodToken` because the payment can never be successfully authorized unless the payment method data is changed. (Your customer's expired card, for example, will never *un*expire.) * **Soft declines** indicate that authorization wasn't possible due to conditions that in some cases may only be temporary, like when the card limit has been exceeded or the issuer is unavailable. It may be possible to complete these payments successfully at a later time with the same information captured in the initial attempt. In these cases, you can use the same `paymentMethodToken` to attempt authorization again. Issues like latency or service disruption at the processor's gateway are usually the cause of **FAILED** payments, but these can also occur when a configuration error prevents the request from being processed. These transactions may also be successful on a later attempt in the event that there was a technical issue, but you should make sure everything is configured correctly before you retry the payment. ### Handle payment errors Set up [Webhooks](/docs/api-reference/get-started/configure-webhooks) to receive information about declined and failed payments and consume the data contained in the `statusReason` object to handle next steps, or consider setting up a fallback or retry scenario in Workflows. Information about HTTP error responses (`4XX`) when making an API call to Primer can be found in the [Errors](/docs/api-reference/get-started/api-responses#error-responses) section of the [API Reference](/docs/api-reference/get-started/overview). ## Optimize for recurring payments Payments are tied together through the `Network Transaction ID`, the ID assigned by card networks to an initial payment in a series of payments. Subsequent payments can then be routed to any processor, rather than being tied to the processor used for the initial authorization. For Mastercard, Primer also captures and sends the Transaction Link ID (TLID) on supported processors. See [Mastercard Transaction Link ID (TLID)](#mastercard-transaction-link-id-tlid) below. While the `Network Transaction ID` is a universal value, every [processor](/docs/get-started/connect-a-processor) has additional, unique requirements around what data is sent for payments made using a stored payment method. Normally you would need to calculate these requirements yourself on a processor by processor basis, but at Primer we handle these fields for you. Let's take a common example - processing subscriptions, using three different processors. For various reasons, including fee and authorization rate optimization, a customer's card could be against any one of those processors throughout the life of their subscription. But each processor has different requirements: | | Code Requirement | Context | | - | - | - | | **Processor 1** | - *merchant\_initiated: recurring* - *first\_stored: 01/01/1970* | - The type of merchant initiated transaction - Where the card was first stored. | | **Processor 2** | - *payment\_type: subscription* - *customer\_present: false* - *externally\_stored: true* | - The type of merchant initiated transaction - If the customer is present - Whether the card was stored with the processor or elsewhere | | **Processor 3** | - *charge\_intent: subscription* | - The type of merchant initiated transaction | Managing these differing needs adds considerable complexity to the already elaborate task of running a subscription business; and that's without considering all of the other intricacies managing multiple processors can bring. **Primer therefore manages this complexity for you.** We store the mapping for each processor and calculate the correct fields to send for each transaction. Our internal logic reviews multiple inputs, including if the customer is present at the point of making the payment, whether the payment method has been stored before and what type of payment method is being used. Importantly, we also take into account the **payment type** you pass in your payment request. While the parameter isn't mandatory, we recommend including it - both for your own reporting and to ensure your intent for the payment is aligned with the fields we calculate. Using this wealth of information, Primer can automatically calculate the correct fields to send to any processor. During this process we also store and handle the related acquirer and scheme data in order to increase approvals. > [!WARNING] > > Note: this logic is present in API v2.4 onwards. We recommend [upgrading to API v2.4](/docs/changelogs/migration-guides/API-2.3-to-2.4) as soon as possible and in the interim, always passing the `paymentType` parameter when processing recurring payments with API ≤v2.3. ### Mastercard Transaction Link ID (TLID) The Transaction Link ID (TLID) is a unique identifier that Mastercard generates for a customer-initiated transaction (CIT). Mastercard requires every later merchant-initiated transaction (MIT) in the same series, such as a subscription renewal or an unscheduled charge, to carry the TLID from the original CIT. The TLID works alongside the `Network Transaction ID`. It does not replace it, and Primer sends both. | Date | What happens | | - | - | | 23 October 2026 | Every Mastercard MIT must carry the TLID from the original CIT. | | 1 December 2026 | Comply-by date. Some acquirers communicate slightly different dates. | | 31 January 2027 | Mastercard starts assessing non-compliance fees. | #### How Primer handles the TLID * When a payment saves a card to Primer's vault, Primer stores the TLID returned by the processor on the saved card. * On every MIT made with that card, Primer sends the stored TLID to the processor. * Cards saved before TLID support pick up a TLID on their next payment. Every MIT after that carries it. This happens automatically. You don't need to change your integration. If your processor stores the card itself (processor-native tokens), the processor handles the TLID. Check with your processor if you have questions. #### Processor coverage * **Live:** Adyen, Checkout.com, Cybersource, Nuvei, Stripe, and processors connected through [Primer for Partners](/docs/connections/primer-for-partners/overview). * **Coming soon:** Worldpay, once Worldpay releases TLID on its side. For Worldpay, ask your Worldpay account manager to enable TLID for your merchant codes. * **Other processors:** Primer adds support as each processor releases TLID on its side. If your processor has confirmed it supports TLID and it isn't listed here, contact your account manager and we'll make sure it's supported. ### Payment Types #### Choose the right payment type Use the table below to pick the values to send for each scenario. | Your scenario | `paymentType` | Other fields to send | Token type | | - | - | - | - | | **One-off payment**: the customer pays once and you are not storing the payment method | Omit it, or send `ECOMMERCE` if you prefer to be explicit | `vaultOnSuccess` and `vaultOn3DS` left unset or `false` | Single-use | | **First payment, storing the card for future customer-initiated payments** ("card-on-file") | `FIRST_PAYMENT` | `vaultOnSuccess: true`, `firstPaymentReason: CardOnFile` | Single-use | | **First payment, storing the card for future merchant-initiated payments** | `FIRST_PAYMENT` | `vaultOnSuccess: true`, `firstPaymentReason: Recurring` (fixed schedule) or `Unscheduled` | Single-use | | **Customer pays with a payment method they saved earlier** | `ECOMMERCE` | None | Multi-use (vaulted) | | **Merchant-initiated payment on a fixed schedule and set amount** | `SUBSCRIPTION` | None | Multi-use (vaulted) | | **Merchant-initiated payment with no fixed schedule or amount** | `UNSCHEDULED` | None | Multi-use (vaulted) | > [!NOTE] > > **The Payments API has no `ONE_OFF` payment type.** For a one-off payment, leave `paymentType` unset; on v2.4, Primer works out the correct one-off fields for the processor. `ECOMMERCE` behaves the same, and makes your intent explicit on the payment. > [!TIP] > > Prefer omitting `paymentType`, or sending `ECOMMERCE`, over `FIRST_PAYMENT` for a one-off payment. > > On v2.4, all three resolve to a one-off as long as `vaultOnSuccess` and `vaultOn3DS` are false. Existing integrations sending `FIRST_PAYMENT` for one-off payments keep working and need no migration. But `FIRST_PAYMENT` states that further payments will follow on the same credential, so it stops being accurate the moment you add a save-card option to the flow: the payment is then treated as the first of a series at the processor. Omitting `paymentType` or sending `ECOMMERCE` stays correct either way. #### Additional parameters **paymentMethod -> paymentType** * *Omitted*: a one-off customer-initiated payment. * `FIRST_PAYMENT`: a customer-initiated payment that is the first in a series, such as subscriptions, unscheduled transactions, or "card-on-file" scenarios. * `ECOMMERCE`: Customer-initiated payment where the cardholder is present, either as a one-off or using a stored payment method. * `SUBSCRIPTION`: Merchant-initiated payment as part of a series of payments on a fixed schedule and for a set amount. * `UNSCHEDULED`: Merchant-initiated payment using stored payment details with no fixed schedule or amount. If you are storing a payment method for the first time, it is also recommended you pass the relevant `paymentMethod.firstPaymentReason` to indicate why the payment method is being stored. **paymentMethod -> firstPaymentReason** * `CardOnFile`: For "card-on-file" scenarios, correlating with the ECOMMERCE paymentType. * `Recurring`: For future subscription payments, correlating with the SUBSCRIPTION paymentType. * `Unscheduled`: For future unscheduled payments, correlating with the UNSCHEDULED paymentType. This field is particularly relevant for processors that rely on precise card storage logic. We recommend setting the correct value when storing cards for a specific purpose, as this ensures compliance with processor requirements and optimizes performance. *Note: Many processors benefit from the `firstPaymentReason` field for enhanced payment flows and compliance. While the implementation is complete for several key processors (e.g., Adyen, Cybersource, MPGS, Checkout), we continue to expand support to provide a seamless experience across additional platforms.* ## Avoid duplicated payments Primer supports a request idempotency mechanism for our Payments API. This optional feature enables you to safely retry a request without risking the user being charged or refunded multiple times. To make an idempotent request, generate an idempotency key and pass it to the header `X-Idempotency-Key`. ```bash theme={"dark"} curl -X POST 'https://api.primer.io/' \ --header 'X-Idempotency-Key: ' ``` Example idempotency error response: ```json JSON theme={"dark"} { "error": { "errorId": "TransactionRequestIdempotencyKeyAlreadyExists", "description": "Transaction request already exists with idempotency key 'IDEMPOTENCY_KEY'.", "diagnosticsId": "3233041960986039254", "validationErrors": [], "paymentId": "6gHJtooK6", "paymentStatus": "SETTLED" } } ``` > [!NOTE] > > `paymentId` and `paymentStatus` are only available from API version 2.2 onwards If an API call fails due to the request being invalid, due to a network issue, or if Primer is momentarily unavailable, make another request with the same idempotency key: * If a request with the same idempotency key has already been successfully processed by Primer, the new request will be ignored. A `400` error will be returned with an `errorId` set to `TransactionRequestIdempotencyKeyAlreadyExists`. * On API version `2.2` and later, we will include the `paymentId` and `paymentStatus` in the error response to provide more insights into the related payment. This data can be used to validate which payment was already created in case of a duplicate request. * Otherwise, Primer will attempt to process the new request. > [!NOTE] > > The way you generate the idempotency key is totally up to you, as long as it is unique per request attempt. # Set up Universal Checkout Source: https://primer.io/docs/get-started/set-up-a-checkout ## What is Universal Checkout? Now you have a processor connected and a workflow to route your payment to your processor, you can start to create payments. To do this, you need to set up [Universal Checkout](/docs/checkout/checkout-builder). Universal Checkout unifies all payment methods and processors behind a single integration, across both web and mobile, and handles the creation of a payment in a PCI-compliant way. ## How to set up Universal Checkout There are two steps required: > [card] [Integrate Universal Checkout](/docs/checkout/overview) > > Integrate Universal Checkout into your application using Primer's SDKs. There are different integration options so make sure to choose the best for your use case. > [card] [Configure your checkout](/docs/checkout/checkout-builder/) > > Determine which payment methods and features should be displayed under which conditions - this is all done without any code via the [Checkout](https://dashboard.primer.io/checkout) section in the dashboard. Once you have configured your checkout and your integration is complete, customers can pay with your checkout and a payment will be created with Primer. Using your workflow, Primer will route the payment to your connected processor to be authorized. > [!NOTE] > > It's also possible to create merchant-initiated payments using vaulted payment methods via the Payments API - [learn more here](/docs/get-started/recurring-payments). These payments don't go through the checkout. # Home Source: https://primer.io/docs/home ![Primer Documentation Light Mode Banner](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/homepage/hero-background/light.png) Everything you need \ to build with Primer ==================== Learn how to connect, build, and scale with Primer. Our docs offer clear guides and technical references to help you get more from our unified payments infrastructure. [AI coding assistants](/docs/checkout/primer-checkout/resources/build-with-ai) > [card] [Get Started](/docs/get-started/overview) > > Your first stop - everything you need to start building with Primer. > [card] [Connections](/docs/connections/payment-methods/overview) > > Plug into your favorite tools and start building powerful flows. > [card] [Changelogs](/docs/changelogs/api-changelog) > > See what's new, what's better, and what's coming next. > [card] [API Reference](/docs/api-reference) > > All the endpoints and payloads you need to build with Primer. > [card] [SDK Reference](/docs/sdk) > > Add our Checkout SDKs and bring your integration to life with just a few lines of code. > [card] [Primer Concepts](/docs/concepts/overview) > > Learn the key concepts that power our platform. # Overview Source: https://primer.io/docs/workflows/apps/native-apps/overview ## Native apps Explore Primer’s suite of native workflow applications that provide essential payment processing functionality. ![Native apps](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/native-apps/banner/light.png) ## Explore our apps > [card] [Primer Payments](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) > > Payment processing and management actions > [card] [Primer Disputes](/docs/workflows/apps/native-apps/primer-disputes-app/dispute-status-update-trigger) > > Handle payment dispute events > [card] [Primer Emails](/docs/workflows/apps/native-apps/primer-emails-app/send-email-action) > > Send automated email notifications > [card] [Primer Monitors](/docs/workflows/apps/native-apps/primer-monitors-app/monitor-event-created-trigger) > > Monitor and track workflow events > [card] [Primer Vault](/docs/workflows/apps/native-apps/primer-vault-app/send-card-details-action) > > Securely handle payment card details > [card] [Primer Web Requests](/docs/workflows/apps/native-apps/primer-web-requests-app/send-web-request-action) > > Make HTTP requests to external services # Dispute status update Trigger Source: https://primer.io/docs/workflows/apps/native-apps/primer-disputes-app/dispute-status-update-trigger > [!TIP] > > The "Dispute status update" Trigger can be used as the starting point for your dispute management workflows, and can be built to send updates to any third party services, or to [automate refunds through the Payments app](/docs/workflows/apps/native-apps/primer-payments-app/refund-payment-action). The "Dispute status update" Trigger will listen for dispute notifications sent by payment processors that have been added as payment connections in the Primer dashboard. All dispute notifications are mapped to the [unified Primer framework](/docs/manage-payments/capture-payment), this Trigger works the same way regardless of the processor that originates the dispute. ## Use cases You can build workflows that **react** to new dispute events. For example, you can have a dedicated workflow to send all new dispute events to a third-party fraud platform to benefit from dispute liability cover, and to help the fraud platform fine tune their risk decision engine. You could also set up a separate workflow to automate the refund of payment where a `retrieval` dispute type is received, to prevent a `dispute` from being created later. > [!NOTE] > > A retrieval signifies an investigation into a payment has been launched. Depending on the results of this investigation, a dispute may be raised, and the payment can be reversed. A dispute not only results in the amount of the payment being debited from your processor account, you are also liable to pay additional fees to the processor, so automating refunds when a retrieval notification is received can save time and money. ## Output reference | Name | Type | Description | | :- | :- | :- | | Dispute ID | string | A unique identifier for this dispute event generated by Primer. This is unique to each dispute event - so is not shared across various `type` and `status` relating to the same payment. | | Processor dispute ID | string | An identifier for this dispute provided by the processor. This is shared across multiple dispute `type` and `status` relating to the same payment. e.g. as an `open` dispute that is later `challenged` will share a `processorDisputeId`. | | Processor | string | The payment processor that you submitted a payment to, and received a dispute notification from. | | Date received | datetime | Date and time at which primer received the processor’s dispute event. Provided as an ISO timestamp in UTC. | | Required response date | datetime | Time by which the merchant must challenge a dispute. This is provided by the processor, where available. | | Type | enum: `RETRIEVAL`, `DISPUTE`, `PREARBITRATION` | The type of dispute event. More information on what the `type` field represents can be found in our [manage disputes guide](/docs/disputes/overview). | | Order ID | string | Your reference for the sale transaction that the dispute relates to. | | Merchant ID | string | The merchant ID registered at the payment processor used for this dispute. | | Status | enum: `OPEN`, `ACCEPTED`, `CHALLENGED`, `EXPIRED`, `CANCELLED`, `WON`, `LOST` | To see which statuses are applicable for a dispute `type`, and how we map `status`, please see our manage disputes guide. | | Reason code | string | The dispute reason code for a dispute. This will be the same code provided by the card schemes. | | Processor reason | string | The dispute reason provided by the processor. | | Amount | integer | The disputed amount. Note: this is not always the same as the payment amount. This will be displayed in minor units. e.g. for \$7, use 700. Some currencies, such as Japanese Yen, do not have minor units. In this case you should use the value as it is, without any formatting. For example for ¥100, use 100. | | Currency code | enum | Currency Code for the disputed amount. The 3-letter currency code in [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) format. e.g. use USD for US dollars. | # Send email Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-emails-app/send-email-action ## Primer Emails app This app gives you the ability to send yourself or your team an email from within a workflow. This can be used with [Monitors](/docs/monitors/overview) notifications, but could also be used together with the Primer Disputes app, or even with the Primer Payments app and "Payment Status updated" trigger when a single payment fails. > [!NOTE] > > Do note that this action is only intended to send email notifications to yourself, not to your customers. There are no customization options and the email will arrive with a Primer header. If you do want to send emails to your customers, we have dedicated integrations with third-parties like Sendgrid for example. ## Action inputs The "Send email" action currently supports the following inputs: | Input | Type | Description | | - | - | - | | Subject | text | Email subject. | | Header | text | The email body can have a different header. | | Email table | list of values | You can manually create a list of fields and values that will be displayed as a table by adding items and setting the "field name" and "field value" fields accordingly. | | Recipient email(s) | text | One or multiple email addresses an email should be sent to. | You can't use HTML or change the formatting or sender. Emails will always be sent from *noreply(@)primer.io* and will come with predefined formatting. Here is an example for an email sent from this action: ![Primer Email example](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/send-email/email_example.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=332a1e0743519b262d38f27d85ba273e) Primer Email example # Monitor event created Trigger Source: https://primer.io/docs/workflows/apps/native-apps/primer-monitors-app/monitor-event-created-trigger ## Primer Monitors app The Primer Monitors app gives you a trigger to react to new monitor events from our [Monitors](/docs/monitors/overview) product. Now you have complete control to build your own notification flows however you want - send yourself a web request, a Slack message, an email, or immediately create an incident. ## Trigger outputs The Monitor event created trigger returns two objects: the monitor object, and the monitor event object. Some fields are only returned for static monitors, and some only for dynamic monitors. ### Monitor | Output | Type | Description | | - | - | - | | ID | number | The monitor Id. | | Name | text | The custom name given to the monitor. | | Metric | text | The metric used for this monitor, for example *Payment.paymentsDeclinedCount*. | | Type | text | `THRESHOLD` for static monitors or `ANOMALY` for dynamic monitors. | | Threshold value | number | Define the value that should trigger the monitor when compared to the measured value. | | Threshold direction | text | Define if the monitor should trigger when the measured value is `ABOVE` or `BELOW` the threshold value. | | Minimum number of samples | number | If this is greater than zero, the monitor will only trigger when at least this many payments are in the event window. | ### Monitor Events | Output | Type | Description | | - | - | - | | Event ID | number | The ID for the specific event, can be used to construct a deeplink to Primer's dashboard. | | Event date | datetime | Datetime in UTC when this event was created. | | Event window start | datetime | Datetime in UTC for the start of the observed period. | | Event window end | datetime | Datetime in UTC for the end of the observed period. | | Measured value | number | Measured value in this event window. | | Lower bound | number | The lower end of the expected range for this window, depending on the metric used. Only returned for dynamic monitors. | | Upper bound | number | The upper end of the expected range for this window, depending on the metric used. Only returned for dynamic monitors. | | Samples | number | The amount of payments within this event window. | ## Example flow Here is an example for a workflow using this trigger: whenever a new monitor event is created, a web request is sent notifying a dedicated endpoint. Afterwards, depending on the metric used, an incident is created via PagerDuty when too many payments start failing, a Slack message is sent when potential 3DS issues are observed, and an email is sent for any other metric. All within one notification flow: ![Escalation flow](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/monitors-app/escalate.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=6b7f1460ec1eadac53959888ad4afe53) Escalation flow ## Workflow Runs [Workflow Runs](/docs/workflows/monitor-workflows/overview) are automatically available for any workflow that was executed using this trigger. # Authorize payment Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/authorize-payment-action ## What does this Action do? The "Authorize payment" Action is responsible for sending the authorization request. It enables you to configure exactly how you want to route the payment, along with other payment services you can configure, such as 3D Secure and fallbacks. Learn more about processing payments [here](/docs/get-started/create-workflow). ![Example workflow](https://mintcdn.com/primer-cc826789/hMQvqYafZsY5btLD/images/workflows/authorize-payment/authorize_1.png?fit=max\&auto=format\&n=hMQvqYafZsY5btLD\&q=85\&s=9dae5c056664a73c00a10931a4e03df0) Example workflow ## How to use the Action * Create a workflow with the ["Payment created" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) * Assign a `payment ID` - this will usually be the "Payment ID" from the "Payment created" Trigger output * Select your processor and associated merchant account you want to process the payment with * Choose the 3D Secure option - see more [here](/docs/payment-services/3d-secure/overview) on the differences between the 3DS options * \[Optional] Configure a fallback processor - learn more [here](/docs/payment-services/fallbacks) Now your "Authorize payment" Action is set up, use the output to continue building your workflow to handle the response or create a new workflow using the ["Payment status updated" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger) to handle your payment after the authorization request. ## Use cases All your initial payment flows will need to include the "Authorize payment" Action. Based on your needs, you can utilize this Action in a few ways. Below are some examples for inspiration: > [!TIP] > > Simple payment flow that if authorized, shows the success screen then captures, else it only shows the failure screen to the customer. ![Use Case 1](https://mintcdn.com/primer-cc826789/hMQvqYafZsY5btLD/images/workflows/authorize-payment/auth_success.png?fit=max\&auto=format\&n=hMQvqYafZsY5btLD\&q=85\&s=3d9440f3cdc5a6854290183f95e40681) Use Case 1 > [!TIP] > > Two "Authorize payment" Actions split by conditional logic that determines whether to authorize payments with 3DS or not. ![Use Case 2](https://mintcdn.com/primer-cc826789/hMQvqYafZsY5btLD/images/workflows/authorize-payment/apply_3ds.png?fit=max\&auto=format\&n=hMQvqYafZsY5btLD\&q=85\&s=f05588f97a37b56a9db905aa1a761303) Use Case 2 > [!TIP] > > Two "Authorize payment" Actions split by conditional logic that determines which processor merchant account to authorize payments with. ![Use Case 3](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/authorize-payment/use_accounts.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=18d7db7a5709c31973ec0446c2db5943) Use Case 3 ## Auto capture/cancel/continue We have added new options to allow you to **simplify your routes** by automatically enabling capture or cancel on success, and other options. Without this setting, when you want to automatically capture payments from within the workflow, you have to add another condition block on each route to check for the payment status, like this: ![without auto capture](https://mintcdn.com/primer-cc826789/hMQvqYafZsY5btLD/images/workflows/authorize-payment/autoccc_before.png?fit=max\&auto=format\&n=hMQvqYafZsY5btLD\&q=85\&s=488778a700ff7494d36d6ddabe771ef5) without auto capture **With the new options you can simplify your workflow routes to look like this:** ![with auto capture](https://mintcdn.com/primer-cc826789/hMQvqYafZsY5btLD/images/workflows/authorize-payment/autoccc_after.png?fit=max\&auto=format\&n=hMQvqYafZsY5btLD\&q=85\&s=56fb81559af54066cca2366fbaf38dbe) with auto capture ### How these settings work ![auto capture cancel settings](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/authorize-payment/autoccc_settings.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=50bf03b8baf3ed6d6e1ee3dfe2b72016) auto capture cancel settings The settings replace the need for some of the manual block placement, but do not change the behavior of payment app. Webhooks will still be sent and each individual action will show on the payment timeline. * **Continue payment flow:** * This option removes the need for a dedicated continue block on this route. * **Continue, then capture payment:** * This option removes the need for dedicated continue, status-check condition, and capture blocks on this route. * While the "Continue payment flow" is always executed, a capture request is only sent when the authorization attempt(s) result in an authorized payment. The request is skipped for failed, declined, settling, or already settled payments. * Note: this is the preferred way to automatically capture, as the time taken by the capture request will not impact the customer journey. * **Capture, then continue payment:** * This option removes the need for dedicated continue, status-check condition, and capture blocks on this route. * A capture request is only sent when the authorization attempt(s) result in an authorized payment. The request is skipped for failed, declined, settling, or already settled payments. The "Continue payment flow" is always executed. * Note: using this option adds the time taken by the capture request to the customer journey, but this may be needed for some routes or some integrations. * **Continue & cancel payment:** * This option removes the need for dedicated continue, status-check condition, and cancel blocks on this route. * While the "Continue payment flow" is always executed, a cancel request is only sent when the authorization attempt(s) result in an authorized payment. The request is skipped for failed, declined, settling, or already settled payments. # Cancel payment Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/cancel-payment-action ## What does this Action do? The "Cancel payment" Action is responsible for sending the cancel request. It enables you to define rules where you wish to automatically cancel a payment after its authorization. Learn more about canceling payments [here](/docs/manage-payments/cancel-payment). ![Workflow example](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/cancel-payment/auth_cancel.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=1398473e44278cb0d2c042c50969bfa4) Workflow example > [!WARNING] > > In order to cancel a payment, the payment must **not** have reached SETTLED status. ## How to use the Action * Assign a `payment ID` - this will usually be the "Payment ID" from the ["Payment created" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) output or ["Payment status updated" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger) output * \[Optional] Set `reason`, which can be used for your own records ## Use cases Based on your needs, you can utilize this Action in a few ways. Below is an example for inspiration: > [!TIP] > > Cancel the payment if it failed the CVV and AVS checks by the processor during authorization. ![Use Case 1](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/cancel-payment/capture_check.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=321e9aef48fd609e20d340836b275449) Use Case 1 # Capture payment Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/capture-payment-action ## What does this Action do? The "Capture payment" Action is responsible for sending the capture request. It enables you to define rules where you wish to perform an automatic capture of funds. Learn more about capturing payments [here](/docs/manage-payments/capture-payment). ![Workflow example](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/capture-payment/action-in-workflow.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=051059c481a81f36f4db34b4cfb053ad) Workflow example > [!WARNING] > > If the payment is not in the AUTHORIZED state, you will not be able to perform a capture. ## How to use the Action * Assign a `payment ID` - this will usually be the "Payment ID" from the ["Payment created" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) output or ["Payment status updated" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger) output * \[Optional] Set `amount` input if you wish to [partial capture](/docs/manage-payments/capture-payment#partial-capture) * \[Optional] Uncheck `final` input if you wish to do multiple automated partial captures > [!NOTE] > > Capture can be asynchronous i.e. once the capture call is sent to the processor, it can take some time for the payment to become SETTLED. Learn more [here](/docs/manage-payments/capture-payment#handle-asynchronous-capture) and how to handle these scenarios. ## Use cases All your payments must be captured to charge the customer’s account and transfer the funds to your merchant account. Based on your needs, you can utilize this action in a few ways. Below are some examples for inspiration: > [!TIP] > > Simple payment flow that if authorized, shows the success screen then captures, else it shows the failure screen to the customer. ![Use Case 1](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/capture-payment/auth_success.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=dbacadf5a9484b7b4c7e06c2bab01dd4) Use Case 1 > [!TIP] > > Separate workflow using the "Payment status updated" Trigger to always automatically capture if the status becomes AUTHORIZED. This is very useful if you have multiple workflows using the "Payment created" Trigger but you want to handle authorized payments in one way (in this case, always capture). ![Use Case 2](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/capture-payment/trigger-set-up.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=334605311978b82ca108527fdde847b4) Use Case 2 > [!TIP] > > Single workflow to determine whether to capture the payment or not based on the results of the CVV and AVS checks. ![Use Case 3](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/capture-payment/capture_check.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=d0f2c03965212572774c551a3cfddc20) Use Case 3 # Continue payment flow Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/continue-payment-flow-action ## What does this Action do? The "Continue payment flow" Action is used to determine when to respond to the payment authorization request. Rather than only using the authorization request result to determine the outcome of a payment request, this Action allows you to choose when to respond to the payment request. The payment request is returned the status of the payment at the time of this Action running. There are several use cases where you may want this flexibility, such as your post-authorization fraud check fails and so you want to reject the payment and show a failure screen to your customer. For customer-initiated transactions (CITs), this Action is ultimately responsible for telling Universal Checkout to display the success or failure screen to the customer. ![Workflow example](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/continue-payment-flow/continue_1.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=7335603954f9ca4c984eb5ade7a929ee) Workflow example > [!WARNING] > > This Action is required for all payments. If you don't have this Action after your payment is authorized, the payment response will time out, showing an error to your customer but the processor authorization transaction can still be successful. ## How to use the Action * Determine when you want to respond to the payment authorization request. This will usually be after the ["Authorize payment" Action](/docs/workflows/apps/native-apps/primer-payments-app/authorize-payment-action) but could be after post-authorization business rules, such as fraud checks. * Assign a `payment ID` - this will usually be the "Payment ID" from the ["Payment created" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) output or ["Payment status updated" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger) output ## Use cases Based on your needs, you can utilize this Action in a few ways. Below are some examples for inspiration: > [!TIP] > > The most to simply use this Action immediately after the "Authorize payment" Action. This will respond to the payment request with the status of the payment after the authorization request. You can then have conditional logic to capture afterwards. ![Use Case 1](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/continue-payment-flow/auth_success.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=d7f6edd7d7c8ce4cafb028e7b12e6e83) Use Case 1 > [!TIP] > > Review processor CVS and AVS checks post-authorization and cancel the payment if it fails the checks. In this scenario, this Action allows you to show a failure screen to your customer if the payment is cancelled and a success screen if not. ![Use Case 2](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/continue-payment-flow/continue_avs.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=0211225547b676e73384d871cad90a75) Use Case 2 > [!TIP] > > Vault cards using an 'auth-and-cancel' payment flow and show a success screen to your customer if the card is vaulted successfully whilst handling the cancellation in the same flow. ![Use Case 3](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/continue-payment-flow/auth_cancel.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=5138b65a133701c2f9aba6a52f8ca292) Use Case 3 ## Control the checkout result with Checkout outcome You can control how the checkout resolves using the `Checkout outcome` setting in the **Continue payment flow** Action. By default, checkout resolution is based on the payment status. However, you can explicitly choose to return a `Checkout complete` or `Checkout failure` result to the customer. This is useful if you want to show a success screen even when the payment is still pending - for example, after a successful 3DS check and before the authorisation. To use this feature, you can add a condition before the **Continue payment flow** Action and select the outcome you want. This gives you full control over the final checkout experience. ![Use Case – Override checkout result](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/continue-payment-flow/checkout_outcome_example.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=fa3c32d611c9b93782b15bbb9457c576) Use Case – Override checkout result # Decline payment Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/decline-payment-action ## What does this Action do? The "Decline payment" Action can be used for overriding the status of a payment to DECLINED. It enables you to define rules where you wish to decline a payment before its authorization. ![Workflow example](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/decline-payment/test-route.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=8f95e8bf41eaefb881fd56b9082221fe) Workflow example > [!WARNING] > > If the payment is not in the PENDING state, you will **not** be able to perform a decline. ## How to use the Action * Assign a `payment ID` - this will usually be the "Payment ID" from the ["Payment created" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) output or ["Payment status updated" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger) output * \[Optional] Set `reason`, which can be used for your own records ## Use cases Based on your needs, you can utilize this Action in a few ways. Below are some examples for inspiration: > [!TIP] > > Block payments for a specific BIN range by declining all payments for this set of cards ![Use Case 1](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/decline-payment/bin_block.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=f68091e2c095f55b01a70ddae19fddc3) Use Case 1 # Payment created Trigger Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger ## When is it triggered? The "Payment created" Trigger is the starting point for your payment workflows. The "Payment created" Trigger will listen for payment creation requests and, once received, will start the workflow. This includes: * payments created via Universal Checkout and via the Payments API. Learn more about creating payments [here](/docs/get-started/set-up-a-checkout#step-3-set-up-universal-checkout) * both customer-initiated payments (CITs) and merchant-initiated payments (MITs) ![Example workflow](https://mintcdn.com/primer-cc826789/xLgoTOSuc1hi-Q-M/images/workflows/img_example.png?fit=max\&auto=format\&n=xLgoTOSuc1hi-Q-M\&q=85\&s=afff550a5abc14d8eb92e6bc3b9d823d) Example workflow > [!NOTE] > > You must have at least one workflow that has the "Payment created" Trigger in order to process payments - see the [Process payments](/docs/get-started/create-workflow#step-2-set-up-a-workflow) guide to learn more. ## Use cases All your initial payment flows will need to start with the "Payment created" Trigger. Based on your needs, you can utilize it in a few ways. Below are some examples for inspiration: > [!TIP] > > A single payment workflow for all payments that: > > * routes to two different processor merchant accounts based on the order country > * captures the payment if authorization was successful ![Use Case 1](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/use_case_1.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=a83bfe6920c683c85bc5494ae3bb7246) Use Case 1 > [!TIP] > > A payment workflow that only handles merchant-initiated transactions (MITs) as you might want to send all MITs to a separate processor versus your customer-initiated transactions (CITs). ![Use Case 2](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/use_case_2.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=bef327c8bbd2ee0468977433fc525e4f) Use Case 2 > [!TIP] > > A payment flow that uses a Trigger Condition based on metadata and only authorizes the payment, where the capture will take place via API > > This is popular in micromobility where the amount to capture is unknown at the time of authorization. ![Use Case 3](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/use_case_3.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=d7209633975a28f901e3dfd49d48328a) Use Case 3 ## How to set up multiple workflows that use this Trigger Trigger Conditions allow you to set conditions that determine if a workflow should be started. Only if both the triggering event and Trigger Conditions are met will your workflow start executing. > [!WARNING] > > If you want to set up multiple workflows with this Trigger, you **need** to set Trigger Conditions when setting up your workflow - if not, it's possible to have more than one authorization request for a single payment request which must be avoided. # Payment status updated Trigger Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger ## When is it triggered? The "Payment status updated" Trigger will listen for payment status changes and when received, will start the workflow. This Trigger can be used to build workflows to react to payment status changes, such as when a payment transitions from PENDING to AUTHORIZED. ![Workflow example](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/payment-sc-trigger/psu_img_example.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=7c225c3e17d1755c61c43aa39a9b9173) Workflow example ## Use cases Below are some examples for inspiration: > [!TIP] > > For asynchronous payment methods such as Multibanco, where the authorization doesn’t happen immediately after the authorization request, set up a workflow to capture once the payment is AUTHORIZED. ![Use Case 1](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/payment-sc-trigger/psu_use_case_1.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=6d6c58e7a4430584b0e428eb02f853cd) Use Case 1 > [!TIP] > > When the payment is settled, send an email to the customer thanking them for their purchase. ![Use Case 2](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/payment-sc-trigger/psu_use_case_2.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=6630941f42b872c010f8eb90f779eb22) Use Case 2 ## How to set up multiple workflows that use this Trigger Trigger Conditions allow you to set conditions that determine if a workflow should be started. Only if both the triggering event and Trigger Conditions are met will your workflow start executing. > [!WARNING] > > If you want to set up multiple workflows with this Trigger, it’s recommended you set Trigger Conditions when setting up your workflow - if not, more than one workflow may try to do something to the same payment which may not be intended. > > You can use the `Status` field if you want a workflow per stage in the payment lifecycle. # Perform 3DS Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/perform-3ds-action ## What does this Action do? The "Perform 3DS" Action enables you to configure 3DS in your workflows decoupled from the "Authorize payment" Action. It is ideal for those who want to build complex, more granular 3DS flows. Use the outputs of this Action to build sophisticated payments logic. ![Perform 3DS Action Example](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/perform-3ds-action-example.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=8a5ad789941949deb58b898c3a75fa12) Perform 3DS Action Example The example above shows how you can use this Action to continue to authorization if `3DS response code` is one of `AUTH_SUCCESS` or `SKIPPED`. Learn more about 3DS [here.](/docs/payment-services/3d-secure/overview) > [!NOTE] > > The ["Authorize payment" Action](/docs/workflows/apps/native-apps/primer-payments-app/authorize-payment-action) enables you to configure 3DS as part of this action, coupling 3DS and authorization to simplify your workflows. > > However, it is limited in what can be configured. You can only determine whether you want 3DS or not, and if 3DS is successful, it'll continue to authorization, otherwise the payment will be declined. > > If you want to build anything more complex, then you should use the "Perform 3DS" Action. ## How to use the Action * Assign a `payment ID` - this will usually be the "Payment ID" from the ["Payment created" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) output * Set the `3DS Profile` to use - this should align with the processor merchant account you intend to authorize the payment with, ensuring the MCCs equal to comply with scheme rules. * If you wish to use the `Mandate Challenge` option, change the dropdown from "False" (default) to "True". This will result in your buyer being presented a challenge rather than them potentially passing through a [frictionless](/docs/payment-services/3d-secure/overview#frictionless-authentication) 3DS experience. * Add the "Authorize Payment" Action downstream in the workflow and ensure the 3DS option is set to `No 3DS`. This is because you've already done 3DS and so don't need to trigger 3DS twice. # Refund payment Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-payments-app/refund-payment-action ## What does this Action do? The "Refund payment" Action is responsible for sending the refund request. It enables you to define rules where you wish to perform an automated refund. Learn more about refunding payments [here](/docs/manage-payments/refund-payment). ![Workflow example](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/refund-payment/refund.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=5fd488479f54fb31f4cc20288c55372b) Workflow example > [!WARNING] > > If the payment is not in the SETTLED state, you will not be able to perform a refund. ## How to use the Action * Assign a `payment ID` - this will usually be the "Payment ID" from the ["Payment created" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger) output or ["Payment status updated" Trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger) output * \[Optional] Set `reason`, which can be used for your own records * \[Optional] Set `amount` if you wish to [partial refund](/docs/manage-payments/refund-payment#partial-refund) > [!NOTE] > > Refunds are usually processed asynchronously. Once the refund request has been made, the refund, and movement of funds back to the customer, will occur and could take days. Learn more [here](/docs/manage-payments/capture-payment#handle-asynchronous-capture) and how to handle these scenarios. # Send card details Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-vault-app/send-card-details-action > [!WARNING] > > This page describes the "Send card details" action for our **Primer Vault app**. This app is only available on demand. Speak to your Customer Success Manager or raise a ticket on our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11). If you don't have access, please contact your account administrator for assistance. ## Primer Vault app Use this app to pass card details to a PCI compliant endpoint using the "Send card details" action. To do so you have to pass in a Primer token, configure the endpoint, and provide a payload with specific placeholders. ## Setting up the action The "Send card details" action currently supports the following inputs: | Input | Type | Description | | - | - | - | | Primer token | string | The **multi use token ID** for a user referring to a specific credit card. | | Target domain | select | A list of enabled PCI compliant third-parties. This list is empty by default and needs to be enabled for each account manually, pending a PCI review. | | Target path | string | The path within the third-party endpoint to post card details to. | | Payload | string | Map a field to pass the payload through. Make sure to use the placeholder variables as needed. | | Content Type | string | Set the content type of the payload, like `application/json` or `application/xml` | | Placeholder variables | - | A set of available token fields that the action will replace with actual values from the token. | | Cardholder name | string | The placeholder for the cardholder name, by default `{{CARDHOLDER_NAME}}` but can be changed according to the individual needs. | | Card number | string | The placeholder for the cardholder name, by default `{{CARD_NUMBER}}` but can be changed according to the individual needs. **Important:** Sending a payload that does not at least contain the placeholder for card number will **fail** the action immediately without attempting a third-party request. | | Expiry month | string | The placeholder for the card expiration month, by default `{{EXPIRATION_MONTH}}` but can be changed according to the individual needs. | | Expiry year | string | The placeholder for the card expiration year, by default `{{EXPIRATION_YEAR}}` but can be changed according to the individual needs. | | Expiry year format | yyyy or yy | Different endpoints handle the expiration year differently, so you can choose which format to send. | | Custom headers | list | You can set additional headers to be sent if necessary. You must not use this for API keys or other authorization methods, as the credentials will be visible in the Workflow Run view. Instead, set credentials and authorization header name when configuring the App itself. | | Request ID | string | You can specify a request ID that will be returned as an output by this action. This can be useful if you want to forward the response to a different endpoint because you can then use the request ID to easier reconcile the requests. | | Fail action on unsuccessful request? | checkbox | By default, this is on and the [Workflow Run](/docs/workflows/monitor-workflows/overview) will fail if we do not get a 2xx response from the PCI compliant endpoint. You can disable this and create branching logic based on response status to build a comprehensive workflow handling different responses. Do note that **timeouts** will always lead the request to fail as you can't assume the request was received or not received. | > [!WARNING] > > This action can only work with MULTI\_USE tokens, as a SINGLE\_USE token would be marked as consumed after the first authorize or forward attempt. ### Card expiry Because third-parties handle expiration dates differently, you can send in a custom string with month & year and primer will update the values appropriately based on the format selected. An example to send in card expiry could be: ```json JSON theme={"dark"} "expiry": "{{EXPIRATION_MONTH}}/{{EXPIRATION_YEAR}}", ``` ### CVV data Keep in mind that the card CVV is only stored for a maximum of **15** minutes. If you need the CVV to be forwarded to a PCI compliant endpoint, you need to create a workflow that is triggered within that time period. ## Action outputs On success, the action will return the following fields as outputs: | Output | Type | Description | | - | - | - | | Request ID | string | You can specify a request ID as input that will be returned as an output by this action. This can be useful if you want to forward the response to a different endpoint because you can then use the request ID to easier reconcile the requests. | | Response body | string | The response we received from the PCI compliant endpoint. You could forward this response back to your own endpoint using the [send web request ](/docs/workflows/apps/native-apps/primer-web-requests-app/send-web-request-action) action. | | Response content-type | string | The content-type for the response from the PCI compliant endpoint. Usually `application/json` or `application/xml`. | | Response status | string | The response status from the PCI compliant endpoint. This is useful if you set the action to not fail the workflow in case the request could not be sent. Do note that **timeouts** will always lead the request to fail as you can't assume the request was received or not received. | ## Use cases There are different reasons as to why card details from a token need to be shared, such as within the travel industry. To forward card details like card number, cardholder name, and expiry date to a PCI compliant endpoint, you have multiple options within workflows: ### Custom flow via web request trigger The [web request received](/docs/workflows/apps/native-apps/primer-web-requests-app/web-request-received-trigger) trigger allows you to send in a custom JSON payload to manually start a workflow based on your own logic. We recommend sending in a payload like this: ```json JSON theme={"dark"} { "requestID": "YOUR_REQUEST_ID", "token": "PRIMER_TOKEN_TO_SHARE", "useCase": "SHARE_PARTNER_1", "payload": { "orderId": "1234", "customerId": "5678" "cardDetails": { "number": "{{CARD_NUMBER}}", "cardholder": "{{CARDHOLDER_NAME}}", "expiry": "{{EXPIRATION_MONTH}}/{{EXPIRATION_YEAR}}", "securityCode": "{{CVV}}" } } } ``` When setting up the action later, these placeholders can be configured, as well as the field for the payload. It is also possible to branch a workflow. If you have different third-parties to share data with, you could use the `useCase` field to branch to send different payloads to different partners. ![Send card details via web request app](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/primer-vault-app/send-card-details.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=20228acb9cdf622c16ebee96d55fc100) Send card details via web request app ### As part of a payment flow If you know that the card details need to be shared as part of a payment journey, you could also set up a dedicated workflow, by using either the [payment status updated](/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger) trigger or the authorize action. If you create a condition on the status AUTHORIZED, then you could add the "send card details" action of the Primer Vault app. Note that you would need to share the required payload within the metadata of the payment request. ![Send card details via payment app](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/primer-vault-app/send-card-details-2.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=bb5111006b2957c9b2d293d8c260d46d) Send card details via payment app ## Monitoring requests [Workflow Runs](/docs/workflows/monitor-workflows/overview) are automatically available for any workflow that was executed. For the "send card details" action the requests/responses will show placeholders instead of the actual card details sent to the endpoint. # Send web request Action Source: https://primer.io/docs/workflows/apps/native-apps/primer-web-requests-app/send-web-request-action > [!TIP] > > This page describes the "Send web request" action. To start a workflow with a web request, use the ["Web request received" trigger](/docs/workflows/apps/native-apps/primer-web-requests-app/web-request-received-trigger). The "Send web request" action can be used to send a web request to an external server. This could be your own endpoint or the endpoint of another service accepting web requests. ## Configuring the app Credentials for outbound requests are configured once on the Primer Web Requests app, not on each action. When you connect the app you can set: | Setting | Description | | :- | :- | | Authorization Header | The credential sent with every request made by the "Send web request" action. By default it is sent as the `Authorization` header. Leave it empty if your endpoint does not require authentication. | | Custom Authorization Header Name | Overrides the name of the header the credential is sent as, for example `X-API-Key`. If left empty, `Authorization` is used. | | Incoming Authorization Token | Only used by the ["Web request received" trigger](/docs/workflows/apps/native-apps/primer-web-requests-app/web-request-received-trigger#securing-the-webhook) to authenticate requests sent to your webhook URL. | Keep credentials on the app rather than in a custom header: values on the app are stored with the app connection, whereas custom header values are part of the workflow definition and visible to anyone who can edit the workflow. Connect the app once per set of credentials; you can connect it several times if different workflows need different credentials. ## Restrictions The action currently has the following restrictions: * requests are synchronous: the workflow waits for the response before continuing * only **https** endpoints are supported * only `GET` and `POST` methods are supported * only JSON and form URL encoded (`application/x-www-form-urlencoded`) request bodies are supported. A JSON payload must be a JSON object * custom headers are supported, except for a set of [blocked headers](#blocked-headers) that are dropped from the request * requests to private or internal network addresses, `localhost`, and any `primer.io` domain are rejected * the request is sent exactly once; failed requests are not retried * the response body is only available to later blocks if it is a JSON object If you have different requirements for your particular automation, please reach out to us directly via our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11) to tell us more about your request. If you don't have access, please contact your account administrator for assistance. ## Sending the request Configure the following inputs to set up the action: | Input | Description | | :- | :- | | Target URL | The external server to send the request to. Only **https** endpoints are supported. The hostname must resolve to a public IP address; see [URL validation](#url-validation). | | Method | `POST` (default) or `GET`. No payload is sent for `GET` requests. | | Body format | `JSON` (default) or `Form URL encoded`. Only available for `POST` requests. | | JSON payload | Shown when **Body format** is `JSON`. The JSON payload for `POST` requests. It must be a JSON object. There is only **partial validation** available when a proper JSON payload is constructed, as the values are replaced only during runtime of the workflow. If the payload is not valid JSON at runtime, the request is not sent and the action fails. Use the [Workflow Runs](/docs/workflows/monitor-workflows/overview) to debug the actual request passed and response received in case of problems. | | Form fields | Shown when **Body format** is `Form URL encoded`. One entry per field, each with a name and a value. Values can use variables from earlier blocks. See [Sending a form URL encoded body](#sending-a-form-url-encoded-body). | | Custom Headers | Additional headers to send as `name`/`value` pairs. These can override the default `Content-Type` and `User-Agent` headers. [Blocked headers](#blocked-headers) are dropped. Do not use this for API keys or other credentials; set those on the app instead (see [Configuring the app](#configuring-the-app)). | | Fail action on unsuccessful request | Boolean (default: **True**). Determines how the workflow handles failed web requests. When **True**, the workflow stops on failure; when **False**, it continues execution even if the request fails. See [Failure handling](#failure-handling). | Example JSON request with a placeholder for some variables. Use the [variable selector](/docs/get-started/create-workflow#add-actions) to assign outputs from different blocks when creating this request. ```json JSON theme={"dark"} { "customRequestType": "RECOMMENDATION_ENGINE", "paymentId": "[PAYMENT_ID]", "orderId": "[ORDER_ID]", "customerId": "[CUSTOMER_ID]", "ruleDescription": "Get recommendation on how to proceed after a payment was created." } ``` ### Sending a form URL encoded body Some APIs expect `application/x-www-form-urlencoded` instead of JSON. Set **Body format** to `Form URL encoded` and add one entry per field under **Form fields**. Brackets in field names are kept, so you can build nested values, for example `items[0][price]`. Names and values are URL encoded when the request is sent. For example, these fields: | Name | Value | | :- | :- | | `amount` | `1000` | | `expand[]` | `customer` | | `expand[]` | `latest_charge` | are sent as: ```text Request body theme={"dark"} amount=1000&expand%5B%5D=customer&expand%5B%5D=latest_charge ``` The following rules apply to form fields: * a field with an empty name is skipped * a field with an empty value is sent as `name=` * the same name can appear more than once, for example `expand[]`. Fields are sent in the order of the list ### Headers sent with the request Every request includes the following headers unless noted otherwise. Header names are case-insensitive, so a custom header with the same name as a default replaces it. | Header | Value | Notes | | :- | :- | :- | | `Content-Type` | `application/json`, or `application/x-www-form-urlencoded` when **Body format** is `Form URL encoded` | Can be overridden with a custom header. The body is not converted to match. | | `User-Agent` | `Primer Web Request App` | Can be overridden with a custom header. | | `Authorization` | The **Authorization Header** value set on the app | Only sent if a value is configured on the app. The header name follows **Custom Authorization Header Name** when set. The app value takes precedence over a custom header with the same name. | | `Referer` | `primer.io` | Always sent and cannot be overridden. It identifies requests coming from Primer and lets the trigger reject requests sent back to Primer. | Tracing headers used internally by Primer are not forwarded to your endpoint. ### Blocked headers For security reasons, some headers cannot be set through **Custom Headers**. If a blocked header is configured, it is dropped and the request is still sent. The Workflow Run shows a message listing the headers that were dropped: ```text Workflow Run message theme={"dark"} The following headers were configured on the workflow, but are not supported: host, x-forwarded-for ``` The following headers are blocked (case-insensitive): | Category | Headers | | :- | :- | | Host and routing | `Host`, `X-Original-URL`, `X-Rewrite-URL` | | HTTP protocol control | `Content-Length`, `Transfer-Encoding`, `Connection`, `Upgrade`, `Expect` | | Client IP and proxy identity | `X-Forwarded-For`, `X-Forwarded-Host`, `X-Forwarded-Proto`, `X-Real-IP`, `X-Client-IP`, `X-Original-IP`, `Forwarded`, `Via` | | Request origin | `Origin`, `Referer` | | Proxy authentication | `Proxy-Authorization`, `Proxy-Authenticate`, `Proxy-Connection` | | Primer internal | `X-Primer-Branch`, `X-Primer-Context`, `X-Primer-Flags`, `X-Primer-Timeout-Policy` | | CDN | Any header starting with `CloudFront-` | ### URL validation The **Target URL** is validated before the request is sent. The action fails without sending anything if: * the URL does not use the `https` scheme * the host is `localhost`, a private or internal IP address (such as `10.x.x.x`, `172.16.x.x` to `172.31.x.x`, `192.168.x.x`, `127.x.x.x`, link-local or other reserved ranges, or their IPv6 equivalents), or a hostname that resolves to one of these addresses * the hostname cannot be resolved * the host is `primer.io` or any subdomain of it. This prevents workflows from calling Primer and starting themselves again in a loop. The error shown in the Workflow Run lists the specific issue, for example `Invalid URL, scheme not allowed: http`. ## Handling the response The following response data is available in the output of the action: | Output | Description | | :- | :- | | Response Body | The payload, available as "unstructured data" if the response is a JSON object. If the response is not JSON, or is a JSON array or scalar, this is empty. | | Response content-type | The content type of the response (e.g., `application/json`). | | Response status | The HTTP status code of the response. | | Success | Boolean indicating whether the request was successful (`2xx` status). | You can pass this data to another workflow block using the variable selector. For the **Response Body**, you must specify the **path** to the variable you want to use. ![Condition example](https://mintcdn.com/primer-cc826789/8xC8Qx3j-Ljaxxyf/images/workflows/send-web-request/web-request-app.png?fit=max\&auto=format\&n=8xC8Qx3j-Ljaxxyf\&q=85\&s=e36ff8e71d9a6754265058681822684e) Condition example It is also possible to use that data to build conditions in the same way. ![Condition example](https://mintcdn.com/primer-cc826789/8xC8Qx3j-Ljaxxyf/images/workflows/send-web-request/web-request-condition.png?fit=max\&auto=format\&n=8xC8Qx3j-Ljaxxyf\&q=85\&s=2745d423f66f581f04c75bd13237754d) Condition example The full request and response, including headers, are shown in the **Request & response** tab of the Workflow Run. Values of credential headers such as `Authorization`, `Cookie`, or headers whose names end in `-Key`, `-Token`, `-Auth` or `-Secret` are masked there. ### Timeouts | Phase | Limit | Description | | :- | :- | :- | | Connecting | 5 seconds | Time allowed to resolve the hostname and open a TCP connection, and then again for the TLS handshake. An endpoint that does not accept connections fails within roughly 10 seconds. | | Waiting for a response | 60 seconds | Time allowed for the server to start responding and for each subsequent read of the response. A connected endpoint that never responds fails after 60 seconds. | The request is sent exactly once. If it times out or fails, it is **not retried**, so your endpoint will not receive duplicate requests from a single action execution. If you need retries, add them to your workflow explicitly or handle them on your side. > [!NOTE] > > Keep your endpoint's response time well below the limits above. When this action runs as part of a payment flow, for example before authorizing a payment, the checkout waits for the workflow to finish and a slow endpoint delays the payment result for your customer. If a use case requires a longer duration, then this synchronous action is not the right approach. Consider splitting the request and using the ["Web request received" trigger](/docs/workflows/apps/native-apps/primer-web-requests-app/web-request-received-trigger) to continue. ### Failure handling A request is treated as unsuccessful when: * the **Target URL** fails [validation](#url-validation) or, when **Body format** is `JSON`, the **JSON payload** is not valid JSON * the connection fails or times out, or the server does not respond in time * the server responds with a status code outside the `2xx` range By default, an unsuccessful request marks the workflow run as `Failed` and no further blocks are executed. The Workflow Run shows the reason, for example `Unexpected http response code [503] from https://example.com/recommend`. Set **Fail action on unsuccessful request** to **False** to let the workflow continue instead. The action then completes with **Success** set to `false`. When a response was received, **Response status**, **Response content-type** and **Response Body** are still populated so you can branch on them. When no response was received, for example on a timeout or an invalid URL, only **Success** is set and the Workflow Run shows a message explaining why, such as `the target server took too long to respond`. ![Handling unsuccessful request example](https://mintcdn.com/primer-cc826789/8xC8Qx3j-Ljaxxyf/images/workflows/send-web-request/web-request-fail-action-on-unsuccessful-request.png?fit=max\&auto=format\&n=8xC8Qx3j-Ljaxxyf\&q=85\&s=a9dc02ec86b92c965a539eb18587b416) Handling unsuccessful request example Learn more about [debugging workflow runs](/docs/workflows/monitor-workflows/overview). ## Example flow An example use of the send web request action could be to use an internal recommendation engine before authorizing a payment. If the response contains a "recommendation" field with a value "PROCEED", then the payment flow continues, otherwise the payment gets declined. ![Send web request action example](https://mintcdn.com/primer-cc826789/8xC8Qx3j-Ljaxxyf/images/workflows/send-web-request/internal-lookup-flow.png?fit=max\&auto=format\&n=8xC8Qx3j-Ljaxxyf\&q=85\&s=1c3a93dbf0b48e6640c4311688e2860a) Send web request action example ## Start automating * Now that you know what can be achieved with this action, start [creating a workflow](/docs/get-started/create-workflow). * Debug received requests or requests sent within the [Workflow Runs](/docs/workflows/monitor-workflows/overview) # Web request received Trigger Source: https://primer.io/docs/workflows/apps/native-apps/primer-web-requests-app/web-request-received-trigger > [!TIP] > > This page describes the "Web request received" trigger. To send web requests to an external server from an existing workflow, use the ["Send web request" action](/docs/workflows/apps/native-apps/primer-web-requests-app/send-web-request-action). The "Web request received" trigger can be used as the starting point for custom workflows. This could be based on your internal logic or based on other services that do not have their own [workflow app](/docs/workflows/apps/overview) yet. ## Setup When you connect the Primer Web Requests app you get a webhook URL that you can send `JSON` requests to. ### Securing the webhook Anyone who knows the webhook URL can send requests to it. To make sure only your systems can start the workflow, set an **Incoming Authorization Token** when configuring the app. Every request to the webhook URL must then carry it as a bearer token: ```text Authorization header theme={"dark"} Authorization: Bearer ``` Requests with a missing or invalid token are rejected with a `403` response and do not start a workflow. If no token is configured, all requests are accepted. The same app configuration also holds the credentials used by the ["Send web request" action](/docs/workflows/apps/native-apps/primer-web-requests-app/send-web-request-action#configuring-the-app). ## Starting a workflow using this trigger Any request sent to this URL will start a workflow when a [published workflow](/docs/get-started/create-workflow#publish-your-workflow) using this trigger exists. ## Restrictions The trigger currently has the following restrictions: * only valid JSON payloads are supported * the webhook responds immediately with a `200` status and the body `{"message": "Webhook received"}`. The response does not contain any workflow output. Use the ["Send web request" action](/docs/workflows/apps/native-apps/primer-web-requests-app/send-web-request-action) if you want to send data to another system. * requests originating from Primer itself (a `Referer` header containing `primer.io`) are rejected, so a workflow cannot start itself through this trigger ## Using the request payload A `JSON` payload can be passed with the web request, but is optional. If provided, the payload is available as "unstructured data" in the output of the trigger. An example payload could be the following JSON: ```json JSON theme={"dark"} { "customRequestType": "TICKET_WORKFLOW", "eMail": "test@test.com", "ticketDescription": "A description to be passed when creating a ticket.", "ticketTitle": "Title for the new ticket to be created" } ``` You can pass this data to another workflow block using the variable selector and specifying the **path** to the variable that should be used. ![Condition example](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/web-request-received/web-request-received.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=e04d2c481a85c639a01f8b98d83547e7) Condition example It is also possible to use that data to build conditions in the same way. ![Condition example](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/web-request-received/web-request-condition.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=067b515a4858e7f572a673915e0f49cc) Condition example ### Preventing accidental triggers You can use [trigger conditions](/docs/workflows/utilities/conditions-block#trigger-conditions-define-when-to-start-a-workflow) to prevent a workflow from being started unless a value defined by yourself is passed through. This could serve as a check for the right payload, or just a custom key that you pass. In this example, a field called `customRequestType` with the value `TICKET_WORKFLOW` is part of the payload. ![Trigger condition example](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/web-request-received/web-request-trigger-condition.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=ad422a10f6b15e4c387bc58fcbbdd38b) Trigger condition example This will only start the workflow if that value is passed, if an empty payload is received, or any other `customRequestType` then no workflow is started. ## Start automating * Now that you know what can be achieved with this trigger, start [creating a workflow](/docs/get-started/create-workflow). * Debug received requests or requests sent within the [Workflow Runs](/docs/workflows/monitor-workflows/overview) # Workflow Apps Source: https://primer.io/docs/workflows/apps/overview Apps are key to facilitating no-code automation for your use cases. Whether you want to orchestrate payments, handle customer support escalations by creating tickets, or want to send e-mails to customers to update them when items have been shipped, you will have to add an App from Primer's marketplace to do so. ![App marketplace](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/workflow-apps/marketplace.png) ## Types of Apps Apps are either **Primer native apps** or **third-party apps**. ### Native Apps The [Payments App](/docs/workflows/apps/native-apps/primer-payments-app) or [Disputes App](/docs/workflows/apps/native-apps/primer-disputes-app) are examples of Primer native Apps. These are created and maintained by Primer and enable the use of existing Primer products within Workflows. ### Third-party Apps Any service that has a public API can become a Workflow App. Primer is constantly adding new apps supporting a wide array of use cases within accounting, chargebacks, communication, data, fraud prevention, inventory management, developer tools, KYC/KYB, loyalty & rewards, marketing, productivity, logistics, subscriptions, customer support... if you are missing your preferred service, be sure to let us know. ## How Apps work An App consists of **Triggers** and **Actions**. Some Apps might only have Triggers, or only have Actions. ### Triggers Triggers are external events which start a workflow when they occur. Examples: * a shipment status is updated via Shippo, the triggering event is "**Tracking updated**" * a support ticket is created through Freshdesk, the triggering event is "**Ticket created**" * a review is submitted on TrustPilot, the triggering event is "**New customer review submitted**" ### Actions Use Actions to execute a certain task as part of a workflow. Examples: * sending a message to Slack, using "**Send message**" * creating a task on Asana, using "**Create task**" * authorizing a Payment using the [Payments app](/docs/workflows/apps/native-apps/primer-payments-app) with a payment processor, the action is "**Authorize payment**" > [!NOTE] > > If you are missing specific Triggers or Actions for an App that you would like to use as part of your workflows, please let us know what use case you would like to automate and we can add these quickly. ### Inputs & Outputs Interaction with apps is based on **Inputs** and **Outputs**. Triggers only produce Outputs, whereas an Action has both Inputs and Outputs. Examples for Inputs: * to post a message to Slack you have to select a destination `channel` where the message should be posted to, as well as the content of the message * to authorize a payment, you need to specify the target `processor` and the `merchant account ID` * to send an e-mail, the required fields are `recipient email`, `subject`, and `mail body` Examples for Outputs: * an action to create a support ticket would return the `ticket ID` and a `link` to the ticket * the action to authorize a payment returns a `payment status`, as well as potential `decline reasons` * a shipping status update trigger might produce fields for `new ETA`, `shipping status`, and `tracking number` Any Outputs are available downstream when building a workflow. The more blocks you add to a route, the more fields are available to be used on every subsequent block. You can see how to use these concepts when you [create a workflow](/docs/get-started/create-workflow). ## Connect to an App In order to build a workflow using the app, you will first have to connect to this app with your existing credentials. Navigate to **Workflows -> Apps** to see a list of your already connected apps or to add new apps: ![Add-new-app](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/workflow-apps/add-new-app.png) Within the app marketplace, you can browse or search for apps. You can either connect to an app directly or use the detail page to learn more about the app and to see which triggers and actions it supports. ![App detail page](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/workflow-apps/app-more-info.png) Once you're ready to connect to your app, a setup screen will appear. Depending on the app, this could be as simple as adding an API key: ![MessageBird API Key](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/workflow-apps/api-key-messagebird.png) Other apps might need more fields in order to set up the app, while some apps might only show a **Connect** button, enabling you to use oAuth for frictionless authentication. ### Follow the setup instructions For some services to work, especially if you want an app's triggers to work, you'll need to complete other steps to ensure that the app is not just using the right credentials, but that data flows are enabled. In the example below, we show a webhook URI that you need to add in Shippo's dashboard so that Shippo's webhooks can trigger your workflows. ![Setup instructions](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/workflow-apps/setup-instructions.png) Follow the setup instructions carefully, as the necessary setup steps will change from app to app. ## Manage your existing apps If you have already set up any apps, you can see them in the overview. From here, you can either edit the app to change its name or credentials, or you can archive the app so that it will no longer be available for new workflows. ![connected apps](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/workflow-apps/connected-apps.png) Workflows will not be automatically updated or otherwise impacted when you archive an app. It is only at the next creation or modification of a workflow that the archived apps will no longer be available for use. Published workflows based on archived apps will continue to run. Make sure to explicitly archive or update the affected workflows accordingly. ## Managing updates When you add an app from the marketplace, you will always add the latest version of this app. Apps have versioning built-in natively and allow app-developers to release updates that don't have breaking changes right away. However, in the case of breaking changes, like introducing new mandatory inputs, a new version of a trigger or action will be created. This will be shown via an "Update available" information on top of the drawer when editing a workflow using a previous version: ![Update available](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/workflow-apps/update-available.png) Proceeding will require confirmation for this block to be updated to the latest version. When updating an action block that has been used multiple times in the same draft, you can confirm if you only want to update the current block or all blocks using this action. We recommend updating all blocks at once, but if you want to test the latest version, then you have the option to only update one block. ![Update one or all blocks](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/workflow-apps/update-all-high.png) Once the update has been performed on this workflow, you will most likely get new [validation](/docs/workflows/workflow-validation) hints telling you to fill out required fields, which has to be done before being able to publish the draft. App updates are optional and don't impact workflow execution. If you're not yet on the latest app version, your workflows will continue to run with the version that is set up when the workflow was published. ## Debugging You can see all the interactions with third-parties in our [Workflow Runs](/docs/workflows/monitor-workflows/overview) where all details of a specific Workflow Run are available down to the individual requests to a third-party and their responses. This will help debug any issues to determine if it is due to a configuration issue or an account issue, like using the wrong credentials. ## Request an App If you do not find the third-party App that you are looking for, you can submit a request for it to be added right from within the marketplace. We're also always happy to learn from you directly to understand which use cases you are looking to automate with said service. [Reach out to us](https://portal.support.primer.io/servicedesk/customer/portal/11) to tell us more about your request. ## Start automating Now that you have set up your apps, you can [create your first workflow](/docs/get-started/create-workflow). # Overview Source: https://primer.io/docs/workflows/overview ## Get started with automation Automate your payments logic in clicks, not code. ![Get started with automation](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/workflows/banner/light.png) Workflows enable you to build end-to-end payment and commerce automation flows without writing any code. Primer gives you all the building blocks to create and manage your workflows based on your own business logic and requirements. A workflow can leverage multiple Primer native and third-party [apps](/docs/workflows/apps/native-apps/overview) to fulfill a use case. Each app offers a set of triggers and/or actions, enabling you to seamlessly automate and orchestrate the services that you need. ![Learn about Workflow Apps](https://mintcdn.com/primer-cc826789/hMQvqYafZsY5btLD/images/overview-pages/workflows/create-workflow.png?fit=max\&auto=format\&n=hMQvqYafZsY5btLD\&q=85\&s=aadf0cc8e3af10d8b4a76072c87b8b5e) ## [Learn about Workflow Apps](/docs/workflows/apps/overview) Primer gives you all the building blocks to create & manage your workflows based on your own business logic and requirements. ## Power your flows with everything you need > [card] [Native apps](/docs/workflows/apps/native-apps/overview) > > Supercharge your flow with our ever-growing library of apps. > [card] [Third-party apps](/docs/connections/workflow-apps/overview) > > Supercharge your flow with our ever-growing library of apps. > [card] [Utilities](/docs/workflows/utilities/workflow-utilities) > > Supercharge your flow with our ever-growing library of apps. ## Get the most out of Workflows > [card] [Best practices](/docs/workflows/best-practices) > > Bring apps into sophisticated flows without a single line of code. > [card] [Discover templates](/docs/workflows/templates) > > Get started with our library of templates. > [card] [Easily monitor your workflows](/docs/workflows/monitor-workflows/overview) > > Get started with our library of templates. ## Use cases > [card] [Send KYC verification link](/docs/workflows/use-cases/send-kyc-verification-link) > > Automate sending a KYC verification link as part of your payment flow. # Conditions Source: https://primer.io/docs/workflows/utilities/conditions-block ![Conditions Utility](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/conditions.png) Conditions Utility ## Using the Conditions Utility Depending on your business requirements you might want to route payments in EUR down one path, and payments in USD down another. You can also create multiple routes based on other available data, from payment status down to individual e-mail addresses if you would want to. The Conditions Utility enables you to create all these conditions. Conditions are used to evaluate if a certain path should be followed during the execution of the workflow. They are based on selecting a **field** (for example: `Currency`), an **operator** (for example: `equals`), and a **value** (for example: `EUR`). > [!WARNING] > > Build conditions only on fields that will be present at runtime. If you build conditions on fields that aren't always present, you might risk unintended consequences. Be sure to test conditions accordingly so that they lead to the right route being followed. You can also use the "is (not) empty" operator to add explicit checks for the presence of fields. ### Available fields Available fields for any condition depend on the [Outputs](/docs/workflows/apps/overview#inputs-and-outputs) from previous blocks. A condition can use information from any block upstream, like the amount and currency for a payment, or a link to a created ticket with Freshdesk. ![Outputs](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/outputs.png) Outputs ### Available operators The available operators to evaluate a condition depend on the data type of the field. For some data types and operators a setting to either use a **case-sensitive** or a **not case-sensitive** comparison is available too. Supported operators are: | Operator | Description | Example | | :- | :- | :- | | **Equal** | The value passed in must be equal to the value set up in the condition. | "Currency equals 'EUR'" or "Order status equals 'CONFIRMED'" | | **Not equal** | The value passed in must be different to the value set up in the condition. | "City **does not equal** 'test'" or "Product category **does not equal** 'gift card'" | | **Greater than or equal** | The value passed in must be greater than or equal to the value set up in the condition. | "Amount is **greater than or equal** to 100" or "discount amount is **greater than or equal** to 15\*\* | | **Less than or equal** | The value passed in must be less than or equal to the value set up in the condition. | "Risk score is **less than or equal** to 50" or "quantity is \*less than or equal\*\* to 10" | | **One of** | If multiple options are set up, either one will be accepted to follow the route for this condition. | "Currency is **one of** EUR, GBP, USD" will evaluate to true for GBP, but not for NOK. | | **Not one of** | If multiple options are set up, any one will stop the route from being followed for this condition. | "Currency is **not one of** EUR, GBP, USD" will follow NOK payments, but not EUR, GBP, or USD. | | **Between** | Evaluates if a numeric value is between two other values. The range is inclusive of the values entered. | "Amount is **between** 30 and 90" or "risk score is **between** 51 and 100" | | **Contains** | The value set up in the condition must be part of the variable it's compared with. | "Email **contains** '@primer.io'" or "Product title **contains** 'test product'" | | **Does not contain** | The value set up in the condition must not be part of the variable it's compared with. | "Statement descriptor **does not contain** 'Authorization'" or "Discount code **does not contain** 'XMAS'" | | **Is empty** | Checks if the field set up in the condition has no value assigned to it or is missing. Good to know: For string values this could be an empty text or a null value, while for numbers "0" counts as **not** empty. | "Cancellation reason **is empty**" or "Zip code **is empty**" | | **Is not empty** | Checks if the field set up in the condition is not missing and has a value assigned to it. Good to know: For string values this could be any value, while for numbers this includes "0". | "Mobile phone number **is not empty**" or "Customer note **is not empty**" | ![Operators](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/operators.gif) Operators ### Assign values Values for the condition can either be entered manually (like e-mails) or select from a list of available values (like currencies or payment states), dependent on the data type of the selected field. We also support **comparing** values to build routes comparing different fields, like issuing country with order country, or billing address zip code and shipping address zip code. ![Dropdown](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/assign-values.png) Dropdown ### Using metadata for routing One special type of conditions is based on unstructured data sent in via the `metadata` field attached to the Client Session when creating a payment. This field is used to send additional information with the payment outside of the available fields from the Payments API. This can also be used to attach information to create routes on, like custom risk scores or customer account status. When using metadata for routing, make sure to specify the full path like in the example here. ```js JS theme={"dark"} "metadata": { "customObject": { "customField": "TEST" }, "accountStanding": "VIP", "internalRisk": "LOW", } ``` ![Metadata](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/metadata.png) Metadata ### Condition evaluation All conditions are evaluated together (`AND`) by default, meaning that if there are three conditions set up, like `Amount`>100, `Currency`=EUR, `Payment Type`=UNSCHEDULED, then all three need to be fulfilled for the path to be followed during workflow execution. ![Grouped Conditions](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/grouped-and.png) Grouped Conditions To avoid having to create too many routes based on specific conditions, you can also create groups of conditions by using the `OR` evaluation. In this example, a blocking route is created evaluating if a payment uses certain e-mail addresses or if a custom flag with the value "BLOCK" is sent in. ![Using OR](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/grouped-or.png) Using OR You can use multiple conditions in a group to achieve an outcome of `(A AND B) OR (C) OR (D AND E) OR (F AND G AND H)`. It is not possible to nest these groups further, but the ability to use trigger conditions, multiple condition builders, and multiple routes already gives you a lot of opportunity for complex branching. ### Conditions are evaluated top down Creating multiple sets of conditions is a great way to branch a workflow into multiple routes. Each block can have its own name, making it easier to keep track, as well as debug the workflow log. When multiple sets are used, they are **evaluated from top to bottom**. In this example, first the conditions within the email block will be checked and if they match, that path will be taken. Otherwise, the conditions within “recurring payments” will be checked, and so on until the “all other conditions” block at the bottom is reached. ![Test Route](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/test-route.png) Test Route > [!WARNING] > > You need to put the most specific routes on top and getting more generic towards the bottom. If you create a route with “Currency=EUR” first and then a second one with “Currency=EUR AND Risk=high” below, then the second one will never be evaluated. ### All other conditions When the Conditions Utility is used within a workflow, then a fallback condition called “all other conditions” is always at the bottom. This could be used as an `else` path, creating a route that is set up more generic than the specialized routes above, or could also be left empty. If left empty and the [Workflow Run](/docs/workflows/monitor-workflows/overview) reaches this condition, the workflow will still end with `Completed` as the workflow ended without a failure. ## Duplicate a route If you have to set up multiple similar routes where only some of the inputs change (like different processors for different markets) then you can use the menu within the condition block to duplicate the route. A new copy will be created below the original, retaining all conditions and assigned blocks. ![Duplicate conditions](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/duplicate-route.gif) Duplicate conditions ## Trigger Conditions define when to start a workflow It is perfectly valid to have **more than one** published workflows based on the same trigger. However, if you want to start each workflow only in very specific cases, be sure to set up the Trigger accordingly. If an event is sent that would trigger a workflow, but the conditions prevent that workflow from being started, then the workflow will neither run nor create a record [in the Runs section](/docs/workflows/monitor-workflows/overview), because the conditions do not apply. > [!WARNING] > > Conditions within a workflow are evaluated top to bottom, but this logic does not apply to Triggers with Conditions as each workflow is evaluated independently. ![Trigger Conditions](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/conditions/trigger-condition.png) Trigger Conditions ### Use explicitly We recommend being very specific about how to use the Trigger Conditions to avoid unnecessarily starting unrelated workflows. If there are two workflows for Cards & Klarna, they can have a triggering condition where for one the payment method is **explicitly** set to cards, and for the other it’s explicitly set to Klarna. Now each workflow only gets started, when the right payment method is used. ### Best practices Head over to the [best practices guide](/docs/workflows/best-practices) to see our recommendations on how to use create granular flows based on distinct use cases. # Workflow Utilities Source: https://primer.io/docs/workflows/utilities/workflow-utilities ## Workflow Utilities In addition to Triggers and Actions provided by Workflow Apps you can also make use of Utilities to automate even more use cases. ![Workflow Utilities](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/workflow-utilities/banner/light.png) ## Conditions Conditions allow you to branch a workflow into multiple routes based on logic using values from previous blocks. This enables you to put a lot of intricate logic into one workflow. Read more about the [Conditions Utility](/docs/workflows/utilities/conditions-block). ![Conditions Utility](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/workflow-utilities/conditions.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=836ce29dbbedb678cba2d466b828e5c9) Conditions Utility ## Split Use this if you want to create branches based on **percentage-based distribution**, rather than logic. Read more about the [Split Utility](/docs/workflows/utilities/split). ![Split Utility](https://mintcdn.com/primer-cc826789/sTKljbqk0yjiDnE9/images/workflows/workflow-utilities/split_utility.png?fit=max\&auto=format\&n=sTKljbqk0yjiDnE9\&q=85\&s=6e5230f2f55d3e2b0dad4b3347fddc13) Split Utility ## Adding more Utilities Primer will build out the library of Utilities over time based on the use cases that we aim to support and that our customers want to automate. If you have any specific requirements, feel free to [reach out to us](https://portal.support.primer.io/servicedesk/customer/portal/11) and let us know, as we are always keen to provide value based on actual use cases. ## Start automating Now that you know how to use Utilities, you can [create even better workflows](/docs/get-started/create-workflow). # API lifecycle Source: https://primer.io/docs/api-reference/get-started/api-lifecycle How Primer versions, supports, and deprecates the Primer API. This page describes the lifecycle of the Primer API: the named stages every version moves through, what Primer commits to at each stage, and the rules that govern transitions. ## Lifecycle stages Every supported version of the API is in one of six stages at any given time. | Stage | Badge | SLA | Support | Breaking changes | Minimum notice before next stage | | - | - | - | - | - | - | | Beta | `BETA` | None — use at own risk. | Best-effort support for our early adopters. | Allowed, documented in the changelog. | — | | Release Candidate | `RC` | None — near-final quality. | Priority support for testers. | Unlikely, but possible. | 30 days before `GA`. | | Generally Available | `GA` | Full production SLA. | Full support: bug fixes, security patches, and new features. | Avoided. A migration path is provided when one is required. | 12 months before deprecation. | | Supported | `Supported` | Reduced — security only. | Critical security patches only. No new features. | None — the version is frozen. | 12 months before end of life. | | Deprecated | `Deprecated` | Reduced. | None. The version still serves traffic and emits deprecation signals. | None. | 12 months before end of life. | | End of Life | `EOL` | None. | None. Calls return `410 Gone`. | — | — | ## How versions move between stages The lifecycle is **time-driven**, with explicit minimum notice periods at each transition. Notice periods are floors, not targets — Primer can stay in any stage for longer than the minimum, but cannot shorten it. * A version in `RC` reaches `GA` no sooner than 30 days after entering `RC`. * A version in `GA` is given at least 12 months of notice before being deprecated. * A version in `Deprecated` remains there for at least 12 months before reaching `EOL`. ```mermaid theme={"dark"} gantt title Example timeline (illustrative) dateFormat YYYY-MM-DD axisFormat %b %Y section vN Beta :vnbeta, 2025-01-01, 60d RC :vnrc, 2025-03-01, 30d GA :vnga, 2025-04-01, 365d Supported :vnsup, 2026-04-01, 365d section vN-1 GA :vmga, 2024-01-01, 455d Supported :vmsup, 2025-04-01, 365d Deprecated :crit, vmdep, 2026-04-01, 365d End of life :milestone, vmeol, 2027-04-01, 0d section vN-2 Supported :vlsup, 2024-04-01, 365d Deprecated :crit, vldep, 2025-04-01, 365d End of life :milestone, vleol, 2026-04-01, 0d ``` ## Current status | Version | Stage | Deprecation | End of life | | - | - | - | - | | `v2.4` | `GA` | — | — | | `v2.3` | `Supported` | 2026-07-01 | 2027-07-01 | | `v2.2` | `Supported` | 2026-07-01 | 2027-07-01 | | `v2.1` | `Supported` | 2026-07-01 | 2027-07-01 | | `v2` | `Supported` | 2026-07-01 | 2027-07-01 | This table is updated as versions transition between stages. For per-version changes, see the [API changelog](/docs/changelogs/api-changelog). ## Machine-readable signals Three HTTP signals communicate the lifecycle state of each request and response: * **`X-Api-Version` request header.** Pin every request to a specific API version. If the header is omitted, requests default to the earliest supported version — which means an unpinned client may silently start hitting an older version as new versions ship. Pinning is strongly recommended. * **`Deprecation` response header.** Emitted from `Deprecated` versions. Carries the date the version was deprecated. Standardised in [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745). * **`Sunset` response header.** Companion to `Deprecation`. Carries the planned end-of-life date. Standardised in the same RFC. Standardised in [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594) Example response from a deprecated version: ```http theme={"dark"} HTTP/1.1 200 OK Deprecation: @1782864000 Sunset: Tue, 01 Jun 2027 00:00:00 GMT Link: ; rel="deprecation" ``` The `Deprecation` and `Sunset` headers are scheduled for rollout alongside this policy. ## End of life behaviour When a version reaches `EOL`, calls to that version return `410 Gone`: ```http theme={"dark"} HTTP/1.1 410 Gone Content-Type: application/json { "error": { "type": "api_version_unsupported", "message": "This API version has reached end of life. Migrate to a supported version." } } ``` To avoid silent breakage, always pin requests to a specific version using the `X-Api-Version` header rather than relying on the default. ## Vocabulary `Supported` is a specific lifecycle stage on this page, not a general adjective. A version in `GA` is actively supported but is not in the `Supported` stage. When referring to a version's state, prefer the badges — `GA`, `Supported`, `Deprecated`, `EOL` — over prose. `Deprecated` and `EOL` are distinct stages. A `Deprecated` version still serves traffic, with deprecation signals attached to every response. An `EOL` version no longer serves traffic and returns `410 Gone`. ## Related * [API changelog](/docs/changelogs/api-changelog) * [SDK lifecycle](/docs/sdk/lifecycle) — the same model applied to the Primer SDKs. # API Responses Source: https://primer.io/docs/api-reference/get-started/api-responses ## Status Codes The following table summarizes the HTTP response codes you may receive from the Primer REST API. | Status Code | Description | | - | - | | `200` | Success | | `400` | Bad Request | | `401` | Unauthorized | | `403` | Forbidden | | `404` | Entity Not Found | | `409` | Entity Already Exists | | `422` | Input Validation Failed | | `429` | Rate Limit Exceeded | ## Error Responses Primer uses conventional HTTP response codes to indicate the success or failure of an API request. HTTP codes in the `2XX` range indicate a successful request, whereas codes in the `4XX` range indicate a failed request usually due to invalid inputs or operations. The format of the payload for all errors is common. When an unsuccessful request occurs, you will receive a payload in the following format: ```json theme={"dark"} { "error": { "errorId": "AnErrorId", "description": "A human description of the error.", "diagnosticsId": "1234567890", "validationErrors": [] } } ``` All error payloads will be comprised of a unique `errorId` which you can use to identify the error, a human description `description`, and a `diagnosticsId` that you can quote when contacting the support team ([support@primer.io](mailto:support@primer.io)). In case of a badly formed request, Primer will also return additional `validationErrors`. > [!NOTE] > > A `403` response with the `SecurityPolicyBlock` error ID does not include a `diagnosticsId`. These requests are blocked before they reach the API, so no diagnostics record is created. When contacting support about these errors, include the source IP address and the time of the failed requests instead. See [Request requirements](/docs/api-reference/get-started/request-requirements). ## Payment Status As the payments are created, processed, and finalised, they go through a number of states that you will get as an API response, through webhook notifications, and in the Dashboard. These states are used across all processors, as processor specific states are mapped to these. An additional message, in the field `processorMessage`, from the processor may also be included that details the reason for the state, primarily on failure states. | Status | Description | | - | - | | PENDING | The payment has been created by Primer but not yet authorized. | | FAILED | The processor failed to process this payment. | | AUTHORIZED | The payment is authorized and awaiting capture. | | SETTLING | The payment has been submitted for settlement and funds will be settled later. | | PARTIALLY\_SETTLED | The payment has been partially settled. | | SETTLED | Funds have been settled into your account. | | DECLINED | This payment was declined by the processor, either at a gateway or acquirer level. See the reason object in your response payload for more details. | | CANCELLED | The payment was cancelled prior to it being settled. | ## Breaking changes Primer commits to not introducing breaking changes in endpoints or API versions without also introducing a minor API version bump. You can expect endpoints that you’re using to not have breaking changes until you upgrade to another version. However, you should expect non-breaking or additive changes, and we encourage you to design your systems to protect against this possibility. Currently, non-breaking changes can happen inside the same minor API version, and breaking changes cannot. Primer considers breaking changes to be changes that can potentially break an integration. Breaking changes include: * removing an entire operation * removing or renaming a parameter * removing or renaming a response field * adding a new required parameter * making a previously optional parameter required * changing the type of a parameter or response field * removing enum values * adding a new validation rule to an existing parameter * changing authentication or authorization requirements Primer considers non-breaking changes to be changes that should not break an integration, and that you should protect against. Additive changes include: * adding an operation * adding an optional parameter * adding an optional request header * adding a response field * adding a response header * adding values to existing enums If, in exceptional circumstances, we do need to introduce a breaking change without bumping the API version, then we will ensure to communicate this ahead of any release, working closely with you to mitigate any possible impact. Don’t hesitate to reach out with any questions or feedback. You can email Primer directly at [support@primer.io](mailto:support@primer.io), or contact your Primer account manager. # Authentication Source: https://primer.io/docs/api-reference/get-started/authentication Primer uses API keys to authenticate requests. You can manage API keys in the [Developers](https://dashboard.primer.io/developers) area of the dashboard. As API keys carry many privileges such as *authorizing payments*, it is important to keep them **private** and **secure**. Do not hardcode or share API keys (particularly in your source version control system), and they should only be used in your backend. > [!NOTE] > > Send server-side requests from a static egress IP address, not a shared or dynamically assigned cloud IP address. See [Request requirements](/docs/api-reference/get-started/request-requirements). Authentication is handled via HTTP headers, specifically the `X-Api-Key` header. ```bash theme={"dark"} curl -X POST 'https://api.primer.io/' \ --header 'X-Api-Key: ' ``` ## Managing API Keys Head up to the [Developers area](https://dashboard.primer.io/developers) on the dashboard to manage your API keys. You will be able to generate or revoke API keys and edit their respective scopes. Be aware that any changes to existing API keys will be reflected immediately and could cause unwanted side effects. ## Available scopes | Scope | Description | | - | - | | `client_tokens:write` | Create client tokens for use with the client SDK. | | `third_party:webhook_trigger` | Allows a third party, typically your payment processor, to post to Primer's callback endpoint. API keys with this scope enable communication between your processor and Primer about important payment lifecycle events. | | `transactions:authorize` | Authorize a payment | | `transactions:cancel` | Cancel a payment. | | `transactions:capture` | Submit a payment for settlement. | | `transactions:read` | Retrieve one or more payments. | | `transactions:refund` | Refund a payment. | | `payment_instrument:read` | Read stored payment methods. | | `payment_instrument:write` | Write stored payment methods. | | `google_pay_merchants:read` | List the Google Pay domains registered through Primer. See [Manage Google Pay domains through Primer](/docs/connections/payment-methods/google-pay/domain-management). | | `google_pay_merchants:write` | Register and remove Google Pay domains through Primer. | # Configure Webhooks Source: https://primer.io/docs/api-reference/get-started/configure-webhooks ## Overview A webhook is a notification sent from Primer to your server using an HTTP `POST` request. You can use webhooks to be notified of: * **Payment status updates**\ Useful for asynchronous processor connections, where you do not get an immediate authorization response. * **Refund completion**\ Notified when a refund reaches a final state. * **Payment operation failures**\ Notified when a capture, cancellation, refund, or authorization adjustment attempt fails without changing the payment status. * **Disputes and chargebacks**\ Notified when a dispute is opened. * **Workflow run failures**\ Recommended if you use Capture or Cancel via Workflows. ## Delivery model (read this first) This section defines the expected behavior of Primer webhooks. ### What counts as a successful delivery A webhook delivery is considered **successful** when Primer receives **any HTTP `2xx`** response from your endpoint. Any response outside the `2xx` range, including `3xx` redirects, is treated as a failure and will trigger retries. ### How fast should my endpoint respond Your endpoint should return a `2xx` response **immediately** upon receiving the webhook. Do **not** perform long or complex processing before responding. A good pattern is: 1. Validate signature and basic payload shape 2. Enqueue the work (or store the event) 3. Respond with a `2xx` status code 4. Process asynchronously ### Timeout Primer uses a **10 second timeout** for webhook delivery attempts.\ If your endpoint does not respond within this window, the attempt is treated as a failure and retries may happen. ### When will I receive webhooks Webhook delivery typically happens **within seconds** of the underlying change (payment status update, refund completion, dispute opened, etc.), but is not guaranteed to be immediate. ## Retries If a delivery attempt fails, Primer retries the webhook up to **5 times** with increasing delays. Typical retry schedule: * \~10 seconds * \~60 seconds * \~5 minutes * \~10 minutes * \~15 minutes Actual retry timings may vary slightly due to random jitter applied to avoid retry bursts, which helps prevent many retries from hitting your server at the same time. The final retry happens approximately **30 minutes** after the first attempt. > [!NOTE] > > After the final retry attempt, the event is dropped and will not be retried again. ## Ordering and event recency Webhook ordering is **not guaranteed**. To detect the latest payment status change, compare `payment.dateUpdated` and keep the newest one. > [!WARNING] > > Never assume the last webhook you received is the newest one. > Always compare timestamps. ## Delivery guarantees and idempotency Primer webhooks are delivered **at least once**. This means that in rare cases, the same webhook event may be delivered more than once. Your system must be able to handle duplicate deliveries safely. To do this, webhook processing should be idempotent. Recommended approaches: * Store a unique key per processed event and ignore duplicates * Use stable identifiers from the payload, for example: * `payment.id` + `payment.dateUpdated` for payment status updates * `payment.id` + latest refund transaction timestamp for refunds * `transactionId` for disputes If a stable identifier cannot be derived, a safe fallback is to store a hash of the payload for a short time window and ignore repeated deliveries. ## Set up webhooks Set up a webhook in the **Developers** area of the Dashboard. Webhooks are sent with a `POST` request to your endpoint. ![](https://mintcdn.com/primer-cc826789/zUtJbc_qshGTc-1X/images/api/add_a_webhook.png?fit=max\&auto=format\&n=zUtJbc_qshGTc-1X\&q=85\&s=9529480da5c84ddca6e1258c8f8871d0) Add a webhook ## Test webhooks Click **Test webhook** to send an example request to your endpoint. ![](https://mintcdn.com/primer-cc826789/2gUFYKfNb_svpxsN/images/api/test_a_webhook.png?fit=max\&auto=format\&n=2gUFYKfNb_svpxsN\&q=85\&s=f15cea8db78b1679a3ec288d78678fc5) Test a webhook Example payload: ```json theme={"dark"} { "message": "Testing your webhook connection" } ``` ## Webhook event types ### Payment status updates Payment status notifications are sent whenever a payment status changes. The webhook payload contains the full payment object. **Example** ```json theme={"dark"} { "eventType": "PAYMENT.STATUS", "date": "2023-02-21T15:36:16.367687", "notificationConfig": { "id": "cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description": "Payment webhook" }, "version": "2.1", "payment": { "id": "DdRZ6YY0", "date": "2023-02-21T15:36:16.167687", "dateUpdated": "2023-02-21T15:36:16.267687", "amount": 3000, "currencyCode": "GBP", "customerId": "cust-123", "orderId": "order-123", "status": "SETTLED", "paymentMethod": { "paymentMethodToken": "-lcWjvBAAs2DnIRXwxNjUzNTYzNjIy", "analyticsId": "LUi5pETUaVsdSEamK25L", "paymentMethodType": "PAYMENT_CARD", "paymentMethodData": { "last4Digits": "1111", "expirationMonth": "03", "expirationYear": "2030", "cardholderName": "ADYEN", "network": "Visa", "isNetworkTokenized": false, "binData": { "network": "VISA", "issuerCountryCode": "US", "issuerName": "JPMORGAN CHASE BANK, N.A.", "regionalRestriction": "UNKNOWN", "accountNumberType": "UNKNOWN", "accountFundingType": "UNKNOWN", "prepaidReloadableIndicator": "NOT_APPLICABLE", "productUsageType": "UNKNOWN", "productCode": "UNKNOWN", "productName": "UNKNOWN" }, "cvvAvailable": true }, "threeDSecureAuthentication": { "responseCode": "NOT_PERFORMED" } }, "processor": { "name": "STRIPE", "processorMerchantId": "acct_1GORasdasqNWFwi8c", "amountCaptured": 3000, "amountRefunded": 0 }, "transactions": [ { "date": "2023-02-21T15:36:16.167687", "amount": 3000, "currencyCode": "GBP", "transactionType": "SALE", "processorTransactionId": "pi_3L3edsGZasdasdc1iget38p", "processorName": "STRIPE", "processorMerchantId": "acct_1GORasvasdNWFwi8c", "processorStatus": "SETTLED" } ] } } ``` > [!NOTE] > > See the [migration guide](/docs/changelogs/migration-guides/payment-status-webhooks) to update to the latest versions of the webhook event. ### Refunds Refund notifications are sent when a refund reaches a final state. Check the most recent `REFUND` transaction in the payment `transactions`: * SETTLED the refund succeeded and funds were returned * FAILED the refund failed **Example** ```json theme={"dark"} { "eventType": "PAYMENT.REFUND", "date": "2023-02-21T15:37:16.367687", "notificationConfig": { "id": "cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description": "Refund webhook" }, "version": "2.1", "payment": { "id": "DdRZ6YY0", "date": "2023-02-21T15:36:16.167687", "dateUpdated": "2023-02-21T15:37:16.267687", "amount": 3000, "currencyCode": "GBP", "customerId": "cust-123", "orderId": "order-123", "status": "SETTLED", "processor": { "name": "STRIPE", "processorMerchantId": "acct_1G2EpYaHgVZqNWFwi8c", "amountCaptured": 3000, "amountRefunded": 3000 }, "transactions": [ { "date": "2023-02-21T15:36:16.167687", "amount": 3000, "currencyCode": "GBP", "transactionType": "SALE", "processorTransactionId": "pi_3L3ed23NWFwiNWFwi8c1iget38p", "processorName": "STRIPE", "processorMerchantId": "acct_1GORcaGv23NWFwi8c", "processorStatus": "SETTLED" }, { "date": "2023-02-21T15:37:16.267687", "amount": 3000, "currencyCode": "GBP", "transactionType": "REFUND", "processorTransactionId": "pi_3L3ed23NWFwiNWFwi8c1iget38p", "processorName": "STRIPE", "processorMerchantId": "acct_1GORcaGv23NWFwi8c", "processorStatus": "SETTLED" } ] } } ``` ### Payment operation failures Failed operation notifications are sent when a capture, cancellation, refund, or authorization adjustment attempt fails but the payment status does not change. These webhooks use a minimal payload. Call `GET /payments/{id}?expand=transactions.events` to retrieve full details. | Event type | Description | | - | - | | `PAYMENT.CAPTURE.FAILED` | A capture attempt failed | | `PAYMENT.CANCELLATION.FAILED` | A cancellation attempt failed | | `PAYMENT.REFUND.FAILED` | A refund attempt failed | | `PAYMENT.AUTHORIZATION_ADJUSTMENT.FAILED` | An authorization adjustment attempt failed | **Example** ```json theme={"dark"} { "eventType": "PAYMENT.CAPTURE.FAILED", "date": "2026-02-19T15:36:16.367687", "notificationConfig": { "id": "cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description": "Payment webhook" }, "version": "2.4", "signedAt": "1689221338", "payment": { "id": "DdRZ6YY0", "amount": 3000, "currencyCode": "GBP", "orderId": "order-123" }, "requestAmount": 1500, "transactionEvent": { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } } ``` ### Disputes and chargebacks Dispute notifications are sent when a dispute or chargeback is opened. | Field | Description | | - | - | | `eventType` | Always `DISPUTE.OPENED` | | `primerAccountId` | Your Primer merchant account id | | `transactionId` | Primer transaction id related to the dispute | | `orderId` | Your order reference | | `processorId` | Processor name | | `processorDisputeId` | Dispute id on the processor side | | `paymentId` | Primer payment id | | **Example** | | ```json theme={"dark"} { "eventType": "DISPUTE.OPENED", "version": "2.1", "primerAccountId": "7fcd50f1-99f2-416e-8013-6ecd1c1285c3", "transactionId": "c3f662ad-d197-492e-b78b-63eefa64a31d", "orderId": "order-123", "processorId": "Adyen", "processorDisputeId": "adyen_ref_123", "paymentId": "ecb8d3bc-805d-4d97-826e-ef8d4cc3d2a2" } ``` ### Workflow run failed This webhook is recommended if you use Capture or Cancel via Workflows. A workflow failure does not necessarily fail the payment or update the payment status. For more details, see the [Automation documentation](/docs/workflows/monitor-workflows/workflow-run-failed-webhook). ```json theme={"dark"} { "eventType": "WORKFLOW_RUN.FAILED", "version": "1.0", "date": "2024-02-21 15:36:16.167687", "primerAccountId": "123abcde-99f2-416e-8013-6ecd1c1285c3", "triggerEventId": "DdRZ6YY0", "workflow": { "id": "ecb8d3bc-123a-4d56-826e-ef8d4cc3d2a2", "name": "MIT UK Card", "version": 8 }, "run": { "timestamp": "2024-03-07T12:20:14.394429", "id": "bbb1c3cc-805d-4d97-826e-ef8d4cc3d2a2", "status": "FAILED", "lastError": { "applicationId": "PRIMER_PAYMENTS", "actionId": "capture_payment", "diagnosticsId": "1234567890", "message": "Payment ID not found." } } } ``` ## Webhook signing Primer can sign webhook events so you can verify that they were sent by Primer. Each webhook request includes the following headers: * `X-Signature-Primary` * `X-Signature-Secondary` only present during signing secret rotation The signature is an HMAC SHA256 of the raw webhook payload using your signing secret, base64 encoded. ### Prevent replay attacks Each webhook payload includes a `signedAt` field, representing the Unix timestamp of when the webhook was signed. When validating a webhook, you should verify that: * the signature is valid * the `signedAt` timestamp is close to your current system time\ Primer recommends a maximum difference of 3 minutes If Primer retries a webhook, it is signed again. Each retry has a new `signedAt` value and a new signature. ### Verify signatures (Python example) ```python theme={"dark"} import base64 import hashlib import hmac def validate_webhook_signature(payload: str, signature: str, secret: str) -> bool: mac = hmac.new( key=secret.encode("utf-8"), msg=payload.encode("utf-8"), digestmod=hashlib.sha256, ) computed = base64.b64encode(mac.digest()).decode("utf-8") return computed == signature ``` ### Set up your signing secret Create a signing secret from the **Webhooks** section of the Primer Dashboard. Signing secrets are environment specific. Each environment (Sandbox and Production) has its own secret. You can only copy the secret once. Make sure to store it securely. ### Rotate your signing secret You can rotate your active signing secret from the Dashboard at any time. When a secret is rotated: * the previous secret remains valid for 24 hours * both signatures are sent during that period Webhook request headers during rotation: * `X-Signature-Primary` signed with the new secret * `X-Signature-Secondary` signed with the previous secret During the transition window, your endpoint should verify the webhook against both signatures. ```python theme={"dark"} @router.post("/my-webhook") async def my_webhook(request: Request, payload: dict): if "X-Signature-Primary" in request.headers: verify(request.headers["X-Signature-Primary"], payload) if "X-Signature-Secondary" in request.headers: verify(request.headers["X-Signature-Secondary"], payload) return {"status": "ok"} ``` ## Checklist If you experience missing or repeated webhook events: * Ensure your endpoint responds with a `2xx` status code quickly * Avoid HTTP redirects * Handle duplicate deliveries safely * Compare `payment.dateUpdated` to determine the latest state * Verify webhook signatures and `signedAt` timestamps # Idempotency Key Source: https://primer.io/docs/api-reference/get-started/idempotency-key ## What is an idempotency key? Primer supports a request idempotency mechanism for our Payments API. This optional feature enables you to safely retry a request without risking the user being charged or refunded multiple times. This is particularly useful when an API call fails due to the request being invalid, due to a network issue, or if Primer is momentarily unavailable. If this is the case, make another request with the same idempotency key: * If a request with the same idempotency key has already been successfully processed by Primer, the new request will be ignored. A `409` error will be returned with an `errorId` set to `IdempotencyKeyAlreadyExists`. * Otherwise, Primer will attempt to process the new request. ## How to use an idempotency key To make an idempotent request, generate an idempotency key and pass it to the header `X-Idempotency-Key`. ```json theme={"dark"} curl -X POST 'https://api.primer.io/' \ --header 'X-Idempotency-Key: ' ``` The way you generate the key is totally up to you, as long as it is unique per request attempt. Keep in mind that a payment request resulting in a declined or failed payment is still considered Successfully processed for the API. Therefore, if you want to allow the user to retry an unsuccessful payment, make sure to not use the same idempotency key. As a such, don’t use anything too restrictive like an `orderId` for the idempotency key as multiple payment attempts and refunds can be made for a single order. # Request requirements Source: https://primer.io/docs/api-reference/get-started/request-requirements Send server-side requests to the Primer API from a static egress IP address so they are not blocked before they reach the API. ## Overview Primer may block API requests based on the IP address they come from. Many cloud platforms send outbound traffic from shared, dynamically assigned IP addresses by default. Other customers of the platform send traffic from the same addresses, so an address can be blocked because of their traffic rather than yours. When that happens, your requests to Primer are blocked, even though your integration has not changed. To avoid this, send all server-side requests to Primer from a static egress IP address that only you use. ## Use a static egress IP address A static egress IP address is a public IP address that you reserve. All outbound traffic from your backend to Primer uses it. This applies to every server-side call, for example: * creating and updating client sessions with `POST /client-session` and `PATCH /client-session` * creating, capturing, cancelling and refunding payments * managing saved payment methods Serverless and container platforms often use shared outbound addresses unless you configure otherwise. Route their traffic through a NAT service with a reserved IP address: | Platform | Configuration | | - | - | | Google Cloud (Cloud Run, Cloud Functions, GKE) | Route outbound traffic through Cloud NAT with a reserved static external IP address. | | AWS (Lambda, ECS, EKS, EC2) | Run the workload in a VPC and route outbound traffic through a NAT gateway with an Elastic IP address. | | Microsoft Azure | Attach a NAT gateway with a static public IP address to the workload's subnet. | Refer to your cloud provider's documentation for the setup steps. > [!NOTE] > > Configure the static egress IP address in your test environment as well as in production. This lets you confirm that requests use the new address before you go live. ## Identify a blocked request When a request is blocked, it does not reach the API and you will receive a `403` response with the `SecurityPolicyBlock` error ID: ```json theme={"dark"} { "error": { "errorId": "SecurityPolicyBlock", "description": "This request has been blocked by a security policy.", "validationErrors": [] } } ``` Blocks depend on the source IP address at the time of the request, so they can start and stop without any change to your integration. If you receive this error: 1. Check which public IP address your backend uses for outbound requests to Primer. 2. If it is a shared or dynamically assigned address, configure a static egress IP address as described above. 3. If the errors continue after you move to a static egress IP address, contact [support@primer.io](mailto:support@primer.io). Include the source IP address and the time of the failed requests. # Overview Source: https://primer.io/docs/api-reference/get-started/v2.4/overview The Primer API is used to manage Client Sessions, Payments and saved payment methods. All other actions are either managed in the Universal Checkout implementation or in the Dashboard. Check out: * [Client Sessions](/docs/checkout/client-session) * [Universal Checkout](/docs/checkout/drop-in/overview) * [Managing Payments](/docs/manage-payments/overview) Test the APIs yourself in our API Reference. Don’t hesitate to reach out with any questions or feedback. You can email Primer directly at [support@primer.io](mailto:support@primer.io), or contact your Primer account manager. ## API Endpoint Deployments * Sandbox: [https://api.sandbox.primer.io](https://api.sandbox.primer.io) * Production: [https://api.primer.io](https://api.primer.io) ## API Versions Primer makes updates to the APIs on a regular basis, as we release new features. To allow you to update your integration as you are ready, we allow for a `X-Api-Version` header to be passed on all API requests. If you omit the version header, your request will default to the earliest supported version of the API. ```bash theme={"dark"} curl -X POST 'https://api.primer.io/' \ --header 'X-Api-Version: 2.4' ``` ## Available Versions Read about the available versions of the APIs below on our [Changelog](/docs/changelogs/api-changelog). For the full policy on how each version is supported, deprecated, and retired, see the [API lifecycle](/docs/api-reference/get-started/api-lifecycle). # Create a client session Source: https://primer.io/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /client-session Creating a client session generates a client token: a temporary key used to initialize [Universal Checkout](/docs/get-started/set-up-a-checkout) and authenticate it against your account. Universal Checkout automatically retrieves all the settings from the client session and the Dashboard to configure the payment methods and the checkout experience. Note: When creating a Client Session, please make sure to provide `currencyCode`, `orderId`, and at least one of `amount` or `lineItems`. If any of these are not yet available, you can provide them when making the payment request. POST /client-session does not have required fields as all fields are not always known when a client session is created. Use PATCH /client-session to update the parameters throughout the checkout session. Client tokens expire after 24 hours. # Retrieve a client session Source: https://primer.io/docs/api-reference/v2.4/api-reference/client-session-api/retrieve-a-client-session https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml get /client-session This API call retrieves all the details associated with the client session corresponding to the client token that is provided in the request. The fields with empty values are excluded from the response. # Update client session Source: https://primer.io/docs/api-reference/v2.4/api-reference/client-session-api/update-client-session https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml patch /client-session You can update a clients session created earlier with the `PATCH /client-session` [API call](#operation/create_client_side_token_client_session_post). The only required field for the request is `clientToken`. Other supported request fields are same as for the `POST /client-session` [API call](#operation/create_client_side_token_client_session_post). You need to specify only the fields you wish to update. However, if the items to be updated are arrays (e.g.`lineItems`), you need to provide the entire array, including any new or modified items. Primer will replace the full array with whatever is sent in the request. If you want to keep existing items, make sure to include them in your request, anything omitted will be removed. If you wish to update nested fields on the client session, such as the customer `emailAddress` field, you can pass the `customer` object with only one field, `emailAddress`, to update. If you simply wish to clear the value of the field, pass `null` as your input. You can update `paymentMethod.vaultOnSuccess` field but updating of the `paymentMethod.options` field through `PATCH /client-session` is not supported. `approvalMode` and `currentAttemptId` are immutable: a request that includes either field is rejected with a `422`. The response will contain all the fields of the client session including the ones that were changed. # Abort a payment attempt Source: https://primer.io/docs/api-reference/v2.4/api-reference/payment-attempts-api/abort-a-payment-attempt https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payment-attempts/{id}/abort

Abort a payment attempt that is awaiting merchant approval. No payment is created. The tokenised payment instrument associated with the attempt is invalidated. Call this endpoint when, after tokenisation, a business decision is made that the payment should not proceed (e.g. a merchant-side fraud check flagged the transaction, the customer cancelled on the merchant's own UI, or an inventory check failed between tokenisation and approval). # Approve a payment attempt Source: https://primer.io/docs/api-reference/v2.4/api-reference/payment-attempts-api/approve-a-payment-attempt https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payment-attempts/{id}/approve

Approve a payment attempt that is awaiting merchant approval, and trigger payment authorization on Primer's side. This endpoint is the merchant entry-point of the **Backend-Driven CIT (MANUAL approval)** flow: after the SDK tokenises a payment method and the merchant backend has decided the payment should proceed (e.g. after a fraud check or inventory validation), the backend calls this endpoint to hand off orchestration to Primer (3DS, retries, webhooks). The `paymentAttemptId` is the idempotency key: concurrent or retried calls converge on a single downstream payment. # Resolve a payment attempt Source: https://primer.io/docs/api-reference/v2.4/api-reference/payment-attempts-api/resolve-a-payment-attempt https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payment-attempts/{id}/resolve

Resolve a payment attempt that succeeded or failed outside of Primer. No payment is created, and the tokenised payment instrument associated with the attempt is invalidated so it cannot be reused. Call this endpoint when you have processed the payment yourself (e.g. via a different PSP) and want to record the outcome against the attempt. Set `vaultPaymentMethod` to vault the card used for the attempt instead of invalidating it. This requires `outcome` to be `SUCCEEDED`. # Delete a saved payment method Source: https://primer.io/docs/api-reference/v2.4/api-reference/payment-methods-api/delete-a-saved-payment-method https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml delete /payment-instruments/{paymentMethodToken} Delete a saved payment method. # List saved payment methods Source: https://primer.io/docs/api-reference/v2.4/api-reference/payment-methods-api/list-saved-payment-methods https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml get /payment-instruments Retrieve a list of stored payment methods for a customer. # Save a payment method token Source: https://primer.io/docs/api-reference/v2.4/api-reference/payment-methods-api/save-a-payment-method-token https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payment-instruments/{paymentMethodToken}/vault

Save a `SINGLE_USE` payment method token so it can be used again later. If you try to vault an already vaulted token, you will get the existing vaulted token back. # Update the default saved payment method Source: https://primer.io/docs/api-reference/v2.4/api-reference/payment-methods-api/update-the-default-saved-payment-method https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payment-instruments/{paymentMethodToken}/default Update a saved payment method to be the default stored payment method for a customer. # Adjust authorized amount Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/adjust-authorized-amount https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payments/{id}/adjust-authorization

Adjust authorized amount. This is only possible if `authorizationType` was set to `ESTIMATED` when the payment was created, and the mechanism is supported by the payment method. **Failed request limit:** Primer limits how many failed requests a single payment can have. Failed capture, cancel, refund and adjust-authorization requests all count towards the same limit, which is currently 100 per payment. Once a payment reaches the limit, any further capture, cancel, refund or adjust-authorization request for that payment is rejected with a `409` and the error ID `PaymentRequestLimitExceeded`. The rejected request is not sent to the processor. Do not retry after this error: retrieve the payment to see why its previous requests failed, and contact Primer support if you need the payment unblocked. # Authorize a payment Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/authorize-a-payment https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payments/{id}/authorize

Manually authorize a payment using a provided processor. This is useful if you want to authorize a payment without a workflow action. The processor merchant ID must be provided which can be found on the [Integrations page](https://dashboard.primer.io/integrations). The processor name is optional but it must be provided if your account has multiple processors configured which share the same merchant IDs. # Cancel a payment Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/cancel-a-payment https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payments/{id}/cancel

Provided the payment has not reached `SETTLED` status, Primer will send a "void" request to the payment processor, thereby cancelling the payment and releasing the hold on customer funds. Upon success, the payment will transition to `CANCELLED`. The payload is optional. **Failed request limit:** Primer limits how many failed requests a single payment can have. Failed capture, cancel, refund and adjust-authorization requests all count towards the same limit, which is currently 100 per payment. Once a payment reaches the limit, any further capture, cancel, refund or adjust-authorization request for that payment is rejected with a `409` and the error ID `PaymentRequestLimitExceeded`. The rejected request is not sent to the processor. Do not retry after this error: retrieve the payment to see why its previous requests failed, and contact Primer support if you need the payment unblocked. # Capture a payment Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/capture-a-payment https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payments/{id}/capture

If you have successfully authorized a payment, you can now fully capture, or partially capture funds from the authorized payment, depending on whether your selected payment processor supports it. The payment will be updated to `SETTLED` or `SETTLING`, depending on the payment method type. The payload sent in this capture request is completely optional. If you don't send a payload with the capture request, the full amount that was authorized will be sent for capture. Below are the available payload attributes, which give you more granular control when capturing funds, if you require it. **Failed request limit:** Primer limits how many failed requests a single payment can have. Failed capture, cancel, refund and adjust-authorization requests all count towards the same limit, which is currently 100 per payment. Once a payment reaches the limit, any further capture, cancel, refund or adjust-authorization request for that payment is rejected with a `409` and the error ID `PaymentRequestLimitExceeded`. The rejected request is not sent to the processor. Do not retry after this error: retrieve the payment to see why its previous requests failed, and contact Primer support if you need the payment unblocked. # Create a payment Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payments

Create and authorize a payment for a given customer order. You should provide a payment method token here to avoid PCI implications. If only a payment method token is passed, the values passed with the Client Session is used to determine the amount, currency etc. Note: `amount`, `currencyCode` and `orderId` are required during payment creation. Make sure to pass these fields when creating a client session, or if not yet available, when creating a payment. All fields provided on this request will take preference over any field on the `order` associated with the client session. E.g. if you pass `amount` on this request, it will override the `amount` on the `order` associated with the Client Session. Parameters that are not on this request will be fetched from previously created Client Session and merged. E.g. if you specify `customer.billingAddress` in Client Session and then pass `customer.emailAddress` data with this request, it will automatically merge the `customer` fields and use both `billingAddress` and `emailAddress` for later calculations. # Get a payment Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml get /payments/{id}

Retrieve a payment by its ID. # Refund a payment Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/refund-a-payment https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payments/{id}/refund

Issue a full or partial refund for a previously settled payment. By default, the full amount will be refunded unless a specific amount is provided for a partial refund. If the payment was partially captured multiple times, you can specify which capture to refund by using the transaction event ID. Refer to the `transactions.events` array in the payment object to find available transaction event IDs (when the appropriate `expand` parameter is passed). When specifying a transaction event ID, the refund amount should not exceed the amount captured in that event. If no refund amount is provided, it defaults to the amount captured in that specific event. **Failed request limit:** Primer limits how many failed requests a single payment can have. Failed capture, cancel, refund and adjust-authorization requests all count towards the same limit, which is currently 100 per payment. Once a payment reaches the limit, any further capture, cancel, refund or adjust-authorization request for that payment is rejected with a `409` and the error ID `PaymentRequestLimitExceeded`. The rejected request is not sent to the processor. Do not retry after this error: retrieve the payment to see why its previous requests failed, and contact Primer support if you need the payment unblocked. # Resume a payment Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/resume-a-payment https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /payments/{id}/resume

Resume a payment's workflow execution from a paused state. This is usually required when a Workflow was paused in order to get further information from the customer, or when waiting for an asynchronous response from a third party connection. # Search & list payments Source: https://primer.io/docs/api-reference/v2.4/api-reference/payments-api/search-&-list-payments https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml get /payments

Retrieve a list of your payments. Results are paginated, they will only return up to 100 payments maximum. To access the next page of result, set the `cursor` query parameter to the value of `nextCursor` in your current result payload. Use `prevCursor` to go back to the previous page. **Note:** this endpoint returns a list of summarized payments. Not all payments attributes are present. You can use the query parameters to filter payments. You can separate multiple query parameters with the `&` symbol. Query parameters with types of the form "Array of strings" (such as the status parameter) can be specified as a comma-separated list. For example, if you wanted to get both `FAILED` and `CANCELLED` payments, for customer `john-123`, you would use: ```bash curl --location --request GET 'https://api.primer.io/payments?status=FAILED,CANCELLED&customer_id=john-123' \ --header 'X-Api-Key: ' ``` You can alternatively specify a list by repeating the parameter multiple times. Query parameters are also accepted in camelCase (for example `customerId`, `fromDate`). If both spellings are supplied, the camelCase value is used. **Note:** payments will be available within a minute from being created. # Forward a request to a PSP, substituting vaulted card data Source: https://primer.io/docs/api-reference/v2.4/api-reference/primer-proxy-api/forward-a-request-to-a-psp-substituting-vaulted-card-data https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml get /{proxyPath} Forwards the request to the host named in `X-Target-Host`, at the given path, substituting any card placeholders in the body first. Any additional headers on the request, including the merchant's own PSP credential (for example `Authorization`), are passed through unchanged. `X-Primer-Api-Key` authenticates you against Primer. A placeholder has the form `{{.}}`, for example `{{tok_abc.CARD_NUMBER}}`, and is substituted anywhere in the body. A placeholder left unresolved fails the request rather than being forwarded. The response is the target PSP's response, relayed byte-for-byte, unless the `X-Primer-Proxy-Error` response header is present, in which case Primer itself raised a fault before or after reaching the PSP. See the `default` response below for both cases. The proxy never retries a request to the PSP. # Forward a request to a PSP, substituting vaulted card data Source: https://primer.io/docs/api-reference/v2.4/api-reference/primer-proxy-api/forward-a-request-to-a-psp-substituting-vaulted-card-data-1 https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml put /{proxyPath} Forwards the request to the host named in `X-Target-Host`, at the given path, substituting any card placeholders in the body first. Any additional headers on the request, including the merchant's own PSP credential (for example `Authorization`), are passed through unchanged. `X-Primer-Api-Key` authenticates you against Primer. A placeholder has the form `{{.}}`, for example `{{tok_abc.CARD_NUMBER}}`, and is substituted anywhere in the body. A placeholder left unresolved fails the request rather than being forwarded. The response is the target PSP's response, relayed byte-for-byte, unless the `X-Primer-Proxy-Error` response header is present, in which case Primer itself raised a fault before or after reaching the PSP. See the `default` response below for both cases. The proxy never retries a request to the PSP. # Dispute lifecycle Source: https://primer.io/docs/disputes/dispute-lifecycle > [!NOTE] > > Full dispute lifecycle updates are currently available for Adyen, Airwallex, Braintree, Checkout.com, PayPal, Stripe and Worldpay. For other supported processors - currently Worldline Connect, Worldline Direct, MPGS, Payplug, and Reach - you will only receive a Webhook with a `status` of `OPEN` where the `type` is `DISPUTE`. Disputes are created in Primer when they are generated by your payment processor. All Primer disputes conform to a single dispute lifecycle, which makes them work the same way regardless of the payment services you use. A dispute always has a dispute `type` (Retrieval, Dispute, and Pre-arbitration), and `status` that depends on the `type`. Every time the `status` or `type` is updated, a new [`DISPUTE.STATUS` webhook](/docs/api-reference/endpoints/v2.4/dispute-and-chargebacks-webhooks/dispute-status) will be sent. ![Dispute lifecycle](https://goat-assets.production.core.primer.io/marketing/disputes/external-docs/dispute-lifecycle/dispute-lifecycle.png) Dispute lifecycle > [!NOTE] > > Visa and Mastercard do not investigate payments before raising a dispute. As a result, these payment methods skip `RETRIEVAL` and go straight to the `DISPUTE` event type. ## Dispute Types As in the diagram above, Primer's disputes framework separates disputes into three different types: `RETRIEVAL`, `DISPUTE` and `PREARBITRATION` ### RETRIEVAL A `RETRIEVAL` signifies an investigation into a payment has been launched. For cards, this is launched by a card issuer. Depending on the results of this investigation, a `DISPUTE` may be raised, and the payment can be reversed. This dispute type is not used by all payment methods or card schemes - Visa and Mastercard do not support it. | **`status`** | **Description** | | - | - | | `OPEN` | Occurs when an investigation is launched into a payment. The merchant has not been debited for this yet. | | `EXPIRED` | Occurs when a retrieval is opened and the merchant has taken too long to provide evidence in a challenge. | | `CHALLENGED` | Occurs when a retrieval is opened, and the merchant submits evidence to uphold the original sale. | ### DISPUTE A `DISPUTE` occurs when a payment is reversed by the payment method (card issuer) after a customer complaint. The end customer will receive money back, and the processor will then debit the merchant the equivalent amount. For card payments, this is also known as a chargeback. | **`status`** | **Description** | | - | - | | `OPEN` | Occurs when a payment has been disputed, and your processor account has debited. | | `ACCEPTED` | Occurs when a disputed payment has been accepted - acknowledged as a fair dispute by the merchant. | | `CHALLENGED` | If a merchant thinks that a dispute has been unfairly raised, they can challenge it. This event is sent when a merchant submits evidence to challenge a dispute, and uphold the original sale. | | `EXPIRED` | Merchants only have a finite time window in which they can challenge a dispute. This status is set when that time window expires. | | `CANCELLED` | When a dispute is withdrawn by the end customer who raised the initial dispute, the dispute status will be changed to CANCELLED. | | `WON` | If a dispute has been successfully challenged by the merchant, the dispute status will be updated to `WON`. For some card flows, this is known as a chargeback reversal. | | `LOST` | If a dispute has been unsuccessfully challenged, the dispute status will be updated to `LOST`. | ### PREARBITRATION If a merchant successfully challenges a dispute, but the payment method (usually a card issuer) believes a further review is required, a `PREARBITRATION` dispute type will be opened. This is effectively an ‘appeal’ process. | **`status`** | **Description** | | - | - | | `OPEN` | If a dispute has been challenged, but is appealed, the dispute status will be updated to `OPEN`. For cards, this occurs if the card issuer does not feel the evidence was compelling enough. | | `WON` | Occurs when the pre-arbitration is won by the merchant, confirming the dispute has been overturned. | | `LOST` | Occurs when the pre-arbitration is lost by the merchant, confirming the original dispute will stand. This is sometimes known as a second chargeback. | # Manage disputes Source: https://primer.io/docs/disputes/manage-disputes ## What are disputes and chargebacks? A **dispute** is an umbrella term for customers contacting their payment provider to request a transaction is reversed and receive their money back. Online sellers will be notified by a payment processor when this occurs. These notifications can be used to proactively communicate with customers, issue refunds, send disputes to risk tools, or to automatically defend disputes. > [!TIP] > > Sometimes *chargeback* and *dispute* can be used interchangeably - at Primer we use the more generic term of 'dispute' as 'chargeback' is usually associated with card payments only. Don't worry if you're looking for information on chargebacks - you're in the right place! A dispute in Primer has: * a **dispute type** and **status** that conforms to a unified dispute lifecycle * information about the original payment submitted to Primer, such as payment method, order ID, and payment ID > [!WARNING] > > **The following currencies are not supported for dispute management:** > > BHD, BIF, CLP, CVE, GNF, HUF, IDR, INR, ISK, KHR, KMF, MMK, PYG, RWF, SAR, UGX, VED, VES, VND, XOF, XPF > > If a dispute is received in one of these currencies no webhook will be triggered. ## Access your dispute information Our [`DISPUTE.STATUS` webhook](/docs/api-reference/endpoints/v2.4/dispute-and-chargebacks-webhooks/dispute-status) will notify you when a dispute event has been received from the processor. The webhook can be set up inside the Primer dashboard. If you want to know more about webhooks, check out our [Webhook guide](/docs/api-reference/get-started/configure-webhooks). For these webhooks to be sent from Primer, you also first have to set up dispute notifications to be sent to Primer from within the processor dashboard. ## Primer Disputes app The [Primer Disputes app](/docs/workflows/apps/native-apps/primer-disputes-app/dispute-status-update-trigger) allows our unified disputes to be used in [Primer Workflows](/docs/get-started/create-workflow). When a new dispute is received from a processor, the dispute app can automate sharing the unified dispute format with other apps. For example, this can be used to send dispute events to fraud tools like Riskified, who often require this information to improve risk models, or indemnify chargebacks. # Overview Source: https://primer.io/docs/disputes/overview ## Handle disputes with ease Track dispute statuses, trigger actions, and keep your systems in sync with automated updates. ![Handle disputes with ease](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/disputes/banner/light.png) ## Analyse all your payments data in one place > [card] [Manage disputes](/docs/disputes/manage-disputes) > > Monitor dispute activity across all processors and respond with workflows and alerts. > [card] [Disputes lifecycle](/docs/disputes/dispute-lifecycle) > > Stay informed through every stage of a dispute, from initiation to resolution. # Adjust authorization Source: https://primer.io/docs/manage-payments/adjust-authorization > [!NOTE] > > This page is only relevant for card payments. ## What is adjust authorization? There are scenarios where the final amount of the payment is not known at payment creation (the initial authorization). Adjust authorization, sometimes referred to as incremental authorization, is a mechanism that enables the authorized amount to be adjusted before finally capturing the payment. This gives merchants great flexibility to increase the amount authorized as conditions change or additional charges accrue. This is the preferred implementation to: * Capturing an amount greater than the authorized amount, which is more likely to be rejected by the card networks * Canceling and reauthorizing for larger amount, which can incur additional processor fees and negatively affects the customer experience > [!NOTE] > > The initial authorization is still necessary. As its name suggests, authorization adjustment aims to modify an authorization that happened previously for an estimated amount. Below are some use cases where authorization adjustment is applicable: > [card] Hospitality > > The final amount may change based on additional incurred costs after the initial payment. > [card] Micromobility / Transport Renting > > The journey length is unknown at the beginning of the journey and so the amount to charge is also not known - it can > only be estimated. > [card] Food ordering/delivery > > An amount is usually authorized at the point of order creation but the final amount can vary up to when the delivery is complete, such as an additional tip or an updated order. ## Availability Adjust authorization is available for Visa, MasterCard, Amex, and Discover card networks, where these networks set specific rules around which businesses are able to adjust an authorization. Your eligibility is determined by your Merchant Category Code (MCC), where support is ultimately up to the issuer. To access the feature, you will need to use a processor on Primer that supports this capability. Below are the processors currently supported on Primer for adjust authorization: * Checkout.com * Paygent Primer is extending the usage across all our connected processors where it’s supported. If there is a processor you use that isn’t currently available, please reach out to your CSM. > [!NOTE] > > Primer is the underlying payment infrastructure and you should still speak to your processor before implementing authorization adjustment to ensure it’s enabled for your account for each card network. ## Get Started with adjust authorization > [!NOTE] > > Only available on API >= v2.2 You can implement adjust authorization in 3 steps: 1. Authorize the payment with an estimated amount 2. Adjust the estimated amount by calling POST 3. Capture the final amount ### Step 1: Create estimated authorization First, you need to pass the flag `authorizationType` = `ESTIMATED` on either: * POST or PATCH * POST if using the advanced manual SDK flow `authorizationType` defaults to `FINAL` if not set to `ESTIMATED`. Authorization adjustments only work on estimated authorizations so without this step, any future attempts to adjust the authorization will not work. #### POST or PATCH `/client-session` ```json JSON theme={"dark"} // POST or PATCH /client-session { "customerId": "customer-123", "amount": 2000, "currencyCode": "GBP", "orderId": "order-123", "paymentMethod": { "authorizationType": "ESTIMATED" } } // response - 200 OK { "customerId": "customer-123", "orderId": "order-123", "amount": 2000, "currencyCode": "GBP", "paymentMethod": { "vaultOnSuccess": false, "authorizationType": "ESTIMATED" }, "clientToken": "client-token-string", "clientTokenExpirationDate": "2023-11-15T10:30:36.020109" } ``` As the `authorizationType` field is optional, it is only included in the response if it is passed on the request. So, by default, this field will not be included in the client session response unless you actively choose to pass it in the request. #### POST /payments ```json JSON theme={"dark"} // POST /payments { "orderId": "order-123", "amount": 2000, "currencyCode": "GBP", "customerId": "customer-123", "paymentMethodToken": "payment-method-token", "paymentMethod": { "authorizationType": "ESTIMATED" } } // response - 200 OK { "id": "kkdEwEEE", "date": "2023-03-21T15:36:16.367687", "status": "AUTHORIZED", "orderId": "order-123", "currencyCode": "GBP", "amount": 2000, "customerId": "customer-123", "paymentMethod": { "authorizationType": "ESTIMATED", "paymentMethodToken": "payment-method-token", ... }, ... } ``` `authorizationType` is always returned in the response to the `POST /payments` endpoint, even if it’s not included in the request - the default `FINAL` will be returned if it’s not set to `ESTIMATED` in the request. Also, as is the case with all other fields, the `authorizationType` value provided in `POST /payments` takes priority over the client session value if you add the field to both requests. ### Step 2: Submit adjust authorization When you want to adjust the authorization amount for a successful estimated authorization, send POST and pass the `amount` field which should equal the new desired authorized amount: ```json JSON theme={"dark"} // POST /payments//adjust-authorization { "amount": 5000 } // response - 200 OK { "id": "kkdEwEEE", "date": "2023-03-21T15:36:16.367687", "status": "AUTHORIZED", "orderId": "order-123", "currencyCode": "GBP", "amount": 5000, "customerId": "customer-123", "paymentMethod": { "authorizationType": "ESTIMATED", "paymentMethodToken": "payment-method-token", ... }, ... } ``` This API call is always synchronous and will not be successful if: * `authorizationType` = `FINAL` * `status` ≠ AUTHORIZED * `paymentInstrumentType` ≠ `PAYMENT_CARD` * the processor used on the initial estimated authorization does not support authorization adjustment. * the amount is not correct (e.g. the processor only supports amount greater than the authorized amount) > [!NOTE] > > See more about this endpoint in the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/adjust-authorized-amount), including examples of unsuccessful responses. You can submit multiple authorization adjustments but the rules around the number supported varies per processor and per network and this could result in failed adjust authorization requests. It’s recommended you confirm your expected use case with your processor. ### Step 3: Capture final amount When you’re ready and the final amount has been authorized, simply capture the payment as usual and it will use the last authorized amount from the last successful authorization adjustment. > [!NOTE] > > [See more here about how to capture a payment.](/docs/manage-payments/capture-payment) ## Additional information * No webhook is sent for a successful adjust authorization as no payment status change has occurred. You can confirm the adjust authorization request is successful by the response to the API request as it is synchronous. * The authorization adjustment event will appear in the payment timeline, including the request and response to the processor. ![](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/adjust-authorization/adjust-auth-timeline.png) Adjust Authorization event in payment timeline * Usually, an unsuccessful adjust authorization doesn’t impact the initial authorization but it’s advised you confirm this with your processor. # Cancel payments Source: https://primer.io/docs/manage-payments/cancel-payment ## How to cancel a payment Primer enables you to cancel a payment across all your processors in a unified way. By cancelling a payment, the authorization is voided and the hold on customer funds is released. In order to cancel a payment, the payment must not have reached SETTLED status. Once the payment is cancelled, the payment can no longer be captured. All cancel requests are sent to the processor used in the authorization request. To check the status of the payment, you can use: * the [payments timeline](https://dashboard.primer.io/payments) in the Primer Dashboard * payment webhooks to [receive status updates](/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-status-update) * the GET API call Cancel a payment with Primer in three ways: > [card] [Payments timeline](#cancel-a-payment-via-the-payments-timeline) > > Manually cancel a payment from an easy-to-use dashboard. > [card] [Workflows](#cancel-a-payment-via-workflows) > > Automate sophisticated payment flows to cancel your payments. > [card] [Payments API](#cancel-a-payment-via-payments-api) > > Programmatically cancel your payments via API based on your business logic. ### Cancel a payment via the Payments Timeline > [!NOTE] > > This is useful to enable your team to cancel payments directly from within the dashboard. Manually cancel a specific payment from the Payments Timeline in the Primer Dashboard. Select the payment from the list view and navigate to the specific payment details page. If the payment has AUTHORIZED or PENDING status, the **Cancel** button in the top right corner will be enabled. ![Cancel button enabled](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/cancel/can-cancel.png) Cancel button enabled Once you select the **Cancel** button, the cancel request will be sent to the processor. After it's been processed, the payment will be cancelled and the payment details page will reflect this. ![Cancelled payment details](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/cancel/canceled-payment.png) Cancelled payment details ### Cancel a payment via Workflows Use Workflows to set up business logic on when and how to cancel a payment - without writing a single line of code. Simply add the ["Cancel payment" action](/docs/workflows/apps/native-apps/primer-payments-app/cancel-payment-action) from the Primer Payments app to a workflow. You can configure any additional business flows in between your ["Authorize payment"](/docs/workflows/apps/native-apps/primer-payments-app/authorize-payment-action) and "Cancel payment" actions, creating powerful payment flows that suit your needs. For example, you may want to validate that the processor CVV and AVS checks `MATCHED` and, if not, cancel the payment - this becomes very easy with Primer. ![Cancelled action example](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/cancel/cancel-payment-action-example.png) Cancelled action example Learn more [here](/docs/workflows/apps/native-apps/primer-payments-app/cancel-payment-action) about the Payments app and the "Cancel payment" action. ### Cancel a payment via Payments API Cancel a payment using the Payments API - see the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/cancel-a-payment) for the details. ```bash BASH theme={"dark"} curl --request POST \ --url https://api.sandbox.primer.io/payments//cancel \ --header 'X-API-KEY: ' \ --header 'X-API-VERSION: 2.2' \ --header 'X-Idempotency-Key: ' ``` Include the Primer payment ID in the request, which you will have received as part of the payment creation and authorization. It is optional to pass the cancellation `reason` in the payload for your own records. # Capture payments Source: https://primer.io/docs/manage-payments/capture-payment ## What does payment capture do? Capturing a payment is the act of settling funds after the payment is authorized. A capture payment call is a request to a payment processor to actually charge the customer’s account and transfer the funds to the merchant's account. This typically occurs after an authorization payment call has been made, ensuring that the funds will be available when the capture payment request is made. The capture payment call is an essential part of the payment process, as it ensures that the merchant receives the funds that they are owed for the goods or services that they have provided. ## How to capture a payment > [!NOTE] > > Some non-card payment methods will automatically capture the payment after the authorization. Primer enables you to fully or partially capture an authorized payment across all your processors in a unified way. In order to capture a payment, its status must be AUTHORIZED. If the capture is successful, the payment status will be automatically updated to: * SETTLED if the processor captured the payment immediately * SETTLING if the processor needs more time to capture the payment i.e. asynchronous capture. See the [section](#handle-asynchronous-capture) below for more. * PARTIALLY\_SETTLED if only a part of the authorized amount was captured - see the [section](#partial-capture) below for more. All capture calls are sent to the processor used in the authorization request. To check the status of the payment, you can use: * the [Payments timeline](https://dashboard.primer.io/payments) in the Primer Dashboard * payment webhooks to [receive status updates](/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-status-update) * the GET API call Capture a payment with Primer in two ways: > [card] [Workflows](#capture-a-payment-via-workflows) > > Automate sophisticated payment flows to capture your payments. > [card] [Payments API](#capture-a-payment-via-payments-api) > > Programmatically capture your payments via API based on your business logic. ### Capture a payment via Workflows Use Workflows to set up business logic on when and how to capture a payment - without writing a single line of code. In your payment workflow, once you have an ["Authorize payment" action](/docs/workflows/apps/native-apps/primer-payments-app/authorize-payment-action) set up from the Primer Payments app, simply add your ["Capture payment" action](/docs/workflows/apps/native-apps/primer-payments-app/capture-payment-action). You can configure any additional business flows in between your "Authorize payment" and "Capture payment" actions, creating powerful payment flows that suit your needs. For example, you may want to send an email to the customer immediately after a successful authorization before capturing the payment - this becomes very easy with Primer. ![Example workflow](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/capture/example-workflow.png) Example workflow > [!NOTE] > > Asynchronous capture considerations still apply to the "Capture payment" action in Workflows. It’s recommended to use Primer’s payment webhooks to confirm when the payment status is SETTLED. Learn more [here](/docs/workflows/apps/native-apps/primer-payments-app/capture-payment-action) about the Payments app and the "Capture payment" action. ### Capture a payment via Payments API Capture a payment using the Payments API - see the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/capture-a-payment) for the details. ```bash BASH theme={"dark"} curl --request POST \ --url https://api.sandbox.primer.io/payments//capture \ --header 'X-API-KEY: ' \ --header 'X-API-VERSION: 2.2' \ --header 'X-Idempotency-Key: ' ``` Include the Primer payment ID in the request, which you will have received as part of the payment creation and authorization. The payload sent in the capture request is completely optional and can be used to partially capture the payment. See the [section](#partial-capture) below to learn more about partial captures. There are several use cases where you may want to capture via API versus Workflows, including scenarios where the full amount isn’t known at the time of authorization. An example is micromobility services where the final amount is based on the duration of the ride post-authorization. As a result, it may be easier to trigger capturing the payment based on internal information rather than via a workflow. ## Handle asynchronous capture Capture can be asynchronous i.e. once the capture call is sent to the processor, it can take some time for the payment to become SETTLED. As a result, it’s recommended you use payment webhooks to receive updates on when the payment becomes SETTLED and not rely on the response to the capture call, which will only tell you that the capture request was successful, not necessarily that the payment is SETTLED. When you attempt to capture a payment with such a processor, the payment status is first set to SETTLING. The processor then automatically notifies Primer once the capture is completed, which sets the payment status to SETTLED and the payment status webhook event to be sent to you. Read more [here](/docs/api-reference/get-started/configure-webhooks) on how to handle webhooks. ## Partial Capture > [!NOTE] > > Not all processors and payment methods support partial capture. Please see the details of the specific processor or payment method to learn more about the capabilities supported. You can choose to capture an amount less than the full authorization amount. There are several use cases where this is valuable, including: * the final amount isn't known at authorization and ends up being less than the authorized amount. * the order is made of multiple physical products that should be shipped separately - do multiple partial captures, one per product shipped. You can partially capture a payment via both Workflows and the Payments API. There are two inputs you can provide which are needed to partial capture: * `amount` - the amount you want to capture. If no amount is specified, it defaults to the full amount. * `final` - if `True` (it is by default), no subsequent captures are allowed, but if `False`, subsequent capture calls are supported. So, for a partial capture, simply set: * the `amount` input to less than the authorization amount If you want to make multiple partial captures, set: * `final` to `False` For subsequent capture requests, the default amount is then calculated by ` - `. ### Refunds Over Partial Captures Primer also supports **refunds over partial captures**, giving you more flexibility in managing your payments. This feature is particularly useful for scenarios like **marketplaces** or logistics-driven workflows. For example, you can capture payments once per seller in a marketplace or once per shipment, ensuring your payment process aligns with your business operations. Each partial capture is uniquely identified by a `transactionEventId`, allowing you to target specific partial captures for refunds with precision and ease. **Limitations to Be Aware Of** While these features are designed to enhance your payment workflows, there is one important consideration: * **Concurrent Partial Captures**: Currently Primer API have certain limitations around handling multiple partial captures at the same time, so we highly recommend to make submit them in sequential manner. > [!WARNING] > > If you want to use this feature, **please contact us** to ensure we can accompany you through the implementation and help address any specific needs or challenges. # Overview Source: https://primer.io/docs/manage-payments/overview ## Control every stage of the payment lifecycle Handle key payment actions like captures, refunds, and updates with tools that simplify managing payments. ![Control every stage of the payment lifecycle](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/payment-operations/banner/light.png) ## Manage payments > [card] [Capture](/docs/manage-payments/capture-payment) > [card] [Cancel](/docs/manage-payments/cancel-payment) > [card] [Refund](/docs/manage-payments/refund-payment) > [card] [Adjust authorization](/docs/manage-payments/adjust-authorization) > [card] [Search payments](/docs/manage-payments/search-payments) # Refund payments Source: https://primer.io/docs/manage-payments/refund-payment ## How to refund a payment Primer enables you to fully or partially refund a settled payment across all your processors in a unified way. In order to refund a payment, its status must be SETTLED. Once refunded, the payment will continue to have: * `status` = SETTLED * `amount` = original settled amount but the payment object will be updated to show the refund details. Specifically: * the processor refund transaction will be part of the `transactions` list * `processor.amountRefunded` will be set to the total refunded amount Below is an example payment object that has been refunded: ```json JSON theme={"dark"} { "id": "ehFTWmh3", "date": "2022-12-05T12:35:46.204690", "amount": 11000, "currencyCode": "GBP", "orderId": "39526", "status": "SETTLED", "paymentMethod": { "paymentMethodToken": "Q-FcqfYCSa2hh2eMqZBjfHwxNjcwMjQzNzQ1", "isVaulted": false, "analyticsId": "fm1_-IOlVoK9eY09EP6-YV8w", "paymentMethodType": "PAYMENT_CARD", "paymentMethodData": { "last4Digits": "1111", "first6Digits": "411111", "firstDigits": "41111111", "expirationMonth": "12", "expirationYear": "2025", "cardholderName": "Joe Bloggs", "network": "Visa", "isNetworkTokenized": false, "binData": { "network": "VISA", "issuerCountryCode": "US", "issuerName": "JPMORGAN CHASE BANK, N.A.", "regionalRestriction": "UNKNOWN", "accountNumberType": "UNKNOWN", "accountFundingType": "UNKNOWN", "prepaidReloadableIndicator": "NOT_APPLICABLE", "productUsageType": "UNKNOWN", "productCode": "UNKNOWN", "productName": "UNKNOWN" } }, "threeDSecureAuthentication": { "responseCode": "NOT_PERFORMED" } }, "processor": { "name": "STRIPE", "processorMerchantId": "acct_1MBdnMJdRxA3z8D5", "amountCaptured": 11000, "amountRefunded": 11000 }, "transactions": [ { "date": "2022-12-05T12:35:47.078285", "amount": 11000, "currencyCode": "GBP", "transactionType": "SALE", "processorTransactionId": "pi_3MBdtgJdRxA3z8D50HwTkJ7A", "processorName": "STRIPE", "processorMerchantId": "acct_1MBdnMJdRxA3z8D5", "processorStatus": "SETTLED" }, { "date": "2022-12-06T21:55:02.830051", "amount": 11000, "currencyCode": "GBP", "transactionType": "REFUND", "processorTransactionId": "re_3MBdtgJdRxA3z8D50WBvqRLy", "processorName": "STRIPE", "processorMerchantId": "acct_1MBdnMJdRxA3z8D5", "processorStatus": "SETTLED" } ] } ``` All refund calls are sent to the processor used in the authorization and capture request. To check the refund status and details of a payment, you can use: * the [Payment timeline](https://dashboard.primer.io/payments) in the Primer Dashboard * payment webhooks to receive the refund complete event - see the [API reference](/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-refund) for more. * the GET API call Refund a payment with Primer in three ways: > [card] [Payments timeline](#refund-a-payment-via-the-payments-timeline) > > Manually refund a payment from an easy-to-use dashboard. > [card] [Workflows](#refund-a-payment-via-workflows) > > Automate sophisticated payment flows to refund your payments. > [card] [Payments API](#refund-a-payment-via-payments-api) > > Programmatically refund your payments via API based on your business logic. ### Refund a payment via the Payments Timeline > [!NOTE] > > This is useful to enable your customer support to provide refunds directly from within the dashboard. Manually refund a specific payment from the Payments Timeline in the Primer Dashboard. Select the payment from the list view and navigate to the specific payment details page. If the payment has SETTLED, the **Refund** button in the top right corner will be enabled. ![Refund button enabled](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/refund/can-refund-eg.png) Refund button enabled Once the **Refund** button is selected, specify the amount you want to refund in the modal. ![Specify refund amount](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/refund/refund-modal.png) Specify refund amount After the refund is processed and complete, the refunded amount will appear next to the payment amount at the top of the payment details page. ![Refunded example](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/refund/payment-refunded.png) Refunded example Once the total settled amount is refunded, you will no longer be able to refund the payment and the **Refund** button will become disabled. ### Refund a payment via Workflows Use Workflows to set up business logic on when and how to refund a payment - without writing a single line of code. Simply add the ["Refund payment" action](/docs/workflows/apps/native-apps/primer-payments-app/refund-payment-action) from the Primer Payments app to a workflow. Learn more [here](/docs/workflows/apps/native-apps/primer-payments-app/refund-payment-action) about the Payments app and the "Refund payment" action. > [!NOTE] > > Asynchronous refund considerations still apply to the "Refund payment" action > in Workflows. It's recommended to use Primer's payment webhooks to confirm > when the payment is refunded. ### Refund a payment via Payments API Refund a payment using the Payments API - see the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/refund-a-payment) for the details. ```bash BASH theme={"dark"} curl --request POST \ --url https://api.sandbox.primer.io/payments//refund \ --header 'X-API-KEY: ' \ --header 'X-API-VERSION: 2.2' \ --header 'X-Idempotency-Key: ' ``` Include the Primer payment ID in the request, which you will have received as part of the payment creation and authorization. The payload sent in the refund request is completely optional and can be used to partially refund the payment. See the [section](#partial-refund) below to learn more about partial refunds. You can also provide a `reason` input that can be used for your own records. ## Handle asynchronous refund Refunds are usually processed asynchronously. Once the refund request has been made, the refund, and movement of funds back to the customer, will occur and could take days. As a result, it’s recommended to set up the refund webhook notification event. Primer notifies you with a `PAYMENT.REFUND` webhook event when a refund request has been fully processed by a payment processor and the refund has reached a final state. To determine whether the refund was successful, check the most recent refund transaction in the `transactions` list. Below is an example of a processor refund transaction: ```json JSON theme={"dark"} { "date": "2022-12-06T21:55:02.830051", "amount": 11000, "currencyCode": "GBP", "transactionType": "REFUND", "processorTransactionId": "re_3MBdtgJdRxA3z8D50WBvqRLy", "processorName": "STRIPE", "processorMerchantId": "acct_1MBdnMJdRxA3z8D5", "processorStatus": "SETTLED" } ``` * If `transactionType` = `REFUND` and `processorStatus` = SETTLED, the refund was successful and the funds have been returned to the customer * If `transactionType` = `REFUND` and `processorStatus` = FAILED, the refund was unsuccessful Read more [here](/docs/api-reference/get-started/configure-webhooks) on how to handle webhooks. ## Partial refund > [!NOTE] > > Not all processors and payment methods support partial refunds. Please see the details of the specific processor or payment method to learn more about the capabilities supported. You can partially refund a payment by setting the optional `amount` input to less than the full settled amount. For subsequent refund requests, the default amount is then calculated by ` - `. You will not be able to have partial refunds that sum to a greater amount than the settled amount. # Search payments Source: https://primer.io/docs/manage-payments/search-payments ## Search for a specific payment You can search for a specific payment and get all the details via: > [card] [Primer Dashboard](#search-for-a-specific-payment-via-the-primer-dashboard) > > Easy-to-use UI to browse and review the details of all your payments. > [card] [Payments API](#search-for-a-specific-payment-via-payments-api) > > Retrieve details of your payments programmatically via API. ### Search for a specific payment via the Primer Dashboard Navigate to the [Payments](https://dashboard.primer.io/payments) section of the Primer Dashboard. To find your specific payment, either: * scroll through until you find your payment * enter the Primer payment ID into the search bar * add your Primer payment ID to the following URL: `https://dashboard.primer.io/payments/` All methods will direct you to the payment details page, where you will see a summary of the key details of the payment, along with a detailed timeline of all events during your payment’s lifecycle. ![Detailed payments timeline](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/search/detailed-payment-timeline.png) Detailed payments timeline View all the requests and responses for each event in the timeline by simply selecting it, along with a summary of the key details of the event. ![Timeline event summary example](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/search/timeline-event-summary.png) Timeline event summary example ### Search for a specific payment via Payments API Use the GET request to retrieve the full payment object. See the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) for more details. Include the Primer payment ID in the request which you will have received as part of the payment creation and authorization. Below is an example response: ```json JSON theme={"dark"} { "id": "kHdEw9EG", "date": "2021-02-21T15:36:16.367687", "status": "AUTHORIZED", "orderId": "order-abc", "customerId": "customer-123", "currencyCode": "EUR", "amount": 42, "paymentMethod": { "paymentMethodToken": "heNwnqaeRiqvY1UcslfQc3wxNjEzOTIxNjc4", "isVaulted": true, "descriptor": "Purchase: Socks", "analyticsId": "VtkMDAxZW5isH0HsbbNxZ3lo", "paymentMethodType": "PAYMENT_CARD", "paymentMethodData": { "first6Digits": "411111", "firstDigits": "41111111", "last4Digits": "1111", "expirationMonth": "12", "expirationYear": "2030", "cardholderName": "John Biggins", "network": "Visa", "isNetworkTokenized": false, "binData": { "network": "VISA", "regionalRestriction": "UNKNOWN", "accountNumberType": "UNKNOWN", "accountFundingType": "UNKNOWN", "prepaidReloadableIndicator": "NOT_APPLICABLE", "productUsageType": "UNKNOWN", "productCode": "VISA", "productName": "VISA" } } }, "processor": { "name": "STRIPE", "processor_merchant_id": "acct_stripe_1234", "amountCaptured": 0, "amountRefunded": 0 }, "transactions": [ { "type": "SALE", "processorStatus": "AUTHORIZED", "processorName": "STRIPE", "processorMerchantId": "acct_stripe_1234", "processorTransactionId": "54c4eb5b3ef8a", "authorizationCode": "831000" } ], "customer": { "email": "customer123@gmail.com" }, "metadata": { "productId": 123, "merchantId": "a13bsd62s" } } ``` ## Search for a set of payments Retrieve all payments or a subset of payments based on a set of conditions, including a date range, status, and other searchable fields. Search for a set of payments via: > [card] [Primer Dashboard](#search-for-a-set-of-payments-via-the-primer-dashboard) > > Easy-to-use UI to browse and review the details of all your payments. > [card] [Payments API](#search-for-a-set-of-payments-via-the-payments-api) > > Retrieve details of your payments programmatically via API. ### Search for a set of payments via the Primer Dashboard Navigate to the [Payments](https://dashboard.primer.io/payments) section of the Primer Dashboard. You can search in two ways: * Use the search bar and enter multiple terms separated with commas * Use the [Filters](/docs/concepts/filters-and-dimensions) The filters are comprehensive and allow you to retrieve the subset of payments you are looking for based on: * date range * currency and amount * status * processor * payment method * events * decline types and reasons ![Filters example](https://goat-assets.production.core.primer.io/marketing/payment-operations/external-docs/search/payment-filters.png) Filters example ### Search for a set of payments via the Payments API Use the [`GET list payments`](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) request to retrieve a list of payments. Filter your payments on as many conditions as you’d like and separate multiple query parameters with the `&` symbol. Results are paginated and will return up to 100 payments in a single call. To access the next page of results, set the `cursor` parameter to the value of `nextCursor` from the last result payload. This endpoint returns a list of summarized payment objects i.e. not the full payment object outputted in the `GET` call when retrieving a specific payment. Here is an example response: ```json JSON theme={"dark"} { "data": [ { "id": "IHQlakKC", "date": "2021-03-24T14:56:56.869248", "status": "SETTLED", "orderId": "my-order-123", "currencyCode": "EUR", "amount": 700, "processor": { "name": "STRIPE", "processorMerchantId": "acct_stripe_1234" }, "metadata": { "productId": 123, "merchantId": "a13bsd62s" } } ], "nextCursor": "string", "prevCursor": "string" } ``` See the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) for the full list of query parameters. > [!NOTE] > > Payments will be available up to a minute from being created. # Managing Monitors Source: https://primer.io/docs/monitors/management Monitors offer you the capability to track crucial payment metrics in near real-time, enabling you to stay on top of your payment operations. Setting up a monitor is a straightforward process, and you can access this feature via the [Monitors](https://dashboard.primer.io/monitors) section in the Primer dashboard. Monitors come in two distinct variations, each serving specific monitoring needs. ### Static Monitors Static monitors empower you to establish a predefined threshold for your selected metric. When using a static monitor, you set a specific limit that your metric should not surpass. If it exceeds this threshold, the monitor triggers, alerting you to the issue. [https://www.loom.com/embed/2337fd10938b4ca0a6f6985f1bde50e3](https://www.loom.com/embed/2337fd10938b4ca0a6f6985f1bde50e3) ### Dynamic Monitors Dynamic monitors take a different approach by predicting an acceptable range for the metric based on historical data and trends. These monitors trigger alerts when the metric falls outside of this expected range. Dynamic monitors provide a more adaptable way to monitor your payment metrics by accounting for natural fluctuations and trends. In the following sections, we will explore how to create, configure, and manage both static and dynamic monitors to ensure you have a comprehensive understanding of your payment data and can take timely actions to optimize your payment operations. To set up a new Monitor, follow these simple steps: 1. Click the **add new monitor** button located in the top right-hand corner of the Monitors home page. 2. Provide a **descriptive name** for your monitor. A clear and recognizable name will make it easy to identify the monitor in the future. 3. Choose the **type of monitor** you want to create. Depending on your requirements, you can opt for either a **Dynamic Monitor** or a **Static Monitor**. * For **Dynamic Monitors**, you need to specify the **payment metric** you want to monitor and set the **minimum number of samples**. The minimum number of samples determines how many payments must be included for the monitor to trigger. Be mindful that setting a lower value for this parameter can lead to more frequent notifications. Dynamic monitors take 6 days to become active once they are created. * Static Monitors require additional configuration. Along with the **metric** and **minimum number of samples**, you'll need to set the **threshold value** and specify the **threshold direction**. For example, if you want to monitor the authorization rate, you would set the direction as "below" to be notified if the measured value drops below a fixed percentage. Static monitors also require you to define the **time window** that the monitor will consider when assessing the metric. The minimum sample window is 5 minutes, meaning the metric will be calculated for the previous 5 minutes. 4. You have the option to select from a range of **filters** to gain a granular view of the metric you wish to monitor. These filters cover various aspects, including processors, payment methods, 3D Secure responses, and even highly detailed data like BIN information. By following these straightforward steps, you can effortlessly create new monitors tailored to your payment metrics, ensuring that you have full control over your payment operations' real-time monitoring. [https://www.loom.com/embed/bd394f9768ba44fcac40878f99805924?sid=9d825ce4-a9a7-49f4-885b-63fc962cdecd](https://www.loom.com/embed/bd394f9768ba44fcac40878f99805924?sid=9d825ce4-a9a7-49f4-885b-63fc962cdecd) ### Editing a Monitor 1. Locate the monitor you wish to edit on the Monitor home page. 2. Click on the **three dots** indicating the menu found on the monitor card. When editing a monitor, you can make adjustments to the following parameters: * **Monitor Name**: Modify the name of the monitor for clarity and accuracy. * **Minimum Number of Samples**: Adjust the threshold for the number of samples needed to trigger the monitor. * **Filters**: Edit or update any filters that are applied to the monitor. This allows you to fine-tune the monitoring criteria according to your evolving needs. ![Editing a monitor](https://goat-assets.production.core.primer.io/marketing/monitors/external-docs/monitors/obs-editing-monitors.png) Editing a monitor ### Deleting a Monitor If you no longer require a monitor, you can easily remove it: 1. Locate the monitor you want to delete on the Monitor home page. 2. Click on the **three dots** in the monitor menu card, which is typically situated within the monitor card. 3. Select the option to **delete** the monitor. Deleting a monitor is a straightforward process, providing you with the flexibility to manage your monitoring configurations as your payment operations evolve. ![Deleting a monitor](https://goat-assets.production.core.primer.io/marketing/monitors/external-docs/monitors/obs-deleting-monitors.png) Deleting a monitor # Monitor notifications Source: https://primer.io/docs/monitors/notifications ## Monitor Events Monitor events are triggered when specific conditions are met: * **Static Monitors**: Events occur when the metric surpasses the predefined threshold, either going **above or below** the desired range. * **Dynamic Monitors**: Events are generated when the metric value falls **outside of the expected range**, as defined by the dynamic monitor model. This model considers historical data and trends. All monitor events can be found in the **event table** within the Monitor section of your dashboard. This table keeps you informed about your payment metrics' status. Events are displayed in the event table only when the **minimum number of samples** is met. This ensures that events are meaningful and based on a sufficient amount of data. ![Monitor events](https://goat-assets.production.core.primer.io/marketing/monitors/external-docs/notifications/monitor-events.png) Monitor events ## Notifications & escalations via Workflows We have added support for two new Primer native Workflow apps, [Primer Monitors](/docs/workflows/overview) and [Primer Emails](/docs/workflows/overview), so you can build your own custom notification or escalation flows. * **Primer Monitors** avail a trigger allowing you to react to new monitor events. Now you have complete control to build your own notification flows however you want - send yourself a web request, a Slack message, an email, or immediately create an incident. * **Primer Emails** now give you the ability to send yourself an email from within a workflow. This can be used with Monitor notifications, but could also be used together with the Primer Disputes app, or even with the Primer Payments app and ["Payment Status updated" trigger](/docs/workflows/apps/native-apps/primer-payments-app/payment-status-updated-trigger) when a single payment fails\*. > [!NOTE] > > Do note that this action is only intended to send email notifications to > yourself, not to your customers. There are no customization options and the > email will arrive with a Primer header. If you do want to send emails to your > customers, we have dedicated integrations with third-parties like Sendgrid for > example. ### Example flow Here is an example for a workflow using these new apps: whenever a new monitor event is created, a web request is sent notifying a dedicated endpoint. Afterwards, depending on the metric used, an incident is created via PagerDuty when too many payments start failing, a Slack message is sent when potential 3DS issues are observed, and an email is sent for any other metric. All within one notification flow: ![Escalation flow](https://goat-assets.production.core.primer.io/marketing/monitors/external-docs/notifications/escalate.png) Escalation flow # Overview Source: https://primer.io/docs/monitors/overview ## Keep track of your payments health Use Monitors to detect issues in real time and stay ahead of problems across your payments stack. ![Keep track of your payments health](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/monitors/banner/light.png) ## Monitor your payments > [card] [Managing monitors](/docs/monitors/management) > > Create, edit, and manage monitors that track key metrics like auth rates, declines, and conversion drops using flexible filters and thresholds. > [card] [Monitor Notifications](/docs/monitors/notifications) > > Trigger alerts via email, Slack, or workflows when a monitor condition is met so your team can take action quickly. ## Use cases > [card] [Monitoring for processor outages](/docs/monitors/use-cases/monitoring-for-processor-outages) > > Get alerted when a processor's performance drops so you can respond with rerouting or fallback strategies. > [card] [Monitor fallback usage](/docs/monitors/use-cases/monitor-fallback-usage) > > Track how often fallbacks are triggered to spot upstream issues and fine-tune your routing logic. # Monitor fallback usage Source: https://primer.io/docs/monitors/use-cases/monitor-fallback-usage ## Using Monitors to identify processor issues when fallbacks are configured Primer ensures seamless payment processing for merchants, automatically retrying payments with a fallback processor in the event of a declined or failed payment. However, merchants may still want to stay informed when fallbacks are used, especially if they may be charged for the initial attempt by the processor experiencing the issue. With monitors, you can keep a close eye on your fallback usage and promptly identify any issues or misconfigurations, even if the payment ultimately succeeds. Here's how you can set up monitors to achieve this: ### Setting Up a Monitor 1. **Create a new monitor**: Click “add new monitor” on the Monitors page, and choose the “static” type. 2. **Select the Metric**: Choose the metric "Fallback Count." This metric tracks the number of payments that fall back to an alternative processor. 3. **Define a Threshold**: Set a defined threshold for the number of fallback payments within a specified window. This threshold serves as your trigger point for monitoring fallback usage. ### Notification Preferences 1. **Configure Notifications**: When the threshold is exceeded, Primer can notify you through various channels, including: * **Slack** * **Email** * **Webhook** Speak to your CSM or reach out to support to configure these channels. Notifications are also delivered in the Primer dashboard. ### Taking Action 1. **Identify outages or misconfigurations**: When you receive a notification, it's an indicator that fallbacks are being used more frequently, suggesting a potential outage or misconfiguration. Check your Recovered Sales dashboard to identify which processor is the cause of the increased number of fallbacks. 2. **Contact the Processor**: With this information at hand, you can proactively contact the processor to understand where the issue is occurring. This ensures that you do not get charged for failed payments moving forward. 3. **Switch Processors**: If you're particularly concerned about costs, consider temporarily swapping the fallback and primary processors in your workflows until the outage has passed. This can minimize the impact of any charges associated with the initial attempt. By setting up monitors in this manner, you can maintain control over your payment processes and swiftly respond to any processor issues, ensuring smooth and cost-effective operations. Primer empowers you with the insights and tools to manage your payments with confidence. # Monitoring for processor outages Source: https://primer.io/docs/monitors/use-cases/monitoring-for-processor-outages ## Setting up Monitors for processor outages Traditionally, monitoring payment performance and potential outages fell within the domain of engineering teams. However, with Primer, you can move this responsibility to the payments team or product manager, streamlining the process and ensuring quicker responses. Here's how you can effectively set up a monitor to track processor outages: ### Why Monitor Processors? It's essential to be proactive in monitoring payment performance, especially when adding new payment methods or processors. We recommend creating a corresponding monitor for each new processor or payment method added. This enables you to identify any issues that may arise specifically for each promptly. ### Monitor Configuration 1. **Threshold Selection**: Decide whether to use a **static threshold** or a **dynamic monitor**: * **Static Monitor**: Set a predefined threshold that triggers an alert after a certain number of declined or failed payments are received. This is the best option if you need immediate monitoring. * **Dynamic Monitor**: This option allows Primer to calculate the expected number of declined or failed payments based on historical data. Dynamic monitors take up to a week to become fully operational. 2. **Failed or Declined Payments**: Choose a metric that focuses on detecting failed or declined payments. This serves as an early warning system for potential processor issues. You can either set up multiple monitors using the **Payments Count (Failed)** and **Payments Count (Declined)** metrics or a single monitor using the **Payments Count** metric, with an additional filter for **Declined** and **Failed Statuses.** 3. **Filter for the processor or payment method**: Set the filter options to monitor the payment method or processor that you have added to Primer. ### Notification Preferences Configure your notification settings for the monitor: * **Dashboard**: Receive notifications directly within the Primer dashboard, where you need to track them proactively. * **Slack**: Get real-time alerts directly to Slack. * **Email**: Receive email notifications for quick response. * **Webhook**: Set up webhooks for integration with other systems. ### Taking Action When you receive a monitor notification, access the Payments Dashboard to examine the number of declined or failed payments for the specific payment method or processor. * Apply a filter to show just the Failed or Declined payments for the processor, and look at the Payments Created tab. * Check to see if the failing payments are for a range of customers and if it is not one single customer impacting performance. * Identify if there is any other single reason for the declined payments. For example, they all relate to a single currency or issuing bank (where applicable). * If a substantial portion of payments needs to be fixed for the new payment route, take swift action. Consider disabling the processor in your workflows or removing the payment method from your checkout. This proactive response ensures minimal disruption to your payment processes and allows customers to continue making purchases through alternative methods. ### Resuming Normal Operations Once the processor outage is resolved, you can re-enable the previously disabled processors and payment methods. This ensures a smooth transition back to normal operations. By implementing this approach, you can stay ahead of processor outages, minimize customer impact, and maintain the reliability of your payment processes. # Custom Dashboards Source: https://primer.io/docs/observability/custom-dashboards/overview ![](https://mintcdn.com/primer-cc826789/kh8YlCAXTDnCrMxk/images/observability/obs-custom-dashboards.png?fit=max\&auto=format\&n=kh8YlCAXTDnCrMxk\&q=85\&s=6de9531a740d2c5645458ff7748401a4) Custom dashboards Custom dashboards empower you to harness the full potential of your payment data, offering the flexibility to adapt to your ever-changing business needs. Whether it's optimizing processes, monitoring specific KPIs, or conducting A/B tests, custom dashboards are your gateway to a more data-driven and efficient payment strategy. > [!NOTE] > > Custom dashboards are available for **Observability PRO users only**. ## Common Use Cases Merchants have set up custom dashboards for various purposes: * **BIN Tracking:** Tracking specific BIN performance across processor authorization rates and 3D Secure authentication. * **Store Performance:** Analysing the performance of store locations using custom metadata. * **Payment Methods:** Payment method-specific dashboards to view performance as new payment methods are rolled out. * **KPIs:** Specific KPI dashboards to be used in C-Suite meetings and shared with company stakeholders. ## Flexibility with Primer Custom dashboards in Primer offer you the flexibility to design dashboards that precisely cater to your specific payment data requirements, and there is **no effort required on your behalf**! ## Get Started 1. **Reach Out:** Contact your Customer Success Manager or Primer Support to express your interest in creating a custom dashboard. 2. **Discussion:** We'll schedule a call to discuss your specific requirements, including the metrics, filters, and dimensions you want. 3. **Design & Creation:** Primer's support team or CSM will work with you to design and create the custom dashboard based on your input. 4. **Access:** Once ready, access your custom dashboard in your Primer account to explore tailored payment data insights. # Dashboards: 3D Secure Source: https://primer.io/docs/observability/dashboards/3d-secure A detailed view into 3D Secure performance and errors for Primer 3DS payments. The 3D Secure dashboard provides users with granular details into their 3D Secure payments. Merchants can identify successful 3D Secure authentications and investigate potential issues. Optimizing 3D Secure conversion is as vital as the authorization rate. This dashboard is an essential tool for that purpose. ### **3DS Attempts** * **Count:** Total payments using 3D Secure, excluding processor 3DS. * **By Response Code:** Breakdown by response codes. * **By Error Code:** Technical error breakdown. * **By Transaction Status:** Breakdown by transaction status. * **By Transaction Status Reason:** Reasons for unsuccessful attempts. * **By Protocol Version:** Analysis by 3D Secure protocol version. * **By Initiator:** Breakdown by 3D Secure initiator. * **By Issuer Country:** Issuing bank's country. * **By Currency:** Breakdown by currency. * **By Customer ID:** Analysis by customer ID. ### **3DS Authentication Rate** * **Overall Rate:** The ratio of successful 3DS attempts, excluding processor 3DS. * **By Protocol Version:** Breakdown by protocol version. * **By Card Network:** Analysis by card network. * **By Issuer Country and Region:** Insights based on issuing bank's country and region. * **By Currency:** Breakdown by currency. * **By Account Funding and Usage Type:** Insights based on funding type and usage type. * **By Initiator:** Breakdown by 3D Secure initiator. * **By Issuing Bank and BIN:** Analysis by issuing bank and BIN. # Declines Source: https://primer.io/docs/observability/dashboards/declines A comprehensive breakdown of decline reasons. The dashboard enables merchants to understand payment declines, facilitating improved success rates. Primer unifies decline codes across all processors and payment methods for easy analysis and comparison. ### **Declines** * **Overview:** Breakdown by the processor-provided reason during the period. * **Rate & Count:** Decline ratio and total count. * **By Processor:** Analysis by processor. * **By Payment Method:** Breakdown by payment method. * **By Merchant ID:** Analysis by merchant ID. * **By Currency:** Breakdown by currency. * **By Payment Type:** Analysis based on payment type. * **By 3DS Response:** Insights on 3DS response codes. * **By Card Details:** Analysis by card network, issuer country, issuer, funding type, usage type, and CVV response. # Dashboards: Network Tokenization Source: https://primer.io/docs/observability/dashboards/network-tokenization Monitor and measure the impact of network tokens created by Primer. ### Payments Provide insights into how many payments were processed with a network token. * **Number of payments processed with a network token** * **By Processor**: Breakdown of network token payments by processors. * **Share of payments for network-tokenized cards**: Percentage of payments processed with a network token compared to all payments made with a network-tokenized card. * **Processing volume per merchant ID**: Number of network-tokenized cards processed with their network token or their card PAN, split by merchant ID. ### Authorization Rate Compare the authorization rates for network-tokenized cards, based on whether the network token or the PAN was used. * **Authorization Rate**: Show the authorization rate of network-tokenized cards over time, split by whether the network token or the PAN was used. * **Authorization Rate per merchant ID**: Breakdown per merchant ID * **Decline reasons**: Show the most common decline reasons for network-tokenized cards, split by whether the network token or the PAN was used. ### Network Tokens (Beta) * **Network tokens created**: Number of network tokens created for Visa and Mastercard. * **Availability across vaulted card payments**: Shows the percentage of available network tokens across the payments made with a vaulted card. * **Network tokenization success rate**: Percentage of cards that were successfully network tokenized. * **Network tokenization errors**: Most common network token creation errors. # Curated dashboards Source: https://primer.io/docs/observability/dashboards/overview ![](https://goat-assets.production.core.primer.io/marketing/observability/external-docs/curated-dashboards/curated-dashboards.png) Custom dashboards Primer’s curated Dashboards give merchants easy access to all the payment metrics they need to optimize their payments stack effectively. Each dashboard has multiple tabs displaying different metrics and includes multiple charts breaking down the metrics into various dimensions. > [!NOTE] > > Only the Snapshot dashboard is available for all users. All other dashboards are exclusive to **Observability PRO** users. > [card] [Snapshot](/docs/observability/dashboards/snapshot) > > This dashboard is designed to give users a high-level view into each aspect of their payments performance. > [card] [Payments](/docs/observability/dashboards/payments) > > This dashboard is most merchants’ first port of call when looking to analyze payments in granular detail. > [card] [Sales](/docs/observability/dashboards/sales) > > This dashboard provides insights into key revenue metrics and helps users manage sales effectively. > [card] [Refunds](/docs/observability/dashboards/refunds) > > This dashboard helps merchants understand the sources of their refunds. > [card] [3D Secure](/docs/observability/dashboards/3d-secure) > > This dashboard provides users with granular details into their 3D Secure (3DS) payments. > [card] [Sales Recovery](/docs/observability/dashboards/sales-recovery) > > This dashboard showcases the revenue saved by using Primer's native payment services. > [card] [Declines](/docs/observability/dashboards/declines) > > This dashboard enables merchants to understand payment declines in detail. > [card] [Network Tokenization](/docs/observability/dashboards/network-tokenization) > > This dashboard helps merchants monitor and measure the impact of network tokens created by Primer. ## # Payments Source: https://primer.io/docs/observability/dashboards/payments A deep dive into your payment & authorization data across all processors. The **Payments** dashboard is most merchants’ first port of call when looking to analyze payments in granular detail. Primer aggregates the data across all processor and payment methods and standardizes it into a unified format for easy analysis. The authorization rate and number of payments created are then broken down across multiple payment dimensions to highlight any anomalies or optimization opportunities quickly. ### **Authorization rate** * **Auth rate & count:** Shows the authorization rate and the total count of authorized payments for the period. The authorization rate is the count of successful payments divided by the total number of payments. Includes payments where the payment reached a processor only. * **By Processor:** Breakdown of auth rate by payment processor. * **By Payment method:** Breakdown of auth rate by payment method. * **By Card network:** Breakdown of auth rate by card network. For payment cards, Apple Pay & Google Pay payments only. * **By Merchant ID:** Breakdown of auth rate by merchant ID. * **By Issuer country:** Breakdown of auth rate by issuer country. For payment cards, Apple Pay & Google Pay payments only. * **By Issuer region:** Breakdown of auth rate by issuer region. For payment cards, Apple Pay & Google Pay payments only. * **By Currency:** Breakdown of auth rate by currency. * **By 3D Secure response:** Breakdown of auth rate by 3DS response. * **By Payment type:** Breakdown of auth rate by payment type, e.g., e-commerce or recurring. * **By Account funding type:** Breakdown of auth rate by the account funding type of the underlying payment card, e.g., credit or debit. For payment cards, Apple Pay & Google Pay payments only. * **By Account usage type:** Breakdown of auth rate by the account usage type of the underlying payment card, e.g., business or consumer. For payment cards, Apple Pay & Google Pay payments only. * **By CVV response:** Breakdown of auth rate by card verification value (CVV) response. For payment cards, Apple Pay & Google Pay payments only. * **By AVS response (postal code):** Breakdown of auth rate by address verification system (AVS) response (postal code). For payment cards, Apple Pay & Google Pay payments only. * **By AVS response (street address):** Breakdown of auth rate by address verification system (AVS) response (street address). For payment cards, Apple Pay & Google Pay payments only. * **By Issuing bank:** Breakdown of auth rate and count of declined payments by issuing bank. For payment cards, Apple Pay & Google Pay payments only. * **By BIN:** Breakdown of auth rate and count of declined payments by bank identification number (BIN). For payment cards, Apple Pay & Google Pay payments only. ### **Payments created** * **Payments created:** Shows the total count of payments for the period. * **By Payment status:** Breakdown of payments count by payment status. * **By Processor:** Breakdown of payments count by payment processor. * **By Payment method:** Breakdown of payments count by payment method. * **By Card network:** Breakdown of payments count by card network. For payment cards, Apple Pay & Google Pay payments only. * **By Merchant ID:** Breakdown of payments count by merchant ID. * **By Issuer country:** Breakdown of payments count by issuer country. For payment cards, Apple Pay & Google Pay payments only. * **By Issuer region:** Breakdown of payments count by issuer region. For payment cards, Apple Pay & Google Pay payments only. * **By Currency:** Breakdown of payments count by currency. * **By 3D Secure response:** Breakdown of payments count by 3DS response. * **By Payment type:** Breakdown of payments count by payment type, e.g., e-commerce or recurring. * **By Account funding type:** Breakdown of payments count by the account funding type of the underlying payment card, e.g., credit or debit. For payment cards, Apple Pay & Google Pay payments only. * **By Account usage type:** Breakdown of payments count by the account usage type of the underlying payment card, e.g., business or consumer. For payment cards, Apple Pay & Google Pay payments only. * **By CVV response:** Breakdown of payments count by card verification value (CVV) response. For payment cards, Apple Pay & Google Pay payments only. * **By AVS response (postal code):** Breakdown of payments count by address verification system (AVS) response (postal code). For payment cards, Apple Pay & Google Pay payments only. * **By AVS response (street address):** Breakdown of payments count by address verification system (AVS) response (street address). For payment cards, Apple Pay & Google Pay payments only. * **By Customer ID:** Breakdown of payments count by customer ID. # Refunds Source: https://primer.io/docs/observability/dashboards/refunds Insights on refund trends across processors and payment methods. This dashboard helps merchants understand the sources of their refunds. Values are shown in the Primer account's default currency and can be converted via the Observability dashboard conversion. ### **Refunds Value** * **Total:** Displays the total refund value and its percentage of sales value for the period. The calculation of the % of sales value is against the sales value at the time of payment creation. * **By Processor:** Breakdown of refund value by payment processors. * **By Payment Method:** Breakdown of refund value by payment method. * **By Merchant ID:** Breakdown of refund value by merchant ID. * **By Currency:** Breakdown of refund value by currency. * **By Payment Type:** Breakdown of refund value by payment types. * **By Order Country:** Breakdown based on the country of the order passed with the payment request. ### **Refunds Count** * **Total:** Displays the total refund count and its percentage of sales count for the period. The % calculation is based on the sales count at the time of payment creation. * **By Processor:** Breakdown of refund count by payment processors. * **By Payment Method:** Breakdown of refund count by payment method. * **By Merchant ID:** Breakdown of refund count by merchant ID. * **By Currency:** Breakdown of refund count by currency. * **By Payment Type:** Breakdown of refund count by payment types. * **By Order Country:** Breakdown based on the country of the order passed with the payment request. ### **Average Refund Value** * **Overall:** Shows the average value of processed refunds. * **By Processor:** Breakdown of the average refund value by payment processors. * **By Payment Method:** Breakdown of average refund value by payment method. * **By Merchant ID:** Breakdown of average refund value by merchant ID. * **By Currency:** Breakdown of average refund value by currency. * **By Payment Type:** Breakdown of average refund value by payment types. * **By Order Country:** Breakdown based on the country of the order passed with the payment request. # Sales Source: https://primer.io/docs/observability/dashboards/sales Sales trends and forecasting metrics. This dashboard provides insights into key revenue metrics and helps users manage sales effectively. The values in this dashboard are represented in the default currency of the Primer account and can be converted using the Observability dashboard conversion. ### **Sales Value** * **Total:** Shows the total sales value for the period, representing the monetary amount of payments that are settled or partially settled. * **By Processor:** Breakdown of sales value by payment processors. * **By Payment Method:** Breakdown of sales value by payment method. * **By Merchant ID:** Breakdown of sales value by merchant ID. * **By Currency:** Breakdown of sales value by currency. * **By Payment Type:** Breakdown of sales value by payment types. * **By Order Country:** Breakdown based on the country of the order passed with the payment request. ### **Sales Count** * **Total:** Shows the total sales count for the period, representing the number of payments settled or partially settled. * **By Processor:** Breakdown of sales count by payment processors. * **By Payment Method:** Breakdown of sales count by payment method. * **By Merchant ID:** Breakdown of sales count by merchant ID. * **By Currency:** Breakdown of sales count by currency. * **By Payment Type:** Breakdown of sales count by payment types. * **By Order Country:** Breakdown based on the country of the order passed with the payment request. ### **Average Order Value** * **Overall:** Shows the average order value of the sales settled or partially settled for the period. * **By Processor:** Breakdown of average order value by payment processors. * **By Payment Method:** Breakdown of average order value by payment method. * **By Merchant ID:** Breakdown of average order value by merchant ID. * **By Currency:** Breakdown of average order value by currency. * **By Payment Type:** Breakdown of average order value by payment types. * **By Order Country:** Breakdown based on the country of the order passed with the payment request. # Sales Recovery Source: https://primer.io/docs/observability/dashboards/sales-recovery Gain insights on sales recovered through Primer. Merchants can recover sales that might have otherwise failed using Primer's tools. The dashboard showcases the revenue saved by using Primer, displayed in the default currency of the Primer account. ### **Overview** * **By Method:** Total monetary value recovered through Primer. * **Payments Count:** Number of recovered payments via Primer. * **Recovery Rate:** Ratio of successful recoveries to attempted recoveries. ### **via Fallback Processor** * **Value:** Monetary value of recovered payments. * **Count & Rate:** Total recovered payments and their recovery rate. * **Initial Decline Reasons:** Reasons triggering a fallback. * **Recovery Decline Reasons:** Reasons for unsuccessful fallbacks. * **By Processor:** Breakdown by recovery attempts and successful recoveries. * **By Merchant ID:** Analysis by merchant ID. ### **via Adaptive 3DS** * **Value:** Monetary value of recovered payments. * **Count & Rate:** Total recovered payments and their recovery rate. # Snapshot Source: https://primer.io/docs/observability/dashboards/snapshot An at-a-glance overview of key metrics. The **Snapshot** dashboard is designed to give users a high-level view into each aspect of their payments performance. This dashboard is great if you need to share some high-level figures with internal stakeholders. ### **Snapshot** * **Sales:** Shows the total sales value and count for the period. Sales value is the monetary amount of payments that are settled or partially settled. Sales count is the number of payments that are settled or partially settled. * **Refunds:** Shows the total refund value and refunds as a percentage of sales value for the period. Refunds value is the monetary amount of refunds that have been processed. The % of sales value calculation is performed against the sales value on the payment creation date. * **Authorization:** Shows the authorization rate and the total count of authorized payments for the period. The authorization rate is the count of successful payments divided by the total number of payments. Includes payments where the payment reached a processor only. * **Payments:** Shows the total count of payments for the period. * **Declines:** Shows the breakdown of declined payments by the reason returned in the response of the processor for the period. Declined payments are payments where a request to a processor was made and was unsuccessful. The decline reason is the detailed decline response returned on declined payments. * **3D Secure:** Shows the 3D Secure authentication rate and the total number of payments where 3D Secure was used for the period. 3DS attempts are the number of payments where 3D Secure was initiated. The authentication rate is the number of successful 3DS attempts divided by the total number of 3DS attempts. Excludes processor 3DS. # Overview Source: https://primer.io/docs/observability/overview ## Get started with Observability Uncover opportunities that boost your bottom line with complete visibility into your payment stack. ![Get started with Observability](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/observability/banner/light.png) ## Analyse all your payments data in one place > [card] [Curated dashboards](/docs/observability/dashboards/overview) > > Access ready-made dashboards that provide insights into various aspects of your payment processes, helping you identify optimizations in your payment orchestration flows. > [card] [Custom dashboards](/docs/observability/custom-dashboards/overview) > > Design dashboards tailored to your specific business needs, enabling you to track key metrics and optimize processes effectively. ## Use cases > [card] [Analyze A/B test results with Split utility](/docs/observability/use-cases/analyze-ab-test) > > Leverage the Split utility to conduct A/B tests and use dashboards to analyze results, facilitating data-driven decisions for payment strategies. > [card] [Optimizing 3D secure conversion](/docs/observability/use-cases/optimizing-3ds-conversion) > > Utilize dashboards to analyze 3D Secure authentication rates and identify areas for improvement to boost conversion rates. > [card] [Using dashboards to optimize payment orchestration](/docs/observability/use-cases/optimize-payment-routing) > > Employ dashboards to gain insights into your payment flows, enabling you to make informed decisions to enhance payment efficiency. # Analyze A/B test results with Split utility Source: https://primer.io/docs/observability/use-cases/analyze-ab-test ## Analyzing A/B test results with Primer's Split utility Primer's [Split utility in Workflows](/docs/workflows/utilities/split) empowers merchants to conduct A/B tests, allowing for the random distribution of traffic based on predefined split percentages. To effectively analyze the results of these A/B tests and optimize payments accordingly, you can leverage Primer's Observability Dashboards. Here's a step-by-step guide to make the most of your split test results: ### Understanding the Split utility 1. **Create A/B test conditions**: Before using the Split utility, it's essential to define your A/B test conditions within your workflow. Ensure that you have clearly set up the conditions and any trigger conditions that guide the split. 2. **Utilize Split utility**: Employ the Split utility to distribute traffic as per your predefined split percentage. This utility is a powerful tool for conducting controlled experiments. ### Analyzing Split test results 1. **Assess workflow conditions**: Begin by closely examining the conditions within your workflow before the Split utility. Understand the different payment setups you are testing and the variables that might impact the results. Don’t forget to look at any [trigger conditions](/docs/workflows/utilities/conditions-block#trigger-conditions-define-when-to-start-a-workflow) that have been set up as part of a workflow, and custom metadata included as part of the authorized action on the payments app. 2. **Choose Relevant Dashboards**: Depending on the nature of your A/B test, select the appropriate dashboards within Observability. For instance: * If you're testing different 3D Secure options, consider using the "3D Secure Dashboard", for example, when comparing Primer’s 3D Secure and Adaptive 3D Secure for specific BINs or issuing banks. * If you’re comparing different processor authorization rate performance for a sub-set of payments, opt for the "Payments Dashboard" which includes a detailed analysis of authorization rates. 3. **Incorporate conditions as filters**: To effectively analyze your split test results, apply the conditions you've set in your workflow as filters within the chosen Dashboard. This step ensures that you isolate and compare the outcomes of different payment setups configured using the Split utility only. 4. **Review and Compare**: Examine the results presented in the dashboard, specifically the chart that compares the two options you're comparing. You can switch between Dashboards if you need to analyze multiple charts, for example, assessing authorization rate and 3D Secure authentication rate together. By following these steps, merchants can effectively assess A/B test results, gain valuable insights, and make informed decisions to optimize payment processes. Primer's Split Utility and Observability features work hand in hand to enable data-driven experimentation and continuous improvement in your payment strategies. # Using Dashboards to Optimize Payment Orchestration Source: https://primer.io/docs/observability/use-cases/optimize-payment-routing ## Using Dashboards to optimize payments: best practices The main function of Dashboards is to help you optimize your payments stack. Having access to the standardized data set Dashboards provides is crucial for informed decision-making and continuous improvement in your payment processes. To make the most of your Dashboard insights, consider the following best practices: ### 1. Ensure comparable data sets * **Consistency Matters**: Make sure you are comparing the same data sets. Ensure that you're examining the same payment types, currencies, countries, etc., and that all essential data is included in each sample. Other common areas to ensure consistency are whether 3D Secure was used and the response that was received, which address information was collected, and the type of payment method being used. Be certain to ensure all critical variables align. ### 2. Beware of dissimilar data sets * **Pitfalls of non-uniform data**: Failing to compare similar data sets can lead to misleading insights. Differences in variables may mask the true impact of optimizations and result in suboptimal decisions. Primer helps in this task by standardizing responses across processors and payment methods. However, it is still important to compare like-for-like samples. ### 3. Identify the key metric * **Focus on the Metric That Matters**: Pinpoint the specific metric you want to optimize. Whether it's the authorization rate, 3D Secure authentication rate, or any other critical KPI, having a clear goal is essential. ### 4. Prioritize impactful dimensions * **Start with high-impact dimensions**: Start by optimizing the most impactful dimensions – those where changes will have the most significant impact. Concentrate on the most common payment types, countries, decline codes, or any factors that have a significant percentage of your payment volume. Equally, focus on the big wins. If there is a very low authorization rate for a specific country, currency, payment type, etc., it will be easier to optimize than when you have close to 100% authorization rates. ### 5. Take Action * **Implement Changes**: Once you identify a potential optimization, take action. Primer allows you to update payment routing in workflows, but you can also adjust data collection at checkout and make other necessary modifications to improve your payment processes. ### 6. Set Up Monitoring * **Monitor Performance**: As an optional but highly recommended step, consider setting up a monitor to track the performance of the optimized metric continuously. Monitors ensure that improvements do not degrade over time and provide proactive insights into any deviations from expected results. By following these best practices, you can make data-driven decisions, enhance your payment efficiency, and ultimately boost your conversion rates. Dashboards in Primer provide you with the tools and insights to optimize your payment processes effectively. # Optimizing 3D Secure Conversion Source: https://primer.io/docs/observability/use-cases/optimizing-3ds-conversion ## A guide to optimizing 3D Secure conversion Optimizing for 3D Secure conversion is a crucial step in enhancing your payment success rates and something often forgotten. While 3D Secure is a regulatory requirement in some regions, it is not in others. You, therefore, can optimize for both payment authorization rate as well as 3D Secure conversion. Here's a best practice guide to effectively optimize your 3D Secure conversion: ### 1. Check Primer’s 3D Secure dashboard Primer offers a dedicated 3D Secure dashboard that provides valuable insights into your authentication rates. In the "3D Secure Authentication Rate" tab, you'll find a comprehensive breakdown of authentication rates. Notably, this includes a list of BINs with the highest number of failed 3D Secure authentications. By focusing on the BINs that have most failed 3D Secure payments, you’ll use your time tackling the largest problem first. ### 2. Identifying critical BINs To make informed decisions about your 3D Secure settings, you'll need to identify critical BINs. High failure rates within specific BINs indicate that it might be beneficial to remove 3D Secure for those particular payments. You can search over a longer time period if there is a limited number of payments with the default settings. Add a filter for the BINs with the most failed payments, and make sure that it is not just one or two customers causing the spike in failed 3D Secure payments in the “3D Secure Attempts” tab. You can also assess if there are any other subsets of payments that are causing the poor conversion, such as a specific currency or country. ### 3. Filter out the noise To assess whether removing 3D Secure is an option, you will also need to analyze the authorization rate for the BINs when 3D Secure is not applied. If the authorization rate when 3D Secure is not used is high, then you’ll likely see a positive impact from removing 3D Secure for these payments. Add filters for any groups of payments that you have identified as causing poor conversion (there may be none). Also, the filter for payments with "is null" in the 3D Response Code indicates that 3D Secure was not used. You’ll want to focus on only the payments where 3D Secure is relevant, so also add a filter for customer-initiated transactions (CIT). ### 4. Checking Authorization Rates Now, you’re ready to dive into the authorization rates to ensure removing 3D Secure won’t have other negative consequences. Use the "Switch Dashboard" toggle to access the Payments Dashboard with the filters applied. Within the "Authorization Rates" tab, check the authorization rate for the filtered payments. A high authorization rate suggests that removing 3D Secure from this specific BIN will likely boost your overall conversion rates. ### 5. Think about the fraud impact If you are removing 3D Secure, then you are also removing a barrier to fraudsters. Make sure that these payments have another fraud solution in place so that you are not left open to a fraudulent attack. The list of external fraud providers Primer works with is [here](/docs/connections/fraud-providers/overview), and some payment processors also have internal fraud tools built in. ### 6. Take action Create a new workflow route for the payments you have identified that would benefit from removing 3D Secure. Add a condition block that includes all of the filters you have applied, and update the 3DS settings in the authorized action of the payments app. # 3D Secure: Exemptions Source: https://primer.io/docs/payment-services/3d-secure/exemptions ## 3DS Exemptions 3D Secure (3DS) exemptions allow merchants to request that certain payments are exempted from regulatory requirements for Strong Customer Authentication (SCA), which is the case under PSD2 regulations. This helps reduce checkout friction and improve conversion rates - especially for returning customers or low-risk transactions. While exemptions can significantly improve conversion rates, they also come with trade-offs. Exempted transactions do not carry [3DS liability shift](/docs/payment-services/3d-secure/overview#liability-shift), meaning that by using exemptions you accept responsibility for potential fraud chargebacks. > [!WARNING] > > Before enabling exemptions, assess your fraud rates, issuer relationships, and > appetite for risk. Primer supports Transaction Risk Analysis (TRA) exemptions in the 3DS authentication flow. This ensures that, if an exemption is not accepted by the cardholder’s bank, the payment continues seamlessly with a standard 3DS authentication - without needing a second authorization request. > [!NOTE] > > Exemptions are only available when using Primer 3DS. 3DS exemptions managed by the processor are not supported. ### How Exemptions Work When a 3DS exemption is requested: 1. The exemption request is included during the 3DS authentication flow. 2. The issuer reviews the transaction data and decides whether to accept or reject the exemption. * If accepted, no challenge is presented and the 3DS result will show `SKIPPED` with a reason code of `EXEMPTION_ACCEPTED`. * If rejected, the request automatically reverts to a standard 3DS flow without affecting the checkout flow. 3. The result of the exemption is then included in the processor's authorization request. You can monitor these outcomes directly in your Primer Dashboard and API responses. > [!NOTE] > > Here is a summary of the outcomes of the 3DS Exemption request > > | Exemption outcome (depends on the issuer) | 3DS status in Primer | Shopper experience | Liability | > | - | - | - | - | > | Accepted | Skipped: Exemption request accepted | No 3DS Challenge | Merchant holds fraud liability | > | Rejected, failover to frictionless | 3DS Authentication successful (frictionless) | No 3DS Challenge | Liability shift applies | > | Rejected, failover to challenge | 3DS Challenge initiatied | 3DS Challenge presented | Liability shift applies if challenge passed | ## Implementing Exemptions ### Before you start Before adding 3DS Exemptions to your payment flow, * Make sure 3DS via Primer is enabled on your account * Ask your processor(s) and/or acquirer(s) to enable 3DS exemptions on your MIDs ### Processor Support Currently, 3DS exemptions are supported for the following processors: | Processor | Authentication Exemption Support | | - | - | | Checkout.com | ✅ Supported on Visa, Mastercard & Cartes Bancaires | | Payplug | ✅ Supported on Visa, Mastercard & Cartes Bancaires | | Adyen | ✅ Supported on Visa, Mastercard & Cartes Bancaires | | Stripe | ✅ Supported on Visa, Mastercard & Cartes Bancaires | | JPMC | ✅ Supported on Visa & Mastercard | > [!WARNING] > > If you perform a 3DS exemption, make to authorize the payment with a supported processor. Non-supported processors will not receive any 3DS data, which may reduce performance. ### Best Practices 1. **Stay within thresholds:** The TRA limit depends on merchant and processor fraud performance - typically €100/£85, €250/£220, or €500/£440. The standard is €250, but we advise confirming the applicable amount with your processor(s) before activating this option. > [!WARNING] > > We strongly recommend communicating with your processor(s) to ensure your > accounts are eligible for exemption usage, as some processors have specific > requirements before enabling this capability. 2. **Apply fraud checks prior to requesting an exemption**: TRA exemptions are designed to be used in combination with additional fraud analysis. Before requesting an exemption, ensure the transaction has passed risk checks, either via your own fraud analysis or via a [pre-authorization fraud check](/docs/payment-services/fraud-checks/overview). 3. **Monitor results:** Compare authorization success between exempted and non-exempted payments. ### Request an Exemption You can request a 3DS exemption in two ways: #### Exemptions via the Perform 3DS action 1. Add a [Perform 3DS action](/docs/workflows/apps/native-apps/primer-payments-app/perform-3ds-action) to your Workflow. 2. Under **3DS options**, select **Request TRA exemption**. 3. Save and publish your Workflow. ![Perform 3DS Exemption Option](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/3d-secure/3ds-exemptions/perform-3ds-exemption-option.png) Perform 3DS - Request Exemption Option > [!NOTE] > > Note: You can only apply one 3DS option per transaction (e.g., Mandate > Challenge or Request TRA Exemption). We recommend using [conditions](/docs/workflows/utilities/conditions-block) to apply exemptions only to specific scenarios - for example: * Transaction amount under €250 * Returning customers * Low fraud risk flagged by an internal fraud detection system ![Exemption Eligible Condition Check](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/3d-secure/3ds-exemptions/exemption-eligible-condition-check.png) Condition Block for Exemptions #### Exemptions via Fraud Provider recommendation in the Authorize action You can also allow your Fraud Provider to decide whether an exemption should be applied or not via [pre-authorization fraud checks](/docs/payment-services/fraud-checks/overview#pre-authorization): ![Forter pre-authorization exemption](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/3d-secure/3ds-exemptions/forter-pre-auth-exemption.png) Condition Block for Mandate Challenge If your fraud provider recommends an exemption and your Workflow is configured to follow that recommendation, Primer will automatically request a TRA exemption. After the exemption is requested, if the issuer rejects it, the payment automatically attempts to authenticate the payment with a standard 3DS authentication flow, before sending the payments to the processor. > [!NOTE] > > You can view more details on configuring the pre-authorization fraud checks in > [our configuration > guide](/docs/payment-services/fraud-checks/get-started#pre-authorization-fraud-check). > [!WARNING] > > This option is currently only supported when using > [Forter](/docs/connections/fraud-providers/forter) as your Fraud Provider. ## Viewing Exemptions You can view exemption outcomes in both your Dashboard and via API responses. #### In the Dashboard Exemption details are visible in two key areas: * **Payment Details View** Under 3DS authentication, the 3DS attempt will show as `Skipped: Exemption request accepted` ![Timeline Exemption View](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/3d-secure/3ds-exemptions/timeline-exemption-view.png) Payment Timeline - Exemption View An `Exempted` flag will also be present within the 3DS details. ![Timeline Exemption View Details](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/3d-secure/3ds-exemptions/timeline-exemptions-view-details.png) 3DS Details - Exempted Flag * **Workflow Run Timeline** Displays events such as `TRA exemption requested` and `TRA exemption accepted` or `TRA exemption rejected` along with output details. ![Workflow Exemption Accepted](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/3d-secure/3ds-exemptions/workflow-exemption-accepted.png) Workflow View - Exemption Accepted ![Workflow Exemption Rejected](https://mintcdn.com/primer-cc826789/VyFK_A0n7sp9FOiH/images/payments/WorkflowExemptionRejected.png?fit=max\&auto=format\&n=VyFK_A0n7sp9FOiH\&q=85\&s=9d83e26d312b7143e10089e2d0344676) Workflow View - Exemption Rejected #### In the API When a 3DS exemption is requested and accepted, the API response will include the object [`threeDSecureAuthentication`](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment#response-payment-method-three-d-secure-authentication) under the 3DS authentication object: ```json theme={"dark"} "threeDSecureAuthentication": { // "responseCode": "SKIPPED", "reasonCode": "EXEMPTION_ACCEPTED", "reasonText": "Exemption request accepted", // } ``` These fields are returned in all relevant API responses and notification payloads where the 3DS data is present - including the Payment, Authorization, and related transaction objects. > [!NOTE] > > Tip: You can use the `reasonCode` to filter and report on exemption > performance across your payments - for example, by tracking the proportion of > transactions with `EXEMPTION_ACCEPTED` against total 3DS attempts. ### Search & Observability Transactions that have had a 3DS exemption applied can be filtered for using the 3DS Reason Code [filter](/docs/concepts/filters-and-dimensions#3ds) option. ![Timeline Exemption Filter](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/3d-secure/3ds-exemptions/timeline-exemption-filter.png) Filtering for Exemptions This can be applied on the [Payment Timeline](/docs/concepts/payment-timeline), along with all [Observability](/docs/observability/overview) dashboards: ![Observability Exemption Filter](https://mintcdn.com/primer-cc826789/VyFK_A0n7sp9FOiH/images/payments/ObservabilityExemptionFilter.png?fit=max\&auto=format\&n=VyFK_A0n7sp9FOiH\&q=85\&s=42e014874cf4bc87f87897305f4e7d96) Filtering for Exemptions in Observability ### Testing the Exemption Flow You can test your exemption setup in sandbox using our 3DS test cards. To confirm your Workflow is correctly requesting and handling exemptions: 1. Configure your "Perform 3DS" action to "Request TRA exemption". 2. Use a "Manual Challenge" test card for Visa or Mastercard from our [3DS testing cards page](/docs/testing/3d-secure). * When an exemption is requested with this card, it will return an exemption result instead of triggering a 3DS challenge. * In your Workflow run and payment logs, you’ll see `TRA exemption requested` followed by `Exemption Accepted`. 3. Verify that the payment proceeds without a challenge and that your API response includes: ```json theme={"dark"} "threeDSecureAuthentication": { "responseCode": "SKIPPED", "reasonCode": "EXEMPTION_ACCEPTED", "reasonText": "Exemption request accepted", } ``` # Get started Source: https://primer.io/docs/payment-services/3d-secure/get-started > [tab] Web > > #### Install 3DS SDK > > > [!NOTE] > > > > There are no additional requirements to enable 3D Secure on Web. You are all set to create a payment with 3D Secure! > > #### Execute 3D Secure > > Universal Checkout drop-in and headless automatically renders the 3DS challenge when required by your workflow. > > #### Testing 3D Secure > > To validate your 3D Secure integration, you can use our dedicated testing guide, which includes sample cards, > challenge flows, and different scenarios. For full details, see the [3DS Testing Guide](/docs/testing/3d-secure). > [tab] iOS > > #### Install Primer3DS SDK > > > [!NOTE] > > > > 3D Secure on iOS requires the addition of the `Primer3DS` library to your project. > > ##### With CocoaPods > > First, modify your `Podfile` like so: > > ```code theme={"dark"} > source 'https://github.com/CocoaPods/Specs.git' > source 'https://github.com/primer-io/primer-podspecs.git' > > use_frameworks! > > target 'PrimerSDK_Example' do > pod 'PrimerSDK' > pod 'Primer3DS' > // ... > end > ``` > > Then run `pod install` to install `Primer3DS` on your workspace. > > > [!NOTE] > > > > In case you encounter an error that the bundle needs signing, add the following post-install script in your podfile. > > > > ```ruby theme={"dark"} > > post_install do |installer| > > installer.pods_project.targets.each do |target| > > if target.respond_to?(:product_type) and target.product_type == "com.apple.product-type.bundle" > > target.build_configurations.each do |config| > > config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' > > end > > end > > end > > end > > ``` > > > [!CAUTION] > > > > In case you notice the warning "WARNING! Failed to import Primer3DS" when you initialize the `PrimerSDK`, add the following post-install script in the end of your pod file. > > > > ```ruby theme={"dark"} > > target 'MyApp' do > > pod 'PrimerSDK' > > pod 'Primer3DS' > > > > # ... > > > > # This is what needs to be added > > post_install do |installer| > > installer.pods_project.targets.each do |target| > > if target.name == "PrimerSDK" > > target.build_configurations.each do |config| > > config.build_settings['OTHER_LDFLAGS'] = '$(inherited) -framework "Primer3DS"' > > end > > end > > end > > end > > end > > ``` > > ##### With Swift Package Manager > > To add PrimerSDK with Swift Package Manager; > > 1. Select your project, and then navigate to `Package Dependencies` > > 2. Click on the **+** button at the bottom-left of the `Packages` section > > 3. Paste [https://github.com/primer-io/primer-sdk-3ds-ios](https://github.com/primer-io/primer-sdk-3ds-ios) into the **Search Bar** > > 4. Press **Add Package** > > 5. Let Xcode download the package and set everything up > > ![Adding Primer 3DS](https://mintcdn.com/primer-cc826789/paB-PZurGrOqghVc/payment-services/3d-secure/ios/swift-package-manager-2.png?fit=max\&auto=format\&n=paB-PZurGrOqghVc\&q=85\&s=78b9678c30a49d53cb2773c37dbd9e43) > > > [!CAUTION] > > > > If `Primer3DS` is not installed, 3DS will fail. In the case of a 3DS triggered by the workflow, the `primerDidFailWithError` functions will be called. > > #### Interoperability matrix > > To ensure compatibility, please verify a supported Primer 3DS SDK [version](https://github.com/primer-io/primer-sdk-3ds-ios/tags) matches your current Primer SDK Version. > Below are the supported interoperable versions: > > | Primer SDK version | Primer 3DS SDK version | > | :- | :- | > | `>= 2.44.0` | `>= 2.7.0` | > | `2.43.0 - 2.44.0` | `2.6.0` | > | `2.35.0 - 2.43.0` | `2.4.2 - 2.5.x` | > | `2.24.0 - 2.34.0` | `2.3.0 - 2.4.1` | > | `2.19.0 - 2.23.0` | `2.1.0 - 2.2.1` | > | `<= 2.18.3` | `2.0.0 - 2.0.2` | > > #### Handle Out-of-Band (OOB) redirects (Optional) > > Starting from 3D Secure protocol version 2.2.0, you can enhance the user experience by implementing > an automatic redirect from another (authentication) application during an OOB challenge to your application once the challenge > is successfully completed. This feature allows for a seamless transition and improved user flow. > > > [!WARNING] > > > > If this feature is not implemented, the user will have to come back to your application manually to complete their payment, which adds significant friction. > > To enable this feature, ensure that you include the `threeDsAppRequestorUrl` parameter when configuring the `PrimerThreeDsOptions` object. > > Please note that the `threeDsAppRequestorUrl` value **must** be an [iOS Universal Link](https://developer.apple.com/ios/universal-links/). > Additionally, it is essential that your application is configured to handle the Universal Link properly in order to facilitate the redirection. > > To configure the Universal Link correctly using Universal Checkout, follow these steps: > > 1. Pass your Universal Link (e.g. `https://{UNIVERSAL_LINK}`) as `threeDsAppRequestorUrl` in the `PrimerThreeDsOptions` object of your settings. > > ```swift theme={"dark"} > let settings = PrimerSettings( > // ... > paymentMethodOptions: PrimerPaymentMethodOptions( > threeDsOptions: PrimerThreeDsOptions( > threeDsAppRequestorUrl: "https://{UNIVERSAL_LINK}" > ), > ), > // ... > ) > ``` > > 2. Implement the `application(_:continue:restorationHandler:) -> Bool` in your `AppDelegate` and call `Primer.shared.application(_:continue:restorationHandler:)` function. > > ```swift theme={"dark"} > import PrimerSDK > import UIKit > > @UIApplicationMain > class AppDelegate: UIResponder, UIApplicationDelegate { > > // ... > > func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { > return Primer.shared.application(application, continue: userActivity, restorationHandler: restorationHandler) > } > } > ``` > > 3. Implement the `application(_:open:options:) -> Bool` in your `AppDelegate` and call `Primer.shared.application(_:continue:restorationHandler:)` function. > > ```swift theme={"dark"} > import PrimerSDK > import UIKit > > @UIApplicationMain > class AppDelegate: UIResponder, UIApplicationDelegate { > > // ... > > func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { > return Primer.shared.application(app, open: url, options: options) > } > } > ``` > > #### Execute 3D Secure > > Universal Checkout drop-in and headless automatically render the 3DS challenge when required by your workflow. > > > [!WARNING] > > > > **Headless Mode UI Consideration** > > > > When using Headless Checkout, ensure no custom `UIWindow` instances, overlays, or modal presentations are active when 3DS authentication begins. The 3DS processing screen may appear behind your UI if custom window levels are in use. > > > > Drop-In Checkout handles this automatically. > > If your application is not installed from a trusted source (e.g. a debug version, not installed from the store, or used on a simulator), try to set > `PrimerDebugOptions.is3DSSanityCheckEnabled` to `false`. > Otherwise 3D Secure library initialization will fail due to security checks being performed. > > > [!WARNING] > > > > `is3DSSanityCheckEnabled` flag should only be used in development mode, and not in production release of your app. > > ```swift theme={"dark"} > let settings = PrimerSettings( > // ... > debugOptions: PrimerDebugOptions( > is3DSSanityCheckEnabled: false > ) > // ... > ) > ``` > > #### Troubleshooting > > * If you notice a console warning "Failed to import Primer3DS" on the SDK initialization, go to *Scheme settings* and select `Manual order`. > > ![Dependencies](https://mintcdn.com/primer-cc826789/paB-PZurGrOqghVc/payment-services/3d-secure/ios/Dependencies.png?fit=max\&auto=format\&n=paB-PZurGrOqghVc\&q=85\&s=d09f2b4bc2b0a3811d18a2ea6c2c6a63) > > #### Testing 3D Secure > > To validate your 3D Secure integration, you can use our dedicated testing guide, which includes sample cards, challenge flows, > and different scenarios. For full details, see the [3DS Testing Guide](/docs/testing/3d-secure). > [tab] Android > > #### Install 3DS SDK > > > [!NOTE] > > > > 3D Secure on Android requires the addition of the `io.primer:3ds-android` library to your project. > > Amend the dependencies section of your app's `build.gradle` to include the `3ds-android` library: > > ```kotlin Kotlin theme={"dark"} > dependencies { > implementation(platform("io.primer:bom:")) > implementation("io.primer:android") > implementation("io.primer:3ds-android") > } > ``` > > ```groovy Groovy theme={"dark"} > dependencies { > implementation platform('io.primer:bom:') > implementation 'io.primer:android' > implementation 'io.primer:3ds-android' > } > ``` > > > [!NOTE] > > > > Replace `` with your Primer SDK version. The BOM sets the library version, so leave it out. [Version alignment](/docs/sdk/android/v2.x.x/installation#version-alignment) explains how versions are set, including on older SDK versions. > > #### Interoperability matrix > > Primer SDK internally uses Primer 3DS SDK as a `compile` time dependency. In order for the SDKs to work properly, > the versions used internally and the one imported to your code **must** match. From SDK 2.54.0, Gradle aligns them for you. > On earlier versions, use the BOM or the version from this table: > > | Primer SDK version | Primer 3DS SDK version | > | :- | :- | > | `2.54.0+` | Same as the Primer SDK version | > | `2.53.1` | `1.9.0` | > | `2.47.0 - 2.53.0` | `1.8.0` | > | `2.46.0 - 2.47.0` | `1.7.0` | > | `2.41.0 - 2.45.1` | `1.6.2` | > | `2.32.0 - 2.40.1` | `1.5.0` | > | `2.27.6 - 2.31.0` | `1.4.3` | > | `2.27.0 - 2.27.5` | `1.4.2` | > | `2.25.0 - 2.27.0` | `1.4.1` | > | `2.24.0 - 2.25.0` | `1.4.0` | > | `2.21.0 - 2.24.0` | `1.3.0` | > | `2.17.2 - 2.20.0` | `1.2.0` | > | `2.16.0 - 2.17.1` | `1.1.2` | > | `2.15.0 - 2.15.1` | `1.1.1` | > | `2.0.0 - 2.14.1` | `1.1.0` | > > To validate that the 3DS SDK is imported correctly: > > 1. Clean and sync your project > 2. Validate that library can be found in `External Libraries` section (if you use Android Studio) > > ![Add 3DS Android](https://mintcdn.com/primer-cc826789/paB-PZurGrOqghVc/payment-services/3d-secure/android/add_3ds_android.png?fit=max\&auto=format\&n=paB-PZurGrOqghVc\&q=85\&s=749d49c1cb6a8ef28502c087eefb3f7f) > > #### Handle Out-of-Band (OOB) redirects (Optional) > > Starting from 3D Secure protocol version 2.2.0, you can enhance the user experience by implementing > an automatic redirect from another (authentication) application during an OOB challenge to your application once the challenge > is successfully completed. This feature allows for a seamless transition and improved user flow. > > > [!WARNING] > > > > If this feature is not implemented, the user will have to come back to your application manually to complete their payment, which adds significant friction. > > To enable this feature, ensure that you include the `threeDsAppRequestorUrl` parameter when configuring the `PrimerThreeDsOptions` object. > > Please note that the `threeDsAppRequestorUrl` value **must** be a [Android App Link](https://developer.android.com/training/app-links). > Additionally, it is essential that your application is configured to handle the App Link properly in order to facilitate the redirection. > > To configure the App Link correctly using Universal Checkout, follow these steps: > > 1. Add the following to your `AndroidManifest.xml` file: > > ```xml theme={"dark"} > android:name="io.primer.android.threeds.ui.ThreeDsActivity" > android:exported="true" > tools:node="merge"> > android:autoVerify="true" > tools:targetApi="m"> > > > > > > android:host="{yourdomain.com}" > android:pathPrefix="/3ds" > android:scheme="https" /> > > > ``` > > 2. Replace the value of `android:host` with your web domain name, ensuring not to modify any other configuration > 3. Once you've made the necessary changes, verify the App Link configuration by following the guidelines provided in the [Android documentation](https://developer.android.com/training/app-links/verify-android-applinks). > 4. Pass your App Link (e.g. `https://{yourdomain.com}/3ds`) as `threeDsAppRequestorUrl` in the `PrimerThreeDsOptions` object of your settings. > > ```kotlin theme={"dark"} > val settings = PrimerSettings( > // ... > paymentMethodOptions = PrimerPaymentMethodOptions( > threeDsOptions = PrimerThreeDsOptions("https://{yourdomain.com}/3ds") > ) > // ... > ) > ``` > > #### Execute 3D Secure > > Universal Checkout drop-in and headless automatically render the 3DS challenge when required by your workflow. > > If your application is not installed from a trusted source (e.g. a debug version, not installed from the store, or used on an emulator), try to set > [`PrimerDebugOptions.is3DSSanityCheckEnabled`](/docs/sdk/android/v2.x.x/common-objects/PrimerSettings#param-is3-ds-sanity-check-enabled) to `false`. > Otherwise 3D Secure library initialization will fail due to security checks being performed. > > > [!CAUTION] > > > > `is3DSSanityCheckEnabled` flag should only be used in development mode, and not in production release of your app. > > #### Testing 3D Secure > > To validate your 3D Secure integration, you can use our dedicated testing guide, which includes sample cards, > challenge flows, and different scenarios. For full details, see the [3DS Testing Guide](/docs/testing/3d-secure). > [tab] React Native > > #### Install 3DS SDK > > > [!NOTE] > > > > 3D Secure on React Native requires the addition of the 3DS SDK on iOS and Android. > > ##### On iOS > > Adding 3D Secure to iOS via React Native requires the addition of the `Primer3DS` pod to your Podfile. > > Depending on how you are using CocoaPods, you may need to add additional configuration to your Podfile. We support three methods for integration: **static library**, **dynamic framework** and **static framework**. > > You can check which of the three your project is using by running `bundle exec pod install` in the `ios` folder of your project and checking the output. > > e.g. > > ```shell theme={"dark"} > bundle exec pod install > Framework build type is static library > ... > ``` > > ###### Using static libraries > > By default, react native apps link pods as static libraries. You can check if your app is using static libraries by running `bundle exec pod install`. If it is, you should see the following first line of output: > > ```shell theme={"dark"} > bundle exec pod install > Framework build type is static library > .... > ``` > > To correctly link the 3DS pod as a static library, open `Podfile` inside the `ios` directory of your React Native project in a text editor, then add the following: > > ```ruby theme={"dark"} > target 'MyApp' do > > # ... other CocoaPods config ... > > pod 'Primer3DS' > > post_install do |installer| > > # ... other post_install step config ... > > # Add this block, taking care to choose the correct config.build_settings['OTHER_SWIFT_FLAGS'] based on the directive below. > installer.pods_project.targets.each do |target| > if target.name == "primer-io-react-native" || target.name == "PrimerSDK" > target.build_configurations.each do |config| > config.build_settings['FRAMEWORK_SEARCH_PATHS'] = "$(inherited) ${PODS_CONFIGURATION_BUILD_DIR}/Primer3DS" > config.build_settings['LIBRARY_SEARCH_PATHS'] = "$(inherited) ${PODS_CONFIGURATION_BUILD_DIR}/Primer3DS" > config.build_settings['SWIFT_INCLUDE_PATHS'] = "$(inherited) ${PODS_CONFIGURATION_BUILD_DIR}/Primer3DS" > > # Note, depending on your integration type, you must choose one of the following settings: > # If you are using frameworks, add the following line > config.build_settings['OTHER_SWIFT_FLAGS'] = '$(inherited) -Xcc -fmodule-map-file="${PODS_CONFIGURATION_BUILD_DIR}/Primer3DS/Primer3DS.modulemap"' > > # If you are using static libraries, instead add this line > config.build_settings['OTHER_SWIFT_FLAGS'] = '$(inherited) -Xcc -fmodule-map-file="${PODS_CONFIGURATION_BUILD_DIR}/Primer3DS/Primer3DS.framework/Modules/Primer3DS.modulemap"' > > config.build_settings['OTHER_LDFLAGS'] = '$(inherited) -weak_library -l"Primer3DS"' > end > end > end > > # ... other post_install step config ... > > end > > end > ``` > > Finally run `bundle exec pod install` to finish setting up. > > ###### Using dynamic frameworks > > Although React Native uses static libraries by default, native iOS apps commonly use dynamic frameworks. You can check if your app is using dynamic frameworks by running `bundle exec pod install`. If it is, you should see the following first line of output: > > ```shell theme={"dark"} > bundle exec pod install > Configuring Pod with dynamically linked Frameworks > ... > ``` > > To correctly link the 3DS pod as a dynamic framework, simply add it to the `Podfile` inside the `ios` directory of your React Native project using a text editor: > > ```ruby theme={"dark"} > target 'MyApp' do > > # ... other RN iOS config ... > > pod 'Primer3DS' > > end > ``` > > Finally run `bundle exec pod install` to finish setting up. > > As it is dynamically linked, it will automatically be detected by our iOS SDK at runtime, so no additional config is needed. > > ###### Using static frameworks > > Static frameworks are a less common use case, but we are able to support it by configuring your Podfile to allow a mix of statically and dynamically linked frameworks, with the 3DS pod being linked dynamically. > > You can check if your app is using static frameworks by running `bundle exec pod install`. If it is, you should see the following first line of output: > > ```shell theme={"dark"} > bundle exec pod install > Configuring Pod with statically linked Frameworks > ... > ``` > > > [!WARNING] > > > > Note: it might be that your `Podfile` is overriding the `use_frameworks` directive elsewhere, in which case the above shell output may appear incorrect. > > > > Check for the following in the app target of your `Podfile`: > > > > ```ruby theme={"dark"} > > use_frameworks! :linkage => :static > > ``` > > > > If this is present, then you are using static frameworks by default, even if the shell output for `bundle exec pod install` says differently. > > Because the 3DS pod is resolved by our SDK at runtime, an additional plugin is required to ensure that it can be loaded correctly. > > Start by adding the following to the end of the `Gemfile` in the root of your app repo: > > ```ruby theme={"dark"} > gem 'cocoapods-pod-linkage' > ``` > > Then, from the same folder (root of your app repo), run `bundle install` in a terminal: > > ```shell theme={"dark"} > bundle install > Fetching gem metadata from https://rubygems.org/....... > Resolving dependencies... > Fetching cocoapods-pod-linkage 0.0.1 > Installing cocoapods-pod-linkage 0.0.1 > Bundle complete! 3 Gemfile dependencies, 40 gems now installed. > Bundled gems are installed into `./vendor/bundle` > ``` > > Add the plugin to your `Podfile` by including the line: > > ```ruby theme={"dark"} > plugin 'cocoapods-pod-linkage' > ``` > > e.g. > > ```ruby theme={"dark"} > linkage = ENV['USE_FRAMEWORKS'] > if linkage != nil > Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green > use_frameworks! :linkage => linkage.to_sym > end > > # 👇 Add this line here, below the framework linkage check > plugin 'cocoapods-pod-linkage' > ``` > > Then, add the SDK and 3DS pods to your app target in the `Podfile`: > > ```ruby theme={"dark"} > > # ℹ️ This is already present if you are using static frameworks > # If this is not present then the USE_FRAMEWORKS environmental variable will be set to `static` > use_frameworks! :linkage => :static > > target 'MyApp' do > > # ... other CocoaPods config ... > > # 👇 Add these lines to ensure both the SDK pod and 3DS pod are linked dynamically > pod 'PrimerSDK', :linkage => :dynamic > pod 'Primer3DS', :linkage => :dynamic > > end > ``` > > Then, add the following to the `post_install` block: > > ```ruby theme={"dark"} > target 'MyApp' do > > # ... other CocoaPods config ... > > post_install do |installer| > > # ... other post_install step config ... > > # Add this entire block > installer.pods_project.targets.each do |target| > if target.name == "primer-io-react-native" || target.name == "PrimerSDK" > target.build_configurations.each do |config| > config.build_settings['FRAMEWORK_SEARCH_PATHS'] = "$(inherited) ${PODS_CONFIGURATION_BUILD_DIR}/Primer3DS" > config.build_settings['LIBRARY_SEARCH_PATHS'] = "$(inherited) ${PODS_CONFIGURATION_BUILD_DIR}/Primer3DS" > config.build_settings['SWIFT_INCLUDE_PATHS'] = "$(inherited) ${PODS_CONFIGURATION_BUILD_DIR}/Primer3DS" > config.build_settings['OTHER_LDFLAGS'] = '$(inherited) -framework Primer3DS' > end > end > end > > # ... other post_install step config ... > > end > > end > ``` > > Note: We recommend putting the above immediately after the call to `react_native_post_install`. > > Finally, run `bundle exec pod install` to finish setting up. > > ##### On Android > > 3D Secure on Android requires the addition of the `io.primer:3ds-android` library to your project. > > 1. Navigate to the `./android` directory in your React Native project. > > 2. Amend the dependencies section of your app's `build.gradle` to include the `3ds-android` library: > > ```groovy build.gradle theme={"dark"} > dependencies { > /* Other dependencies... */ > implementation 'io.primer:3ds-android' > } > ``` > > > [!NOTE] > > > > Leave out the version. From React Native SDK 2.49.0, the SDK sets it for you. On earlier versions, see [Android library versions](/docs/sdk/react-native/v2.x.x/installation#android-library-versions). > > #### Interoperability matrix > > Primer SDK internally uses Primer 3DS SDK as a `compile` time dependency. In order for the SDKs to work properly, > the versions used internally and the one imported to your code **must** match. > > Here is a breakdown of supported interoperable versions: > > | Primer React Native SDK version | Primer 3DS Android SDK version | Primer 3DS IOS SDK version | > | :- | :- | :- | > | `>= 2.49.0` | Set by the SDK | `>= 2.7.0` | > | `2.48.0` | `1.9.0` | `>= 2.7.0` | > | `2.42.0 - 2.47.1` | `1.8.0` | `>= 2.7.0` | > | `2.41.0 - 2.42.0` | `1.7.0` | `2.6.0 - 2.7.0` | > | `2.35.0 - 2.40.0` | `1.6.2` | `2.4.2 - 2.5.x` | > | `2.34.1 - 2.35.0` | `1.6.2` | `2.3.0 - 2.4.2` | > | `2.27.2 - 2.34.0` | `1.5.0` | `2.3.0 - 2.4.2` | > | `2.24.0 - 2.27.1` | `1.4.3` | `2.3.0 - 2.4.2` | > | `2.21.0 - 2.23.0` | `1.4.2` | `2.3.0 - 2.4.2` | > | `2.20.0` | `1.4.0` | `2.1.0 - 2.2.1` | > | `2.19.0 - 2.19.2` | `1.3.0` | `2.1.0 - 2.2.1` | > | `2.17.2 - 2.18.0` | `1.2.0` | `2.0.0 - 2.0.2` | > | `2.16.0 - 2.17.1` | `1.1.2` | `2.0.0 - 2.0.2` | > | `2.15.0 - 2.15.1` | `1.1.1` | `2.0.0 - 2.0.2` | > > #### Handle Out-of-Band (OOB) redirects (Optional) > > Starting from 3D Secure protocol version 2.2.0, you can enhance the user experience by implementing > an automatic redirect from another (authentication) application during an OOB challenge to your application once the challenge > is successfully completed. This feature allows for a seamless transition and improved user flow. > > > [!WARNING] > > > > If this feature is not implemented, the user will have to come back to your application manually to complete their payment, which adds significant friction. > > To enable this feature, ensure that you include the `threeDsAppRequestorUrl` parameter when configuring the `threeDsOptions` > property of your settings for each platform. > > Please note that the `ios.threeDsAppRequestorUrl` value **must** be an [iOS Universal Link](https://developer.apple.com/ios/universal-links/) and the `android.threeDsAppRequestorUrl` value **must** be an [Android App Link](https://developer.android.com/training/app-links) in order to facilitate the redirection. > > To configure the Universal Link correctly using Universal Checkout, follow these steps: > > 1. Pass your iOS Universal Link (e.g. `https://{UNIVERSAL_LINK}`) as `threeDsAppRequestorUrl`, and your Android App Link > (e.g. `https://{yourdomain.com}/3ds`) in the `threeDsOptions` object of your settings. > > ```tsx theme={"dark"} > const settings: PrimerSettings = { > // ... > paymentMethodOptions: { > threeDsOptions: { > iOS?: { > threeDsAppRequestorUrl?: string; > } > android?: { > threeDsAppRequestorUrl?: string; > } > }, > // ... > } > } > ``` > > 2. Follow Step 2 & 3 from the [iOS guide](./get-started#handle-out-of-band-oob-redirects-optional). > > 3. Follow Steps 1 to 3 from the [Android guide](./get-started#handle-out-of-band-oob-redirects-optional-2). > > #### Execute 3D Secure > > Universal Checkout drop-in and headless automatically render the 3DS challenge when required by your workflow. > > If this application is not installed from a trusted source (e.g. a debug version, not installed from store, or used on an emulator), try to set > [`PrimerDebugOptions.is3DSSanityCheckEnabled`](/docs/sdk/react-native/v2.x.x/common-objects/PrimerSettings#param-is3-ds-sanity-check-enabled) to `false`. > Otherwise 3D Secure library initialization will fail due to security checks being performed. > > > [!CAUTION] > > > > `is3DSSanityCheckEnabled` flag should only be used in development mode, and not in production release of your app. > > ```tsx theme={"dark"} > const settings: PrimerSettings = { > // ... > debugOptions: { > is3DSSanityCheckEnabled: true, > }, > } > ``` > > #### Testing 3D Secure > > To validate your 3D Secure integration, you can use our dedicated testing guide, which includes sample cards, > challenge flows, and different scenarios. For full details, see the [3DS Testing Guide](/docs/testing/3d-secure). # 3DS Challenge Mandate Source: https://primer.io/docs/payment-services/3d-secure/mandatechallenge ## 3DS Challenge Mandate The Mandate Challenge option lets you explicitly request that a 3D Secure (3DS) challenge be presented to your buyer, rather than allowing the card issuer to decide whether to use a frictionless or challenge flow. This can help merchants meet compliance requirements, particularly when storing a card for future Merchant-Initiated Transactions (MITs), or when additional buyer verification is desired for risk or policy reasons. While issuers are not obligated to honor a mandated challenge request, most issuers in regulated regions (such as the EEA and UK) will do so under PSD2 Strong Customer Authentication (SCA) rules. ## How Mandate Challenge Works By default, issuers decide whether to authenticate a buyer via a frictionless or challenge 3DS flow. When Mandate Challenge is enabled, Primer includes a flag in the 3DS authentication request that signals your preference for the buyer to be challenged. If the issuer supports mandated challenges, this usually results in a challenge screen being shown to the buyer (e.g., a one-time passcode, app approval, or biometric verification). If the issuer does not honor the mandate, the transaction will continue as a normal 3DS flow. ## When to Use Mandate Challenge You should use the Mandate Challenge option when: * You’re storing a card for future Merchant-Initiated Transactions (MITs) (for example, subscriptions, recurring payments, or delayed charges) within a region that has requirements for 3DS, such as the EEA. * PSD2 guidance recommends using a 3DS challenge for the initial card-on-file transaction, ensuring the cardholder has explicitly authenticated the storage consent. * You need strong assurance of buyer authentication for higher-value or higher-risk payments. * Your internal fraud or compliance policies require step-up authentication. In general, Mandate Challenge helps ensure that the buyer explicitly completes SCA during checkout, rather than relying on an issuer’s risk-based decision to allow frictionless authentication. ## Implementing Mandate Challenge in Workflows You can enable Mandate Challenge directly from the [Perform 3DS action](/docs/workflows/apps/native-apps/primer-payments-app/perform-3ds-action) in your Workflows. ### Steps 1. Add a **Perform 3DS** block to your Workflow. 2. Under 3DS Options, select Mandate Challenge. 3. Save and publish your Workflow. ![Perform 3ds Mandate Challenge](https://mintcdn.com/primer-cc826789/VyFK_A0n7sp9FOiH/images/payments/Perform3DSMandateChallenge.png?fit=max\&auto=format\&n=VyFK_A0n7sp9FOiH\&q=85\&s=f64154e4210251876048910083a0e084) Mandate Challenge in the Perform 3DS action You can also use [conditions](/docs/workflows/utilities/conditions-block) to mandate challenges only for specific scenarios - for example: * First time payments * Transaction amount over £1000.00 ![Mandate Challenge Condition](https://mintcdn.com/primer-cc826789/VyFK_A0n7sp9FOiH/images/payments/MandateChallengeCondition.png?fit=max\&auto=format\&n=VyFK_A0n7sp9FOiH\&q=85\&s=3d8e955c3e8b0bb5d87da66a96206f6c) Condition Block for Mandate Challenge This configuration ensures that your first card-on-file payment always requests a challenge, while repeat payments can proceed frictionlessly under MIT rules. > Note: Mandating a challenge may increase friction during checkout and can impact conversion rates. It should be applied selectively, based on transaction context and business requirements. ## Viewing Challenge Results You can see whether a challenge was presented in both the **Dashboard** and **API** responses: * **Dashboard:** The 3DS Authentication section will display the authentication method used - `Challenge` or `Frictionless`. * **API:** The `paymentMethod.threeDSecureAuthentication.challengeIssued` boolean will return `TRUE` if a challenge was presented. You can use these values to audit and report on your 3DS flows. ## Best Practices * **Always use a challenge for first-time card storage (MIT setup) in regulated regions.** This ensures regulatory compliance and reduces the risk of failed subsequent MITs. * **Combine with conditions.** For example, only mandate challenges for new customers, high-risk transactions, or first-time card use. * **Monitor completion rates.** Track your 3DS challenge completion success to balance security and conversion. # 3D Secure: Overview Source: https://primer.io/docs/payment-services/3d-secure/overview ## What is 3DS? 3D Secure (3DS) is an online protocol that aims to reduce fraud and increase security for online payments. 3DS requires customers to complete an additional verification step with the card issuer when paying. Each card network has its own branded name for 3DS, including Visa Secure, Mastercard Identity Check and American Express Safekey. 3DS is mandatory for online card payments in the EU, meeting the Secure Customer Authentication (SCA) regulation as part of Revised Payment Services Directive (PSD2). It can be optionally used in other regions as an effective tool to reduce fraud. 3D Secure 1 (3DS1) is the original version of 3DS, dating back to 2001. Although compliant as part of PSD2, it caused friction for customers, including a suboptimal mobile experience and not recognizing soft declines. A decision was made to decommission 3DS1 from October 2021 and it has now been sunset in favour of 3D Secure 2 (3DS2). 3DS2 (sometimes referred to as EMV® 3-D Secure) maintains the required SCA compliance but addresses the limitations of 3DS1 which includes a much better customer experience. ### Frictionless authentication Unlike 3DS1, 3DS2 supports frictionless authentication, which leverages the additional customer information passed in the 3DS2 flow to determine scenarios where no additional customer input is required to authenticate the payment. In these instances, the payment is authenticated '*frictionlessly*', which leads to a much better customer experience. ### Challenge authentication Issuers can determine that additional verification is required from the customer in order to authenticate a payment. As a result, a challenge is presented to the customer that outlines a two-factor authentication process the customer needs to undertake to verify themselves. The two-factor authentication process will vary across issuers. > [!NOTE] > > You can request that a challenge is mandated for the buyer from within the ["Perform 3DS" action](/docs/workflows/apps/native-apps/primer-payments-app/perform-3ds-action). Note that while we cannot guarantee issuers will honour the request, it generally results in the buyer being presented a challenge, particularly in regulated regions. ### Liability shift Generally, for payments that are successfully authenticated, liability for fraud-related chargebacks shifts from the merchant to the issuer. > [!NOTE] > > Note that there are some variances for when liability shift applies based on region and card network, which you should confirm with your processor/acquirer. ### ECI Values The Electronic Commerce Indicator (ECI) values are returned by the Directory Server (DS) and Access Control Server (ACS) as part of the 3DS flow. They indicate the outcome of the authentication request. Below is a table outlining the main ECI values: #### Mastercard | **ECI Value** | **Description** | **Liability Shift** | | - | - | - | | 00 | Authentication rejected or could not be attempted (EG information was incorrect, cardholder cancelled the authentication process, the ACS is not able to handle the request) | No liability shift | | 01 | Authentication attempted but was not available at the issuer. Instead, the DS stands in, which generates proof the merchant attempted authentication. | Liability shift can sometimes apply | | 02 | Authentication successful | Liability shift applies | #### Visa, American Express and other card networks | **ECI Value** | **Description** | **Liability Shift** | | - | - | - | | 05 | Authentication successful | Liability shift applies | | 06 | Authentication attempted but was not available at the issuer. Instead, the DS stands in, which generates proof the merchant attempted authentication. | Liability shift can sometimes apply | | 07 | Authentication rejected or could not be attempted (EG information was incorrect, cardholder cancelled the authentication process, the ACS is not able to handle the request) | No liability shift | > [!NOTE] > > If Primer receives the ECI during the 3DS flow, it is passed on to the processor during the authorization request. However, if the 3DS flow doesn't get to this stage, then there is no ECI value generated for that payment and no ECI is passed on to the processor. ## 3DS via Primer Primer has decoupled 3D Secure from any underlying processor and simplified the implementation of 3DS across all your platforms. Configure 3D Secure in your workflow, and Universal Checkout will handle the rest, presenting a fully in-context and optimized 3D Secure flow to your customer on web and mobile. [See our guide on how to configure 3DS on Primer](/docs/get-started/overview). ### 3DS statuses Below are the possible 3DS statuses: | **Status** | **Description** | | - | - | | `AUTH_SUCCESS` | The payment is successfully authenticated. | | `AUTH_FAILED` | The authentication was attempted but did not pass the required verification. This could be due to the cardholder failing to provide the correct authentication details or it could also be due to the assessment of the transaction's risk being deemed too high. The risk evaluation could be based on various factors such as unusual spending patterns, suspicious behaviour, or discrepancies in the provided information. | | `SKIPPED` | Authentication was attempted but could not be completed due to an error. These errors include technical issues such as system failures and invalid responses from the ACS or DS. | | `NOT_PERFORMED` | No 3DS authentication was attempted for this payment. | | `METHOD` | Transitory status for Web only 3DS authentication flows, where the Web SDK retrieves the URL and handles the 3DS Method browser fingerprint. | | `CHALLENGE` | Transitory status for authentications where a challenge is required and the 3DS challenge flow will be shown to the customer. | ### Adaptive 3DS Adaptive 3DS is designed to improve conversion and abstract the complexity required to optimally configure when to show 3DS. When Adaptive 3DS is activated, payments are always processed without 3DS. If the processor declines the payment due to a lack of 3DS, Primer automatically runs 3DS and retries the payment immediately. > [!NOTE] > > Adaptive 3DS also skips 3DS in cases where 3DS is mandatory. As a result, Adaptive 3DS may lead to declined payments that are eventually authorized. > > Contact your processor/acquirer to make sure this strategy is allowed. #### When is Adaptive 3DS triggered? Primer standardizes decline codes and reasons from processors so you only need to rationalize about payments once. Payments have the following fields which have been standardized across all processors: * `status` * `error decision type` * `error decline type` * `error decline reason` Adaptive 3DS will be triggered when the payment has one of the following sets of field values: | **Status** | **Error Decision Type** | **Error Decline Type** | **Error Decline Reason** | | :- | :- | :- | :- | | Declined | Gateway Rejected | N/A | N/A | | Declined | Issuer Declined | Soft Decline | Authentication Required | | Declined | Issuer Declined | Soft Decline | Do Not Honor | | Declined | Issuer Declined | Soft Decline | Refer to Card Issuer | | Failed | Application Error | N/A | N/A | > [!NOTE] > > Adaptive 3DS and [Fallbacks](/docs/payment-services/fallbacks) have overlapping triggers. If both features are activated for a payment, Adaptive 3DS always has priority. If the second authorization attempt still fails, a fallback may be triggered. ### Processor 3DS There are a small proportion of processors that do not support third-party 3DS. In these instances, Primer seamlessly redirects the customer to the processor's 3DS challenge page instead. As Primer is not involved in the 3DS flow, there are several limitations around using processor 3DS, including: * It is incompatible with [fallbacks](/docs/payment-services/fallbacks) and the ["Perform 3DS" action](/docs/workflows/apps/native-apps/primer-payments-app/perform-3ds-action). * There is not the same level of visibility into the 3DS flow so it is harder to debug any issues that may arise. > [!NOTE] > > Please reach out to us directly via our [Service Desk](https://portal.support.primer.io/servicedesk/customer/portal/11) if you are unsure if your processor only supports Processor 3DS. ### Supported card networks The following card networks are supported for 3DS on Primer: * Visa * Mastercard * American Express (Amex) * Discover/Diners Club * JCB * Union Pay (UPI) * Cartes Bancaires (for [integrations where co-badged support is available](/docs/payment-services/cobadged-cards#integrations)) ### Start your integration > [!NOTE] > > Use our [Get Started](./get-started/) guide to implement 3DS via Primer. # Advanced Metadata Mapper Source: https://primer.io/docs/payment-services/advanced-metadata-mapper ## Configure how your metadata is mapped Primer's advanced metadata mapping tool allows you to specify how information from your [client session](/docs/checkout/client-session) `metadata` object is mapped to the payload we send to third-party payment connections. This means: * You can build custom rules and pass the needed data without Primer being involved * You can pass fields as part of the third-party metadata objects to activate the relevant fraud flows and rules-based mappings on the third-party processor ## Supported connections This functionality is only supported for authorization on the following connections: * Adyen * Airwallex * Braintree * Checkout.com * Cybersource * Everypay * J.P. Morgan Chase (JPMC) * Klarna * Merchant Warrior * Monext * Nuvei * Payplug * Stripe * Thunes * Trust Payments * Worldpay * Worldline Connect * Worldline Direct This functionality is supported for capture on the following connections: * Braintree * Cybersource * Payplug * Worldline Direct This functionality is supported for pre-authorization and post-authorization fraud checks. ## How does it work? ### Step 1: Prepare the metadata mapping * Navigate to an existing integration that you have configured on your Primer dashboard and select **Advanced mapping**. The example below is for Stripe. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/advanced-metadata-mapping/stripe-metadata-mapping.png) Accessing advanced mapping settings in Stripe integration * You can now add as many fields as you want. > [!NOTE] > > The mapping respects nested fields as well. You can use dot notation to specify the nested field locations. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/advanced-metadata-mapping/stripe-metadata-mapping-empty.png) Adding metadata mapping fields ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/advanced-metadata-mapping/stripe-metadata-mapping-populated.png) Configuring nested metadata fields > [!NOTE] > > If the connection you wish to add fields to supports authorization and capture, you can specify the fields for both > the authorization and capture requests by choosing the appropriate tab. ### Step 2: Make the payment request All you need to do now is pass the correct metadata fields in the client session if the payment is made via Universal Checkout, or directly in the payment request. Below is an example client session or payment request payload for the mapping above: ```json JSON theme={"dark"} { "orderId": "order-123", "amount": 3000, "currencyCode": "GBP", "customerId": "cust-123", "metadata": { "customer_data": { "customer_ip_address": "127.0.0.1" }, "my_additional_data": { "field_1": "foo", "field_2": "bar" }, "some_unmapped_field": 123 } } ``` ### Step 3: Capture your payment with metadata If you require metadata to be passed to the third-party processor when capturing a payment, you can do so by passing the metadata in the capture request, alternatively, you can also add the metadata to the client session initially ready for use in the capture request. Below is an example capture request payload for the mapping above: ```json JSON theme={"dark"} { "amount": 9, "final": false, "metadata": { "customer_data": { "customer_ip_address": "127.0.0.1" }, "my_additional_data": { "field_1": "foo", "field_2": "bar" }, "some_unmapped_field": 123 } } ``` The resulting request to the third-party (Stripe in this example) will then contain your mapped fields per action. ## Current Limitations ### Limitations with arrays We currently do not fully support mapping array fields with custom objects as elements. The following is an example of this: ```json JSON theme={"dark"} { "amount": 9, "final": false, "metadata": { "customer_data": { "customer_ip_address": "127.0.0.1" }, "my_additional_array_field": [ { "my_additional_array_element": { "field_1": "foo", "field_2": "bar" } } ] } } ``` However, as a workaround to this, it is possible to just map the array field in metadata mapper, without specifying the details of the elements of the array. This has a small caveat though: since we are not mapping the array elements, we need to add the field value in the payload in the format expected from the connection. To illustrate this workaround, we can consider an example from Sift. Since it requires the fields to be prefixed with `$`, the usage of their `$bookings` field would look like the following: ```json JSON theme={"dark"} { "amount": 9, "final": false, "metadata": { "bookings": [ { "$booking_type": "$accomodation", "$start_time": 1678062720000, "$end_time": 1679062720000, "$location": { "$name": "Marriot New London", "$phone": "1-415-555-6041", "$address_1": "2100 Main Street", "$city": "New London", "$region": "New Hampshire", "$country": "US", "$zipcode": "03257" }, "$room_type": "Seaside View Queen", "$price": 103082000, "$currency_code": "USD", "$quantity": 2 } ] } } ``` In the account, the metadata mapper would look like the following: ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/advanced-metadata-mapping/sift-metadata-mapping.png) ### Limitations with decimals Decimal types are not supported. If this type is passed and used in metadata mapping, it will be sent to the third party as a string type. For example, if you send the following metadata in your request to Primer ```json theme={"dark"} { ..., "metadata": { "decimal_number": 101.95 } } ``` and this is used in metadata mapping, it will be sent as ```json theme={"dark"} { ..., "mapped_field": "101.95" } ``` # BIN data Source: https://primer.io/docs/payment-services/bin-data How Primer enriches card payments with BIN data, and why you should build on card attributes rather than raw BIN digits. Every card number starts with a Bank Identification Number (BIN). These are the first digits of the card number, and they tell you a lot about the card: its network, the bank that issued it and in which country, whether it is a debit, credit, or prepaid card, whether it belongs to a consumer or a business, and more. Primer enriches every card payment with BIN data automatically. You can use it to adapt your checkout UI in real time, to build routing and compliance rules in Workflows, and to read card attributes from the API and webhooks. ## How Primer analyzes BIN data **Primer analyzes cards on the first 12 digits.** When a card is tokenized, Primer looks it up starting from the first 12 digits of the card number. It falls back to a shorter prefix only when there is no more precise range to match. So every card attribute you see, whether in the checkout, in Workflows, or in the API, comes from this 12-digit analysis, not from a simple 6-digit match. This matters because BINs have outgrown 6 digits. Since 2022, card networks have been expanding BIN ranges to 8 digits, and the newest ranges can need up to 12 digits to be identified precisely. The same 6-digit prefix can now belong to several issuers in different countries. Because Primer always matches the most precise range it can, your card attributes stay accurate as BIN ranges keep changing. > [!NOTE] > > **For card logic, prefer attributes over raw BIN digits.** > > Because every attribute comes from a 12-digit analysis, the attributes Primer returns are more accurate than anything you could build on the first 6 or 8 digits yourself. They are also easier to maintain. A rule like `Product usage type is BUSINESS` stays clear and correct over time, while a list of raw prefixes like `First 6 digits is 411111` becomes very hard to keep up to date as BIN ranges change. > > The exception is when you need to identify a specific card product rather than a category of card. Issuers often use the 8-digit BIN as the identifier of an individual product, so a campaign targeting one partner bank's product requires the BIN itself. For those cases, use `firstDigits`, described below. ## The BIN digits Primer returns Primer returns two BIN fields in the `paymentMethodData` object of a payment, in API responses and webhooks: | Field | What it contains | | - | - | | `firstDigits` | The full BIN Primer can share: 6 or 8 digits, depending on the card and the network | | `first6Digits` | Always the first 6 digits | Use `firstDigits` whenever you need to identify a specific card product, for example a reward campaign with a partner bank that targets an 8-digit range. Use `first6Digits` where your logic depends on a fixed 6-digit length. Both fields are permanent. `first6Digits` is not deprecated and existing integrations do not need to change. > [!WARNING] > > **`firstDigits` is not always 8 digits.** > > If the PCI DSS prohibits Primer from exposing the first 8 digits for a card, `firstDigits` returns 6 digits instead. An exact comparison against an 8-digit value will not match those payments, and it will fail silently. > > Check the length before you compare, and treat a 6-digit result as "this range is not defined on 8 digits" rather than as an error. If you are matching a range, compare on the number of digits you actually received. PCI DSS permits sharing the card's BIN together with the last 4 digits, and the BIN is at most 8 digits. ## Use BIN data in your checkout The Checkout SDK surfaces BIN data as soon as the customer types their card number, before any payment is created. You can use it to adapt your UI early: show or hide payment options, display the detected network, or block card types you do not support. The data arrives through the `primer:bin-data-available` event. For co-badged cards, such as Visa and Cartes Bancaires on the same card, it lists every detected network with its own attributes: ```json theme={"dark"} { "preferred": { "network": "VISA", "displayName": "Visa", "issuerCountryCode": "FR", "issuerName": "SOCIETE GENERALE S.A.", "accountFundingType": "DEBIT", "prepaidReloadableIndicator": "NOT_APPLICABLE", "productUsageType": "CONSUMER", "productCode": "F", "productName": "Visa Classic", "issuerCurrencyCode": "EUR", "regionalRestriction": "UNKNOWN", "accountNumberType": "PRIMARY_ACCOUNT_NUMBER", "allowed": true }, "alternatives": [ { "network": "CARTES_BANCAIRES", "displayName": "Cartes Bancaires", "issuerCountryCode": "FR", "issuerName": "SOCIETE GENERALE", "accountFundingType": "DEBIT", "prepaidReloadableIndicator": "UNKNOWN", "productUsageType": "CONSUMER", "productCode": "C", "productName": "CB Cobadgé - Classic", "issuerCurrencyCode": "EUR", "regionalRestriction": "UNKNOWN", "accountNumberType": "PRIMARY_ACCOUNT_NUMBER", "allowed": true } ], "status": "complete", "firstDigits": "497355" } ``` > [!NOTE] > > `firstDigits` on this event always returns 6 digits, even where the payment object returns 8. The two fields share a name but not a length. If your logic needs the full BIN, read `firstDigits` from `paymentMethodData` once the payment is created. See [Use BIN data to control Click to Pay](/docs/checkout/primer-checkout/guides-and-recipes/use-bin-data-to-control-click-to-pay) for a step-by-step guide, including how to listen to the event, read its loading and completeness states, and handle co-badged cards correctly. ## Use BIN data in Workflows Card attributes from BIN data are available as conditions in Workflows, under **Card information** on the *Payment created* trigger. Use them to build routing, compliance, fraud, or 3DS rules based on what the card actually is. ![The Workflows condition builder showing the Card information variables available on the Payment created trigger](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/bin-data/workflow-card-information.png) Card information conditions on the Payment created trigger in the Workflows builder The following attributes are available: | Attribute | Type | | - | - | | Account funding type | Text | | Account number type | Text | | Cardholder name | Text | | Expiration month | Text | | Expiration year | Text | | First 6 digits | Text | | First digits | Text | | Is network tokenized | Boolean | | Issuer country code | Country | | Issuer currency code | Text | | Issuer name | Text | | Last 4 digits | Text | | Card network | Text | | Network transaction ID | Text | | Product usage type | Text | **First 6 digits** always matches on 6 digits. **First digits** matches `firstDigits` from the API: 6 or 8 digits, depending on the card and network. Note: `productCode`, `productName`, `prepaidReloadableIndicator`, and `regionalRestriction` are returned by the API and webhooks but are not yet available as Workflow conditions. For example, to route business cards to a specific processor, use a single condition: `Product usage type is BUSINESS`. This is more accurate and easier to maintain than keeping lists of BIN prefixes in your rules. > [!WARNING] > > **Avoid hard-blocking conditions based only on BIN attributes.** > > BIN data can never be 100% reliable. Card networks update and expand BIN ranges all the time, newly issued cards may not be in the BIN data sources yet, and some attributes can resolve to `UNKNOWN` for certain ranges. This is true across the industry, not just for Primer. > > Because these sources are refreshed over time, the same card can occasionally resolve to slightly different attributes across payments, most often an attribute moving from `UNKNOWN` to a known value. > > BIN attributes are a strong signal for routing, 3DS, and fraud decisions. But if a rule declines or blocks payments based only on a BIN attribute, a small share of legitimate payments will be affected. When you build such a rule, always decide how to handle `UNKNOWN` values, and prefer a fallback path over a hard block. ## Use BIN data via the API and webhooks Once a payment is created, the resolved card attributes are returned in the `paymentMethodData` object of the payment, both in API responses and in webhook notifications: ```json theme={"dark"} "paymentMethodData": { "first6Digits": "497355", "firstDigits": "49735534", "last4Digits": "1111", "expirationMonth": "03", "expirationYear": "2030", "cardholderName": "John Appleseed", "network": "Visa", "isNetworkTokenized": false, "binData": { "network": "VISA", "issuerCountryCode": "FR", "issuerName": "SOCIETE GENERALE S.A.", "issuerCurrencyCode": "EUR", "regionalRestriction": "UNKNOWN", "accountNumberType": "PRIMARY_ACCOUNT_NUMBER", "accountFundingType": "DEBIT", "prepaidReloadableIndicator": "NOT_APPLICABLE", "productUsageType": "CONSUMER", "productCode": "F", "productName": "Visa Classic" } } ``` You can use these attributes to reconcile payments, feed your own analytics, or drive post-payment logic on your side, all without ever handling raw card numbers. Each attribute takes a value from a fixed list, and any attribute can be `UNKNOWN` when the range is not precisely identified: * **`accountFundingType`**: `CREDIT`, `DEBIT`, `PREPAID`, `CHARGE`, `DEFERRED_DEBIT`, `UNKNOWN` * **`productUsageType`**: `CONSUMER`, `BUSINESS`, `GOVERNMENT`, `UNKNOWN` * **`accountNumberType`**: `PRIMARY_ACCOUNT_NUMBER`, `NETWORK_TOKEN`, `DIGITAL_PAN`, `UNKNOWN` * **`prepaidReloadableIndicator`**: `RELOADABLE`, `NON_RELOADABLE`, `NOT_APPLICABLE`, `UNKNOWN` * **`regionalRestriction`**: `DOMESTIC_USE_ONLY`, `NONE`, `UNKNOWN` `productCode` and `productName` are not enums. They are network-defined free-text values (for example `F` and `Visa Classic`), so treat them as opaque strings rather than a fixed set. ## BIN data for Apple Pay and Google Pay Wallet payments behave differently from raw card payments, because of how wallets tokenize cards. ### Apple Pay Apple Pay payments always use a network token. The encrypted payment token Primer receives contains a **device PAN (DPAN)**, not the customer's actual card number. A DPAN is a tokenized card number that the card network issues for one specific device. Primer never sees the underlying funding card. As a result, BIN data for Apple Pay payments comes from the DPAN. DPANs are issued from their own BIN ranges, so some attributes can differ from the physical card. The funding type, the product type, or even the issuer details can be different. ### Google Pay Google Pay payments come in two forms: * **`PAN_ONLY`**: the token contains the real card number (FPAN). BIN data reflects the customer's real card, exactly as for a raw card payment. * **`CRYPTOGRAM_3DS`**: the token contains a DPAN, like Apple Pay. BIN data comes from the DPAN and can differ from the funding card's attributes. ### What this means for your integration Two attributes help you tell DPAN-based payments apart from raw card payments. Both are available as Workflow conditions and in `paymentMethodData`. `isNetworkTokenized` means the card is represented by a digital PAN. It is always `true` for Apple Pay, and `true` for Google Pay `CRYPTOGRAM_3DS` payments, so a `true` value on a wallet payment tells you the BIN data came from a DPAN. Keep in mind that this flag can also be `true` for regular card payments that use Primer network tokenization, so on its own it does not prove that a payment is a wallet payment. `accountNumberType` is the most precise signal. When BIN data comes from a digital PAN it resolves to `NETWORK_TOKEN` or `DIGITAL_PAN`, and to `PRIMARY_ACCOUNT_NUMBER` for a raw card. > [!WARNING] > > Be careful when you build strict compliance or blocking rules on BIN attributes for wallet payments. Because the attributes come from the DPAN, they may not match what your processor reports. During acquiring, a processor can look up the funding card's details from the network and classify the same payment differently. For rules that must apply to the funding card, such as blocking credit cards or restricting to domestically issued cards, handle network-tokenized payments explicitly in your workflow logic. # Enable local card schemes with Primer Source: https://primer.io/docs/payment-services/cobadged-cards/Enable-local-card-schemes-with-Primer Learn how to enable local card schemes through co-badged cards using Primer. ## Overview Primer lets you support **local card schemes through co-badged cards**, without redesigning your checkout or building custom logic. You keep a single card form.\ Primer handles detection, selection, and routing, while helping you stay compliant with local regulations. This page explains: * where co-badged cards are supported in Primer * which platforms and integrations are compatible * how to enable co-badged cards in your integration *** ## How Primer supports co-badged cards At a high level, Primer allows you to: * detect all card networks available on a card * define which networks you want to accept * control network preference and defaults * let the shopper choose when regulations require it * pass the selected network to your processor *** ## Primer platform compatibility The table below shows where co-badged card handling is supported across Primer platforms. | Platform | Compatibility | | - | - | | Web Drop-in | ❌ | | Web Headless | ✅ | | Web Primer Checkout (Components) | ✅ | | iOS Drop-in | ✅ | | iOS Headless | ✅ | | Android Drop-in | ✅ | | Android Headless | ✅ | | React Native Drop-in | ✅ | | React Native Headless | ❌ | *** ## Supported integrations and compatibility The integrations listed below are **fully compatible** with co-badged cards in Primer. “Fully compatible” means: * the local card scheme is supported by the processor * the integration works with Primer’s **agnostic 3DS** * end-to-end routing and compliance requirements are covered Other integrations may allow payments via local schemes but are not listed here, as they are **not yet fully compatible with processor-level 3DS flows**. > [!NOTE] > > If you have a question or a project involving local card schemes, contact your Customer Success Manager or reach out to Primer Support. ### Cartes Bancaires (France) Cartes Bancaires (CB) is the domestic card network in France. More than **95% of CB cards are co-badged** with Visa or Mastercard.\ This means the same card can be processed on: * the Cartes Bancaires network, or * the Visa or Mastercard networks When processing co-badged cards in the EEA, merchants must allow shoppers to **select the network** they want to use at checkout. #### Supported integrations * MONEXT * Adyen * Stripe * Checkout.com * Payplug > [!NOTE] > > **Monext: 3DS card brand identifier** > > When processing 3DS authentication via Monext, the `cardBrand` field in the 3DS authentication data returns `"CB"` for all card types, including Visa and Mastercard. This is expected Monext behavior — in the French payments ecosystem, "CB" is used as a generic identifier covering Cartes Bancaires, Visa, and Mastercard under the co-badging scheme. The actual card network is determined separately during the payment flow and is not affected by this value. ### eftpos (Australia) eftpos is the domestic debit card network in Australia. More than **90% of eftpos cards are co-badged** with Visa or Mastercard, which means they can be processed through either network depending on configuration and routing. > [!NOTE] > > Non co-badged eftpos cards (also known as “proprietary eftpos cards”) are only supported for in-person payments and cannot be used for online transactions. #### Supported integrations * Worldpay *** ## US debit networks (United States) ### What are US debit networks? Most US debit cards are co-badged: they carry Visa or Mastercard plus one or more US domestic debit networks, such as Maestro USA, NYCE, Pulse, STAR or Accel. Domestic networks usually cost less, so routing debit payments to them (debit routing, or least-cost routing) can lower your processing fees. In the United States the shopper doesn't choose the network. See the [co-badged cards overview](/docs/payment-services/cobadged-cards/Overview) for the regulatory background. ### Routing co-badged US debit cards Primer identifies US debit cards as Visa or Mastercard, and the domestic debit networks aren't available in `orderedAllowedCardNetworks` or in workflow conditions. Route these cards to your processor as you would any Visa or Mastercard payment. Your processor manages routing across the domestic debit networks. Primer passes on the option you choose: * **Process as Visa or Mastercard (default).** Primer asks the processor to use Visa or Mastercard, so card payments stay on those networks. * **Debit routing.** Primer lets the processor pick the network for each card payment. It applies to all card payments on your account with that processor. You can't enable it for individual workflow routes. For Apple Pay and Google Pay payments, the processor always chooses the network, whichever option you use. Debit routing is available with: * **Adyen**: enabled on request. * **Checkout.com**: through [Pinless Debit](/docs/connections/payment-methods/pinless-debit/overview), which you integrate as a separate payment method. ### Impact of enabling debit routing #### Capture logic can differ per domestic debit network Domestic debit networks usually process payments as a **sale**: authorization and capture happen in a single step, and the full amount is taken at authorization. By default, a capture for a smaller amount, multiple partial captures and incremental authorizations are declined on these payments. Some processors can enable partial captures on domestic debit networks for your merchant account. Support varies by network. #### Other co-badged cards on the same account If you also process EEA co-badged cards on the same account, Primer may no longer pass the shopper's network choice to the processor. Contact Primer before enabling debit routing on an account that serves both regions. #### Steps to enable 1. Check whether you ever capture a different amount than you authorize, for example as a marketplace, with split shipments, or when the final amount is only known after checkout. 2. If you do, ask your processor to enable partial captures on US debit networks for your merchant account. Disable any network that doesn't support them in your processor account: Primer can't exclude individual networks. 3. Contact your Customer Success Manager or Primer Support to enable debit routing on your Primer account. 4. Test with a real US debit card. Sandbox test cards may not reproduce routing to domestic networks. *** ## Process to enable local card schemes ### Step 1 – Enable local schemes with your processor Before enabling co-badged cards in Primer, make sure that: * the local card scheme is enabled on your processor account * the scheme supports **online card payments** * your merchant account is correctly configured for the relevant region > [!NOTE] > > If the local scheme is not enabled at processor level, Primer cannot reliably route payments to it, which may result in inconsistent scheme routing or failed payments. ### Step 2 – Allow card networks in the client session Co-badged card behaviour is controlled from the **client session**. When creating a client session, define which card networks you want to accept using `orderedAllowedCardNetworks`. ```json theme={"dark"} // POST /client-session { "paymentMethod": { "orderedAllowedCardNetworks": [ "EFTPOS", "VISA", "CARTES_BANCAIRES", "MASTERCARD" ] } } ``` This configuration: * defines which card networks are accepted * defines the default preference order #### Supported card network identifiers Use the following identifiers when configuring `orderedAllowedCardNetworks`: `VISA`, `MASTERCARD`, `AMEX`, `MAESTRO`, `UNIONPAY`, `CARTES_BANCAIRES`, `DANKORT`,\ `EFTPOS`, `DINERS_CLUB`, `DISCOVER`, `ENROUTE`, `ELO`, `HIPER`, `INTERAC`, `JCB`, `MIR`, `OTHER` > [!NOTE] > > Network availability depends on your processor and region. #### How network preference works The order of `orderedAllowedCardNetworks` matters. Primer uses this order to: * select a **default network** when a card is co-badged * fall back automatically if the shopper does not make a choice ##### Example ```json theme={"dark"} ["CARTES_BANCAIRES", "VISA", "MASTERCARD"] ``` * CB + Visa card → defaults to Cartes Bancaires * Visa-only card → uses Visa * Unsupported card → rejected If regulations require shopper choice, Primer will always respect the shopper’s final selection. ### Step 3 – Workflow configuration To ensure payments are routed to the correct processor, you must explicitly configure routing for local schemes in **your card workflow**. #### How to configure 1. Open **your card workflow** 2. Add a **Condition** node based on **Card network** 3. Configure the condition: * Card network **equals** the local scheme you want to route\ (for example: `EFTPOS`, `CARTES_BANCAIRES`, or `VISA`) 4. On the **true** branch: * Add an **Authorize payment** step using a processor that supports this card network 5. On the **else** branch: * Keep your existing routing ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/co-badged-cards/eftpos-in-workflows.png) Example of workflow routing based on card network > [!WARNING] > > If a local scheme is not explicitly routed to a compatible processor, payments may fall back to another network or fail, depending on processor behaviour. *** ## Apple Pay and Google Pay The same configuration you apply for card payments **automatically applies to Apple Pay and Google Pay**. If a local scheme is enabled for cards, it will also be enabled for Apple Pay and Google Pay when supported by the wallet and the underlying card. This means: * no additional frontend work is required * changes made to the card configuration also affect Apple Pay and Google Pay However, wallets handle card network selection differently: * the shopper selects the card **inside the wallet UI**, not in your checkout * there is **no card network selector** displayed in your checkout for Apple Pay or Google Pay * the wallet may automatically choose a network on behalf of the shopper * depending on the wallet and platform, Primer **may or may not receive an explicit network preference** ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/co-badged-cards/network-selection-apple-pay.png) Native card network selection in Apple Pay Primer always processes the payment using the network information provided by the wallet. If you allow Apple Pay or Google Pay, make sure your **workflows are adapted accordingly** and local schemes are routed to processors that support them. *** ## Testing co-badged cards Primer provides test cards for some co-badged scenarios through the **Sandbox processor**. Use the following resources to validate your integration: * [Primer Sandbox Processor](/docs/testing/primer-sandbox-processor) * [Test card payments](/docs/testing/primer-sandbox-processor#test-card-payments) *** ## Common pitfalls Before going live, make sure that: * **Local schemes are enabled at processor level**\ Otherwise, routing may be inconsistent or fail. * **Your Client Session only advertises supported networks**\ `orderedAllowedCardNetworks` must match what your processors can handle. * **Saved (vaulted) cards keep using the originally selected network**\ The network used for the first transaction is stored with the payment method and cannot be changed later. * **Recurring payments reuse the initial network choice**\ MITs and recurring payments must be processed using the same network as the original transaction. # Get started with Headless Checkout Source: https://primer.io/docs/payment-services/cobadged-cards/Get-started-with-Headless-Checkout Configure co-badged cards with Express Checkout using Primer Headless Checkout. ## Overview The guide below will help you configure **co-badged cards** with **Headless Checkout**. > [!NOTE] > > We’ve introduced a new way to integrate our Checkout for Web. > > Learn how to build a fully customizable checkout using modular components in our documentation here: > [Primer Checkout (Web Components)](/docs/checkout/overview) *** ### Example projects Feel free to use these example projects to get started quicker: * [Web (Vanilla JS)](https://github.com/primer-io/checkout-web/tree/main/examples/features/cobadged) * [iOS (SwiftUI)](https://github.com/primer-io/checkout-examples-ios/tree/main/Co-Badged%20Cards) * [Android](https://github.com/primer-io/checkout-examples-android/tree/main/co-badged-cards) ### Pre-requisites This guide assumes that you have already integrated a card form with Headless Checkout. Make sure to follow the ["Get Started with Headless Checkout"](/docs/checkout/headless/) first. ### Step 1. Set the list of supported card networks in the client session When creating a client session, it is recommended to pass the list of the card networks supported for this particular session. This ensures that the customer is not asked to choose a card network that you do not accept. The card network should be sorted in order of preference. This enables us to identify the default card network to consider if the user enters a co-badged card. ```json JSON theme={"dark"} // POST /client-session { "paymentMethod": { "orderedAllowedCardNetworks": ["VISA", "CARTES_BANCAIRES", "MASTERCARD"] } } ``` With the example above: * If the user enters a "Visa & Cartes Bancaires" card, the default network will be Visa * If the user enters a "Mastercard & Cartes Bancaires" card, the default network will be Cartes Bancaires > [!NOTE] > > Learn more about `orderedAllowedCardNetworks` in the [API Reference](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#request.body.paymentMethod.orderedAllowedCardNetworks). > [tab] Web > > ### Step 2. Detect the card networks > > On Web, the card form is implemented using PCI-compliant hosted fields that can be put anywhere on the web page. > > When the customer enters their card number, Headless Checkout retrieves the list of card networks available on the card. The list of card networks is passed to the developers through a callback called `onBinDataAvailable`. > > > [!NOTE] > > > > The previous `onCardNetworksChange` callback remains available for backwards compatibility, but we recommend using `onBinDataAvailable` for new integrations as it provides richer data including issuer information and card attributes. > > ```ts Typescript theme={"dark"} > const cardManager = await headless.createPaymentMethodManager('PAYMENT_CARD', > { > onBinDataAvailable({ > status, > preferred, > alternatives > }) { > // Handle the detected card networks > } > }) > ``` > > This callback returns the following data: > > * `status` \ > The status of the BIN data retrieval. > * `partial` if the card networks come from the SDK, usually by leveraging the first few digits, or if Primer's server fails to be reached. > * `complete` if the card networks come from Primer's server with full BIN data. > * `alternatives`\ > The list of all the detected card networks, including the ones that are not allowed. > * `preferred` \ > The recommended card network based on `orderedAllowedCardNetworks`. Can be `undefined` if the user entered a card that is not allowed. > > To get the list of selectable networks for co-badged cards, use: > > ```ts Typescript theme={"dark"} > const selectableNetworks = [preferred, ...alternatives].filter(n => n?.allowed) > ``` > > The card networks returned by `onBinDataAvailable` are objects that contain the network id, its display name, a flag `allowed` stating if the card network is in `orderedAllowedCardNetworks`, and additional issuer information when available. > > > [!NOTE] > > > > Learn more about `onBinDataAvailable` in the [API reference](/docs/sdk/web/v2.x.x/primer-headless-checkout/methods/createPaymentMethodManager#card.parameters.options-properties.onBinDataAvailable). > > #### Less than 8 digits > > If the user enters less than 8 digits, Headless Checkout cannot detect co-badged cards. Instead, Headless Checkout tries to detect major card networks using data available locally. > > In this case: > > * `status` is set to `partial` > * `preferred` contains the card network you should present to the user > * `alternatives` contains all the detected card networks > * Selectable networks will have only one allowed network (no co-badge selection needed) > > #### 8 digits or more > > If the user enters 8 digits or more, Headless Checkout attempts to make a request to Primer to retrieve the list of card networks available on the card using our BIN data. > > In this case: > > * `status` is set to `complete` > * For co-badged cards where multiple networks are allowed, you should present the selectable networks to the user > > If Headless Checkout fails to contact Primer, Headless Checkout falls back to a local detection (similar to when less than 8 digits are entered). In this case, `status` is set to `partial`. > > > [!NOTE] > > > > Let's say `orderedAllowedCardNetworks` is `["CARTES_BANCAIRES", "VISA", "MASTERCARD"]` > > > > If the user enters a card that is co-badged Visa and Cartes Bancaires: > > > > * `alternatives` contains `CARTES_BANCAIRES` and `VISA` > > * `preferred` is `CARTES_BANCAIRES` > > * Selectable networks: `CARTES_BANCAIRES` and `VISA` (both allowed) > > > > If the user enters a card that is only Visa: > > > > * `alternatives` contains only `VISA` > > * `preferred` is `VISA` > > * Selectable networks: only `VISA` (no co-badge selection needed) > > > > If the user enters an Amex card (not allowed for this session): > > > > * `alternatives` contains only `AMEX` > > * `preferred` is `undefined` > > * Selectable networks: empty (card not allowed) > > #### Example > > ```ts Typescript theme={"dark"} > const cardManager = await headless.createPaymentMethodManager("PAYMENT_CARD", { > onBinDataAvailable({ > status, > preferred, > alternatives, > }) { > if (status === "partial") { > // BIN data may be incomplete - could be less than 8 digits or network failure > console.info("Using local card network detection"); > } > > // Get networks that the user can select from > const selectableNetworks = [preferred, ...alternatives].filter(n => n?.allowed); > > if (selectableNetworks.length > 1) { > // Co-badged card detected - ask the user to select a card network > // You can use `preferred` to pre-select the recommended network > return showCardNetworkSelect(selectableNetworks); > } > > // Show the detected card network (or preferred if available) > showAllowedCardNetwork(preferred || alternatives[0]); > }, > }); > > ``` > > ### Step 3. Present the list of card networks and handle the selection > > It is now your responsibility to present the list of card networks to the customer and enable them to choose the network they want to pay with. > > To support you, Headless Checkout exposes the logos and human readable names of each card network via the `AssetsManager`. > > ```ts Typescript theme={"dark"} > // After headless checkout is started > const assetsManager = headless.createAssetsManager(); > > const { cardUrl } = await assetsManager.getCardNetworkAsset('CARTES_BANCAIRES') > ``` > > > [!NOTE] > > > > Learn more about `getCardNetworkAsset` in the [API Reference](/docs/sdk/web/v2.x.x/primer-headless-checkout/methods/getAssetsManager#returns.IAssetsManager-iassetsmanager.getCardNetworkAsset). > > ### Step 4. Create a payment with the selected card network > > When the user clicks on “Pay”, call the `submit` function with the selected card network to let us know which card network the customer chose. > > ```ts Typescript theme={"dark"} > cardManager.submit({ > cardNetwork: "CARTES_BANCAIRES" > }); > ``` > > If `cardNetwork` is not present, Primer follows the order of preference given by the option `orderedAllowedCardNetworks` passed in the client session API. > > ### Step 5. (Optional) Show the list of the supported card networks > > We highly recommend you to present the list of allowed card networks close to the card form. > > You can retrieve `orderedAllowedCardNetworks` on the Web SDK by listening to `onClientSessionUpdate`. After that, you can use > > ```ts Typescript theme={"dark"} > const primer = await Primer.createHeadless(clientToken, { > // Other options and callbacks > onClientSessionUpdate({ paymentMethod: { orderedAllowedCardNetworks } }) { > showCardNetworks(orderedAllowedCardNetworks) > }, > }) > ``` > > > [!NOTE] > > > > Learn more about `onClientSessionUpdate` in the [API Reference](#). > [tab] iOS > > ### Step 2. Detect the card networks > > When you pass a full or partial card number by setting `rawData` on the `RawDataManager` object, Headless Checkout retrieves the list of card networks available for the card. > > Retrieving the cards requires a network call, so `primerRawDataManager(_:willFetchMetadataForState:)` is called to indicate that the network request has started. > > After a response is received, the list of card networks is passed to your integration through a callback called > `primerRawDataManager(_:didReceiveMetadata:forState:)`. > > ```swift SWIFT theme={"dark"} > @objc optional > func primerRawDataManager(_ rawDataManager: PrimerHeadlessUniversalCheckout.RawDataManager, > willFetchMetadataForState state: PrimerValidationState) { > // ... Do nothing, or show a loading spinner ... > } > > @objc optional > func primerRawDataManager(_ rawDataManager: PrimerHeadlessUniversalCheckout.RawDataManager, > didReceiveMetadata metadata: PrimerPaymentMethodMetadata, > forState state: PrimerValidationState) { > > if let cardMetadata = metadata as? PrimerCardNumberEntryMetadata { > // ... Display received card networks to the user ... > if let cardState = state as? PrimerCardNumberEntryState { > // ... If you want to check which card number caused the returned card networks ... > } > } > } > ``` > > This callback returns the following data: > > * `source` \ > Enum value indicating how the card networks were retrieved > * `.local` if the card networks come from the SDK, usually by leveraging the first few digits. > * `.remote` if the card networks come from Primer's server. > * `.localFallback` if Primer's server fails to be reached. This works similarly to `.local`. > * `detectedCardNetworks.items`\ > The list of all the detected card networks, including the ones that are not allowed. > * `detectedCardNetworks.preferred` \ > The first allowed card network in the detected card networks. Can be `nil` if the user entered a card that is not allowed. > * `selectableCardNetworks?.items` \ > The list of all the detected card networks that can be selected by the user. `selectableCardNetworks` is `nil` if Headless Checkout does not detect a co-badged card. > * `selectableCardNetworks?.preferred` \ > The card network selected by default, according to the order set in `orderedAllowedCardNetworks`. `selectableCardNetworks` is `nil` if Headless Checkout does not detect a co-badged card. > > The card networks returned by `primerRawDataManager(_:didReceiveMetadata:forState:)` are `PrimerCardNetwork` objects that contain the network id, its display name, and a flag, `allowed`, that indicates whether the card network is in `orderedAllowedCardNetworks`. > > > [!NOTE] > > > > Learn more about `primerRawDataManager(_:didReceiveMetadata:forState:)` in the [API reference](/docs/sdk/ios/v2.x.x/primer-headless-checkout/). > > #### Less than 8 digits > > If the user enters less than 8 digits, Headless Checkout cannot detect co-badged cards. Instead, Headless Checkout tries to detect major card networks using data available locally. > > In this case: > > * `source` is set to `.local` > * `detectedCardNetworks.preferred` contains the card network you should present to the user > * `detectedCardNetworks.items` contains all the detected card networks > * `selectableCardNetworks` is always `nil` > > #### 8 digits or more > > If the user enters 8 digits or more, Headless Checkout attempts to make a request to Primer to retrieve the list of card networks available on the card using our BIN data. > > In this case: > > * `source` is set to `.remote` > * `selectableCardNetworks` is only available if the user has entered a co-badged card and both its detected networks are allowed for this session > * `selectableCardNetworks.items` contains the list of card networks from which the user can select > > If Headless Checkout fails to contact Primer, Headless Checkout falls back to a local detection (similar to when less than 8 digits are entered). In this case, `source` is set to `.localFallback` . > > > [!NOTE] > > > > Let’s say `orderedAllowedCardNetworks` is `["CARTES_BANCAIRES", "VISA", "MASTERCARD"]` > > > > If the user enters a card that is co-badged Visa and Cartes Bancaires: > > > > * `detectedCardNetworks.items` is `CARTES_BANCAIRES` and `VISA` > > * `detectedCardNetworks.preferred` is `CARTES_BANCAIRES` > > * `selectableCardNetworks?.items` is `CARTES_BANCAIRES` and `VISA` > > * `selectableCardNetworks?.preferred` is `CARTES_BANCAIRES` > > > > If the user enters a card that is only Visa: > > > > * `detectedCardNetworks.items` is only `VISA` > > * `detectedCardNetworks.preferred` is `VISA` > > * `selectableCardNetworks` is `nil` > > > > If the user enters an Amex card (not allowed for this session): > > > > * `detectedCardNetworks.items` is only `AMEX` > > * `detectedCardNetworks.preferred` is `nil` > > * `selectableCardNetworks` is `nil` > > #### Example > > ```swift SWIFT theme={"dark"} > > extension MyViewController: PrimerHeadlessUniversalCheckoutRawDataManagerDelegate { > > func primerRawDataManager(_ rawDataManager: PrimerHeadlessUniversalCheckout.RawDataManager, > willFetchMetadataForState cardState: PrimerValidationState) { > guard let state = cardState as? PrimerCardNumberEntryState else { > logger.error("Received non-card metadata. Ignoring ...") > return > } > /* ... display spinner ... */ > } > > func primerRawDataManager(_ rawDataManager: PrimerHeadlessUniversalCheckout.RawDataManager, > didReceiveMetadata metadata: PrimerPaymentMethodMetadata, > forState cardState: PrimerValidationState) { > > guard let metadata = metadata as? PrimerCardNumberEntryMetadata, > let cardState = cardState as? PrimerCardNumberEntryState else { > logger.error("Received non-card metadata. Ignoring ...") > return > } > > var networksForDisplay: [PrimerCardNetwork] = [] > var isAllowedNetwork: Bool = true > > if metadata.source == .remote, let selectableNetworks = metadata.selectableCardNetworks?.items, !selectableNetworks.isEmpty { > networksForDisplay = selectableNetworks > } else if let preferredDetectedNetwork = metadata.detectedCardNetworks.preferred { > networksForDisplay = [preferredDetectedNetwork] > } else if let cardNetwork = metadata.detectedCardNetworks.items.first { > networksForDisplay = [cardNetwork] > isAllowedNetwork = false > } > > /* ... networksForDisplay contains the models to display to the user 🎉 ... */ > } > } > > ``` > > ### Step 3. Present the list of card networks and handle the selection > > It is now your responsibility to present the list of card networks to the customer and enable them to choose the network they want to pay with. > > To support you, Headless Checkout exposes the logos and human readable names of each card network via the `AssetsManager`. > > ```swift SWIFT theme={"dark"} > let cardAssets: [PrimerCardNetworkAsset] = networksForDisplay.compactMap { network in > return PrimerHeadlessUniversalCheckout.AssetsManager.getCardNetworkAsset(for: network) > } > > cardAssets.forEach { asset in > // ... display the card, e.g. ... */ > showCard(title: asset.displayName, image: asset.cardImage) > } > ``` > > When the user selects a card network, set `rawData`, passing the relevant card network to let us know which the customer chose. > > ```swift SWIFT theme={"dark"} > let selectedCardNetwork: CardNetwork = primerCardNetwork.value // Enum value for the network > > rawDataManager?.rawData = PrimerCardData( > cardNumber: cardNumber, > expiryDate: expiryDate, > cvv: cvvNumber, > cardholderName: cardholderName, > cardNetwork: selectedCardNetwork // pass the enum value here > ) > ``` > > > [!NOTE] > > > > Learn more about `getCardNetworkAsset(for:)` in the [API Reference](/docs/sdk/ios/v2.x.x/primer-headless-checkout). > > ### Step 4. Create a payment with the selected card network > > When the user clicks on “Pay”, call the `submit` function to start the payment. > > ```swift SWIFT theme={"dark"} > rawDataManager.submit() > ``` > > If the card network was not provided via `rawData`, Primer follows the order of preference given by the option `orderedAllowedCardNetworks` passed in the client session API. > [tab] Android > > ### Step 2. Detect the card networks > > When you pass the card number using [setRawData](/docs/snippets/sdk/android/primerHeadlessUniversalCheckout/rawDataManager/), > Headless Checkout retrieves the list of card networks available on the card. > The list of card networks is passed to the developers through a callback called `onMetadataStateChanged`. > > ```kotlin Kotlin theme={"dark"} > val rawDataManagerListener = > object : PrimerHeadlessUniversalCheckoutRawDataManagerListener { > > override fun onMetadataStateChanged(metadataState: PrimerPaymentMethodMetadataState) { > when (metadataState) { > is PrimerCardMetadataState -> > when (metadataState) { > is PrimerCardMetadataState.Fetched -> // handle metadata fetched state > is PrimerCardMetadataState.Fetching -> // handle metadata fetching state > } > } > } > } > ``` > > This callback yields the `PrimerCardMetadataState` and encompasses two distinct states: > > * `PrimerCardMetadataState.Fetching` Indicates that the card metadata is currently being retrieved from the Primer server. > * `PrimerCardMetadataState.Fetching` Signifies the state when the card metadata has been fetched, encompassing the following `cardNumberEntryMetadata`: > * `source` \ > Enum value indicating how the card networks were retrieved: > * `LOCAL` if the card networks come from the SDK, usually by leveraging the first few digits. > * `REMOTE` if the card networks come from Primer's server. > * `LOCAL_FALLBACK` if Primer's server fails to be reached. This works similarly to `LOCAL`. > * `detectedCardNetworks.items`\ > The list of all the detected card networks, including the ones that are not allowed. > * `detectedCardNetworks?.preferred` \ > The first allowed card network in the detected card networks. Can be `null` if the user entered a card that is not allowed. > * `selectableCardNetworks?.items` \ > The list of all the detected card networks that can be selected by the user. `selectableCardNetworks` is `null` if Headless Checkout does not detect a co-badged card. > * `selectableCardNetworks?.preferred` \ > The card network selected by default, according to the order set in `orderedAllowedCardNetworks`. `selectableCardNetworks` is `null` if Headless Checkout does not detect a co-badged card. > > The card networks returned by `onMetadataStateChanged` are objects that contain the network type, its display name, and a flag `allowed` stating if the card network is in `orderedAllowedCardNetworks`. > > > [!NOTE] > > > > Learn more about `onMetadataStateChanged` in the [API Reference](/docs/sdk/android/v2.x.x/primer-headless-checkout/raw-data-manager/). > > #### Less than 8 digits > > If the user enters less than 8 digits, Headless Checkout cannot detect co-badged cards. > Instead, Headless Checkout tries to detect major card networks using data available locally. > > In this case: > > * `source` is set to `LOCAL` > * `detectedCardNetworks.preferred` contains the card network you should present to the user > * `detectedCardNetworks.items` contains all the detected card networks > * `selectableCardNetworks` is always `null` > > #### 8 digits or more > > If the user enters 8 digits or more, Headless Checkout attempts to make a request to Primer to retrieve the list of card networks available on the card using our BIN data. > > In this case: > > * `source` is set to `REMOTE` > * `selectableCardNetworks` is only available if the user has entered a co-badged card and both its detected networks are allowed for this session > * `selectableCardNetworks.items` contains the list of card networks from which the user can select > > If Headless Checkout fails to contact Primer, Headless Checkout falls back to a local detection (similar to when less than 8 digits are entered). In this case, `source` is set to `LOCAL_FALLBACK` . > > > [!NOTE] > > > > Let’s say `orderedAllowedCardNetworks` is `["CARTES_BANCAIRES", "VISA", "MASTERCARD"]` > > > > If the user enters a card that is co-badged Visa and Cartes Bancaires: > > > > * `detectedCardNetworks.items` contains networks with identifiers `CARTES_BANCAIRES` and `VISA` > > * `detectedCardNetworks.preferred` is a network with identifier `CARTES_BANCAIRES` > > * `selectableCardNetworks.items` contains networks with identifiers `CARTES_BANCAIRES` and `VISA` > > * `selectableCardNetworks.preferred` is a network with identifier `CARTES_BANCAIRES` > > > > If the user enters a card that is only Visa: > > > > * `detectedCardNetworks.items` is only a network with identifier `VISA` > > * `detectedCardNetworks.preferred` is only a network with identifier `VISA` > > * `selectableCardNetworks` is `null` > > > > If the user enters an Amex card (not allowed for this session): > > > > * `detectedCardNetworks.items` is only a network with identifier `AMEX` > > * `detectedCardNetworks.preferred` is `null` > > * `selectableCardNetworks` is `null` > > #### Example > > ```kotlin Kotlin theme={"dark"} > val rawDataManagerListener = > object : PrimerHeadlessUniversalCheckoutRawDataManagerListener { > > override fun onValidationChanged(isValid: Boolean, errors: List) { > // use the `isValid` to enable/disable pay button > // use the `errors` list and handle validation errors respectively > } > > override fun onMetadataStateChanged(metadataState: PrimerPaymentMethodMetadataState) { > when (metadataState) { > is PrimerCardMetadataState -> > when (metadataState) { > is PrimerCardMetadataState.Fetched -> { > val cardNumberMetadata = metadataState.cardNumberEntryMetadata > if (cardNumberMetadata.source === ValidationSource.LOCAL_FALLBACK) { > // feel free to send an event to your backend > Log.w(MY_TAG, "Cannot detect card networks.") > } > > cardNumberMetadata.selectableCardNetworks?.let { networksMetadata -> > // if `selectableCardNetworks` is non-null, > // then ask the user to select a card network > // you can use `selectableCardNetworks.preferred` to pre-select the > // card network > val cardNetworks: List = networksMetadata.items > showCardNetworkSelect(cardNetworks) > } ?: run { > cardNumberMetadata.detectedCardNetworks.let { networksMetadata -> > // show the detected card network > val cardNetwork: PrimerCardNetwork? = > networksMetadata.preferred ?: networksMetadata.items.firstOrNull() > showAllowedCardNetwork(cardNetwork) > } > } > } > is PrimerCardMetadataState.Fetching -> showLoadingView() > } > } > } > } > > val cardManager = PrimerHeadlessUniversalCheckoutRawDataManager.newInstance("PAYMENT_CARD") > > cardManager.setListener(rawDataManagerListener) > ``` > > ### Step 3. Present the list of card networks and handle the selection > > It is now your responsibility to present the list of card networks to the customer and enable them to choose the network they want to pay with. > > To support you, Headless Checkout exposes the logos and human readable names of each card network via the `PrimerHeadlessUniversalCheckoutAssetsManager`. > > ```kotlin Kotlin theme={"dark"} > // After headless checkout is started > val cardNetworkAsset = PrimerHeadlessUniversalCheckoutAssetsManager.getCardNetworkAsset( > requireContext(), > CardNetwork.Type.CARTES_BANCAIRES > ) > ``` > > When the user selects a card network, call [setRawData](/docs/snippets/sdk/android/primerHeadlessUniversalCheckout/rawDataManager/) > with the relevant card network to let us know which card network the customer chose. > > ```kotlin Kotlin theme={"dark"} > cardManager.setRawData( > PrimerCardData( > cardNumber = cardNumber, > expiryDate = expiryDate, > cvv = cvvNumber, > cardHolderName = cardholderName, > cardNetwork = CardNetwork.Type.CARTES_BANCAIRES > ) > ) > ``` > > > [!NOTE] > > > > Learn more about `getCardNetworkAsset` in the [API Reference](/docs/sdk/android/v2.x.x/primer-headless-checkout/assets-managers/getCardNetworkAsset). > > ### Step 4. Create a payment with the selected card network > > When the user clicks on “Pay”, call the [submit](/docs/sdk/android/v2.x.x/primer-headless-checkout/raw-data-manager/) function to start the payment. > > ```kotlin Kotlin theme={"dark"} > cardManager.submit() > ``` > > If the card network was not provided with [setRawData](/docs/sdk/web/v2.x.x/primer-headless-checkout/methods/createPaymentMethodManager), > Primer follows the order of preference given by the option `orderedAllowedCardNetworks` passed in the client session API. > [tab] React Native > > > [!NOTE] > > > > This feature is currently not available on React Native. ## Notes ### Slow and unreliable internet connection When the customer's network connection is slow or unreliable, it is possible that the customer finishes entering their card details before Universal Checkout retrieves the card networks. In order to keep the friction low, it is important to note that Universal Checkout does not block the creation of a payment while the card networks are being retrieved or if the card networks could not be retrieved at all. This means that, if a co-badged card is entered, the customer is not guaranteed to be presented a card choice before they submit their card details. ### Selected card network on the payment method data In the case of a card payment, you can get the selected network by looking at `paymentMethodData.network`. > [!WARNING] > > We recommend against using `paymentMethodData.binData.network` as it only contains the international card network. # Co-badged cards: Overview Source: https://primer.io/docs/payment-services/cobadged-cards/Overview Understand co-badged cards, regional rules (EEA, Australia and United States), and how to implement compliance with Primer. ## What are co-badged cards? A co-badged card is a debit or credit card that can be processed on more than one card network. If you want a quick refresher on what card networks are and how they work, refer to our blog article:\ [What are card networks and how do they work?](https://primer.io/blog/what-are-card-networks-and-how-do-they-work) In most cases, it combines: * a global network like **Visa** or **Mastercard** * a local network like **Cartes Bancaires** (France), **Dankort** (Denmark), or **eftpos** (Australia) From the shopper’s point of view, it’s just “one card”. Behind the scenes, however, the same card can follow different payment rails, with different fees, rules, and regulations. > [!NOTE] > > Some regions have specific requirements that must be implemented to be compliant with local regulations. > > It is your responsibility to meet these compliancy criteria. ## Co-badged vs co-branded cards These two concepts are often mixed up, but they are very different. * **Co-badged card**\ A card that supports multiple **payment networks** (for example Cartes Bancaires + Visa).\ This affects checkout behavior and is regulated in some regions. > [!NOTE] > > In some regions, co-badged cards are also referred to as **dual-network cards**. This terminology is commonly used in Australia. * **Co-branded card**\ A card that combines one payment network with a **commercial brand** (for example an airline or retailer).\ This is about loyalty and issuing, and has no impact on checkout or compliance. This documentation only covers **co-badged cards**. *** ## Where do co-badged cards exist? Co-badged cards mainly exist in countries with strong local card networks. ### Europe * **Cartes Bancaires** (France) co-badged with Visa or Mastercard * **Dankort** (Denmark) co-badged with Visa or Mastercard * **Bancontact** (Belgium), sometimes co-badged with Visa ### Australia * **eftpos** co-badged with Visa or Mastercard ### United States * US debit cards carry a global network (**Visa** or **Mastercard**) plus one or more domestic debit networks, such as **Maestro USA**, **NYCE**, **Pulse**, **STAR** or **Accel** * At checkout, the shopper usually only sees the Visa or Mastercard brand ### Other regions * **mada** (Saudi Arabia) * **elo** (Brasil) > [!NOTE] > > Not all local networks are available for online payments, and not all of them are supported by every processor. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/co-badged-cards/identify.png) Accept local card schemes through co-badged cards *** ## How co-badged cards work in practice When a shopper enters their card details: 1. The card number is analysed to detect which networks are available. 2. Depending on the country and local regulation: * the shopper may be asked to choose a network, or * the merchant or payment platform selects one automatically. 3. The payment is authorised and processed using the selected network. For saved cards and recurring payments, the network used for the **first payment** usually becomes the network used for future charges. *** ## Regulation ### Europe – giving the shopper a choice In the European Economic Area, co-badged cards are covered by Regulation (EU) 2015/751. Key things to remember: * You are **not required** to support local card networks. * You must clearly communicate which card networks you support, for example by displaying the logos of all supported schemes at checkout. * If you *do* support multiple networks available on the same card, you must let the shopper choose. * You can preselect a default network, but you must respect the shopper’s choice. * For saved cards and recurring payments, the original choice must be reused. **Example**\ If you support both Cartes Bancaires and Visa, and a French shopper uses a co-badged card, your checkout must clearly let them choose between CB and Visa. **Frontend impact** * The choice must be visible and easy to understand * Network logos and labels must not be misleading To go deeper on the regulatory side, you can also read our blog post:\ [Are you meeting the EU’s co-badged card requirements?](https://webflow.primer.io/blog/are-you-meeting-the-eu-s-co-badged-card-requirements) > [!NOTE] > > **New**: our new Primer Checkout natively supports the display of a co-badged card selector. > > Don't hesitate to have a look and play with our showcase: > [Primer Checkout Showcase](/docs/checkout/overview) ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/co-badged-cards/regulations-example.png) Primer Checkout automatically displays the available networks for co-badged cards, in line with European regulations. *** ## Australia – merchant routing behind the scenes Australia follows a different model for **dual-network debit cards** such as eftpos. ### Key differences * You are **not required** to present a card network choice to the shopper. * If the shopper is **not explicitly given a choice**, you can control routing and apply your own default rules (for example least-cost routing). * If the shopper **is explicitly given a choice and makes a selection**, this choice **must not be overridden**. * You must not mislead the shopper about which card networks may be used. ### Example A shopper sees a Visa debit card in the UI.\ Because no explicit network choice is presented, you apply your default routing rules and process the payment via eftpos in the background. This approach is commonly used in Australia to avoid exposing eftpos branding, which may be unfamiliar or confusing for shoppers, while still optimising routing and costs. ### Regulatory references For more details, refer to the Reserve Bank of Australia guidance on dual-network debit cards and least-cost routing: [Dual-network debit cards and mobile wallet technology](https://www.rba.gov.au/publications/consultations/201612-dual-network-cards-and-mobile-wallet-technology/dual-network-debit-cards.html) *** ## United States – debit routing by the processor In the United States, card issuers must enable every debit card on at least two unaffiliated networks, and neither issuers nor networks may stop the merchant from choosing which one processes the payment. ### Key differences * The shopper is **not** asked to choose a network. There is no network selector at checkout. * The routing decision is usually made by your **processor**, typically to find the cheapest network (least-cost routing). * Domestic debit networks usually process payments as a **sale**: authorization and capture happen in a single message, and the full amount is taken at authorization. As a result, **partial captures, multiple captures and incremental authorizations are not available** on these networks by default. ### Example A shopper pays with a Visa debit card that is also enabled on a domestic debit network. Your processor routes it to the domestic network because it's cheaper. The payment is captured in full straight away, so a later capture for a smaller amount is rejected. See [US debit networks](/docs/payment-services/cobadged-cards/Enable-local-card-schemes-with-Primer#us-debit-networks-united-states) for how debit routing works with Primer and what to check before enabling it. ### Regulatory references For more details, refer to the Federal Reserve's guidance on Regulation II: [Regulation II (Debit Card Interchange Fees and Routing)](https://www.federalreserve.gov/paymentsystems/regii-about.htm) *** ## Why support co-badged cards? Co-badged cards let you accept local card networks **without adding complexity to your checkout**. In markets where local schemes matter, this can make a real difference, both on cost and performance. By supporting co-badged cards, you can: * **Reduce processing costs** by routing transactions through local networks when available * **Improve authorisation rates** with rails optimised for local issuers * **Increase acceptance** by supporting the payment methods shoppers trust most in their country * **Stay compliant by design** with regional card regulations, without custom work The result is simple: one checkout, multiple networks, and better outcomes, for you and your customers. # Fallbacks Source: https://primer.io/docs/payment-services/fallbacks ## What are fallbacks? A fallback is a payment recovery service that is used when the primary processor fails and the payment is routed to a backup processor. There are scenarios where a payment may fail or decline with one processor but be authorized with another, such as when the first processor has technical issues. By setting up fallbacks to route the payment to a second processor under certain conditions, you increase the chance of a successful payment. ## How to set up fallbacks Setting up fallbacks is very simple with Primer: 1. Create a workflow with the Payment created Trigger. Learn more about this Trigger [here](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger). 2. Add the ["Authorize payment" action](/docs/workflows/apps/native-apps/primer-payments-app/authorize-payment-action) to your workflow. In the configuration panel, you will see the option to select a fallback processor. 3. Select your fallback processor from one of your existing connected processors and assign a merchant account. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/fallbacks/configure-fallbacks.png) Configuring fallbacks Once set up, when this workflow is triggered and it processes a payment, the fallback service will be utilized during authorization. ## Fallbacks with 3DS Fallbacks can be configured with the following 3DS settings within the "Authorize payment" action of the Payments App: * Primer 3DS * Adaptive 3DS During checkout, your customer will complete the 3DS authentication and this data will be included in the first authorization request. When the second authorization request is sent to the fallback processor, the 3DS data is included so the customer won't have to complete the 3DS flow twice. > [!WARNING] > > Fallbacks are **not** compatible with Processor 3DS. This is because the processor handles the 3D Secure authentication flow and Primer is not involved in the flow. ## When are fallbacks triggered? Primer standardizes decline codes and reasons from processors so you only need to rationalize about payments once. Payments have the following fields which have been standardized across all processors: * `status` * `error decision type` * `error decline type` * `error decline reason` Fallbacks will be triggered when the payment has one of the following sets of field values: | **Status** | **Error Decision Type** | **Error Decline Type** | **Error Decline Reason** | | :- | :- | :- | :- | | Declined | Gateway Rejected | N/A | N/A | | Declined | Issuer Declined | Soft Decline | Declined | | Declined | Issuer Declined | Soft Decline | Refer to Card Issuer | | Declined | Issuer Declined | Soft Decline | Issuer Temporarily Unavailable | | Declined | Issuer Declined | Soft Decline | Do Not Honor | | Failed | Application Error | N/A | N/A | > [!NOTE] > > Fallbacks and [Adaptive 3DS](/docs/payment-services/3d-secure/overview#adaptive-3ds) have overlapping triggers. If both features are activated for a payment, Adaptive 3DS always has priority. If the second authorization attempt still fails, a fallback may be triggered. ## See your fallback payments There are two ways to see your fallback payments: > [!NOTE] > > **Payments timeline** > > Easy-to-use UI to browse and review the details of your fallback payments. > [!NOTE] > > **Payments API** > > Retrieve details of your payments programmatically via API. ### Payments timeline You can see all your Primer payments from the [Payments timeline](https://dashboard.primer.io/payments) in the Primer Dashboard. Navigate to the specific payment detailed timeline page. You will see the fallback details, where the first processor was unsuccessful and the fallback was triggered sending a second authorization request to your fallback processor. Primer is not a black box, but rather your payments infrastructure. By selecting a specific event, you can see the requests and responses, providing full transparency into everything that's happened to your payment throughout its journey. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/fallbacks/request-response-example.png) Payment timeline event summary > [!NOTE] > > Merchants will soon be able to filter for all fallback payments in the Payments list view. ### See your fallback payments via the Payments API For a programmatic solution, either: * retrieve a single payment using the Primer payment ID - see the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) for more. * search and retrieve a list of payments - see the [API reference](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) and [specific guide](/docs/manage-payments/search-payments) for more. ## Testing fallbacks > [!NOTE] > > [Read the detailed guide on how to test fallbacks on Primer.](/docs/testing/fallbacks) # Fingerprinting Source: https://primer.io/docs/payment-services/fingerprinting ## What is fingerprinting? Fingerprinting is the process of generating an identifier for a specific payment method, without revealing any sensitive information. Contrary to payment method tokens, fingerprints cannot be used to make payments, which makes them a secure representation of payment method details. Fingerprints are extremely valuable to: * Check whether a particular card is used by multiple customers, which can be an indicator of fraud * Track if a user is using the same card for multiple customer-present payments, which is a signal that a vault could greatly improve the user experience * Save the preferred card of a customer A payment method token is not a valid fingerprint since tokenizing or vaulting the same card multiple times yields different payment method tokens. ## Fingerprinting with Analytics ID Primer API exposes [`analyticsId`](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment#response.body.paymentMethod.analyticsId) to act as a fingerprint for all payment methods. You can find this value * in the Payment object, in the [API](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment#response.body.paymentMethod.analyticsId) and in the Workflow * attached to a [saved payment method token](/docs/api-reference/v2.4/api-reference/payment-methods-api/list-saved-payment-methods#response.body.data.analyticsId) `analyticsId` is unique per Primer account. Tokenizing the same card on multiple Primer accounts will generate different `analyticsId` > [!NOTE] > > When Universal Checkout tokenizes the same payment method multiple times, a new single-used payment method token is generated each time, even if the payment method is part of your unified vault. On the other hands, the `analyticsId` attached to the payment method token remains the same. > > As a result, we recommend storing the `analyticsId` when you want to save the preferred vaulted payment method. ## How is Analytics ID created? Although `analyticsId` is available for every payment method, its value heavily relies on how it is generated. Check the following table to better understand how we create an `analyticsId` for each payment method: | Payment Instrument Type | Analytics ID is created from... | | - | - | | Card |

  • Primer Account ID
  • Card number
  • Expiry date
| | Google Pay |
  • Primer Account ID
  • Card DPAN
  • Expiry date
| | Apple Pay *Agnostic processor* |
  • Primer Account ID
  • Card DPAN
  • Expiry date
| | Apple Pay *Tied to a processor* |
  • Primer Account ID
  • Apple Pay encrypted token (unique per payment attempt)
| | PayPal *Order (Single payment)* |
  • Primer Account ID
  • PayPal Order ID (unique per payment attempt)
| | PayPal *Billing Agreement (Recurring payments)* |
  • Primer Account ID
  • PayPal Billing Agreement ID (unique per agreement)
| | Klarna *Single payment* |
  • Primer Account ID
  • Klarna authorization token (unique per payment attempt)
| | Klarna *Recurring payments* |
  • Primer Account ID
  • Klarna authorization token (unique per agreement)
| | *Other* | *Random ID* | ## Example: Blocking payments coming from a specific card Let’s imagine you have identified a very specific card that you want to block from making any additional payments. First, retrieve the `analyticsId` you want to block from the payment object. Then, head to your card-processing workflow and add a route with a condition that checks if the Analytics ID of the payment matches the `analyticsId` you want to block. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/fingerprinting/condition-analyticsid.png) Conditions with analyticsId Finally, add a "Decline payment" action to this specific route so that payments with this `analyticsId` are automatically blocked. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/fingerprinting/fingerprinting-workflow.png) Workflow > [!NOTE] > > If you want to block an entire BIN, you can instead create a condition that checks the first 6 digits of the card. > > ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/fingerprinting/condition-bin.png) > > Conditions with BIN # Fraud Checks: Get Started Source: https://primer.io/docs/payment-services/fraud-checks/get-started ## Configuration steps ### Step 1: Connect your fraud detection provider > [!NOTE] > > You need at least one fraud detection provider connected to begin processing fraud checks through Primer. This process is very similar to [connecting a processor](/docs/get-started/connect-a-processor). Set up the connection by following the steps below to enable Primer to communicate with the fraud detection provider on your behalf: 1. Select the fraud prevention provider you want to add via the [Primer Dashboard](https://dashboard.primer.io/integrations?status=active) 2. Add your provider by populating and submitting the form ![Connecting a fraud detection provider example](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/embedded-fraud-checks/get-started/connect-provider-example.png) ### Step 2: Add fraud checks to your payment workflow > [!NOTE] > > This guide assumes you already have a payment workflow configured. To learn more about how to set up a payment flow, read more **[here](/docs/get-started/create-workflow)**. Add pre-authorization and/or post-authorization fraud checks to any of your “Authorize payment” Actions in your workflows. In the Action side drawer, the Fraud Checks input section contains all the configurations required to set up your fraud checks. ![Select Fraud Provider Example](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/embedded-fraud-checks/get-started/select-fraud-provider.png) Select the fraud detection provider you will use for your fraud checks (pre-authorization and/or post-authorization) from the dropdown menu. This will be populated with all fraud detection providers connected in Step 1. #### Pre-authorization fraud check Toggle on “Apply pre-auth check” by selecting the checkbox. This means that every payment that is processed by this Action will attempt a pre-authorization fraud check. ![Activate Pre-Authorization Fraud Check](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/embedded-fraud-checks/get-started/activate-pre-auth-check.png) To enable your pre-authorization fraud check to dictate when to show 3DS, set the "3D Secure preference" to `Pre-auth fraud check settings`. ![3D Secure Preference Example](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/embedded-fraud-checks/get-started/3ds-preference.png) > [!WARNING] > > If this is not set, regardless of the outcome of the pre-authorization fraud check, the "3D Secure preference" will take priority. You need to determine the business logic for your pre-authorization fraud check and configure it appropriately. For each possible pre-authorization fraud check outcome, decide whether to show 3DS, run a 3DS exemption, go straight to authorization, or reject the payment. This is configured by selecting one of the options from the dropdown for each outcome. ![Example of where to configure how to handle pre-auth check outcomes](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/embedded-fraud-checks/get-started/select-pre-auth-outcomes.png) > [!NOTE] > > If you decide to reject a payment after a fraud recommendation, the payment will either be: > > * automatically declined after a pre-authorization fraud check > * or automatically cancel after a post-authorization fraud check > > In any case, this status will be visible in the payment status and payment timeline. See more below on this in the [How to monitor fraud checks](#how-to-monitor-fraud-checks) section. If it’s a customer-initiated payment, the customer will see the fail screen. #### Post-authorization fraud check Toggle on “Apply post-auth check” by selecting the checkbox. This means that every payment that is processed by this Action will attempt a post-authorization fraud check. Similarly to the pre-authorization fraud check, you need to decide how to handle scenarios where there’s a technical problem preventing the fraud check and the request fails: either the payment remains authorized or cancel the payment. ![Activate Post-Authorization Fraud Check](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/embedded-fraud-checks/get-started/activate-post-auth-check.png) > [!NOTE] > > If the fraud check does not pass, the payment will be canceled automatically. If it’s a customer-initiated payment, the customer will see the fail screen. ### Step 3: Pass additional data in the client session > [!NOTE] > > The same applies if you use the [advanced manual SDK flow](/docs/checkout/advanced/manual-payment-creation) and send the POST request. The `customer` and `order` objects that can be passed in POST and POST are used to populate the request to your fraud detection provider. It’s recommended you agree with your provider on what fields should be passed to ensure optimum accuracy of the fraud check as this does vary based on which fraud detection provider you use. The following additional data points will also be used in the fraud request if they are passed: | Field | Type | | - | - | | `fraud_context.device_details.device_id` | string | | `fraud_context.device_details.referring_site` | string | | `fraud_context.device_details.source` | string | | `fraud_context.device_details.browser_ip` | string | | `fraud_context.device_details.accept_language` | string | | `fraud_context.device_details.user_agent` | string | | `fraud_context.device_details.cookie_token` | string | | `fraud_context.merchant_details.merchant_name` | string | | `fraud_context.merchant_details.merchant_provider_id` | string | | `fraud_context.merchant_details.merchant_category_code` | string | To pass these, add the `fraud_context` object to the `metadata` object passed in the request. Below is an example: ```json theme={"dark"} // POST /client-session { "customerId": "customer-123", "amount": 2000, "currencyCode": "GBP", "orderId": "order-123", "order": { "lineItems": [ { "itemId": "item 1", "name": "item 1", "description": "description of item 1", "amount": 1900, "quantity": 1 } ], "countryCode": "GB", "shipping": { "amount": 100 } }, "customer": { "emailAddress": "user@email.com", "mobileNumber": "07777777777", "firstName": "firstname", "lastName": "lastname", "billingAddress": { "firstName": "firstname", "lastName": "lastname", "addressLine1": "address line 1", "addressLine2": "address line 2", "city": "city", "state": "state", "countryCode": "GB", "postalCode": "W1 2AW" }, "shippingAddress": { "firstName": "firstname", "lastName": "lastname", "addressLine1": "address line 1", "addressLine2": "address line 2", "city": "city", "state": "state", "countryCode": "GB", "postalCode": "W1 2AW" } }, "paymentMethod": { "vaultOnSuccess": true }, "metadata": { "fraud_context": { "device_details": { "device_id": "id-123", "referring_site": "https://google.com", "source": "web", "browser_ip": "127.0.0.1", "accept_language": "EN", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36", "cookie_token": "9dc6f83f78b0490" }, "merchant_details": { "merchant_name": "merchant-name", "merchant_provider_id": "id-123", "merchant_category_code": "4414" } } } } ``` ## How to monitor fraud checks You can monitor your fraud checks using the: * payment timeline * payment object ### Payment timeline Primer is not a black box - your fraud check events will be visible in the payment timeline. ![Payment timeline example](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/embedded-fraud-checks/get-started/payment-timeline-example.png) Select a specific event to see the full requests and responses with your fraud detection provider. ![Side drawer example](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/embedded-fraud-checks/get-started/side-drawer-example.png) ### Payment object For POST & GET (>=v2.2), the response includes the following object: ```json theme={"dark"} "riskData": { "fraudCheck": { "source": "FRAUD_PROVIDER", // name of provider "preAuthorizationResult": "THREE_DS", // standardised result status "postAuthorizationResult": "ACCEPT" // standardised result status } } ``` preAuthorizationRecommendation clarifies which SCA exemption to apply when `preAuthorizationResult` is `THREE_DS_EXEMPTION`. See the API enum for possible values: * [PreAuthorizationRecommendationEnum](/docs/api-reference/v2.4/api-reference/payments-api/authorize-a-payment#response-risk-data-fraud-checks-pre-authorization-recommendation) Note: `preAuthorizationRecommendation` is only returned when `preAuthorizationResult` is `THREE_DS_EXEMPTION`. This is also part of the [Payment Status Update webhook](/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-status-update) notification as well. ## Testing > [!NOTE] > > [Read the detailed guide on how to test pre-authorization and post-authorization fraud checks on Primer.](/docs/testing/fraud-checks) ## Notes * The `riskData.fraudCheck.postAuthorizationResult` field won't be included in the [Payment Status Update webhook](/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-status-update) as the payment status updates before the post authorization fraud check is run. * If this field is required when you receive this webhook, use the GET request. The field will only be present once the post-authorization fraud check is complete. * If the payment is CANCELLED due to the post-authorization fraud check, a new webhook notification will be sent and this field will be included. # Fraud Checks: Overview Source: https://primer.io/docs/payment-services/fraud-checks/overview Fraud checks are crucial in preventing fraudulent transactions and reducing financial losses for merchants when accepting payments online. According to [Statista](https://www.statista.com/statistics/1273177/ecommerce-payment-fraud-losses-globally/#:~:text=According%20to%20estimates%2C%20e%2Dcommerce,billion%20U.S.%20dollars%20by%202023.), fraud losses for online merchants globally is expected to grow to \$48 billion by 2023. Visa and Mastercard both recommend a layered approach to fraud prevention, including pre-authorization and post-authorization fraud checks, to help protect against fraud. ### Pre-authorization Pre-authorization fraud checks involve verifying the validity of the payment method, checking the customer's identity, and assessing the risk associated with the transaction before it is authorized. This helps prevent fraudulent transactions from being approved in the first place and, in cases where 3DS is mandatory or recommended, this creates a flow without 3DS for low-risk customers, ensuring they can complete their order with minimal friction. ### Post-authorization Post-authorization fraud checks involve monitoring transactions after they have been authorized to identify any suspicious activity. This can include analyzing transaction data for patterns indicating fraud or conducting manual reviews of transactions flagged as potentially fraudulent. ## Fraud checks within Primer Primer has integrations with 3rd party fraud detection providers, enabling you to easily configure pre-authorization and/or post-authorization fraud checks as part of your payment flow with your preferred fraud detection provider. Fraud checks are embedded into the authorization flow and you have flexibility over the business logic. Similarly to processing payments, Primer has simplified the setup of fraud checks through its unified framework. > [!NOTE] > > Not all fraud detection providers support all payment methods. You can check payment method compatibility with your chosen fraud detection provider in the [Fraud Detection Providers](/docs/connections/fraud-providers/overview/) section of the docs. ### Pre-authorization fraud checks Pre-authorization fraud checks can have the following outcomes: | **Status** | **Description** | | - | - | | `Pass` | provider recommends you continue to authorization | | `3DS` | provider recommends [running a 3DS authentication](/docs/payment-services/3d-secure/overview) to comply with local regulations or reduce fraud | | `3DS Exemption` | provider recommends [requesting a 3DS exemption](/docs/payment-services/3d-secure/exemptions) to reduce friction in the regions that enforce SCA | | `Reject` | suspected fraud detected and the provider recommends declining the payment | | `Fail` | technical issue preventing the pre-authorization fraud check from being processed correctly | You can determine how to handle all outcomes within the "Authorize Payment" action in Workflows. ### Post-authorization fraud checks Post-authorization fraud checks have the following outcomes: | **Status** | **Description** | | - | - | | `Pass` | provider recommends the authorization is legitimate | | `Reject` | fraud risk detected and provider recommends canceling the payment | | `Fail` | technical issue preventing the post-authorization fraud check from being processed correctly | Primer simplifies the configuration for post-authorization fraud checks by always canceling the payment for the `Reject` outcome. > [!NOTE] > > See our [Get Started guide](/docs/connections/fraud-providers/overview) for how to configure your pre-authorization and/or post-authorization fraud checks on Primer. # Network Tokenization Source: https://primer.io/docs/payment-services/network-tokenization ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/network-tokenization/network-tokenization-concept.png) Network Tokenization Overview ## What is Network Tokenization? Network tokenization is a service provided by card networks, such as Visa and Mastercard, where they directly provide a token as a substitute for the 14 to 19 digit primary account number (PAN). A network token can be used instead of the PAN when processing payments and is more secure because: * It minimizes the risk of exposing customers' sensitive information because a token is exchanged instead of the raw card details. * The token is unique to the customer and merchant pairing, and can't be used by a bad actor for any merchant online like they could with the PAN. * For customer-initiated payments, a one-time cryptogram called the Token Authentication Verification Value (TAVV) needs to be generated which acts as the equivalent of the CVV. This can only be generated by the token requestor who created the network token. As well as being secure, network tokens aren't impacted by updates to a card. This means that if a card expires but a network token is already created, the network token can continue to be used for recurring payments and help to reduce churn. > [!NOTE] > > Learn more about network tokens by [reading this blog post on how to optimize payments using network tokenization.](https://primer.io/blog/how-to-optimise-payments-using-network-tokenization/) ## Get Started with Primer As your unified payments infrastructure, Primer acts as your centralized Technical Service Provider (TSP), giving you all the powerful capabilities of using network tokens without you having to do any engineering work. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/network-tokenization/network-tokenization-diagram.png) Network Tokenization Flow > [!NOTE] > > Primer currently only supports network tokens for Visa and Mastercard. Creating network tokens and processing payments with them requires three steps: 1. Activate network tokenization for your Primer account 2. Create network tokens 3. Process payments with network tokens ### Activate network tokenization for your Primer account To activate network tokenization, speak to your Customer Success Manager or raise a ticket on our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11). As part of enrolling, we will register your company as a token requestor and generate a token requestor ID (TRID) directly with the card networks on your behalf. > [!WARNING] > > This can take up to 48 hours to become active due to back-office operations on the card network side. ### Create network tokens Once network tokenization is fully activated for your account, go to the [Network Tokenization section](https://dashboard.primer.io/payment-services/network-tokenization/configuration) of your Dashboard to start creating network tokens. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/network-tokenization/creation-configuration.png) Network Token Creation Configuration Three strategies are available for creating network tokens: | Strategy | Description | Recommendation | | - | - | - | | **for newly-vaulted cards** | Attempts to create a network token after a new card is vaulted. | This strategy is the cheapest but also the slowest at increasing the pool of available network tokens to make payments. | | **for previously-vaulted cards** | Attempts to create a network token after an already-vaulted card is used. | This strategy can greatly increase the number of available network tokens in the short term to speed up your experiment. ⚠️ As this strategy does not create network tokens for new cards added to your vault, the pool of available network tokens will reduce over time. We recommend using the next strategy. | | **for all vaulted cards** (Recommended) | A combination of the above two strategies. Attempts to create a network token after a new card is vaulted or an already-vaulted card is used. | This strategy ensures the highest number of available network tokens at all time. | Based on the selected strategy, we will automatically try to create a network token on: * vaulting events i.e. if you set `vaultOnSuccess` or `vaultOn3DS` to `True` in POST or POST * new payments i.e. if you make a payment with an already-vaulted card Once created, the network token will be linked to the vaulted Primer token so that it can be used for processing. > [!NOTE] > > In any case, the network token is **not** created and used for the first payment, but only created after the first payment and then used for processing on subsequent payments. > > This is the advice from card networks due to the additional latency that would be caused during the first payment flow and the negative impact it would have on the checkout. #### Check the creation of network tokens If a network token was successfully created, this will be reflected in the `paymentMethod` object of subsequent payments where `isNetworkTokenized` will be set to `True`. The number of created Network Tokens is also visible in the [Network Tokenization's Reporting section](https://dashboard.primer.io/payment-services/network-tokenization/reporting"). ### Process payments with your network tokens By default, Primer ignores the created network tokens and uses the PAN to process card payments. When you are ready to process payments with your network tokens, go to the [Network Tokenization section](https://dashboard.primer.io/payment-services/network-tokenization/configuration) of your Dashboard to activate and configure when network tokens should be used. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/network-tokenization/processing-configuration.png) Network Token Processing Configuration There, select which processor merchant accounts should use a network token if it's available when processing payments. You can also set the processing volume for each merchant account based on your rollout or experiment strategy: | Processing Volume | Description | When to use? | | - | - | - | | 10% | 10% of the payments initiated with a network tokenized card will be processed using the network token. The other 90% will use the PAN instead. | When you want to start slow and validate that everything is ready to process network tokens at scale. | | 50% | 50% of the payments initiated with a network tokenized card will be processed using the network token. The other 50% will use the PAN instead. | When you want to run an A/B test that compares the performance of network token vs. PAN. | | 90% | 90% of the payments initiated with a network tokenized card will be processed using the network token. The other 10% will use the PAN instead. | When you want to fully rollout network tokens but you still want to compare the performance of network token vs. PAN. | | 100% | This merchant account will always use the network token if it is available. The PAN will be ignored. | When you want to fully rollout network tokens. ⚠️ You will not be able to accurately compare the performance of network tokens vs. PAN. | The processing volume applies to both customer-initiated payments (CIT) using a saved card and merchant-initiated payments (MIT). For CITs, in the background, a one-time cryptogram (TAVV) is generated directly from the card network which acts as the equivalent of the CVV. If the TAVV generation fails for whatever reason, we will fall back to using the PAN as usual. > [!NOTE] > > Not all processors support external network tokens and some processors, such as Stripe, require your account to be gated in on their side before allowing external network tokens. > > Please speak to your Customer Success Manager or our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11) to understand which of your processors are able to process network tokens created by Primer. #### Check that a payment was processed with a network token There are two ways to see if a network token was used for a payment: 1. In the payment object, the `cardTokenType` field is set to `NETWORK_TOKEN`. It is set at the payment level and transaction level. This field is available in both the [API response](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment#response.body.cardTokenType) and the [webhook body](/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-status-update). > [!NOTE] > > This is only available on API and Webhook version 2.2 or greater. See below for an example: ```json JSON theme={"dark"} { "id": "kHdEw9EG", "date": "2021-02-21T15:36:16.367687", "status": "AUTHORIZED", "orderId": "order-abc", "customerId": "customer-123", "currencyCode": "EUR", "amount": 42, "cardTokenType": "NETWORK_TOKEN", ... "transactions": [ { "type": "SALE", "processorStatus": "AUTHORIZED", "processorName": "STRIPE", "processorMerchantId": "acct_stripe_1234", "processorTransactionId": "54c4eb5b3ef8a", "cardTokenType": "NETWORK_TOKEN" } ] } ``` 2. In the payment timeline, you can see the raw processor requests and responses. When a network token is used, you'll see `{{NETWORK_TOKEN_*}}` fields in the request instead of `{{PRIMER_*}}` fields. See below for an example: ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/network-tokenization/payment-timeline-example.png) Payment Timeline Example 3. The payment appears when you set the filter `Card Token Type Used` to `NETWORK_TOKEN`. > [!NOTE] > > If the payment falls back to a merchant account that is not configured for network tokens, the payment will be processed using the PAN and will be not considered to be a Network Token payment anymore. ### Managing card updates You don't have to do anything here - Primer handles this for you and will update the records accordingly. ## Testing network tokens > [!NOTE] > > [Read the detailed guide on how to test network tokens on Primer.](/docs/testing/network-tokenization) ## PAN retries > [!NOTE] > > PAN retries are deactivated by default. Contact us to activate it on your account. Primer can automatically retry a declined network token transaction with the underlying PAN to maximize the overall chances of payment success. When this capability is activated, network token transactions declined with one of the following reasons will be automatically retried by sending the PAN to the same processor: | **Status** | **Error Decision Type** | **Error Decline Type** | **Error Decline Reason** | | :- | :- | :- | :- | | Declined | Gateway Rejected | N/A | N/A | | Declined | Issuer Declined | Soft Decline | Declined | | Declined | Issuer Declined | Soft Decline | Refer to Card Issuer | | Declined | Issuer Declined | Soft Decline | Issuer Temporarily Unavailable | | Declined | Issuer Declined | Soft Decline | Do Not Honor | | Declined | Issuer Declined | Soft Decline | Suspected Fraud | | Declined | Issuer Declined | Soft Decline | Expired Card | | Declined | Issuer Declined | Soft Decline | Error | | Failed | Application Error | N/A | N/A | The performance of the Network Token strategy, including and excluding the performance of the "PAN retry" logic, is visible in your Dashboard. ## Caveats ### Activate external network tokens with Stripe Although Stripe can process the network tokens created by a third-party like Primer, Stripe disables this capability by default. Before processing Primer network tokens with Stripe, please contact your Account Manager at Stripe and ask them to gate all your accounts in for *Bring Your Own Token (BYOT)*. If you need support, speak to your Solution Engineer, Customer Success Manager or our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11). ### Activate external network tokens with Nuvei By default, Nuvei does not expose the Network Transaction ID after customer-initiated payments. This identifier is required in order to: * Use Nuvei to process Primer network tokens for merchant-initiated payments * Use another payment processor to perform merchant-initiated payments with cards that were originally saved through Nuvei Before processing Primer network tokens with Nuvei, confirm that Nuvei returns the field `externalSchemeTransactionId` in the authorization response. If this field is empty, contact your Nuvei Account Manager and request that they enable the setting `ShouldReturnSchemeReference` on all your accounts. If you need support, speak to your Solution Engineer, Customer Success Manager or our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11). # Overview Source: https://primer.io/docs/payment-services/overview ## How Primer enhances every payment Every payment on Primer can be powered by a set of built-in features that help you route, secure, and optimize transactions by default. ![How Primer enhances every payment](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/features/banner/light.png) ## Processing payments > [card] [Save payment methods](/docs/payment-services/save-payment-methods) > > Let customers save cards for faster repeat purchases and smoother checkout. > [card] [Co-badged cards](/docs/payment-services/cobadged-cards) > > Support domestic and international schemes on a single card and optimize routing. > [card] [Advanced metadata mapper](/docs/payment-services/advanced-metadata-mapper) > > Attach structured metadata to payments to improve reporting and downstream logic. > [card] [Surcharge](/docs/payment-services/surcharge) > > Apply fees dynamically based on the selected payment method or currency. ## Boosting performance > [card] [Network Tokenization](/docs/payment-services/network-tokenization) > > Use network-issued tokens to improve authorization rates. > [card] [Fallbacks](/docs/payment-services/fallbacks) > > Automatically reroute failed payments to a backup processor to boost success rates. ## Keeping your payments safe > [card] [3D Secure](/docs/payment-services/3d-secure/overview) > > Add an extra layer of verification for card payments with flexible 3DS flows. > [card] [Fraud checks](/docs/payment-services/fraud-checks/overview) > > Route transactions through fraud prevention tools based on configurable rules. > [card] [Fingerprinting](/docs/payment-services/fingerprinting) > > Create a unique ID for each payment method to help detect fraud and inform workflows. # Save Payment Methods Source: https://primer.io/docs/payment-services/save-payment-methods ## Overview of Primer's Vault > [!NOTE] > > Looking to migrate your existing saved payment methods to Primer? Check out our [token migration guide](/docs/changelogs/migration-guides/token-migration) ### Securely store payment method information Primer's Vault is a centralized PCI-DSS Level 1 service you can use to store the details of a customer payment method in a unified way. Sensitive payment data is stored as a secure multi-use `paymentMethodToken` that enables: * recurring merchant-initiated payments * a seamless one-click experience for your customers with Universal Checkout Each `paymentMethodToken` is paired with a `customerId` which uniquely identifies identify a customer. You can use any unique identifier for this such as a UUID or an email address. This `customerId` is required for: * **generating a client session** to allow Universal Checkout to present your customer's vaulted payment data for one-click checkout * **creating a payment request** using `vaultOnSuccess` or `vaultOn3DS` to save the customer's payment data * **managing stored payment data with the Payment Methods API** to allow customers to add and delete vaulted payment method data from your site or app ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/save-payment-methods/vault.png) Primer's Vault ### Intelligently optimized for auth rate approval We're fanatical about improving payments success. Primer will intelligently store data returned from your underlying processors to ensure the highest likelihood of success for recurring payments. This includes SCA authentication data as well as other data returned from card schemes and acquirers. ## Add payment methods to the vault > [!NOTE] > > Not all payment methods can be added to Primer's centralized vault. Refer to our [payment method guides](/docs/connections/payment-methods/overview) to know more about the capabilities of each payment method. Vaulting a payment method starts by capturing the payment method credentials using Drop-In Checkout or Headless Checkout. You will then encounter two distinct behaviors: * Vault the payment method directly after the user has completed the payment method flow * Vault after a successful authorization ### Vault directly To vault a supported payment method directly, additional options have to be passed to the SDK. Check the [payment method guides](/docs/connections/payment-methods/overview) to properly configure the Drop-in Checkout and Headless Checkout to vault each compatible payment method. ### Vault after authorization success or 3DS authentication For card-based payment methods (Cards, Google Pay and Apple Pay), it is recommended to vault after a payment has been successfully authorized. This ensures the card is valid and is suitable for making payments. > [!WARNING] > > A vaulted Apple Pay or Google Pay credential is not reusable in the same way as a saved card. You can charge it for **merchant-initiated** payments only. When the customer is present, the wallet's terms require a fresh authorization that generates a new cryptogram, so you cannot charge the stored credential as a customer-initiated payment. See [Reuse Apple Pay and Google Pay credentials](#reuse-apple-pay-and-google-pay-credentials). Primer supports two vaulting options for card flows. These can be set in the Client Session API or the Payments API under `paymentMethod`. Make sure to pass `customerId` to specify the customer's vault this payment method should be added to. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/save-payment-methods/vault-token-flow.png) Vaulting Token Flow #### vaultOnSuccess When `paymentMethod.vaultOnSuccess` is set to `true` (and the payment method supports it), the payment method is added to the vault **only after the authorization succeeds**. Use this when you want to save the card only if the payment is successful. #### vaultOn3DS When `paymentMethod.vaultOn3DS` is set to `true` (and the payment method supports it), the payment method is added to the vault **as soon as 3DS authentication succeeds**. Use this when your flow can have a successful 3DS authentication followed by an authorization that may fail (for example soft decline and later retry), and you still want to save the card after the customer completed SCA. #### vaultOnAgreement When `paymentMethod.vaultOnAgreement` is set to `true`, the payment method is added to the vault when the customer explicitly agrees to future payments. This option is intended for agreement or mandate based flows **without an immediate authorization**, such as ACH Direct Debit. At the moment, `vaultOnAgreement` is primarily supported for **ACH payments via Stripe**, where the customer mandate is collected separately from any charge. `vaultOnAgreement` is mutually exclusive with other vaulting options and cannot be combined with `vaultOnSuccess` or `vaultOn3DS`. > [!WARNING] > > Only one vaulting option is applied. > > If multiple vaulting options are set to `true`, the following rules apply: > > * If both `vaultOnSuccess` and `vaultOn3DS` are set, `vaultOnSuccess` takes precedence and `vaultOn3DS` is ignored. > * `vaultOnAgreement` cannot be combined with any other vaulting option. > > We recommend using only one vaulting strategy per flow. ## Make payments with a vaulted payment method ### Simplify the drop-in payment flow Vaulted payment methods appear automatically on the drop-in checkout if `customerId` has been provided in the client session and the customer has vaulted payment methods stored with Primer. This enables your customers to seamlessly pay with one of their saved payment method. For saved cards, we recommend to set `paymentMethod.paymentType` to `ECOMMERCE` in the client session or payment request. This ensures the right data is sent to the processor to maximize the authorization rate. Apple Pay and Google Pay are the exception: a stored wallet credential cannot be charged as an `ECOMMERCE` payment. The customer re-authorizes through the wallet instead, which produces a new single-use token for that payment. See [Reuse Apple Pay and Google Pay credentials](#reuse-apple-pay-and-google-pay-credentials). ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/save-payment-methods/vault-1.png) Universal Checkout Vault ### Recapture the CVV of saved cards PCI standards prevent entities like Primer from [storing the CVV of a card](https://blog.pcisecuritystandards.org/faq-can-cvc-be-stored-for-card-on-file-or-recurring-transactions) when saving the card credentials for future payments. This means that subsequent card-on-file customer-initiated payments are always processed without the CVV. Although Primer sends the relevant parameters to tell each processor when a card-on-file payment occurs, some processors or issuers have a lower authorization rate when the CVV is not provided. To increase the chances of payment success, Primer enables you to ask the customer to re-enter the CVV of the selected saved card before processing the payment. #### Enabling CVV recapture on Drop-in Checkout Include the `captureVaultedCardCvv` option within the `PAYMENT_CARD` payment method options in the `POST /client-session` request. When set to `true`, this flag activates the CVV recapture functionality in the Drop-In implementation, providing an out-of-the-box solution for transactions with vaulted payment cards. **Example Request:** ```json JSON theme={"dark"} POST /client-session { "paymentMethod": { "options": { "PAYMENT_CARD": { "captureVaultedCardCvv": true } } } } ``` ### Create merchant-initiated payments You can use the Payment Methods API and the Payments API together to create merchant-initiated payments with a saved payment method. 1. First, make a call to GET to get the list of payment methods tied to a `customerId`. Each entry in the list contains a `token` representing the payment method token to use to create a payment. 2. Then, create a payment by calling POST. In addition to the required fields for creating a payment, pass the following data: | Parameter Name | Description | | - | - | | paymentMethodToken | The vaulted payment method token | | paymentMethod ↳ [paymentType](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment#body-payment-method-type) | Type of payment. Used to improve conversion.
  • `SUBSCRIPTION` if the payment is part of a series of payments on a fixed schedule and a set amount
  • `UNSCHEDULED` if the payment is not following a fixed schedule or amount
| > [!NOTE] > > Reuse the multi-use (vaulted) token only for **subsequent** merchant-initiated payments (`SUBSCRIPTION` or `UNSCHEDULED`). The customer's **first** payment should use a single-use token with `vaultOnSuccess` — see [Choose the right token type](/docs/get-started/recurring-payments#choose-the-right-token-type). ### Reuse Apple Pay and Google Pay credentials Apple Pay and Google Pay credentials can be vaulted, but a stored wallet credential is not a drop-in replacement for a saved card. Both wallets allow you to charge a stored credential for merchant-initiated payments only. The wallet authorizes a payment with a cryptogram generated at the moment the customer confirms with Face ID, Touch ID, or their device unlock. That cryptogram covers one payment. If the customer is present in the flow, the wallet's terms require you to have them authorize again so the wallet issues a new cryptogram, rather than charging the credential you stored earlier. | Payment | Saved card | Vaulted Apple Pay or Google Pay | | - | - | - | | Customer-initiated, customer present (`ECOMMERCE`) | Charge the vaulted token | **Not permitted.** Have the customer authorize through the wallet again | | Merchant-initiated on a fixed schedule and amount (`SUBSCRIPTION`) | Charge the vaulted token | Charge the vaulted token | | Merchant-initiated with no fixed schedule or amount (`UNSCHEDULED`) | Charge the vaulted token | Charge the vaulted token | #### When the customer is present Present the Apple Pay or Google Pay button and let the customer complete the wallet flow, exactly as you would for a first payment. Each completed flow returns a new single-use token, which you charge for that payment. Don't send `paymentType: ECOMMERCE` with a vaulted wallet token. This also means a vaulted Apple Pay or Google Pay credential does not give the customer a one-click checkout. The customer confirms in the wallet on every payment. #### When the payment is merchant-initiated Charge the vaulted token with `paymentType: SUBSCRIPTION` or `UNSCHEDULED`, as described in [Create merchant-initiated payments](#create-merchant-initiated-payments). For Apple Pay, request a [merchant token (MPAN)](/docs/connections/payment-methods/apple-pay/overview#apple-pay-mpan-configuration) when you vault the credential, and set `firstPaymentReason` to match the payments you intend to make. A credential vaulted without the matching request configuration may not be chargeable later. > [!NOTE] > > This restriction is specific to Apple Pay and Google Pay, which are backed by network tokens and per-payment cryptograms. It does not apply to the other payment methods you can vault, such as PayPal billing agreements or ACH mandates. ## Manage vaulted payment methods ### With the Payment Methods API The [Payment Methods API](/docs/api-reference/v2.4/api-reference/payment-methods-api/list-saved-payment-methods) lets you interact with the vaulted payment methods for all your customers. Use the Payments API to: * retrieve the saved payment methods associated to a customer with GET * delete a saved payment method with DELETE ### With Drop-in Checkout When using Drop-in Checkout, customers have the ability to remove any of their previously vaulted ones. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/save-payment-methods/vault-1.png) ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/save-payment-methods/dropin-vault-edit.png) Universal Checkout Vault # Surcharge Source: https://primer.io/docs/payment-services/surcharge ## What is surcharging? Surcharging enables you to charge customers an additional fee depending on the payment method or card they pay with. Applying this surcharge fee is a way to cover the costs associated with processing payments on each of the available payment methods. Universal Checkout can help you manage and present your surcharge in a unified way across all your platforms and payment methods. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/surcharge/web-card.png) Card surcharge on Web > [!NOTE] > > It is worth noting that, while Universal Checkout supports this feature natively, payment method surcharge is regulated, or even prohibited, in many countries. > > In addition, some payment methods have guidelines and agreements that prohibit surcharging fees. Universal Checkout is not opinionated in this regard, and will always attempt to present the surcharge to the user. > [!WARNING] > > Surcharging is currently available on Drop-in Checkout for all payment methods except Klarna. > > Headless Checkout does not support surcharging natively. ## Get started with Drop-in Checkout ### High level flow * First, create a client session with the line items and the surcharge amount for all of your payment methods and card networks. * During its initialization, Drop-in Checkout automatically retrieves the surcharge data and presents the amount to the user. * When the user selects a payment method, Drop-in Checkout automatically adds the surcharge amount to the client session. * When a payment is created, the full amount including surcharging is used to process the transaction. ### Step 1. Configure the client session Pass the [surcharge amount](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session) for each payment method that you support when creating a client session. The surcharge feature is activated when at least one payment method has a surcharge amount attached. > [!TIP] > > Keep in mind that all amounts on Primer are in minor units ```json JSON theme={"dark"} { "currencyCode": "EUR", "order": { "lineItems": [ { "itemId": "shoe-123", "description": "Blue Shoe", "amount": 100, "quantity": 1 } ], "fees": [] }, "paymentMethod": { "options": { "PAYPAL": { "surcharge": { "amount": 300 } }, "PAYMENT_CARD": { "networks": { "VISA": { "surcharge": { "amount": 100 } }, "MASTERCARD": { "surcharge": { "amount": 150 } } } }, "ADYEN_IDEAL": { "surcharge": { "amount": 100 } }, "BUCKAROO_IDEAL": { "surcharge": { "amount": 100 } } } } } ``` The list of payment method types is available [here](/docs/connections/payment-methods/available-payment-methods). > [!WARNING] > > The surcharge feature dynamically updates the total order amount for you by updating the `order.fees` array when at least one line item is provided. > > **Do not specify a top-level `amount` as this will override the dynamically-calculated amount.** ### Step 2. Present the drop-in checkout Once the client session is created, use the client token to present the drop-in checkout as usual. The drop-in checkout automatically retrieves the surcharge fees from the client session and displays them on its UI. ![](https://goat-assets.production.core.primer.io/marketing/payment-capabilities/external-docs/surcharge/web-apm.png) Surcharge > [!NOTE] > > On Web, applying surcharge forces the payment method "Card" to appear as a button instead of a form. When the user selects a payment method, the SDK automatically patches the client session to add a fee of type `SURCHARGE` with the relevant surcharge amount. Similarly, when the user unselects a payment method, the SDK automatically patches the client session to remove the surcharge fee. ### Step 3. Update the surcharge amount (optional) You can [update the client session](/docs/checkout/client-session#update-a-client-session) at any time to modify the surcharge fees attached to each payment method. This is particularly useful on Web if the user has the opportunity to update their cart while interacting with our drop-in checkout. This automatically updates the fee of type `SURCHARGE` added by the SDK to the new amount for the currently selected payment method. You can also use this mechanism to enable and disable surcharging during a client session. ```typescript Typescript theme={"dark"} // Content of the client session { "currencyCode": EUR, "order": { "lineItems": [{ "itemId": "shoe-123", "description": "Blue Shoe", "amount": 100, "quantity": 1 }], "fees": [{ /* This is automatically added by the SDK when the user selects a payment method*/ "type": "SURCHARGE", "amount": 300 }], }, "paymentMethod": { "options": { /* Surcharge values ... */ } } /* ... */ } ``` > [!WARNING] > > On Web, if `card.preferredFlow` is not provided or is set to `EMBEDDED_IN_HOME` , the checkout will attempt to show the card form on the home screen. > This cause the card form to break when surcharging is enabled and then disabled during a client session. > > We highly encourage you to set `card.preferredFlow` to `DEDICATED_SCENE` to force the card form to appear behind a button. This ensures that the card form can always be presented. ### Step 4. Create a payment By default, the drop-in checkout creates payments automatically. This payment takes into account the surcharge amount, so you don't have to do anything. If you choose to [create payment manually](/docs/checkout/advanced/manual-payment-creation), make sure to not pass the top-level `amount` or `order.fees` on the payment request as this would override the amount set during the client session. ### Considerations Security measures have been put in place to prevent users, malicious or not, to bypass surcharging: * If the surcharge options have been passed but no surcharge fee is present in the client session, the payment will fail to be created. * If the surcharge options have been set but the surcharge fee does not match the selected payment method, the payment will fail to be created. ## Get started with Headless Checkout > [!WARNING] > > At the moment, payment method surcharging is not supported by Headless Checkout. We encourage you to not pass the surcharge options in the client session. # Cost Insights Source: https://primer.io/docs/reconciliation/cost-insights All insights in the Cost Insights dashboard are derived from the settlement reports ingested from your processors, and Primer's Payment services data, transformed into the [Primer Unified Report](/docs/reconciliation/report-content). The Cost Insights dashboard is available to all merchants with Reconciliation product access. *** ## Filters and controls | Control | Description | | :- | :- | | `Cost volume / Cost rate` | Toggle between viewing costs as absolute amounts (Cost volume) or as a percentage of total transaction value (Cost rate). | | `Split by Processor / Split by Region` | Switch between a processor-level and region-level breakdown. Split by Region only includes cost data for payments processed through Primer, and shows aggregated cost data per region across all PSPs. | | `By hour / day / week` | Controls the granularity of the time axis. Applies to the Costs over time chart only, for both Cost volume and Cost rate views. | *** ## Summary cards > The % change indicator compares the current period to the previous equivalent period. A **red** value means costs have increased; a **green** value means costs have decreased. > Costs are always displayed as positive values. Values shown in parentheses are negative and represent credits issued to the merchant. | Metric | Description | | :- | :- | | `Total processing costs` — *Cost volume* | What payment processing is costing you. The sum of all processing fees across transactions in the selected period, converted to base currency. Excludes FX costs. | | `Total processing costs` — *Cost rate* | How much of your transaction volume goes to payment processing. Calculated as (Processing cost ÷ TPV) × 100, where TPV (Total Processed Volume) = sum of Sale, Refund, and Dispute transaction values in the selected period, converted to base currency. | | `Estimated total FX costs` — *Cost volume* | What currency conversion is costing you. For every FX transaction, we compare the processor's applied rate to the mid-market rate — the difference multiplied by the transaction amount is the FX cost. Summed across all FX transactions and converted to base currency. | | `Estimated total FX costs` — *Cost rate* | What share of your FX volume is lost to currency conversion. FX cost per transaction = (processor rate − mid-market rate) × transaction amount. Calculated as (Total FX cost ÷ FX transaction volume) × 100, converted to base currency. | | `Sale costs` — *Cost volume* | The processing costs of Sale transactions. The sum of all processing fees on Sale transactions in the selected period, converted to base currency. Excludes FX costs. | | `Sale costs` — *Cost rate* | How much of your Sale volume goes to processing fees. Calculated as (Sale processing cost ÷ Sale transaction volume) × 100, where Sale transaction volume is the sum of Sale transaction values in the selected period, converted to base currency. | | `Refund costs` — *Cost volume* | The processing costs of Refund transactions. The sum of all processing fees on Refund transactions in the selected period, converted to base currency. Excludes FX costs. | | `Refund costs` — *Cost rate* | How much of your Refund volume goes to processing fees. Calculated as (Refund processing cost ÷ Refund transaction volume) × 100, where Refund transaction volume is the sum of Refund transaction values in the selected period, converted to base currency. | | `Dispute costs` — *Cost volume* | The processing costs of Dispute transactions. The sum of all processing fees on Dispute transactions in the selected period, converted to base currency. Excludes FX costs. | | `Dispute costs` — *Cost rate* | How much of your Dispute volume goes to processing fees. Calculated as (Dispute processing cost ÷ Dispute transaction volume) × 100, where Dispute transaction volume is the sum of Dispute transaction values in the selected period, converted to base currency. | | `Transfer costs` — *Cost volume* | The processing costs of Transfer transactions. The sum of all processing fees on Transfer transactions in the selected period, converted to base currency. Excludes FX costs. | | `Transfer costs` — *Cost rate* | How much of your Transfer volume goes to processing fees. Calculated as (Transfer processing cost ÷ Transfer transaction volume) × 100, converted to base currency. Excludes FX costs. | | `Fee costs` — *Cost volume* | The processing costs of standalone Fee transactions. The sum of all processing fees on Fee transactions in the selected period, converted to base currency. Excludes FX costs. | | `Fee costs` — *Cost rate* | Not available. Because standalone Fee transactions represent pure cost with no associated transaction volume, the cost rate would always be 100% and is not a meaningful metric. | *** ## Charts | Chart | Description | | :- | :- | | `Costs over time` — *Cost volume* | Your payment processing costs over time, split by processor. Each bar shows the total processing fees for that hour, day, or week, converted to base currency. Excludes FX costs. | | `Costs over time` — *Cost rate* | Your payment processing cost rate over time, split by processor. Each data point is (Processing cost ÷ TPV) × 100 for the period, where TPV = sum of Sale, Refund, and Dispute transaction values, converted to base currency. Excludes FX costs. | | `Costs by processor` — *Cost volume* | Your total payment processing costs grouped by payment processor. Each bar is the total cost for that processor over the selected period, converted to base currency. Excludes FX costs. | | `Costs by processor` — *Cost rate* | Your payment processing cost rate by processor. Each bar is (Processing cost ÷ TPV) × 100 over the selected period, where TPV = sum of Sale, Refund, and Dispute transaction values, converted to base currency. Excludes FX costs. | | `Costs by fees category` — *Cost volume* \* | Your payment processing costs grouped by fee category (Interchange, Scheme, Processor), with bars per payment processor. Each bar is the total for that combination over the selected period, converted to base currency. Excludes FX costs. | | `Costs by fees category` — *Cost rate* \* | Payment processing cost rate by fee category (Interchange, Scheme, Processor), with bars per payment processor. Each bar is (Fee category cost ÷ TPV) × 100 over the selected period, where TPV = Sale + Refund + Dispute volume, converted to base currency. Excludes FX costs. | | `Estimated FX costs by top currency pairs` — *Cost volume* | FX costs across all currency pairs, with bars per processor. FX cost is calculated as the difference between the processor's applied exchange rate and the mid-market rate, multiplied by the transaction amount — summed over the selected period and converted to base currency. | | `Estimated FX costs by top currency pairs` — *Cost rate* | FX cost rate across all currency pairs, with bars per processor. Each bar is (FX cost ÷ FX transaction volume) × 100 over the selected period, converted to base currency. FX cost = (processor rate − mid-market rate) × transaction amount. | | `Authorized sales over time` — *Cost volume* | Number of approved sale attempts per hour/day/week, stacked by processor or region. Only payments processed through Primer are included, and only for processors you reconcile. Every attempt counts, so fallback retries are attributed to the processor that ran them. Dated by attempt time. | | `Sales authorization rate over time` — *Cost rate* | Share of sale attempts approved per hour/day/week, split by processor or region. Each line is (Authorized sale attempts ÷ Sale attempts) × 100. Only payments processed through Primer are included, and only for processors you reconcile. Every attempt counts, so fallback retries are attributed to the processor that ran them. Dated by attempt time. | \*The fee category breakdown depends on the granularity of cost data provided by each PSP in their settlement reporting. Where a PSP reports a single aggregated cost per transaction rather than a line-by-line breakdown, all costs for that PSP will appear under Processor — it is not possible to allocate them to Interchange or Scheme. # Overview Source: https://primer.io/docs/reconciliation/overview ## Stay on top of payment reconciliation Track settlements across processors, match transactions, and surface payout discrepancies with confidence. ![Stay on top of payment reconciliation](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/reconciliation/banner/light.png) ## Understanding reconciliation > [card] [Settlement Report](/docs/reconciliation/unified-settlement-report/) > > Understand how settlement reports track transactions and fund movements > [card] [Support Processors](/docs/reconciliation/supported-processors/) > > Review the list of supported processors and how they integrate with reports > [card] [Report Content](/docs/reconciliation/report-content) > > Explore the structure and fields included in reconciliation reports # Report Content Source: https://primer.io/docs/reconciliation/report-content ## Available values | Field and data type | Description | | :- | :- | | `id` *string* | The unique Primer payment ID returned by Primer's Payments API when the payment request was made. | | `amount` *decimal, >= 0* | The amount the customer was charged, refunded or claimed as a chargeback. This is Primer's record of the payment. | | `paymentMethod` *string* | The payment method or card scheme used to process this payment. | | `orderId` *string* | The order ID you send to Primer via Primer's API when creating the payment. | | `processor` *string* | The identifier of the processor. | | `merchantId` *string* | The merchant ID registered at the payment processor used for this payment. | | `transactionType` *enum: SALE, FEE, REFUND, TRANSFER, DISPUTE, PAYOUT* | Explains the type of transaction that took place but maps the various `transactionTypeDetail` values to a simplified Primer type. | | `direction` *enum: CREDIT, DEBIT* | Whether this is a credit to the settlement or deducted as a debit. | | `createdDate` *date-time* | Date and time the payment was created in Primer (ISO-8601). | | `capturedDate` *date-time* | Date and time the payment capture was settled in Primer (ISO-8601). | | `processorTransactionId` *string* | The processor's unique identifier for the transaction. | | `status` *enum: PENDING, FAILED, AUTHORIZED, SETTLING, PARTIALLY\_SETTLED, SETTLED, DECLINED, CANCELLED* | The status of the payment in Primer. | | `currencyCode` *string* | The code of the currency you charged the customer. 3-digit currency code in ISO 4217 format. e.g. USD for US dollars. This is Primer's record of the payment. | | `metadata` *JSON object* | Additional data to be used throughout the payment lifecycle. A dictionary of key-value pairs where the values can only be strings or integers. e.g. `{"productId": 1001, "merchantId": "a13bsd62s"}`. This may be sent to Primer's API. | | `reconciliationAmount`\* *decimal, >= 0* | The amount the customer was charged, refunded or claimed as a chargeback. This is the processor's payment record from the settlement report. | | `reconciliationCurrencyCode`\* *string* | The code of the currency you charged the customer. It is a 3-digit currency code in ISO 4217 format, e.g., USD for US dollars. This is the processor's payment record from the settlement report. | | `payoutGrossAmount`\* *decimal, >= 0, default: 0* | The original transaction amount in the currency of payoutCurrencyCode. This is also known as Gross settlement. | | `payoutNetAmount`\* *decimal, default: 0* | Original transaction amount, less totalFee, in the currency of payoutCurrencyCode. This is also known as Net settlement. Can be negative when deductions exceed the gross amount. | | `payoutTotalDeductionsAmount` *decimal, default: 0* | Total fees incurred and deductions due to this transaction in the currency of payoutCurrencyCode. It is possible for that value to have a negative amount (if it increases the payoutGrossAmount) or positive amount (if it decreases the payoutGrossAmount). *Note: This field will not be populated if the processor provides a separate line item fee transaction type.* | | `processorFeeAmount`\* *decimal, default: 0* | This is the fee that the acquiring bank charges when a payment is made. It is possible for that value to have a negative or positive amount. The value for processorFeeAmount is already added to payoutTotalDeductionsAmount. *This value is only filled when the upstream source is reporting with that granularity.* | | `interchangeFeeAmount`\* *decimal, default: 0* | This is the fee that the issuing bank charges when a payment is made. It is possible for that value to have a negative or positive amount. The value for interchangeFeeAmount is already added to payoutTotalDeductionsAmount. *This value is only filled when the upstream source is reporting with that granularity.* | | `schemeFeeAmount`\* *decimal, default: 0* | This is the fee paid to the scheme/network when a payment is made. It is possible for that value to have a negative or positive amount. The value for schemeFeeAmount is already added to payoutTotalDeductionsAmount. *This value is only filled when the upstream source is reporting with that granularity.* | | `reconciliationOrderId`\* *string* | The processor record of the Order ID from the settlement file. | | `network` *string* | The card scheme that the payment went through (e.g. Visa, Mastercard, American Express). | | `payoutDate`\* *date-time* | The date and time at which the payout was submitted in UTC format. | | `payoutBatchId` *string* | Shared ID of all transactions contained within this batch of settlement data from the processor. | | `payoutCurrencyCode`\* *string* | The code of the currency used for this payout. 3-digit currency code in ISO 4217 format. e.g. USD for US dollars. This is also known as settlement currency. | | `transactionTypeDetail`\* *string* | Raw transaction type provided by the processor. | | `reconciliationResult` *enum: TRUE, FALSE* | Indicates whether the transaction content from the processor matches the content stored in Primer. Note: **Transfers**, **fees**, **disputes**, and **payouts** will be automatically marked as reconciled because they are not recorded in Primer. | | `reconciliationResultHistory` *string* | Gives more information on the reason for the mismatches found, highlighting the values expected and the value received from the processor. | | `conflictReason` *enum: TRANSACTION\_UNKNOWN, AMOUNT, TRANSACTION\_TYPE, CURRENCY* | Identifies the reason for the conflict for transactions that can't be matched between Primer and the processor's settlement report. | | `processorAccountId`\* *string* | An optional account identifier for the processor. This can be helpful to attribute costs to account-level fees, rather than specific to a payment or merchant Id. | | `transactionEventId` *string* | An ID referencing the Primer transaction lifecycle to help track individual events against a payment, such as capture, or refunds. | > [!NOTE] > > Fields marked with `*` are taken from the processor's settlement report, whereas the remaining fields originate from the Primer Payment or from Primer's Reconciliation [batch processing](/docs/reconciliation/unified-settlement-report#report-structure) logic. ## Decimal amounts > [!NOTE] > > We are using decimal amounts in the reports, which is a deviation from how Primer's Payment API works. This is so that we can accurately reflect the granularity by which third parties report settlement data, like transaction fees, without introducing rounding errors. Amounts will therefore always come with eight decimal places for consistency, even for currencies like JPY that don't use minor units. ## Transaction types * `SALE`: Refers to a settled payment and might include cost/fee information. * `REFUND`: Refers to a refund on a settled payment and might include cost/fee information. This could also refer to blind credits not related to Primer payments. * `DISPUTE`: Refers to payment funds being reversed due to a dispute and might include cost/fee information. * `FEE`: Refers to fees not tied to a settled payment, such as authorization fees or other standalone charges. * `PAYOUT`: Groups any transaction related to the processor balance and bank account funds movement. * `TRANSFER`: Any other money transfer (credit or debit) beyond the specifically mapped ones like Sale or Refund. ## Using the `direction` field The `direction` field determines how funds flow in or out of your account. Always combine `direction` with `payoutNetAmount` to determine the financial effect of a record. | Direction | Meaning | Gross amount | Deductions | Net amount | | :- | :- | :- | :- | :- | | `CREDIT` | Funds **to** the merchant | Total credited before deductions | Subtracted from gross | Actual payout to merchant | | `DEBIT` | Funds **from** the merchant | Total amount charged or reversed | Added to gross | Total amount deducted from merchant | **Formulas:** * `CREDIT`: `payoutGrossAmount - payoutTotalDeductionsAmount = payoutNetAmount` * `DEBIT`: `payoutGrossAmount + payoutTotalDeductionsAmount = payoutNetAmount` **Examples** (all amounts in USD): | `direction` | `payoutGrossAmount` | `payoutTotalDeductionsAmount` | `payoutNetAmount` | Meaning | | :- | :- | :- | :- | :- | | `CREDIT` | 100.00 | 2.50 | 97.50 | A positive credit. Merchant receives 97.50 | | `CREDIT` | 0.00 | 0.50 | -0.50 | A negative credit. Merchant is charged 0.50 (e.g. a fee correction) | | `DEBIT` | 0.00 | 1.00 | 1.00 | A positive debit. Merchant is charged 1.00 | | `DEBIT` | 50.00 | 10.00 | 60.00 | A positive debit. Merchant is charged 60.00 (e.g. reversed payout) | | `DEBIT` | 2.00 | -5.00 | -3.00 | A negative debit. Merchant receives 3.00 | > [!NOTE] > > Gross amounts can be `0.00`, especially in fee-only transactions. `direction` still clarifies whether the net amount represents funds to or from you. ## Understanding fees Fee values use a consistent sign convention across all records. You do not need to rely on `direction` or `transactionType` to interpret them: * Fee **> 0**: a deduction from your payout * Fee **\< 0**: returned funds (e.g. a fee reversal) This applies to all fee columns: `processorFeeAmount`, `interchangeFeeAmount`, `schemeFeeAmount` and `payoutTotalDeductionsAmount`. Fee values can have many decimal places due to fractional reporting from some PSPs. ## Special case: `transactionType = FEE` `FEE` records appear in the following scenarios: * **Platform or account-level fees** not tied to a specific transaction * **Fees for non-settled payments**: the matching engine only has access to settled payments, so fees for payments that did not settle (e.g. declined authorization fees) cannot be matched and appear as `FEE` records * **Delayed fee application**: fees such as authorization charges can appear in the report days after the original transaction * **Fallback**: when Primer **cannot identify the matching transaction for a fee**, it falls back to the `FEE` type ## Transaction type tips * `SALE`, `REFUND`, `DISPUTE`: can be `CREDIT` or `DEBIT`, and can appear with `payoutGrossAmount = 0` when only fees are being reported for that day. Always rely on `direction` and the amount fields rather than the transaction type alone. * `TRANSFER`: represents general fund transfers not tied to a specific transaction. This is also used as a fallback when none of the other specific types apply. ## Field interpretation tips | Field | Tip | | :- | :- | | `direction` | `CREDIT` means funds to you; `DEBIT` means funds from you. Ensure you take into account whether the amount is a negative or a positive | | `payoutCurrencyCode` | Your settlement currency. Used for `payoutGrossAmount`, `payoutNetAmount`, `payoutTotalDeductionsAmount`, `processorFeeAmount`, `interchangeFeeAmount` and `schemeFeeAmount` | | `payoutGrossAmount` | Amount before deductions, in settlement currency | | `payoutNetAmount` | Final settled amount, in settlement currency. Can be negative when deductions exceed the gross amount | | `reconciliationAmount` | Transaction amount in the presentment (transaction) currency | | `reconciliationCurrencyCode` | Presentment (transaction) currency | | `createdDate` | Timestamp of the transaction event | | `reconciliationOrderId` | Order ID from the PSP. On refunds, some PSPs support a separate order ID matching the one you passed on the refund request; others return the same ID as the original authorization. This field reflects whatever the PSP reports. | ## Integration checklist Before going live with your reconciliation integration, confirm the following: * Use `direction` to determine whether gross and net amounts represent funds to or from you. * Handle both positive and negative net amounts correctly for `CREDIT` and `DEBIT` records. * Use `payoutTotalDeductionsAmount` as the primary fee value for total deductions. ## Batches and files Primer generates one unified file per batch of settlement data received from a processor. All files follow the same structure regardless of processor. To calculate the total net payout for a batch: ```text theme={"dark"} A = sum of payoutNetAmount where direction = CREDIT B = sum of payoutNetAmount where direction = DEBIT Total net payout = A - B ``` ## Conflict reasons > [!NOTE] > > A batch status of `Conflict` in the dashboard means there could be any number of reasons on why we flagged a particular transaction. The actual available values for `conflictReason` in the report are as follows: * `TRANSACTION_UNKNOWN`: We don't have a record of the processor transaction ID to map to a Primer payment. Usually for payments created outside of Primer. * `AMOUNT`: Our record of the amount differs to the amount reported. * `CURRENCY`: Our record of the currency differs to the currency reported. * `TRANSACTION_TYPE`: This could only happen if we recorded a payment as a sale but the settlement report indicates it as a refund, or the other way round. Depending on the reason and amount of conflicts, you can investigate by looking at the payment within the Primer dashboard, and comparing its state within the processor's dashboard. ## Sample report [Download an example CSV file](https://drive.google.com/file/d/1d0JLKNyQ7iaS3oMSbh_0vybZXoKxuhFz/view). The file structure will be the same for every processor, but naturally IDs like transaction IDs or merchant IDs, or raw transaction types, will vary from one processor to another. # Supported Processors Source: https://primer.io/docs/reconciliation/supported-processors Settlement reporting - and the available data and data granularity - is different from provider to provider. This page lists the processors that we currently support, including a mention of which reports are currently integrated. > [!NOTE] > > New processors are added regularly. If you don't see your preferred processor(s) here, but would like to use Reconciliation via Primer, speak to your Customer Success Manager or raise a ticket on our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11). ## Adyen We have integrated [Adyen's settlement details report](https://docs.adyen.com/reporting/settlement-reconciliation/transaction-level/settlement-details-report/) via API, specifically the **Batch closing report.** **Setup Instructions:** * Within Adyen's dashboard, create new API credentials for "Report service user" under Developers - API credentials. * Enter these credentials when adding the Adyen connection in Primer's dashboard. ## Checkout.com We have integrated [Checkout.com's **Financial Actions** Report](https://www.checkout.com/docs/business-operations/retrieve-reports/reconciliation-reports/financial-actions-reports). Checkout.com sets up daily report generation during the new scheduled report creation. > [!NOTE] > > As per Checkout.com: If you have multiple entities set up, you must create various instances on Primer, as reports are split by entity. In the report, some data, such as costs, are assigned to the entity rather than to a specific MID. > > Additionally, you will need to create a separate API key for each entity for reporting. **Setup Instructions:** * In the Checkout.com dashboard, go to **Reports** > **Manage schedules**. Create a new report by clicking the **New report** button. The new report must use the **Financial Actions** report type. * Create a new **Secret API key** with the following scopes: `FINANCIAL-ACTIONS`, `FINANCIAL-ACTIONS:VIEW`, `REPORTS`, and `REPORTS:VIEW` ("Reporting" filter). * Enter this API key when adding the reconciliation connection in Primer's dashboard. * Enter the `Entity ID` from Checkout.com in the credentials. ## dLocal We have integrated with the dLocal settlement reports via SFTP. **Setup Instructions:** * Contact your dLocal account manager to configure your settlement reports for the Primer configuration. * Contact your dLocal account manager to provision your SFTP credentials. * Enter these credentials when adding the dLocal connection in Primer's dashboard. ## Klarna We have integrated [Klarna's Settlement Reports](https://docs.klarna.com/settlement-reports/) via API. **Setup Instructions:** * Create an API key within Klarna's dashboard. * Enter this key when adding the Klarna connection in Primer's dashboard. ## Mollie We have integrated with [Mollie's settlement report](https://docs.mollie.com/reference/settlements-api) via API. These reports are reconciled with a delay of approximately 2 hours and 20 minutes after they are made available by Mollie, to ensure all transactions are fully processed and matched. **Setup Instructions:** * Create an API key within Mollie's dashboard. * Enter this key when adding the Mollie connection in Primer's dashboard. ## Monext We have integrated with the [Payments file](https://docs.monext.fr/display/DT/Payments+file) from Monext via SFTP. **Setup Instructions:** * Request an SFTP account with username and password to be shared with Primer. Monext has already cleared Primer's IP addresses. * Request Monext to create one file per Merchant ID. * Enter these credentials when adding the Monext connection in Primer's dashboard. ## PayPal We have integrated with [PayPal's Single account settlement report](https://developer.paypal.com/docs/reports/sftp-reports/settlement-report/#single-account-report) via SFTP. **Setup Instructions:** * [Create a secure FTP server user from within PayPal's portal](https://developer.paypal.com/docs/reports/sftp-reports/settlement-report/#link-creatingasecureftpserveruser). * Enter these credentials when adding the PayPal connection in Primer's dashboard. ## Stripe We have integrated with [Stripe's Payout reconciliation report](https://docs.stripe.com/reports/payout-reconciliation) via API. **Setup Instructions:** To create a restricted API key in Stripe: * Go to Developers > API keys > Create restricted key * Set **Files** permission to Read * Set **Report Runs** permission to Write * Set **Report Types** permission to Write Enter the generated key in the designated API key field to connect Stripe to Primer's Reconciliation. ## Thunes Thunes can set up an SFTP account and populate it with settlement reports according to your requirements. **Setup Instructions:** * Request a new SFTP account from Thunes. Thunes has already cleared Primer's IP addresses. * Request Thunes to add the column for `FinancialOperationType` to the report. * Enter these credentials when adding the connection in Primer's dashboard. # Primer's Unified Settlement Report Source: https://primer.io/docs/reconciliation/unified-settlement-report Primer has created a unified payments infrastructure and abstracted [Payments](/docs/concepts/overview), and [Disputes](/docs/disputes/overview). Our Reconciliation product represents the abstraction of settlement reports across processors. Every processor provides different ways to access their settlement reports, in different formats, and with different data within their reports. Primer has created a unified report that allows you to consume your own settlement data much easier, and you only have to reason about one report, without having to learn all the differences and intricacies of direct integrations. > [!NOTE] > > The report content focuses on transactional data, such as sales and refunds. We will forward additional transfers within reports sent by third parties. However, we do not process any additional reports outside of transaction reports. Refer to [supported processors](/docs/reconciliation/supported-processors) to see which reports we are consuming per processor. ## Report structure When we receive a settlement report from a processor, we create Primer Reconciliation **Batches** out of it based on the combination of `processor` + `MID` + `Settlement currency`. So `Processor A + mid1 + EUR` and `Processor A + mid2 + EUR` and `Processor A + mid3 + GBP` would be individual batches, even if **Processor A** were to send all of this into one report. Refer to the [settlement report description](/docs/reconciliation/report-content) to learn about the data and columns represented in the report. Depending on the processor and merchant accounts used, it is possible for a report to contain payments across multiple presentment currencies with the same settlement currency. ### Requesting a batch update In the case of problems with the original data, the processor could issue a new report on their side. By requesting a batch update you can instruct Primer to reprocess and replace the existing report with the updated data. ### Downloading a batch You can download a batch from the reports overview, or from the reports detail page. No matter if you download the file from the dashboard or the [SFTP folder](#consuming-reports-via-sftp), the content will be the same. ### CSV Content Refer to the [settlement report description](/docs/reconciliation/report-content) to learn about the data and columns represented in the report. ### Filenames * CSV files follow this convention, no matter if accessed via SFTP or Dashboard: `Primer_Unified_Report_{processor}_Batch_{batch_id}_Date_{payout_date}.csv` (format for payout date: `YYYY-MM-DD`) * The logic for batch IDs is different per processor. ### Good to know * We start importing data from the time when reconciliation is enabled for you and don't backfill historic data. * Individual batches could be updated (reprocessed) on demand. In this case, an existing file will be overwritten. * Payout dates are not guaranteed to be unique. Depending on the processor and their setup, it is possible for two separate batches to have the same payout date. * Data on sales is not guaranteed to be final within one payout. Depending on your processor, additional fees might show up days later. Examples of this include fees for Authorization and Capture, where the actions do not happen within the same payout period. Another example is fees that are only reported days later, like interchange fees with Checkout.com. In these cases, looking for the `reconciliationOrderId` is key to assign fees correctly. * Some processors will report additional data that is not tied to sales, such as account level fees. These will show in the report but will not be tied to a payment or `merchantId`. * Some processors also split the reports based on criteria other than `merchantId`, for example based on entities, where a merchant has multiple entities set up. ## Setup Speak to your Customer Success Manager or raise a ticket on our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11) to get access to our reconciliation product. Once access is granted, you will need to set up your processors accordingly and select the merchant accounts that you wish to enable. After setup, as soon as Primer receives new settlement reports from the processors, we transform them into our unified format and make them available either in the dashboard, where they can also be downloaded individually as CSV files, or via SFTP folders. > [!NOTE] > > Processors settle on their own schedule, which differs by PSP (e.g. T+1, T+2, T+X). The Primer unified settlement report becomes available shortly after the processor generates the file and it is ingested by Primer. For example, if your processor generates a file on the 15th, the Primer unified settlement report appears on the same day. ## Supported processors and reports Settlement reporting, along with the available data and data granularity, differs between providers. [See more details for each of the currently supported processors and reports per processor.](/docs/reconciliation/supported-processors) ## Reconciliation data in the dashboard Accessing reconciliation data in the dashboard enables you to have immediate visibility into all batches that were created by Primer. The view allows you to see all reports across all processors, currencies, and payout dates. ![](https://goat-assets.production.core.primer.io/marketing/reconciliation/external-docs/unified-settlements-report/recon-dashboard.png) Reconciliation data overview in the Primer Dashboard The batch status can show you right away if all transactions were reconciled, or if there were any [conflicts](/docs/reconciliation/report-content#conflict-reasons) recorded. ## Consuming reports via SFTP It is possible to access and download the CSV files via SFTP **on our production environment only**. Speak to your Customer Success Manager or raise a ticket on our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11) to request access. Primer will need a public key from you, and we support the following signing algorithms: * **ED25519**: `ssh-ed25519` * **RSA**: `rsa-sha2-256`, `rsa-sha2-512` * **ECDSA**: `ecdsa-sha2-nistp256`, `ecdsa-sha2-nistp384`, `ecdsa-sha2-nistp521` We will then set up the access and send you a hostname and username. * There is no retention period, all files created by Primer will be available in this folder. * File names are based on batch IDs and payout dates. A new batch for a new payout date will always be a new file. ## Batch reviews Depending on the processor added, batches might not immediately show up on the SFTP folder or in the dashboard. This allows Primer to review incoming data and adjust logic if needed. While we aim to integrate the full extent of available transactions, we occasionally have to update mappings based on production data. Examples of when this is necessary include situations where processors do not support sandbox environments, have limited settlement reporting capabilities in sandbox versus production, or when data varies between merchant types or geographies. This review state allows Primer to validate the integration. # Use FunnelFox with Primer Source: https://primer.io/docs/subscriptions/funnelfox Primer payments power FunnelFox's subscription engine FunnelFox Payments is a subscription engine with a native Primer integration. FunnelFox is the system of record for your product catalog and subscription state: what each customer bought, what they have access to, and when they are charged next. Primer processes every payment, from the first checkout through each renewal, using your Primer account and the processors connected to it. FunnelFox runs the recurring payment logic: it schedules and starts renewals and retries through Primer. You are not required to handle any logic to create payments and report the results back to the billing system. On your side, you add a checkout to your paywall and handle FunnelFox webhooks to keep access in your product in sync. ## How it works ```mermaid theme={"dark"} sequenceDiagram participant C as Customer participant W as Your paywall participant F as FunnelFox participant P as Primer participant X as Processor participant M as Your backend C->>W: Selects a plan W->>F: Create checkout for a price point (FunnelFox Web SDK) C->>P: Pays via Primer Checkout P->>X: Authorise, vault the payment method X-->>P: Approved P-->>F: Payment result F->>M: Webhook: subscription started Note over F: Before each billing cycle F->>P: Renewal payment with the vaulted payment method P->>X: Process the renewal X-->>P: Approved or declined P-->>F: Result F->>M: Webhook: renewed, or recovery started ``` *Figure 1. FunnelFox owns the subscription and decides when to charge. Primer runs every payment.* FunnelFox keeps what a customer can access separate from what they pay: * **Offerings** are entitlements, such as access to a feature. * **Price points** are versioned pricing configurations (currency, trial, renewal terms) that grant one or more offerings. * **Purchases** are what a customer holds: a recurring subscription, a one-off lifetime purchase, or a consumable. This lets you change what you charge without changing what existing customers can access. A subscription moves through statuses such as `INTRO` (trial), `RECURRING`, `GRACE`, `RETRY`, `PAUSED`, `AUTORENEW_OFF` and `EXPIRED`. A `RECURRING` subscription is charged two hours before each billing cycle starts. See [subscription statuses](https://funnelfox.com/docs/billing/view-subscriptions-billing#status). ### Failed payment recovery When a renewal fails, FunnelFox runs recovery: * **Retry schedules.** Choose a long or a short schedule. Both adapt to the billing interval, and later attempts can be partial charges, for example 70% or 50% of the amount. * **Grace period.** The customer keeps access while recovery is in progress. * **Cascading.** A failed payment can be sent to a backup processor before the retry schedule starts. * **Adaptive 3DS.** Payments are first attempted without 3DS. 3DS is triggered only when the issuer requires authentication. If the payment then cascades, the 3DS result is reused on the backup processor. See FunnelFox documentation for [Retries and cascading](https://funnelfox.com/docs/billing/payments-retries) and [Adaptive 3DS](https://funnelfox.com/docs/billing/payments-adaptive-3ds). ### Who owns what | FunnelFox | Your team | Primer | | - | - | - | | Offerings and price points, trials, subscription state and lifecycle, renewal scheduling, retries, grace periods, cascading, plan changes, pauses, cancellations and refunds, subscription webhooks | Paywall or funnel, customer identifiers, granting and revoking access based on FunnelFox webhooks | Checkout, vaulting and network tokens, payment processing across your connected processors, 3DS, decline codes | ## Things to plan for * FunnelFox enables FunnelFox Payments for each account. Contact FunnelFox to set up a sandbox account. Your agreement with FunnelFox is separate from your Primer agreement. * Checkout uses Primer's Checkout, either through the FunnelFox Web SDK or through FunnelFox funnels. Primer's Web SDK must load on the page before the FunnelFox SDK. * The Subscription engine allows at most two charges per day per payment method token. * FunnelFox offers dispute prevention through Ethoca and Verifi alerts, which refund a disputed transaction before it becomes a chargeback. It takes about two weeks to go live. See [Disputes](https://funnelfox.com/docs/billing/disputes). ## Set up FunnelFox with Primer ### Prerequisites * A Primer account with at least one processor connected and a Workflow configured. See [Connect a processor](/docs/get-started/connect-a-processor). * A Primer API key. See [Authentication](/docs/api-reference/get-started/authentication). * A FunnelFox Payments account. ### Steps 1. **Connect Primer to FunnelFox.** In FunnelFox Payments, go to **Settings > Main** and add your Primer credentials under **Payment provider credentials**: * **Domain:** `https://api.sandbox.primer.io` for sandbox, or `https://api.primer.io` for production. FunnelFox uses the domain to tell whether you're in live mode. * **Private key:** your Primer API key. * **Webhook signing secret:** your Primer webhook signing secret, from the Primer Dashboard. 2. **Create offerings and price points** in FunnelFox. See [Offerings](https://funnelfox.com/docs/billing/settings-offerings) and [Price points](https://funnelfox.com/docs/billing/settings-price-points). 3. **Add checkout to your paywall.** In FunnelFox funnels, select FunnelFox Billing as the payment provider. On your own paywall, install `@funnelfox/billing` together with `@primer-io/checkout-web`, then call `createCheckout`. See the [Web SDK quickstart](https://funnelfox.com/docs/develop/web-sdk-quickstart). 4. **Handle FunnelFox webhooks** to grant and revoke access in your product. FunnelFox sends events for orders, subscriptions, one-off purchases, refunds and disputes. See [Webhooks](https://funnelfox.com/docs/develop/webhooks-billing). 5. **Configure recovery.** Choose your retry schedule in FunnelFox **Settings**, and set up cascading and Adaptive 3DS with FunnelFox. 6. **Test in sandbox** before you switch the domain to production. See [Testing](https://funnelfox.com/docs/billing/testing). > [!NOTE] > > Payments are processed by your own Primer account, so they show up in the Primer Dashboard next to your other transactions. ## Reference documentation * [FunnelFox Subscription Engine documentation](https://funnelfox.com/docs/billing/subscription-engine-overview) # Overview Source: https://primer.io/docs/subscriptions/overview ## Process subscription payments with Primer Keep your subscription engine for plans, invoices, and renewals while Primer executes every first payment, renewal, and retry. ![Process subscription payments with Primer](https://mintcdn.com/primer-cc826789/Xq555ZpUYmf8cxLp/images/light.png?fit=max\&auto=format\&n=Xq555ZpUYmf8cxLp\&q=85\&s=a57cac7a3023ea6a5c1595026a3ebeb8) You can use Primer with your subscription engine of choice, with Primer processing every payment and the engine keeping track of plans and subscriptions. ## Integration Guides > [card] [Stripe Billing](/docs/subscriptions/stripe-billing) > > Keep Stripe Billing as your subscription engine and process every payment through Primer > [card] [FunnelFox](/docs/subscriptions/funnelfox) > > Primer payments power FunnelFox's subscription engine ## What Primer brings to every attempt * **One vault, many processors.** Payment methods are tokenized once with Primer and usable across every processor you connect, today and in future, so your billing engine never needs to know where a payment is processed. * **Network tokens.** Issued and managed automatically, improving authorisation rates on renewals and surviving card reissues. * **Correct recurring context.** Renewals are transmitted to issuers with the proper stored-credential framing, which is essential for how issuers score recurring traffic. * **Routing and fallbacks.** Workflows decide processor selection per attempt, including fallbacks on technical failures and different routes on later retries. * **Decline intelligence.** Normalised decline codes across processors power the hard and soft classification that gates every retry. * **Observability.** Every attempt, route, and outcome is visible in one place across all processors. ## Understanding subscription payments > [card] [Recurring Payments](/docs/get-started/recurring-payments) > > Choose the right payment type and token for first payments and renewals > [card] [Save Payment Methods](/docs/payment-services/save-payment-methods) > > Vault payment methods on the first payment for use in later renewals > [card] [Declined Payments](/docs/get-started/recurring-payments#recover-declined-or-failed-payments) > > Separate hard declines from soft declines before scheduling a retry Each guide below covers one engine: how to set it up, how payments flow, and what the engine, your team, and Primer each handle. ## Use other subscription engines Any subscription engine can work with Primer in the same way if it supports: * A reference to a payment method stored outside the billing engine * A notification when a payment is due, including for each scheduled retry * An API to record payment outcomes against invoices * A configurable retry schedule, or the option to turn off its own automatic collection Contact your Primer account team to discuss a subscription engine that isn't listed on this page. # Use Stripe Billing with Primer Source: https://primer.io/docs/subscriptions/stripe-billing Use Stripe Billing as your subscription engine alongside the advantages of using Primer for processing every subscription payment. Stripe Billing is the system of record for plans, subscriptions, and invoices. Primer executes every payment, with vaulting, network tokens, routing across processors, and empowers you to control when, how and if any charge is retried. The integration approach addresses the goals we hear most often from subscription merchants: keeping every retry informed by the decline response, protecting your standing with issuing banks and card schemes, and diversifying processing across providers, while Stripe Billing remains the subscription engine. ## Things to plan for * Confirm with your Stripe account team that [third-party payment processing](https://docs.stripe.com/billing/subscriptions/third-party-payment-processing) (custom payment methods and payment records) is enabled for your account, and that your Stripe business entity country is supported. * The collection surface for these payments is Primer Checkout. Stripe Checkout and Stripe's hosted invoice page do not apply to payments processed outside Stripe. * Stripe's automatic recovery emails do not apply either; customer communications are yours, as covered below. * Refunds are executed through Primer and reported to Stripe. Disputes are managed with the processor that handled the payment, supported by Primer's [Dispute Webhooks](/docs/disputes/manage-disputes). * Only subscription invoices can be collected this way. One-off invoices can still be created in Stripe but not collected through Primer. * Stripe Billing fees apply to billing volume including payments processed outside Stripe. Confirm the treatment on your plan with Stripe. ## How it works When using Stripe Billing with Primer, the plan catalogue and live subscription state is kept in Stripe Billing and the payment processing layer is kept on Primer. Stripe supports this natively for payments processed outside Stripe, built on two objects: * **Custom payment methods.** A Stripe object that references a payment method held outside Stripe. The Primer token reference is stored in its metadata, and it works with automatically charged subscriptions, so Stripe continues to drive the billing cycle and signals when to collect. * **Payment records.** How each Primer-processed outcome is reported back to Stripe, keeping invoices and subscription states accurate. ### Prerequisites * A Primer account with at least one processor connected and a Workflow configured. See [Connect a processor](/docs/get-started/connect-a-processor). * A Primer API key with the `client_tokens:write` and `transactions:authorize` scopes. See [Authentication](/docs/api-reference/get-started/authentication). * A Stripe account with Stripe Billing and [third-party payment processing](https://docs.stripe.com/billing/subscriptions/third-party-payment-processing) enabled. Request access from your Stripe account team, and confirm that your business country is [supported](https://docs.stripe.com/billing/subscriptions/third-party-payment-processing#supported-countries). ### Configure Stripe In the Stripe Dashboard: 1. Create a [custom payment method type](https://dashboard.stripe.com/settings/custom_payment_methods) to represent payment methods processed by Primer. Store its ID in your configuration, because custom payment method types can't be retrieved through the Stripe API. 2. Register a webhook endpoint and subscribe it to `invoice.payment_attempt_required`, `invoice.updated`, and `invoice.payment_failed`. 3. Configure your retry schedule, either in your [revenue recovery retry settings](https://dashboard.stripe.com/revenue-recovery/retries) or with [Billing automations](https://docs.stripe.com/billing/automations). See [Renewals and decline-aware retries](#renewals-and-decline-aware-retries). ### Sign-Up and first payment ```mermaid theme={"dark"} sequenceDiagram participant C as Customer participant M as Merchant backend participant S as Stripe Billing participant P as Primer participant X as PSP C->>M: Selects a plan M->>S: Create customer + subscription (payment_behavior: default_incomplete) S-->>M: Subscription incomplete + open invoice (amount includes tax and proration) M->>P: Create client session (amount = invoice due, vault on success) C->>P: Pays via Primer Checkout (CIT) P->>X: Authorise + capture X-->>P: Approved P-->>M: Success + vaulted token M->>S: Create custom payment method, set as default (Primer token reference in metadata) M->>S: Report payment, attach to invoice Note over S: Invoice paid, subscription active ``` *Figure 1. Sign-Up and first payment: Stripe raises the invoice, Primer collects, the result is reported back.* The customer and subscription are created first because the chargeable amount comes from Stripe's invoice (tax, proration). The customer then pays through Primer Checkout, the payment method is vaulted, and a custom payment method carrying the Primer token reference is attached to the customer and set as the subscription default. Reporting the payment marks the invoice paid and activates the subscription. #### Create the subscription in Stripe Create the customer and subscription in Stripe as you do today, with `payment_behavior` set to `default_incomplete`. Expand `latest_invoice` to get the amount to charge, which includes tax, discounts, and proration. ```bash Create the subscription theme={"dark"} curl https://api.stripe.com/v1/subscriptions \ -u ":" \ -d customer="" \ -d "items[0][price]"="" \ -d payment_behavior=default_incomplete \ -d "expand[0]"=latest_invoice ``` The subscription is now `incomplete`, with an open invoice. Keep the subscription ID, the invoice ID, and the invoice's `amount_due` and `currency` for the next step. > [!WARNING] > > Report the first payment within 23 hours of creating the subscription. Otherwise, the subscription moves to `incomplete_expired` and you need to create it again. #### Collect the first payment with Primer Create a client session for the invoice amount with `vaultOnSuccess` enabled, then render Primer Checkout with the returned client token. ```bash Create a client session theme={"dark"} curl -X POST 'https://api.sandbox.primer.io/client-session' \ --header 'X-Api-Key: ' \ --header 'X-Api-Version: 2.4' \ --header 'Content-Type: application/json' \ --data '{ "orderId": "", "customerId": "", "amount": , "currencyCode": "USD", "paymentMethod": { "paymentType": "FIRST_PAYMENT", "vaultOnSuccess": true }, "metadata": { "stripeSubscriptionId": "", "stripeInvoiceId": "" } }' ``` > [!NOTE] > > Stripe and Primer both express amounts in minor units, so you can pass `amount_due` unchanged. Stripe returns currency codes in lowercase, and Primer expects uppercase ISO 4217 codes. #### Link the payment method and report the payment When the first payment succeeds, retrieve the customer's vaulted payment method token from Primer with `GET /payment-instruments`. Then, in Stripe: 1. Create a custom payment method that stores the Primer token in its metadata. 2. Attach it to the customer and set it as the subscription's default payment method. 3. Report the payment and attach the payment record to the invoice. ```javascript Link and report the first payment theme={"dark"} // primerPayment: the successful Primer payment for the first invoice // primerToken: the vaulted payment method token from GET /payment-instruments const paymentMethod = await stripe.paymentMethods.create({ type: 'custom', custom: { type: process.env.STRIPE_CUSTOM_PAYMENT_METHOD_TYPE_ID }, metadata: { primer_payment_method_token: primerToken }, }); await stripe.paymentMethods.attach(paymentMethod.id, { customer: stripeCustomerId }); await stripe.subscriptions.update(subscriptionId, { default_payment_method: paymentMethod.id, }); const now = Math.floor(Date.now() / 1000); const paymentRecord = await stripe.paymentRecords.reportPayment({ amount_requested: { value: invoice.amount_due, currency: invoice.currency }, payment_method_details: { payment_method: paymentMethod.id }, customer_details: { customer: stripeCustomerId }, initiated_at: now, customer_presence: 'on_session', processor_details: { type: 'custom', custom: { payment_reference: primerPayment.id } }, outcome: 'guaranteed', guaranteed: { guaranteed_at: now }, }); await stripe.invoices.attachPayment(invoice.id, { payment_record: paymentRecord.id }); ``` Attaching the payment record marks the invoice as paid and moves the subscription to `active`. > [!NOTE] > > **Good to know** > > * The first payment is initiated by your backend with no webhook prompt. Renewal webhooks begin from the first renewal onward. > * Report the first payment within 23 hours of creating the subscription, or the subscription expires as incomplete. > * If the first payment fails, there will be an open invoice for the customer, and you should retry charging the customer. > * For every invoice, Stripe creates a default PaymentIntent and cancels it when you report a payment record. The canceled PaymentIntent appears next to your reported payment and doesn't affect the invoice or subscription status. Webhooks events for these events can be ignored entirely ### Renewals and decline-aware retries ```mermaid theme={"dark"} sequenceDiagram participant S as Stripe Billing participant M as Merchant backend participant P as Primer participant X as PSPs S->>M: Webhook: invoice.payment_attempt_required M->>P: MIT payment with vaulted token (paymentType: SUBSCRIPTION) P->>X: Route per workflow (network tokens, fallback) X-->>P: Result P-->>M: Approved or declined, with decline code alt Approved M->>S: Report payment: invoice paid else Declined M->>S: Report attempt failed Note over S: Retry policy schedules the next attempt loop Each scheduled retry S->>M: Webhook: invoice.payment_attempt_required Note over M: Apply your retry logic M->>P: MIT payment with vaulted token (paymentType: SUBSCRIPTION) P-->>M: Approved or declined M->>S: Report attempt against the same payment record end Note over S: Schedule exhausted, final state end ``` *Figure 2. Renewals: every attempt is executed by Primer and every retry is gated by your decline classification.* Retry scheduling uses Stripe Billing Automations, configured in your Dashboard. Because the decline detail comes from the processor through Primer, your backend supplies that context: before reporting a failed attempt, it stamps the invoice metadata with the decline classification derived from Primer's decline code. > [!NOTE] > > **Why this matters for retries** > > Stripe Billing schedules each retry, and your backend decides whether to execute it, informed by the decline code Primer returns. Hard declines can be stopped after a single attempt; soft declines follow the retry policy you configure in Stripe. * **Hard declines** (stolen card, closed account): the automation cancels the subscription or marks the invoice as `uncollectible`. * **Soft declines** (insufficient funds, temporary issuer errors): the automation attaches your retry policy, for example day 2, day 5, day 8. Each scheduled attempt arrives as a webhook, and execution still sits with you and Primer, so later attempts can be routed to a different processor. Attempts beyond the schedule are also possible at any time: charge through Primer and report the attempt against the same payment record, which keeps one consolidated attempt history per invoice. You can also build your own retry logic on your backend that reads these metadata values, instead of or alongside the Dashboard automations. You have full flexibility on when these retries are done with your own logic. > [!NOTE] > > **Key design point** > > Stripe's Smart Retries is not currently supported for custom payment methods (a Stripe limitation), so retries follow a prescribed policy, set globally or on an automation (the automation takes precedence where it applies). Combined with the decline classification above, issuers and schemes only see attempts with a realistic chance of succeeding. #### Handle renewals When Stripe finalises a renewal invoice, it sends `invoice.payment_attempt_required`. Your webhook handler creates a merchant-initiated payment through Primer with the vaulted token and `paymentType` set to `SUBSCRIPTION`, then reports the outcome to Stripe. ```javascript Handle invoice.payment_attempt_required theme={"dark"} async function collectInvoice(invoice) { if (invoice.amount_remaining <= 0) return; // The subscription's default payment method is the custom payment method created at signup const paymentMethod = await stripe.paymentMethods.retrieve(defaultPaymentMethodId); const response = await fetch('https://api.sandbox.primer.io/payments', { method: 'POST', headers: { 'X-Api-Key': process.env.PRIMER_API_KEY, 'X-Api-Version': '2.4', 'X-Idempotency-Key': `${invoice.id}-${invoice.attempt_count}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ orderId: invoice.id, amount: invoice.amount_remaining, currencyCode: invoice.currency.toUpperCase(), paymentMethodToken: paymentMethod.metadata.primer_payment_method_token, paymentMethod: { paymentType: 'SUBSCRIPTION' }, }), }); const payment = await response.json(); await reportOutcome(invoice, paymentMethod, payment); } ``` > [!NOTE] > > If Primer returns the payment as `PENDING`, wait for the `PAYMENT.STATUS` webhook with the final status before you report the outcome to Stripe. See [Configure webhooks](/docs/api-reference/get-started/configure-webhooks). Primer runs the payment through your Workflow, which selects the processor and applies any fallbacks you've configured. Use the invoice ID and attempt count as the idempotency key so that a redelivered webhook doesn't create a second payment. See [Avoid duplicated payments](/docs/get-started/recurring-payments#avoid-duplicated-payments). #### Report retries against the payment record When you report a failed attempt, the invoice stays open and the subscription moves to `past_due`. Stripe then schedules the next attempt according to your retry settings, and sends a new `invoice.payment_attempt_required` event for each one. Report every retry against the existing payment record with `reportPaymentAttempt`, rather than creating a new record with `reportPayment`. This keeps a single payment with a consolidated attempt history on the invoice. ```javascript Report the outcome of an attempt theme={"dark"} async function reportOutcome(invoice, paymentMethod, payment) { const now = Math.floor(Date.now() / 1000); const succeeded = ['AUTHORIZED', 'SETTLING', 'SETTLED'].includes(payment.status); const outcome = succeeded ? { outcome: 'guaranteed', guaranteed: { guaranteed_at: now } } : { outcome: 'failed', failed: { failed_at: now } }; const existing = await stripe.invoicePayments.list({ invoice: invoice.id, payment: { type: 'payment_record' }, }); if (existing.data.length > 0) { await stripe.paymentRecords.reportPaymentAttempt(existing.data[0].payment.payment_record, { initiated_at: now, payment_method_details: { payment_method: paymentMethod.id }, ...outcome, }); return; } const paymentRecord = await stripe.paymentRecords.reportPayment({ amount_requested: { value: invoice.amount_remaining, currency: invoice.currency }, payment_method_details: { payment_method: paymentMethod.id }, customer_details: { customer: invoice.customer }, initiated_at: now, customer_presence: 'off_session', processor_details: { type: 'custom', custom: { payment_reference: payment.id } }, ...outcome, }); await stripe.invoices.attachPayment(invoice.id, { payment_record: paymentRecord.id }); } ``` #### Detect the final attempt With standard retry settings, failures arrive as `invoice.payment_failed`. When automations control retries, `next_payment_attempt` is updated through `invoice.updated`, so handle both events. There is no dedicated event for an exhausted schedule so you should treat a failure-related invoice update with no remaining `next_payment_attempt`, together with the resulting subscription state, as the final signal. ### Dunning and payment method recovery Failed-payment emails and card-update prompts are owned by your systems, driven by the same webhooks. When a stored credential is no longer usable after a hard decline, recovery is a customer-present journey: bring the customer back, take a fresh payment through Primer Checkout, vault the new token, and attach a new custom payment method in Stripe. Stripe's customer portal continues to work for plan changes and cancellations on these subscriptions. With automations enabled, read the next scheduled attempt time from `invoice.updated` events. #### Update the customer's payment method 1. Bring the customer back to a payment page and collect the new payment method with Primer Checkout, with `vaultOnSuccess` enabled. 2. Create a new custom payment method with the new Primer token, and set it as the subscription's default payment method. 3. If an invoice is still open, charge it through Primer and report the attempt against its payment record. > [!WARNING] > > The Stripe customer portal lets customers switch to a Stripe-supported payment method. Renewals on a Stripe payment method are processed by Stripe, not Primer. To keep every payment on Primer, turn off payment method updates in your portal configuration and handle card updates in your own flow. ### Refunds Refund the payment through Primer, with the API or the Dashboard. Then report the refund to the payment record in Stripe, and create a credit note to adjust the invoice. Both full and partial refunds are supported. ```javascript Report a refund to Stripe theme={"dark"} const refund = await stripe.paymentRecords.reportRefund(paymentRecordId, { processor_details: { type: 'custom', custom: { refund_reference: primerRefundReference } }, outcome: 'refunded', refunded: { refunded_at: Math.floor(Date.now() / 1000) }, }); await stripe.creditNotes.create({ invoice: invoiceId, refunds: [{ type: 'payment_record_refund', payment_record_refund: { payment_record: paymentRecordId, refund_group: primerRefundReference }, }], }); ``` Disputes are handled with the processor that processed the payment, and can't be managed in Stripe. ### Who owns what | Stripe Billing | Your team | Primer | | - | - | - | | Plans, subscriptions, invoices, tax and proration, lifecycle states, retry scheduling via Automations | Webhook handling, payment creation, decline classification, reporting back, dunning communications, recovery journeys | Payment execution, vault and network tokens, recurring credential context, routing and fallbacks, decline codes, integration support | ## Integration checklist | Step | Where | What to build | | - | - | - | | 1 | Stripe Dashboard | Create the custom payment method type and store its identifier in configuration. | | 2 | Stripe Dashboard | Configure the two payment-failure automations (hard decline cancels, soft decline applies your retry policy). | | 3 | Stripe Dashboard | Register your webhook endpoint and subscribe to `invoice.payment_attempt_required` and `invoice.updated`. | | 4 | Your backend | Your backend: create the customer and subscription with an incomplete first invoice. | | 5 | Your frontend and backend | Create a Primer client session for the invoice amount and take the first payment through Primer Checkout with vaulting enabled. | | 6 | Your backend | Create the custom payment method with the Primer token reference, attach it, and set it as the subscription default. | | 7 | Your backend | Report the first payment and attach it to the invoice within 23 hours. | | 8 | Your backend | Handle the renewal webhook from Stripe and create merchant-initiated payments through Primer with `paymentType` `SUBSCRIPTION`. | | 9 | Your backend | Classify declines, stamp the invoice metadata, and report attempts against the payment record. | | 10 | Your backend | Execute refunds through Primer and report them to Stripe with a credit note. | | 11 | Your backend | Handle failed-payment emails to customers and the card-update journey through Primer Checkout. | ## Testing in sandbox Stripe test clocks cover sign up and renewals. For testing successful subsequent payments, you need to advance the test clock and ensure that the payment will succeed. On dunning attempts, where a subsequent payment fails and triggers retry Automation on Stripe's end, for the most production-representative validation, run a subscription without a test clock on a short custom retry schedule and let it elapse in real time. In our testing, a webhook handler triggered by one test clock advance was still updating an invoice when a second advance started, and its next invoice update failed with HTTP `429` and the message `Test clock advancement underway`. Before you advance a clock again, wait until your webhook handlers have finished processing the events from the previous advance. Also wait for the clock's `status` to be `ready`: poll the clock, or listen for the `test_helpers.test_clock.ready` event. > [!TIP] > > When you advance a test clock directly past `invoice.next_payment_attempt`, the retry webhook may not be sent immediately. Once the clock is `ready`, advance it again by a small increment, such as one minute, to trigger the pending attempt. ## Reference documentation * [Stripe, integrate with third-party payment processors](https://docs.stripe.com/billing/subscriptions/third-party-payment-processing) * [Stripe, Billing automations](https://docs.stripe.com/billing/automations) * [Primer documentation (payments API, client sessions, vaulting, webhooks)](https://primer.io/docs) # Testing 3d-secure Source: https://primer.io/docs/testing/3d-secure This page explains how to test 3D Secure flows in sandbox. You can test: * 3DS outcomes only using network test cards * Full end to end flows using processor specific test cards ## 1. Testing 3DS outcomes only Use the cards below to simulate 3DS behavior regardless of the processor. These cards are handled directly by our 3DS provider. > [!WARNING] > > **Sandbox limitation (effective March 2, 2026):** > > When a challenge is mandated via the challenge indicator, our sandbox environment will always trigger a challenge flow, regardless of the test card used. > > To test frictionless scenarios, use the **Perform 3DS** action *without* a mandate challenge indicator. ### Visa | Scenario | Platform | Card number | CVV | Expiry date | | - | - | - | - | - | | Manual Challenge | Web | 4916994064252017 | Any 3 digit number | Any future expiry date | | Manual Challenge | iOS & Android | 4000000000000051 | Any 3 digit number | Any future expiry date | | Frictionless Successful | Web | 4929251897047956 | Any 3 digit number | Any future expiry date | | Frictionless Unsuccessful | Web | 4716429323842524 | Any 3 digit number | Any future expiry date | | Frictionless Successful | iOS & Android | 4000000000000010 | Any 3 digit number | Any future expiry date | | Frictionless Unsuccessful | iOS & Android | 4000000000000044 | Any 3 digit number | Any future expiry date | ### Mastercard | Scenario | Platform | Card number | CVV | Expiry date | | - | - | - | - | - | | Manual Challenge | Web | 5306889942833340 | Any 3 digit number | Any future expiry date | | Manual Challenge | iOS & Android | 5267648608924299 | Any 3 digit number | Any future expiry date | | Frictionless Successful | Web | 5512459816707531 | Any 3 digit number | Any future expiry date | | Frictionless Unsuccessful | Web | 5487971631330522 | Any 3 digit number | Any future expiry date | | Frictionless Successful | iOS & Android | 5333259155643223 | Any 3 digit number | Any future expiry date | | Frictionless Unsuccessful | iOS & Android | 5328720384582224 | Any 3 digit number | Any future expiry date | ### Amex | Scenario | Platform | Card number | CVV | Expiry date | | - | - | - | - | - | | Manual Challenge | Web | 348638267931507 | Any 3 digit number | Any future expiry date | | Manual Challenge | iOS & Android | 349531373081938 | Any 3 digit number | Any future expiry date | | Frictionless Successful | Web | 347899129656655 | Any 3 digit number | Any future expiry date | | Frictionless Unsuccessful | Web | 345197771649926 | Any 3 digit number | Any future expiry date | | Frictionless Successful | iOS & Android | 341502098634895 | Any 3 digit number | Any future expiry date | | Frictionless Unsuccessful | iOS & Android | 345695399207589 | Any 3 digit number | Any future expiry date | ### Cartes Bancaires | Scenario | Platform | Card number | CVV | Expiry date | | - | - | - | - | - | | Manual Challenge | Web | 5070000000000020 | Any 3 digit number | Any future expiry date | | Manual Challenge | iOS & Android | 5070000000000053 | Any 3 digit number | Any future expiry date | | Frictionless Successful | Web | 5070000000000087 | Any 3 digit number | Any future expiry date | | Frictionless Unsuccessful | Web | 5070000000000095 | Any 3 digit number | Any future expiry date | | Frictionless Successful | iOS & Android | 5070000000000012 | Any 3 digit number | Any future expiry date | | Frictionless Unsuccessful | iOS & Android | 5070000000000046 | Any 3 digit number | Any future expiry date | ## 2. Challenge behavior When a challenge is triggered, the challenge screen asks for a one time passcode. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/testing/testing-3d-secure/3ds-challenge.png) Challenge Screen The value entered controls the authentication result. | Code | Result | Reason code | Description | | - | - | - | - | | 1234 | AUTH\_SUCCESS | - | Authentication successful | | 1111 | AUTH\_FAILED | CARD\_AUTHENTICATION\_FAILED | Authentication failed | | 2222 | AUTH\_FAILED | CARD\_AUTHENTICATION\_FAILED | Authentication failed | | 3333 | SKIPPED | UNKNOWN\_ACS\_RESPONSE | Unknown ACS response | | 4444 | AUTH\_SUCCESS | - | Authentication successful | ## 3. Testing full end to end flows with processors Some processors only accept a restricted list of card numbers. For these cases, you must use processor specific test cards that also trigger 3DS. These cards allow you to test: * Payment acceptance by the processor * 3DS challenge flow * Final authorization result Important: * These cards are processor specific * Results may differ from network test cards * Use them only when testing full integration ### Processor specific 3DS cards Common rules: * Expiry date: any future date unless specified * CVV: any valid value unless specified | Processor | Networks | Card number | Expiry | CVV | | - | - | - | - | - | | Worldpay | EFTPOS, Visa | 4434020000000006 | Any future | 555 | | Worldpay | Cartes Bancaires, Mastercard | 5131072454408923 | Any future | 555 | | Worldline SIPs | Cartes Bancaires | 5017679210000700 | Any future | Any 3 digit number | | Worldline Direct | Cartes Bancaires, Visa Debit | 4010061372166100 | Any future | Any 3 digit number | | Worldline | Visa | 4874970686672022 | Any future | Any 3 digit number | | Worldline | Mastercard | 5130257474533310 | Any future | Any 3 digit number | | Worldline | Amex | 379764422997381 | Any future | Any 3 digit number | | Stripe | EFTPOS, Mastercard | 5555050360000080 | Any future | Any 3 digit number | | Stripe | Cartes Bancaires, Visa | 4000002500001001 | Any future | Any 3 digit number | | Payplug | Cartes Bancaires, Visa Debit | 4234601857080001 | Any future | Any 3 digit number | | JPMC | Cartes Bancaires, Visa | 4978743800000007 | Any future | Any 3 digit number | | JPMC | Cartes Bancaires, Mastercard | 5498580000000009 | Any future | Any 3 digit number | | CKO | Cartes Bancaires, Mastercard | 5137210000000158 | Any future | Any 3 digit number | | Adyen | EFTPOS | 4687380100010006 | Mar-30 | 737 | | Adyen | Cartes Bancaires, Visa Debit | 4035501428146300 | Mar-30 | 737 | # Testing Fallbacks Source: https://primer.io/docs/testing/fallbacks To test fallbacks, you need: * a test card that will decline or fail with your primary processor under one of the conditions outlined above * a fallback processor that will authorize the payment based on the test card used to decline or fail with the first processor ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/testing/testing-fallbacks/fallback-configuration.png) Example fallback configuration > [!WARNING] > > If the fallback processor doesn't accept the test card, the payment will be declined and you'll see both authorization requests declined in the payment details page. ### Primer test processor In sandbox, set the Primer test processor as the primary processor and an alternative processor as the fallback processor, such as Braintree, Stripe or Worldpay. Failed and declined authorization Use the following test cards to simulate a failed or declined authorization. Use any 3-digit CVV and future expiry date to trigger the test scenario. | Scenario | Card Network | Card Number | | - | - | - | | Generic decline | Visa | 4000 0000 0000 0002 | | Generic decline | Mastercard | 5100 0000 0000 0008 | | Generic fail | Visa | 4000 0000 0000 0010 | | Generic fail | Mastercard | 5100 0000 0000 0016 | Using one of Primer's test cards for generic decline and fail authorizations above, the authorization request will decline or fail (depending on the card used) and trigger a fallback. The fallback authorization request should then be sent and be authorized. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/testing/testing-fallbacks/fallback-primer-test-processor.png) Example test fallback with Primer test processor ### Other sandbox processors It's possible to test fallbacks without using the Primer test processor. You will need to review the testing guides for your processors and ensure: * you can decline or fail a payment with your primary processor for the conditions outlined above * the test card or test scenario can lead to a successful authorization request with your fallback processor See below for some example processors and how to test fallbacks using them. #### Braintree Braintree enable [authorization responses to be determined by the authorization amount](https://developer.paypal.com/braintree/docs/reference/general/testing#transaction-amounts). You can test fallbacks using Braintree as your primary processor. > [!NOTE] > > If the amount is set to 3000.00-3000.99, then this will trigger a fallback. Set Braintree as the primary processor and configure your fallback processor. Then, create a test payment with the amount set to 3000.00-3000.99 and use any test card from your fallback processor that will result in an authorized payment. The authorization will decline and trigger a fallback. The fallback request should then be sent and be authorized. > [!NOTE] > > You can test fallbacks with 3DS using Braintree as your primary processor as the authorization response is determined by the amount, not the test card. You will also need a fallback processor, such as the Primer test processor, that will accept [Primer's 3DS test card](/docs/testing/3d-secure#new-test-card-values) which is required to trigger 3DS in sandbox. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/testing/testing-fallbacks/fallback-3ds-test.png) Example test fallback with 3DS #### Worldpay Worldpay enable [authorization responses to be determined by the cardholder name](https://developer.worldpay.com/docs/access-worldpay/testing/payments-test-values#issuer-response-test-values). You can test fallbacks using Worldpay as your primary processor. > [!NOTE] > > If the cardholder name is set to "ERROR", then this will trigger a fallback. Set Worldpay as the primary processor and configure your fallback processor. Then, create a test payment with the cardholder name set to "ERROR" and use any test card from your fallback processor that will result in an authorized payment. The authorization will decline and trigger a fallback. The fallback request should then be sent and be authorized. > [!NOTE] > > You can test fallbacks with 3DS using Worldpay as your primary processor as the authorization response is determined by the cardholder name, not the test card. You will also need a fallback processor, such as the Primer test processor, that will accept [Primer's 3DS test card](/docs/testing/3d-secure) which is required to trigger 3DS in sandbox. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/testing/testing-fallbacks/fallback-3ds-test-worldpay-nuvei.png) Example test fallback with 3DS using Worldpay as primary processor and Nuvei as fallback processor #### Stripe Stripe enable [authorization responses to be determined by the card number](https://stripe.com/docs/testing#declined-payments). You can test fallbacks using Stripe as your primary processor. > [!NOTE] > > If the card number is set to `4000000000000119`, then this will trigger a fallback. Set Stripe as the primary processor and configure your fallback processor. Then, create a test payment with the card number `4000000000000119` and ensure this card will result in an authorized payment with your fallback processor. The authorization will decline and trigger a fallback. The fallback request should then be sent and be authorized. ![](https://goat-assets.production.core.primer.io/marketing/external-docs/getting-started/testing/testing-fallbacks/fallback-3ds-test-stripe-nuvei.png) Example test fallback with 3DS using Worldpay as primary processor and Nuvei as fallback processor > [!NOTE] > > You can't test fallbacks with 3DS using Stripe as your primary processor as the authorization response is determined by the card number. This clashes with [Primer's 3DS test card](/docs/testing/3d-secure) which is required to trigger 3DS in sandbox. # Testing Fraud Checks Source: https://primer.io/docs/testing/fraud-checks ## To test fraud checks in sandbox, you will need to pass the right data to trigger the specific fraud check outcome you want to test. This will vary per fraud detection provider so ensure you check their documentation and our [fraud provider specific documentation](/docs/connections/fraud-providers/overview) on what needs passing. # Testing Network Tokens Source: https://primer.io/docs/testing/network-tokenization > [!NOTE] > > Before testing network tokens in sandbox, make sure your account is fully enrolled to network tokenization. > > Speak to your Customer Success Manager or raise a ticket on our [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11). If you don't have access, please contact your account administrator for assistance. > [!WARNING] > > Visa's testing environment is frequently reset, which makes testing Visa network tokens extremely unreliable. > > As a result, testing Visa network tokenization is not available on Primer sandbox. We encourage you to only test Mastercard network tokenization in sandbox, and to test Visa network tokenization in production. ### Provisioning network tokens > [!NOTE] > > On sandbox, Primer attempts to provision a network token whenever a card is added to the vault of a customer ID starting with `primer-nt-testing`. The best way to vault a card is to use Universal Checkout. Make sure to call POST with a ["customerId"](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#body-customer-id) and ["vaultOnSuccess"](/docs/api-reference/v2.4/api-reference/client-session-api/create-a-client-session#response-payment-method-vault-on-success) set to `true`. This automatically vaults the card if the payment is successfully authorized. This first payment is processed using the raw card data. Once vaulted, it usually takes a few seconds for the network token to be provisioned and available for subsequent payments. Use the following test cards to simulate scenarios: | Scenario | Card Network | Card Number | CVV | Expiry date | | - | - | - | - | - | | Eligible card | Mastercard | 2222 6904 2006 4590 | Any 3 digit number | Any future expiry date | | Eligible card | Mastercard | 2222 6904 2006 4574 | Any 3 digit number | Any future expiry date | | Eligible card | Mastercard | 2222 6904 2006 4590 | Any 3 digit number | Any future expiry date | | Eligible card | Mastercard | 5120 3501 0006 4594 | Any 3 digit number | Any future expiry date | | Non-eligible card | Mastercard | 5460 1261 2820 0800 | Any 3 digit number | Any future expiry date | To validate that the card was properly network tokenized, call GET to list the saved payment methods for a specific `customerId`. The field ["paymentMethod.isNetworkTokenized"](/docs/api-reference/v2.4/api-reference/payment-methods-api/list-saved-payment-methods#response.body.data.paymentMethodData.Payment%20Card%20Token%20API%20Schema.isNetworkTokenized) is set to `true` when the network token was successfully provisioned and attached to the vaulted card. ### Processing payments with network tokens When a payment is created with a vaulted card that has been network tokenized, Primer automatically attempts to pass the network token to the processor, if the processor is supported. You can test this by creating a payment with: * the Payments API by following this [guide](/docs/payment-services/save-payment-methods#create-merchant-initiated-payments) * or with the vault section of Universal Checkout, by selecting a vaulted card that was network tokenized To validate that the payment used a network token, call GET with the payment ID to retrieve the payment object. The field ["cardTokenType"](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment#response.body.cardTokenType) is set to: * `NETWORK_TOKEN` if the payment was processed with a network token * `CARD_PAN` if the payment was processed with the raw credentials # Overview Source: https://primer.io/docs/testing/overview ## Test your entire payment flow Use Primer’s testing tools to simulate real payment scenarios and validate your setup before going live. ![Test your entire payment flow](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/testing/banner/light.png) ![Primer Sandbox Processor](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/testing/primer-sandbox-processor.png) ## [Primer Sandbox Processor](/docs/testing/primer-sandbox-processor) Simulate and validate payment workflows with the Primer Sandbox Processor. ## Test cases > [card] [Testing 3D Secure](/docs/testing/3d-secure) > > Verify 3D Secure authentication flows and edge cases in sandbox mode. > [card] [Testing Fallbacks](/docs/testing/fallbacks) > > Test fallback scenarios when primary authentication methods are unavailable. > [card] [Testing Fraud Checks](/docs/testing/fraud-checks) > > Ensure fraud detection rules and risk checks trigger correctly in sandbox. > [card] [Testing Network Tokens](/docs/testing/network-tokenization) > > Validate network tokenization behaviors and token lifecycle events. # Primer Sandbox Processor Source: https://primer.io/docs/testing/primer-sandbox-processor Primer provides a Sandbox Processor that can be used in the Sandbox environment to make test payments and validate your integration. This processor comes with: * a set of test card numbers to trigger various scenarios * a set of mocked payment methods to create your first payments on the checkout > [!WARNING] > > Keep in mind: > > * For PCI-compliance reasons, only test card numbers are allowed in Sandbox. A payment will fail if a non-test card number is used. > * No error will be raised in production for using a test card number > * Sandbox is intended for functional testing of your integration, such as verifying payment flows and how your system handles declines and errors. It is offered under fair use and is not a load-testing environment. To keep Sandbox available to everyone, requests may be rate limited. ### Test card payments For test card payments, you can use the following test cards to simulate scenarios: Successful authorization Use the following test cards to simulate a successful authorization. | Card Network | Card Number | CVV | Expiry date | Account Funding Type | | - | - | - | - | - | | Visa | 4111 1111 1111 1111 | Any 3 digit number | Any future expiry date | Debit | | Visa | 4242 4242 4242 4242 | Any 3 digit number | Any future expiry date | Credit | | Mastercard | 5252 5252 5252 5258 | Any 3 digit number | Any future expiry date | Debit | | Mastercard | 5555 5555 5555 4444 | Any 3 digit number | Any future expiry date | Credit | | Visa / Cartes Bancaires | 4035 5000 0000 0000 | Any 3 digit number | Any future expiry date | | | Mastercard / Cartes Bancaires | 5132 0000 0000 0000 | Any 3 digit number | Any future expiry date | | | Cartes Bancaires | 4970 0000 0000 0008 | Any 3 digit number | Any future expiry date | | Failed and declined authorization \ Use the following test cards to simulate a failed or declined authorization. | Scenario | Card Network | Card Number | | - | - | - | | Generic decline | Visa | 4000 0000 0000 0002 | | Generic decline | Mastercard | 5100 0000 0000 0008 | | Generic fail | Visa | 4000 0000 0000 0010 | | Generic fail | Mastercard | 5100 0000 0000 0016 | ### Test mocked payment methods The Primer Sandbox Processor bundles a mocked version of PayPal, Sofort and Klarna. For each of these payment methods, you can trigger the desired outcome of the "Authorization" using the Drop-In Checkout. ![](https://mintcdn.com/primer-cc826789/kh8YlCAXTDnCrMxk/images/getting-started/testing/pm_cards_web_ui.png?fit=max\&auto=format\&n=kh8YlCAXTDnCrMxk\&q=85\&s=54f046c7aec9c61c7991768d0bbc8c5e) ![](https://mintcdn.com/primer-cc826789/kh8YlCAXTDnCrMxk/images/getting-started/testing/dummy_apm.png?fit=max\&auto=format\&n=kh8YlCAXTDnCrMxk\&q=85\&s=0fa606a6b069f3f6fbb840d360696eaf) Testing PM Cards Web UI # After the payment Source: https://primer.io/docs/vault/after-the-payment > [!NOTE] > > This feature is not available on all Primer accounts. Contact your Customer Success Manager to receive access. What happens once a payment has gone through: saving the card, charging it again without the customer present, and growing from a vault-only integration into Primer orchestration. ## Save and reuse cards Vault the card when you [report the outcome](/docs/vault/during-the-payment#report-the-outcome), by setting `vaultPaymentMethod: true` on the `resolve` call: ```bash theme={"dark"} curl -X POST https://api.primer.io/payment-attempts/{paymentAttemptId}/resolve \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "outcome": "SUCCEEDED", "vaultPaymentMethod": true }' ``` This is opt-in per payment: Primer doesn't see the result of a proxied payment, so nothing is saved unless you say so in this call, and only once the outcome is `SUCCEEDED`. Primer returns a saved (multi-use) token, distinct from the single-use token the attempt started with. Store that token against the customer; it's what you use for [a saved card in the checkout](#a-returning-customer-in-the-checkout) and for [charging the card later](#charge-a-saved-card-without-the-customer). ### A returning customer in the checkout Create the client session with the same `customerId` as before. The checkout shows the customer's saved card (network and last four digits); they pick it and click Pay, with or without re-entering the CVV, depending on whether you've enabled recapture. The SDK creates a new single-use token from the saved card for this payment (the saved card itself isn't consumed), and the flow continues exactly as in [During the payment](/docs/vault/during-the-payment): your backend decides whether to approve or send the new token to the proxy. ### CVV recapture PCI rules mean Primer never stores a card's CVV, so a saved token has no `CVV` field available. See [Proxy reference](/docs/vault/reference#proxy-reference). A returning customer can still supply a fresh CVV at checkout if you enable [CVV recapture](/docs/payment-services/save-payment-methods#recapture-the-cvv-of-saved-cards): the SDK exchanges it for a single-use token that carries the CVV like any other, which you can then send through the proxy with the `CVV` placeholder. ## Charge a saved card without the customer For a merchant-initiated payment, such as a subscription charge, there's no checkout and no client session. Your backend calls the proxy directly with the saved token, the same way it would call your PSP directly today. ```bash theme={"dark"} curl -X POST https://proxy.primer.io/v1/payment_intents \ -H "X-Primer-Api-Key: YOUR_API_KEY" \ -H "X-Target-Host: api.stripe.com" \ -H "Authorization: Bearer YOUR_PSP_SECRET_KEY" \ -d "amount=1000&off_session=true&confirm=true&card[number]={{tok_saved_789.CARD_NUMBER}}&card[exp_month]={{tok_saved_789.EXPIRY_MONTH}}&card[exp_year]={{tok_saved_789.EXPIRY_YEAR}}" ``` Set whatever flag your PSP uses to mark the request as merchant-initiated (`off_session` and `confirm` for Stripe above), exactly as you would calling them without Primer. There's no `CVV` placeholder available on a saved token; most PSPs don't require it for a card already on file. > [!NOTE] > > The **network transaction ID (NTID)** and, for Mastercard, the **Transaction Link ID (TLID)** that some PSPs return from the first payment on a card, and expect on later merchant-initiated payments, aren't stored by Primer Vault yet. If your PSP requires them for recurring authorization, keep tracking them yourself for now rather than relying on Primer to carry them forward. See [Mastercard Transaction Link ID (TLID)](/docs/get-started/recurring-payments#mastercard-transaction-link-id-tlid) for what the TLID is and why Mastercard requires it. If you also use Primer for orchestration (a processor connected and a workflow set up), the same saved token works with [`POST /payments`](/docs/api-reference/v2.4/api-reference/payments-api/create-a-payment) instead of the proxy, so Primer runs the payment's full lifecycle, including retries: ```bash theme={"dark"} curl -X POST https://api.primer.io/payments \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "orderId": "order-124", "amount": 1000, "currencyCode": "USD", "customerId": "customer-456", "paymentMethodToken": "tok_saved_789", "paymentMethod": { "paymentType": "SUBSCRIPTION" } }' ``` The same token works both ways. Pick whichever one you want for a given payment, and switch for the next one if you need to. ## Move traffic to Primer > [!NOTE] > > This is optional, for merchants who want to grow from a vault-only integration into Primer processing some or all of their payments. Because every payment already runs through the same client session, checkout, and token regardless of where it's processed, moving traffic to Primer is a routing change, not a re-integration: | | Stays the same | Changes | | - | - | - | | **Client session** | `customerId`, `orderId`, amount, currency | Nothing, you're already creating it this way | | **Checkout** | The card form, the approval event | Nothing | | **Your backend** | Nothing | Where you send the decision made in [Decide where the payment goes](/docs/vault/during-the-payment#decide-where-the-payment-goes): call `approve` instead of sending the request through the proxy | | **Primer account** | Nothing | A processor connected and a workflow configured, so there's somewhere for `approve` to route to | A practical way to start is with a share of traffic rather than a full cutover. Pick a rule you already use to decide where payments go (one card network, one issuer country, one customer segment) and route just that slice to `approve` while everything else keeps going through the proxy. Compare the results against what your own PSP was doing, then widen the share once you're satisfied. # During the payment Source: https://primer.io/docs/vault/during-the-payment > [!NOTE] > > This feature is not available on all Primer accounts. Contact your Customer Success Manager to receive access. See [Get started](/docs/vault/get-started) for one-time setup. This page covers everything between creating the client session and showing the customer a result: capturing the card, deciding where the payment goes, calling your PSP through the proxy, handling 3D Secure, and reporting the outcome. For the simplest end-to-end path, see [Your first payment](/docs/vault/get-started#your-first-payment). ## Create the client session Create a [client session](/docs/checkout/client-session) with the vault's approval mode and a `customerId`: ```bash theme={"dark"} curl -X POST https://api.primer.io/client-session \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "orderId": "order-123", "currencyCode": "USD", "amount": 1000, "customerId": "customer-456", "mode": "MANUAL" }' ``` | Field | Required | Description | | - | - | - | | `mode` | Yes | `MANUAL` pauses the flow after the card is tokenized, so your backend can either approve the payment for Primer to process, or take the token to your own PSP. Set at creation only; immutable afterwards. | | `customerId` | **Always**, even for a one-off payment | The token Primer issues is only reusable later if it's attached to a `customerId`. Without it, saving the card for a returning customer or moving to orchestration later means re-tokenizing instead of reusing what you already have. | | `orderId` | Recommended | Your own reference, so you can match a Primer request ID back to your order when something goes wrong. | | `amount`, `currencyCode` | Recommended | Not needed by the proxy itself, but the checkout uses them to show the total, and Primer needs them if you approve the attempt for Primer to process. | ### The decision window Once the customer submits their card, your backend has 15 minutes to either approve the attempt or report an outcome from your own PSP, covering your own checks, the PSP request, and any 3D Secure challenge at your PSP. See [Payment attempt states and decision window](/docs/vault/reference#payment-attempt-states-and-decision-window) for what happens if you miss it. ## Show the checkout and capture the card Render the checkout with the client token from the session: ```html theme={"dark"} ``` The customer sees your usual Primer Checkout card form; there's nothing vault-specific in the UI itself. When they submit the form, the SDK tokenizes the card and waits; no payment is created yet. Register a listener for `primer:payment-approval-required`: ```javascript theme={"dark"} const checkout = document.querySelector('primer-checkout'); checkout.addEventListener('primer:payment-approval-required', async (event) => { const { paymentAttemptId, paymentMethodToken, continueFlow } = event.detail; await fetch('/my-backend/handle-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paymentAttemptId, token: paymentMethodToken.token }), }); await continueFlow(); }); ``` `paymentMethodToken` carries the token your backend uses next, plus the data it needs to decide where the payment goes. See [Decide where the payment goes](#decide-where-the-payment-goes) below. > [!WARNING] > > If the customer refreshes the page while an attempt is still awaiting your decision, the SDK re-emits `primer:payment-approval-required` for the same `paymentAttemptId`. Deduplicate on that ID: if you've already sent this attempt to your PSP or to Primer, don't do it again, just call `continueFlow()`. ## Decide where the payment goes Your backend receives, from the approval event, the payment method token and the card's BIN data: card network, first digits, last four digits, and issuer. If you only use the vault and have no Primer processing connected, the decision is made for you. Take the token and go to the proxy. If you've also connected a processor in Primer, you choose per payment, for example by card network, issuer country, or any rule you already run: ```javascript theme={"dark"} checkout.addEventListener('primer:payment-approval-required', async (event) => { const { paymentAttemptId, paymentMethodToken, continueFlow } = event.detail; await fetch('/my-backend/handle-payment-approval', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paymentAttemptId, network: paymentMethodToken.paymentInstrumentData?.network, firstDigits: paymentMethodToken.paymentInstrumentData?.firstDigits, }), }); await continueFlow(); }); ``` A common rule is to route by BIN, for example sending issuer countries you already process well at your own PSP through the proxy, and routing everything else to Primer. **Route to Primer:** call `approve` on the attempt. Primer creates the payment and manages the rest of the lifecycle, including 3DS and retries. ```bash theme={"dark"} curl -X POST https://api.primer.io/payment-attempts/{paymentAttemptId}/approve \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" ``` `approve` needs the `transactions:authorize` scope. If the decision window has expired, `approve` returns `410 PaymentAttemptExpired` and the attempt can no longer be acted on; the customer has to submit a new payment. **Route to your own PSP:** take `paymentMethodToken.token` and send your usual PSP request through the [proxy](#send-the-request-through-the-proxy), then [report the outcome](#report-the-outcome). **Stop the payment:** call `abort` if you decide not to proceed at all, for example because your own fraud check failed before you've even tried a PSP. ```bash theme={"dark"} curl -X POST https://api.primer.io/payment-attempts/{paymentAttemptId}/abort \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "reason": "fraud-check-failed" }' ``` No payment is created and the token is invalidated. Use `abort` for a decision made before you've sent anything to a PSP; if your own PSP processing fails after you've already tried it, that's a [fallback to Primer](#fall-back-to-primer) or a reported failure, not an abort. > [!NOTE] > > Only card payments can route to the proxy. Alternative payment methods always go through Primer orchestration, so mixing card and non-card payment methods in the same checkout needs no extra integration work. ## Send the request through the proxy Send the same request you'd normally send to your PSP, but to the proxy, with the card fields replaced by placeholders referencing the token: | Header | Purpose | | - | - | | `X-Primer-Api-Key` | Your Primer API key. Set once wherever your PSP client is configured. | | `X-Target-Host` | The PSP host to forward the request to, for example `api.stripe.com`. Must be on your account's destination allowlist. | | `Authorization` (or your PSP's usual auth header) | Your own PSP credential, unchanged. | Replace card fields in the request body with `{{.}}` placeholders: | Field | Value | | - | - | | `CARD_NUMBER` | The card number | | `EXPIRY_MONTH` | Unpadded month, e.g. `6` | | `EXPIRY_MONTH_PADDED` | Zero-padded month, e.g. `06` | | `EXPIRY_YEAR` | Four-digit year | | `EXPIRY_YEAR_SHORT` | Two-digit year | | `CVV` | The security code. Only available on a single-use token from the current checkout session, not on a saved token. | | `CARDHOLDER_NAME` | As captured, if captured | Placeholders work regardless of how your PSP structures its request body. They're only resolved in the request body; a placeholder in a header or in the URL path is never substituted and the request fails. A placeholder that's malformed, references an unknown field, or references a field not available on that token (such as `CVV` on a saved token) fails the whole request rather than being silently dropped. **Stripe example** (form-encoded): ```bash theme={"dark"} curl -X POST https://proxy.primer.io/v1/payment_intents \ -H "X-Primer-Api-Key: YOUR_API_KEY" \ -H "X-Target-Host: api.stripe.com" \ -H "Authorization: Bearer YOUR_PSP_SECRET_KEY" \ -d "amount=1000¤cy=usd&card[number]={{tok_abc.CARD_NUMBER}}&card[exp_month]={{tok_abc.EXPIRY_MONTH}}&card[exp_year]={{tok_abc.EXPIRY_YEAR}}&card[cvc]={{tok_abc.CVV}}" ``` **Adyen example** (JSON): ```bash theme={"dark"} curl -X POST https://proxy.primer.io/payments \ -H "X-Primer-Api-Key: YOUR_API_KEY" \ -H "X-Target-Host: YOUR_ADYEN_API_HOST" \ -H "X-API-Key: YOUR_ADYEN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "amount": { "value": 1000, "currency": "USD" }, "paymentMethod": { "type": "scheme", "number": "{{tok_abc.CARD_NUMBER}}", "expiryMonth": "{{tok_abc.EXPIRY_MONTH_PADDED}}", "expiryYear": "{{tok_abc.EXPIRY_YEAR}}", "cvc": "{{tok_abc.CVV}}" }, "reference": "order-123", "merchantAccount": "YOUR_MERCHANT_ACCOUNT" }' ``` Most PSP SDKs let you override the base URL and add custom headers, so in many cases you only need to change the base URL your existing PSP client points to and add the two Primer headers; the rest of your integration, including how you build the request body, stays the same. Some SDKs can't easily add custom headers on every call (notably on OAuth/token calls some SDKs make internally); in that case, call the PSP's HTTP API directly for the proxied request instead of going through the SDK. See [Proxy reference](/docs/vault/reference#proxy-reference) for the full header and error catalogue. The proxy relays your PSP's response untouched, including its status code. If Primer can't process the request (for example, an unknown or expired token), the response carries an `X-Primer-Proxy-Error` header and a problem-details body instead of a PSP response. See [Errors and retries](/docs/vault/reference#errors-and-retries). ## Handle 3DS at your PSP 3D Secure, when it's needed, runs at your own PSP. Primer doesn't run 3DS on a proxied payment. * **In-page challenge:** your PSP's response tells you a challenge is required; render it in your page using your PSP's SDK, exactly as you do today. The customer completes it without leaving your checkout. * **Redirect challenge:** the customer is sent to the issuer's page and back. Your return URL should land them back on your checkout with the same client session. While the customer is at your PSP or completing a challenge, the Primer checkout has no visibility into what's happening there, so it shows a loading state while it waits for you to report the outcome. If the customer reloads the page mid-challenge, reload the checkout with the same client token; the SDK reads the current state of the attempt and shows the loading state again, or the result, once you've resolved it. This all has to happen inside the 15-minute decision window. Issuers typically time out a 3D Secure challenge after about 10 minutes, so with quick checks on your side the challenge should finish well within the window. See [Payment attempt states and decision window](/docs/vault/reference#payment-attempt-states-and-decision-window) for what happens if the window runs out. ## Report the outcome Once you have a result from your PSP, resolve the attempt so the checkout can show it: ```bash theme={"dark"} curl -X POST https://api.primer.io/payment-attempts/{paymentAttemptId}/resolve \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "outcome": "SUCCEEDED", "vaultPaymentMethod": true }' ``` | Field | Type | Required | Description | | - | - | - | - | | `outcome` | `SUCCEEDED` or `FAILED` | Yes | The result from your PSP. | | `vaultPaymentMethod` | boolean | No, default `false` | Save the card before the token is consumed. Only valid with `outcome: SUCCEEDED`. Saved against the `customerId` already on the client session, so you don't repeat it here. See [Save and reuse cards](/docs/vault/after-the-payment#save-and-reuse-cards). | `resolve` needs the `payment_instrument:write` scope. It's idempotent on `paymentAttemptId`: a retried call with the same body returns the original response instead of failing, so you can safely retry after a timeout without risking a duplicate. See [Errors and retries](/docs/vault/reference#errors-and-retries) for the full error catalogue, including what happens if you resolve after the window has expired. Once the outcome is reported, call `continueFlow()` from your frontend. The checkout listens for the result and shows a success or failure screen: ```javascript theme={"dark"} checkout.addEventListener('primer:payment-success-external', (event) => { const { paymentAttemptId, paymentMethodType } = event.detail; window.location.href = `/confirmation?attempt=${paymentAttemptId}`; }); checkout.addEventListener('primer:payment-failure', (event) => { console.error('Payment failed:', event.detail.error?.diagnosticsId); }); ``` `primer:payment-success` and `onPaymentSuccess` always carry a Primer `payment` object and don't fire for a proxied payment. Listen for `primer:payment-success-external` instead if your integration handles success itself. ## Fall back to Primer If you send a card through the proxy and your own PSP declines or fails, the token is still usable, since the attempt is still open. You can retry with a different PSP of your own, or fall back by calling `approve` on the same attempt, so Primer processes the same card instead of you reporting `FAILED`: ```bash theme={"dark"} curl -X POST https://api.primer.io/payment-attempts/{paymentAttemptId}/approve \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" ``` Primer doesn't see your PSP's response, so it's your responsibility to only approve once you've confirmed your own PSP hasn't already charged the card. There's no path in the other direction. Once you approve an attempt for Primer to process, you can't switch that same attempt to the proxy. If you need your own PSP after an approved payment fails, that's a new payment attempt, created when the customer retries. # Get started Source: https://primer.io/docs/vault/get-started > [!NOTE] > > This feature is not available on all Primer accounts. Contact your Customer Success Manager for access. ## What Primer sets up for you Before your first payment, your Primer representative sets up three things on your account: * **Vault enabled.** The proxy rejects every request from an account that isn't enabled for Primer Vault. * **Card available in the checkout builder, without a processor.** You turn Card on in the Checkout builder with your usual conditions, the same way an orchestration merchant does. There's nothing vault-specific to configure for the card form itself. * **Your PSP destinations, allowlisted.** The proxy only forwards to PSP hosts on your account's allowlist. Primer also keeps its own separate list of PCI-approved destinations, so a host has to be on both before the proxy sends anything to it. For now, your Primer representative sets your list up from the hosts you give them; self-service management is planned but not available yet. The list is per environment. See [Environments](#environments) below. ## What you do * **Create an API key with the right permissions.** In [Developers](https://dashboard.primer.io/developers/apiKeys), create a key scoped to: * `client_tokens:write`, to create the client session. * `payment_instrument:read`, to read the vaulted card. * A permission for the proxy and for saving a vaulted card. At the time of writing this is new and the dashboard scope isn't finalized. Confirm the exact scope name with your Primer representative. A vault-only integration doesn't need `transactions:authorize`, `transactions:capture`, or the other payment-processing scopes, since you never ask Primer to create a payment. * **Point your PSP client at the proxy.** Wherever your backend configures its Stripe, Adyen, or other PSP client, change the base URL to the proxy host and add the two Primer headers. See [Send the request through the proxy](/docs/vault/during-the-payment#send-the-request-through-the-proxy) for the exact headers and a worked example per PSP. ## Environments Primer Vault has separate sandbox and production hosts, and a key or token from one environment never works in the other: | | Sandbox | Production | | - | - | - | | Primer API | `api.sandbox.primer.io` | `api.primer.io` | | Primer proxy | `proxy.sandbox.primer.io` | `proxy.primer.io` | | API keys | Sandbox keys only | Production keys only | | Client tokens and payment method tokens | Valid only against the sandbox API | Valid only against the production API | | PSP destinations | Your PSP's test/sandbox host | Your PSP's live host | Create separate API keys for each environment, and keep your destination allowlist for sandbox pointed at your PSP's test hosts, not its live ones. Mixing them up either leaks a test card to your live PSP account or fails outright, since the host on your allowlist for one environment generally isn't the host you want in the other. ## Testing in the sandbox Test the full flow in sandbox before going live: * **Use your PSP's own test/sandbox mode.** The proxy forwards to whatever host is on your sandbox allowlist; put your PSP's test host there (for example, Adyen's test endpoints are on a different hostname than its live ones, while Stripe uses the same host with a test secret key; check your PSP's own docs for which applies). * **Use test cards from your PSP, not from Primer.** The card is tokenized by Primer, but the authorization itself happens at your PSP, so the test card numbers and expected outcomes (approved, declined, requires 3DS) are your PSP's, the same ones you'd use calling them directly today. * **Test the outcomes you'll see in production:** a successful proxy payment with the card vaulted, a decline reported back to Primer, a 3DS challenge, and the fallback to Primer approval if you've also connected a processor. ### Checklist before going live * [ ] Vault enabled on your production account. * [ ] Card enabled in the Checkout builder. * [ ] A production API key with the right permissions, kept separate from your sandbox key. * [ ] Your PSP's live host on your production destination allowlist. * [ ] Your PSP client pointed at the production proxy host with your live PSP credential. * [ ] A full payment, a decline, and a 3DS challenge tested end to end in sandbox. ## Your first payment The simplest case: every payment goes to your own PSP, with no Primer fallback. One complete example, from creating the session to showing the result. **1. Create the client session.** ```bash theme={"dark"} curl -X POST https://api.sandbox.primer.io/client-session \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "orderId": "order-123", "currencyCode": "USD", "amount": 1000, "customerId": "customer-456", "mode": "MANUAL" }' ``` See [Create the client session](/docs/vault/during-the-payment#create-the-client-session) for the required fields and what each one is for. **2. Load the checkout.** ```html theme={"dark"} ``` **3. Listen for the approval event.** ```javascript theme={"dark"} const checkout = document.querySelector('primer-checkout'); checkout.addEventListener('primer:payment-approval-required', async (event) => { const { paymentAttemptId, paymentMethodToken, continueFlow } = event.detail; await fetch('/my-backend/handle-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paymentAttemptId, token: paymentMethodToken.token }), }); await continueFlow(); }); ``` See [Show the checkout and capture the card](/docs/vault/during-the-payment#show-the-checkout-and-capture-the-card) for the full event payload. **4. Send the request through the proxy.** ```bash theme={"dark"} curl -X POST https://proxy.sandbox.primer.io/v1/payment_intents \ -H "X-Primer-Api-Key: YOUR_API_KEY" \ -H "X-Target-Host: api.stripe.com" \ -H "Authorization: Bearer YOUR_PSP_SECRET_KEY" \ -d "amount=1000&card[number]={{tok_abc.CARD_NUMBER}}&card[exp_month]={{tok_abc.EXPIRY_MONTH}}&card[exp_year]={{tok_abc.EXPIRY_YEAR}}&card[cvc]={{tok_abc.CVV}}" ``` See [Send the request through the proxy](/docs/vault/during-the-payment#send-the-request-through-the-proxy) for the full placeholder reference and a second example for Adyen. **5. Resolve the attempt.** ```bash theme={"dark"} curl -X POST https://api.sandbox.primer.io/payment-attempts/{paymentAttemptId}/resolve \ -H "X-Api-Key: YOUR_API_KEY" \ -H "X-Api-Version: 2.4" \ -H "Content-Type: application/json" \ -d '{ "outcome": "SUCCEEDED", "vaultPaymentMethod": true }' ``` See [Report the outcome](/docs/vault/during-the-payment#report-the-outcome) for the full request, response, and error codes. **6. Call `continueFlow()`.** ```javascript theme={"dark"} checkout.addEventListener('primer:payment-success-external', (event) => { const { paymentAttemptId } = event.detail; window.location.href = `/confirmation?attempt=${paymentAttemptId}`; }); ``` That's the whole flow for a card that always goes to your own PSP. [During the payment](/docs/vault/during-the-payment) covers every step in detail, including deciding per payment whether to use Primer or your own PSP, and falling back to Primer if your PSP declines. ## Bring your existing cards If you already store cards at your current processor or in another vault, you can bring them into Primer rather than asking every customer to re-enter their card. This is the same [token migration](/docs/changelogs/migration-guides/token-migration) process used by merchants moving onto Primer orchestration, and there's nothing vault-specific about it. Your current processor's token files are transferred to Primer (by SFTP, either direction), and Primer imports them and issues a Primer token for each card. Who does what: * **You** arrange for your current processor to hand over the token files, following [Token migration](/docs/changelogs/migration-guides/token-migration) for the transfer method (processor-hosted SFTP, or Primer's). * **Primer** imports the files and issues a saved (multi-use) token for each card, usable through the proxy exactly like a card saved from a vault payment, and tells you via the [Support Portal](https://portal.support.primer.io/servicedesk/customer/portal/11) once the migration is done. The reverse direction, exporting your Primer-vaulted tokens to a different provider, is covered separately in [Token export](/docs/changelogs/migration-guides/token-export). Timelines depend on token volume and how quickly your current processor completes their side; talk to your Primer representative before you start. # Overview Source: https://primer.io/docs/vault/overview > [!NOTE] > > This feature is not available on all Primer accounts. Contact your Customer Success Manager to receive access. ## What is Primer Vault Primer Vault stores your customers' cards for you and keeps card data off your servers, so you stay out of PCI scope. You keep your own PSPs and your own payment logic. When you want Primer to process a payment, it is one call away, with the same checkout and the same card. ## Who is it for > [card] You want a vault and keep your own PSPs > > You have PSP integrations and routing logic that work, and you want to keep them. You want Primer to store the cards and take card data off your hands. > [card] You use Primer and want control over some payments > > Primer already processes your payments. For some of them, for example one market or one card type, you want to go straight to your own PSP. ## You decide for each payment After your customer clicks Pay, your backend decides where the payment goes. It can send it to Primer, which processes it with 3D Secure, retries, and fallbacks. Or it can send it to your own PSP through Primer Vault. It is the same checkout, the same session, and the same saved card either way. You can mix both in the same checkout. Sending a payment to Primer instead of your PSP means approving the payment instead of sending the request through the proxy. It is not a new integration. ![A vaulted token goes through your logic, which sends each payment to Primer orchestration, Stripe, or Braintree depending on market and currency](https://goat-assets.production.core.primer.io/marketing/external-docs/overview-pages/vault/decide-at-runtime.png) Vault or orchestration, you decide at runtime ## What you get * A card form from Primer Checkout, so card data never reaches your page or your servers. * Your own PSP request, sent through Primer Vault with the card details filled in for you. The PSP's answer comes back to you as it is. * Saved cards for returning customers and recurring payments. * A way to move to Primer orchestration at your own pace. > [!NOTE] > > The proxy that sends your requests to your PSP runs as its own service, on its own host, separate from the Primer API. However reliable each one is, a problem with Primer's payment processing does not affect proxied payments. ## Grow at your own pace 1. **Start with your own PSP.** Every payment goes to your PSP through Primer Vault. Primer stores the cards. You keep everything else as it is today. 2. **Send some payments to Primer.** Connect a processor in Primer, then choose a share of your traffic, one country, one card type, or a new market. Compare the results with your own PSP. 3. **Move everything to Primer.** When you are ready, send every payment to Primer, with the processors and workflows you set up in Primer. ## Next steps > [card] [Get started](/docs/vault/get-started) > > One-time setup, environments, sandbox testing, and your first payment end to end. > [card] [During the payment](/docs/vault/during-the-payment) > > Create the session, capture the card, decide where the payment goes, and report the outcome. > [card] [After the payment](/docs/vault/after-the-payment) > > Save and reuse cards, charge a saved card without the customer, and move traffic to Primer. > [card] [Reference](/docs/vault/reference) > > Proxy headers and placeholders, errors and retries, attempt states, and limitations. # Reference Source: https://primer.io/docs/vault/reference > [!NOTE] > > This feature is not available on all Primer accounts. Contact your Customer Success Manager to receive access. ## Proxy reference **Endpoint:** `POST https://proxy.primer.io/`. The path after the host is forwarded to your PSP untouched, so use the same path you'd call on your PSP directly. **Headers:** | Header | Required | Purpose | | - | - | - | | `X-Primer-Api-Key` | Yes | Your Primer API key. | | `X-Target-Host` | Yes | The PSP host to forward to, for example `api.stripe.com`. Must be on your account's destination allowlist, which is set per environment. See [Environments](/docs/vault/get-started#environments). | | Your PSP's own auth header (`Authorization`, `X-API-Key`, etc.) | Yes | Unchanged from how you'd call the PSP directly. | **Placeholders:** `{{.}}` anywhere in the request body, regardless of how your PSP structures it. See the field table in [Send the request through the proxy](/docs/vault/during-the-payment#send-the-request-through-the-proxy). A placeholder is never resolved outside the body. One in a header or in the URL path is left as-is and the request fails. **Every response carries `X-Primer-Request-Id`**, whether it's your PSP's own response relayed untouched or a fault Primer raised. Give this ID to support when you need help tracing a request. **Limits and timeouts:** request size and PSP response timeouts apply as with any proxied HTTP call; confirm current numeric limits with your Primer representative, as these are still being finalized. ## Errors and retries The proxy relays your PSP's response byte for byte whenever your request reached the PSP: same status code, same body. A fault Primer raises instead carries an `X-Primer-Proxy-Error` header and a problem-details (`application/problem+json`) body with a `type`, `title`, `status`, `detail`, and the request ID. Use the presence of that header to tell a Primer error apart from your PSP's own response. | Status | Error type | Meaning | | - | - | - | | 400 | `invalid-request` | Malformed or missing required header, malformed placeholder, or a placeholder outside the body. | | 400 | `content-type-not-set` | The request has a body but no `Content-Type` header. | | 401 | `unauthorized` | Your Primer API key is invalid or revoked. | | 403 | `vault-not-enabled` | Your account isn't enabled for Primer Vault. | | 403 | `destination-not-allowed` | The `X-Target-Host` isn't on your destination allowlist. | | 404 | `token-not-found` | The token doesn't exist, or belongs to another account. | | 405 | `method-not-allowed` | The HTTP method used is not allowed. | | 409 | `token-consumed` | A single-use token has already been used; your PSP has already seen this card. | | 410 | `token-expired` | The token is past its expiry (see [decision window](#payment-attempt-states-and-decision-window)). | | 413 | `payload-too-large` | The request body is over the proxy's size limit. | | 415 | `unsupported-content-type` / `unsupported-content-encoding` | The request body is in an encoding not supported by the proxy. | | 422 | `unresolved-placeholder` / `unknown-field` / `field-not-available` | A placeholder couldn't be filled, for example `CVV` on a saved token. The error names the token and field. | | 422 | `card-data-in-request` | Raw card-shaped data was found in the request instead of a placeholder. | | 422 | `too-many-tokens` | The request body names more tokens than the proxy allows in a single request. | | 502 | `psp-unreachable` | The proxy couldn't connect to your PSP, or your PSP's connection was blocked. | | 502 | `psp-response-too-large` | Your PSP's response was over the proxy's size limit. | | 503 | `vault-unavailable` | The token exchange is temporarily unavailable; nothing was sent to your PSP. | | 504 | `psp-timeout` | Your PSP didn't answer within the proxy's timeout. | An error can also come from in front of the proxy (rate limiting, a WAF block) before it reaches Primer's own logic. Those carry no `X-Primer-Proxy-Error` header and no request ID. If you need to trace one, ask support to look it up by timestamp and source IP instead. **Knowing whether it's safe to retry:** * **The error says the request wasn't forwarded** (`invalid-request`, `content-type-not-set`, `unauthorized`, `destination-not-allowed`, `token-not-found`, `token-consumed`, `token-expired`, the `422`s, or a `psp-unreachable` before anything was sent): nothing reached your PSP. Safe to retry once you've fixed the underlying problem. * **The outcome is unknown** (a `psp-timeout`, or a `psp-unreachable` after the request may have left): your PSP may or may not have processed it. Don't blindly retry. Check with your PSP first, using your own idempotency key if you set one on the PSP request, or query their API for the order. * **`psp-response-too-large` means your PSP did answer**, but the response was over the proxy's size limit and couldn't be relayed to you. Check with your PSP for the outcome; don't treat this as a failed payment. * **The proxy never retries a request to your PSP itself.** If you need retry behavior at your PSP, build it the same way you would calling that PSP directly, including reusing the PSP's own idempotency key on a retried call so you don't risk a duplicate charge. If the same request to your backend keeps happening twice (for example, you call the proxy twice for the same payment because your own retry logic fired), rely on your PSP's own idempotency key, the same way you would without Primer in the path. The proxy itself doesn't deduplicate PSP requests for you. ## Payment attempt states and decision window A payment attempt moves through the following states: | State | Meaning | | - | - | | `REQUIRES_APPROVAL` | The card has been tokenized and the attempt is waiting on your backend's decision. | | Approved (processing with Primer) | You called `approve`; Primer is processing the payment. | | Resolved externally | You called `resolve` with `SUCCEEDED` or `FAILED`, reporting what happened at your own PSP. | | Aborted | You called `abort` before sending the card anywhere; no payment was created. | | Expired | Neither `approve`, `resolve`, nor `abort` was called before the decision window closed. | **Transitions:** `REQUIRES_APPROVAL` is the only state you can act from. `approve`, `abort`, and sending the token through the proxy are all only valid while the attempt is in this state. Once an attempt reaches a resolved, approved, aborted, or expired state, it's terminal. A retry is a new payment attempt, created when the customer submits their details again. **The decision window is 15 minutes**, from the moment the card is tokenized. It gives your backend time to run your own checks, call your PSP, and handle any 3D Secure challenge, before the attempt expires. **The token's lifecycle:** a token isn't consumed by a proxy request itself. While the attempt is still in `REQUIRES_APPROVAL`, you can send the same token through the proxy more than once, for a 3DS challenge, a retry after a decline, or trying a second PSP of your own. The token is only consumed when you resolve the attempt, approve it (falling back to Primer), or it expires. ## Limitations What Primer Vault doesn't support yet: * **Mobile SDKs.** The vault flow is web-only for now; iOS and Android support is planned but not available. * **Apple Pay and Google Pay.** These wallets produce a device token and cryptogram instead of a card number, which the proxy doesn't yet place into a PSP request. * **Network tokens.** Charging a network token instead of the underlying PAN through the proxy isn't supported yet. * **Primer 3DS on the vault.** 3D Secure for a proxied payment has to run at your own PSP; Primer can't authenticate the card on your behalf and hand you the result. * **Stored PSP credentials.** You send your PSP credential on every proxy request, the same way you would calling the PSP directly; Primer doesn't yet let you register it once and omit it from subsequent calls. * **PSPs that sign requests.** A PSP that requires a signature over the whole request body, card data included (for example, dLocal), isn't supported, since Primer fills the card fields in after you've built the request. * **Raw card data without the Primer checkout.** Capturing a card yourself and handing it to Primer Vault directly, without going through the checkout, isn't supported yet. Every card has to be tokenized through Primer's own card form. This is what's out of scope for the initial release, not a permanent limitation. ## Troubleshooting **Nobody decided within the window, and the attempt expired.** Check whether your backend actually received the `primer:payment-approval-required` event and called one of `approve`, `abort`, or your PSP; a silent failure in that handler (a crash, an unhandled promise rejection) leaves the attempt waiting until it times out. Add logging around the handler if you can't otherwise tell. **Your PSP processing failed, but you never called `abort` or `resolve`.** The attempt stays open until the decision window closes, and the customer is left on a loading screen in the meantime. Always resolve the attempt (or abort it) from a `finally`-style path in your backend, even on an unexpected error, so the customer isn't left waiting longer than necessary. **The customer reloaded the page mid-flow.** Reload the checkout with the same client token. The SDK reads the current state of the attempt. If it's still `REQUIRES_APPROVAL`, you'll see the approval event fire again (deduplicate on `paymentAttemptId`); if it's been resolved, you'll see the result. **Your PSP charged the card, but the decision window had already expired by the time you tried to report it.** Resolving an expired attempt fails, since the token and the attempt are both gone. The payment still happened at your PSP, so you need to reconcile it on your own side (refund it, or treat it as a successful out-of-band payment) rather than relying on Primer's state. This is the main reason to keep your own PSP calls, including any 3DS challenge, comfortably inside the decision window. # Best practices Source: https://primer.io/docs/workflows/best-practices Automating your use cases with Primer is very powerful, and flexible. You can build almost anything without a line of code. Like any open tool, Automation comes with its own set of dos and don’ts. Mastering them will make your workflows **more resilient, more efficient, and easier to maintain.** Our recommendations on how to set up Workflows in the most efficient way possible depend greatly on your use cases. This page introduces some of what we consider best practices when building workflows - and outlines why we think these proposals are more beneficial than the alternative. ## Create more granular workflows With all the tools available to create sophisticated workflows, you might be tempted to create big workflows achieving many tasks in one go. While this is technically possible, it will become cumbersome to maintain and potentially introduces a lot of redundancy when you have to repeat certain steps. Workflows give you many tools to have more granular workflows based on use cases: * [Apps](/docs/workflows/apps/overview) will emit events as [Triggers](/docs/workflows/apps/overview#triggers) which you can react to in a workflow. * When you create multiple workflows based on the same Trigger, the [Trigger Conditions](./utilities/conditions-block#trigger-conditions-define-when-to-start-a-workflow) can ensure only certain conditions actually start a workflow. ### Reduce redundancy When you set up a payment flow that includes [multiple routes](/docs/workflows/utilities/conditions-block), every time you authorize a payment for that route, you can set the “Authorize payment” action up in the best way possible to ensure payment success. However, once the action performed its assigned task, then you would need to check if the payment was authorized or declined before adding the “Capture payment” action. ![One workflow with many routes](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/best-practices/all-routes.png) One workflow with many routes This can be simplified by splitting the workflow into two: 1. one workflow to authorize payments 2. and one to capture payments that have been authorized **Authorize payments:** Use the [Conditions Utility](/docs/workflows/utilities/conditions-block) to route to the required processor. ![Authorization flow](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/best-practices/authorization-flow.png) Authorization flow Then create a workflow based on the “Payment status updated” trigger. Here there are **two** options to react to the payment status update to capture the payment if the status is Authorized: **1: Adding the Conditions Utility** to check for “Payment Status = Authorized" before adding the “Capture Payment” block. If you don't check for Authorized, then a capture attempt would be made for any payment status change, of which there are many. ![Capture flow](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/best-practices/capture-flow.png) Capture flow **or 2: Using the Trigger Conditions** The Trigger Conditions allow you to set conditions that determine if a workflow should even be started. Only if the triggering event and the conditions that were set on the Trigger are met your workflow will start executing. This needs to be done very carefully, as otherwise you are risking starting more than one workflow if the set-up is not explicit enough, or no workflows if the set-up is too restrictive. Set the trigger up with a condition for “Payment status = Authorized” and add “Capture payment” as the first and only block. This will now capture every payment that was authorized. ![Trigger Set-Up](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/best-practices/create-shipping-label.png) Trigger Set-Up These principles apply for non-payment workflows as well. If you react to an order being created, you could react to a specific flag only, or create multiple conditions within the workflow if you want to handle more than one use case. ![Multiple conditions](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/best-practices/marketing-opt-in.png) Multiple conditions ### Flexibility The aforementioned examples are not mutually exclusive, but can be combined based on use cases to allow for greater flexibility. An example would be if you want to create a support ticket for declined payments, **and** post failed payments into a Slack channel. Here you can either create two workflows, one with a Trigger Condition each (”Status=Declined”, “Status=Failed”) **or** combine them into one workflow for “*Error handling*” with the Trigger Condition being “Status one of Declined, Failed". If you do the latter, then you can still add the condition builder and create one route for “Status = Declined", and one route for “Status = Failed". It's best to keep the conditions explicit like that, and just keep the “all other conditions” block unmapped for better readability of the workflow. ## Handle third-party issues Let’s consider a workflow using the “Post message to channel” action from Slack. During the execution of the workflow, anything **but** Slack successfully posting the message will result in a stop of the workflow execution at this block and result in a `Failed` [Workflow Run](/docs/workflows/monitor-workflows/overview). In case of failures, the Workflow Runs can be used to troubleshoot. Actions do not return a response status in the Outputs, which means that we assume that all Actions are running without issue. If Slack did not post the message successfully then you can look at the Workflow Runs. Within the timeline you will be able to identify if the action was not successful due to invalid credentials, or any other possible configuration issue by opening the details for each event. See [monitor workflows](/docs/workflows/monitor-workflows) for more details on the Workflow Run details. The assumption of an action being successful will allow you to chain multiple actions together, for example in a flow like this, where a ticket is created via Zendesk and then posted to Slack: ![Create ticket for declines and post to slack](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/best-practices/declined-zendesk-slack.png) Create ticket for declines and post to slack If the “Create ticket” action fails, the whole Workflow Run will be marked as `Failed` and no Slack message will be posted. ### Workflow vs object status Keep in mind that an app action can manipulate objects, for example the “Authorize payment” action can lead to a new payment status, whereas third-parties can avail actions to manipulate their objects, for example: * “Update customer” action updating a customer status from `PENDING_REVIEW` to `APPROVED` * “Update order” action updating an order status from `DISPATCHED` to `FULFILLED` * “Confirm shipping” action returning an updated shipping status of `CONFIRMED` These statuses can be used to create subsequent workflows on the back of them, just like continuing different workflows based on payment status Authorized or Declined. ## Avoid infinite loops Certain combinations of triggers & actions can lead to an infinite loop of workflows being triggered. This must be avoided when building a workflow. If you combine the Zendesk trigger "Ticket created" with the Zendesk action "Create ticket", that would result in an infinite loop: ![Infinite loop example](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/best-practices/ticket-created.png) Infinite loop example We recommend setting up the Trigger accordingly, or putting [Conditions](/docs/workflows/utilities/conditions-block) in place to prevent an infinite loop. > [!NOTE] > > If you accidentally create an infinite loop, Primer has technical mitigations in place to terminate workflow execution for the affected workflows and alert the product support team. ## Creating test routes The Conditions Utility allows you to reference any data point from a previous block, such as the Output of a Trigger or an action. During your integration you might want to create different routes to get familiar with branching logic. You could create different routes based on amount, currency, down to the individual e-mail address. This capability also allows you to create very specific test routes: ![Test route via e-mail address ](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/best-practices/test-route.png) Test route via e-mail address ## Start automating * Now that you know the best practices, why not put the concepts to a test and [start building workflows](/docs/get-started/create-workflow)? * In case your new workflows do not work as intended, check our [monitor workflows](/docs/workflows/monitor-workflows) guide to troubleshoot your workflows # Export & Import Source: https://primer.io/docs/workflows/export-import Workflows can be exported from one account or environment and imported to a different account or environment. This can be used in several ways: * **Move from sandbox to production faster**: Once your workflows are created on the sandbox environment and you want to move to production, you can export from sandbox and import on production. * **Use as custom template across accounts**: If you have multiple Primer-merchant accounts, you could create comprehensive flows on one account, export them, and import across all other accounts. ## Exporting a workflow You can export workflows in two ways: * **From the workflow list**: select a workflow and use the menu to export the version that is currently selected. This could be a draft, published, or archived flow. * **From the workflow builder**: open any specific version that you want to export, be it a current draft or an older version, and use the menu next to the workflow name to export this version. Good to know: only the selected workflow version will be exported, no matter how many versions already exist for this workflow. ![Exporting a workflow](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/export-import/export.png) Exporting a workflow ## Importing workflows When you create a new workflow, you can start with a template, start from scratch or choose to import one or more workflows. This can be found next to the "New workflow" button. Either drag & drop, or pick an existing file. You can repeat this multiple times to import multiple workflows, too. ![Importing one or multiple workflows](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/export-import/import-overview.png) Importing one or multiple workflows ### Replacing a draft Rather than import as a new workflow, you can also overwrite an existing draft. This is helpful so that you can update an already published workflow without having to archive it and publish a separate workflow. This reduces the risk of no workflow getting triggered for a short period of time. Open the draft and select the "Overwrite draft" option. This opens the import workflow dialog again. Be aware that * in this case, only one workflow can be selected. * the trigger of the provided workflow needs to match. For example, you can't change a workflow starting with "Payment created" to start with "Dispute status updated" instead. ![Replacing a draft](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/export-import/overwrite-draft.png) Replacing a draft Exporting & importing workflows comes with a few considerations to be aware of. Once a workflow is imported, several checks will be applied to ensure the integrity of the workflow submitted. We also apply the usual [validation](/docs/workflows/workflow-validation) to show you which steps are needed before you can publish your workflow. * **Assign workflow apps**: If you export a workflow that, for example, contains a Slack action, but the app Slack is not set up on the account imported to, then validation will make you aware that this is a necessary step. Depending on the third parties and credentials provided, there might be other fields that are then required to be set again, such as the Slack channel, whereas the static content of the message would remain in place as is. * **Reassign processors and risk tools**: Whenever you cross environments or accounts, the assigned processors or risk tools will be reset and have to be reviewed and reassigned. This way you can ensure that you only publish a workflow that's been reviewed and the right third parties are assigned for this particular environment or account. * **Assign workflow apps**: If you export a workflow that, for example, contains Slack, but Slack is not set up on the account where you import to, then validation will make you aware that this is a necessary step. Depending on the third parties and credentials provided, there might be other fields that are then required to be set again, like the Slack channel, whereas the static content of the message would remain in place as is. ## Start automating You now know how to get the most out of Workflows, but there's more that you can do: * Learn about the [Payments App](/docs/workflows/apps/native-apps/primer-payments-app) * Check our guide to [monitor workflows](/docs/workflows/monitor-workflows) * Learn more about Workflows [best practices](/docs/workflows/best-practices) # Monitor workflows Source: https://primer.io/docs/workflows/monitor-workflows/overview > [!NOTE] > > **Pre-requisites**: [Created a workflow](/docs/get-started/create-workflow) Workflows allow you to set up automations that can run 24/7. We encourage you to regularly monitor your workflows to make sure everything still works as expected. Primer provides you with a set of monitoring tools and statistics that will support you while troubleshooting your workflows. These tools bring visibility to the execution of your workflows and enable you to detect any problems with ease. ## Workflow Runs A published workflow will be started automatically every time an [App](/docs/workflows/apps/overview) emits an event matching that [Trigger](/docs/workflows/apps/overview/#triggers). Each Workflow Run is unique and will have a dedicated timeline. The timeline of that run can be found in the Primer dashboard, alongside an overview of the workflow route that was taken. This can be used for validating that the workflow was set up correctly. ![Workflow run status](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/monitors/workflow-run-status.png) Workflow run status ## Workflow Run status A Workflow Run can have one of the following four statuses: | Status | Description | | - | - | | `Running` | The workflow has started and is still running | | `Waiting` | The Workflow Run is waiting for an external event in order to be continued (e.g. shopper needs to complete authentication for 3DS) | | `Completed` | The run has reached the end of the configured workflow | | `Failed` | Something went wrong during the execution of the workflow or one of its actions. We recommend listening to the [webhook event](/docs/workflows/monitor-workflows/workflow-run-failed-webhook) to be informed immediately when a workflow run fails. | ### Workflow Run status vs payment status When using Workflows to [process payments](/docs/checkout/overview), be aware that the payment status is completely decoupled from its run status. > [!WARNING] > > A workflow run marked as `Completed` does not necessarily mean that the payment has been successfully authorized. Let’s look at a workflow to authorize a payment as an example. If the processor declines the payment the payment status will be set to Declined, and the workflow execution will continue and could end with a workflow run status of `Completed`. **Similarly: a Workflow Run marked as `Failed` does not mean that the payment has failed.** For this example, assume a workflow authorizing a payment and then sending a message to Slack. If the processor successfully authorizes the payment, the payment status will be Authorized and the workflow run will continue. However, if Slack is down and the message was not sent, then the workflow will be marked as `Failed` because it did not get to execute all expected steps. ## Workflow Run details Each Workflow Run comes with a detailed timeline. This timeline shows events that happened during the execution in chronological order. You can choose to reverse the order in which the timeline is displayed so that the most recent blocks are presented first. ![Workflow timeline](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/monitors/workflow-timeline.png) Workflow timeline You can access the runs for each workflow within the Dashboard. Then you can select a Workflow Run to learn more about the route that was taken, the actions that were executed, and the Utilities that were used. Click on one of the blocks of the Workflow Run to retrieve additional details, such as: * the set of Inputs and Outputs used by the trigger or action * the API calls made by the trigger or action * the Conditions met by the Conditions Utility (the ‘all other conditions’ block will show when none of the conditions were applicable) ![Payment outputs](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/monitors/payment-outputs.png) Payment outputs ![Workflow API calls](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/monitors/workflow-api-calls.png) Workflow API calls ![Workflow condition](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/monitors/workflow-condition.png) Workflow condition > [!NOTE] > > For additional details on the [Payments App](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger), visit the Payments section of the dashboard. > The Payments timeline will give you additional insights on the steps a payment went through. ## Metrics The duration for each workflow run - and even for each individual block - is displayed on the Workflow Runs list, the timeline, and each block and it's drawer. This way you know exactly how long any given step took. This is based on the time it took from the run start to when it finished and is not displayed for runs that are ongoing or in a waiting state. > [!NOTE] > > The displayed duration also includes any time that the workflow might have been put into a "waiting" state, for example by waiting for the user to complete an action like performing a 3D Secure authentication. ## Workflow Runs retention period The run information is not available forever, we only persist the full run information on production for **90 days** currently. This does not impact the [payment timeline](/docs/manage-payments/search-payments). ## Start automating Now that you know how to troubleshoot and debug your workflow, check our [best practices guide](/docs/workflows/best-practices) to learn how to create powerful and resilient workflows! # Workflow Run failed Source: https://primer.io/docs/workflows/monitor-workflows/workflow-run-failed-webhook Consume the Workflow Run failed webhook to know when a workflow didn't complete successfully. While you can observe [Workflow Runs](/docs/workflows/monitor-workflows/overview) for any outcome and a full run timeline for every workflow that has been started, it is important to also know when a workflow failed. > [!WARNING] > > Even if you already listen to the [Payment status updates webhooks](/docs/api-reference/get-started/configure-webhooks#status-updates), consuming this additional webhook is strongly encouraged if you use Capture or Cancel via Workflows, as a failure to capture or cancel will neither fail the payment itself nor lead to an update of the payment status. Not knowing that a capture or cancel failed could therefore result in unintended consequences. ## Webhook setup As with any [Webhook setup](/docs/api-reference/get-started/configure-webhooks), head to the "Developers" section in the dashboard to configure a webhook. Once the webhook is active, your endpoint will be notified the next time a Workflow Run fails. When [Webhook signing](/docs/api-reference/get-started/configure-webhooks#webhook-signing) is enabled in the dashboard, the Workflow Run failed webhooks will also contain the signature header. ## Webhook payload Version 1.0 of the webhook payload consists of the below fields. New fields could be added and are not considered breaking changes. | Payload field | Description | | :- | :- | | **eventType** | `WORKFLOW_RUN.FAILED` for failed runs. We might support additional types in the future. | | **version** | Webhook version for this eventType. | | **date** | Date and time when the webhook event was sent. | | **primerAccountId** | Primer Account ID of the account that belongs to the failed run. | | **triggerEventId** | An optional ID passed with the trigger to identify the origin of the event that started the workflow. For payments created, this would be the payment ID, but other triggers might not set an event ID and the value returned with the webhook will then be `null`. | | **workflow / id** | The ID of the workflow that had a failed run. | | **workflow / name** | The name of the workflow that had a failed run. | | **workflow / version** | The version of the workflow that had a failed run. | | **run / timestamp** | Date and time when the workflow run failed. | | **run / id** | The ID of the workflow run that failed. This can be used to easier access the workflow run in the dashboard. | | **run / status** | The Workflow Run status will always be `FAILED` currently. In the future, `COMPLETED` might become an additional option for Workflow Run Webhooks. | | **lastError / applicationId** | The application used for the block that lead to the workflow run failure. The values here are dependent on the applications used within workflows, but could for example be `SLACK`, `ONFIDO`, `PRIMER_PAYMENTS`, etc. | | **lastError / actionId** | The ID of the action used for the block that lead to the workflow run failure. The values here are dependent on the actions used within workflows, but could for example be `send_message`, `capture_payment`, `create_ticket`, etc. | | **lastError / diagnosticsId** | A diagnostics ID helping Primer to debug traces when needed (optional). | | **lastError / message** | The error message as also displayed in the Workflow Run Timeline (optional). | ### Example for a payment workflow The payload for a payment workflow will not contain any payment data, only the Payment ID in a field called `triggerEventId`, as the trigger event ID for a payment workflow is the Payment ID. Use the [Payments API](/docs/api-reference/v2.4/api-reference/payments-api/get-a-payment) to get the latest status and payment data for the payment linked to this ID. The below example represents a failed Workflow Run using the "Payment created" trigger from the [Payments app](/docs/workflows/apps/native-apps/primer-payments-app/payment-created-trigger): ```json JSON theme={"dark"} { "eventType": "WORKFLOW_RUN.FAILED", "version": "1.0", "date": "2024-02-21 15:36:16.167687", "primerAccountId": "123abcde-99f2-416e-8013-6ecd1c1285c3", "triggerEventId": "DdRZ6YY0", "workflow": { "id": "ecb8d3bc-123a-4d56-826e-ef8d4cc3d2a2", "name": "MIT UK Card", "version": 8 }, "run": { "timestamp": "2024-03-07T12:20:14.394429", "id": "bbb1c3cc-805d-4d97-826e-ef8d4cc3d2a2", "status": "FAILED", "lastError": { "applicationId": "RISKIFIED", "actionId": "checkout_denied", "diagnosticsId": "1234567890", "message": "Order already decided" } } } ``` ### Example for any other workflow The below example represents a failed Workflow Run from a non-payment app. Do note that the `triggerEventId` in this case does not refer to a payment. ```json JSON theme={"dark"} { "eventType": "WORKFLOW_RUN.FAILED", "version": "1.0", "date": "2024-02-22 12:12:12.121287", "primerAccountId": "123abcde-99f2-416e-8013-6ecd1c1285c3", "triggerEventId": "O-45276805409793-TZ", "workflow": { "id": "ccc8c3cc-805c-4d97-826e-ef8d4cc3d2a2", "name": "Create tickets for fraud suspected declines", "version": 2 }, "run": { "timestamp": "2024-03-07T12:20:14.394429", "id": "dd1d9af0-1acf-42c1-a72f-d1234dd40465e", "status": "FAILED", "lastError": { "applicationId": "FRESHDESK", "actionId": "create_issue", "message": "Project key TEST not found" } } } ``` As there is no other information to query in this case, you have to inspect the [Workflow Run Timeline](/docs/workflows/monitor-workflows) to debug. # Templates Source: https://primer.io/docs/workflows/templates Templates are pre-configured workflows that will help you hit the ground running. When creating a new workflow, you can browse all available templates that Primer has made available for a wide array of use cases, such as Payment Orchestration and Operational Efficiency. A template, same as a workflow, consists of a [Trigger](/docs/workflows/apps/overview#triggers) and multiple blocks ([Utilities](/docs/workflows/utilities/workflow-utilities/), or [actions](/docs/workflows/apps/overview#actions) with [Inputs](/docs/workflows/apps/overview#inputs-and-outputs) already set up). Each template covers a very specific use case but you can always tailor the workflow according to your requirements once you added it to your account. ## Discover templates When you [create a new workflow](/docs/get-started/create-workflow) you will have two options: either select a template or manually create a workflow from scratch. For every template that is available you have the option to preview to learn more about it, or to use it as a workflow right away. ![Templates list](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/templates/templates-list.png) Templates list ![Template preview](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/templates/templates-preview.png) Template preview Choosing to use the template will create a new workflow in your account that comes pre-configured and is yours to change. From here on out the workflow is no longer connected to the template. ### Publishing Publishing a workflow created from a template depends on whether all apps are connected and all required inputs are set. [Workflow validation](/docs/workflows/workflow-validation) will show if any additional actions need to be taken, such as filling required fields or connecting an app. You can use a template and convert it to a workflow even if you are not yet connected to any of the third-parties used within that template. In the above example, Shippo has not been connected yet, but that does not prevent you from building a workflow accordingly. However you will have to connect the app in order to be able to publish your workflow. ![Add an app right from the canvas](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/templates/unauthenticated-apps.png) Add an app right from the canvas ## Start automating * Once your new workflow is published, it's time to check the [Workflow Runs](/docs/workflows/monitor-workflows/overview) to see if the workflows work as intended or if there are any issues to debug. * Do you have suggestions for other use cases we should be covering with templates? [Reach out to us](https://portal.support.primer.io/servicedesk/customer/portal/11) and let us know! # Send KYC verification link Source: https://primer.io/docs/workflows/use-cases/send-kyc-verification-link ### Sending the verification link Given the requirement of only sending the link to payments with the type "first payment" (see: [vaulting](/docs/payment-services/save-payment-methods)), the "Payment status updated" trigger can be used to react to the previous authorization attempt. ![Capture or send link](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/use-cases/send-kyc-verification-link/capture-or-send-link.png) Capture or send link Therefore, this workflow is set up like this: * Trigger: **Payment status updated** from the Payments app * Trigger Condition: **Payment status = AUTHORIZED** * Utility: **Conditions** * Branches: **Transaction type = `FIRST_PAYMENT`** This means any payment using an existing payment method can be captured automatically if the authorization attempt was successful, but `FIRST_PAYMENT` will be handled differently. Next, create the verification link using Onfido's "Create Smart Capture Link" action. > [!NOTE] > > Do note that for some apps to properly work, they also have to be configured within the third-party. In the case of Onfido, the verification process is set up to take a payment ID in and return that payment ID via the result webhook, so that the verification can be tied back to the correct payment. With the link created, an email can be sent to the customer. There are different services and ways to send email, either as plain text, as HTML, or using the templates created within the third-party (like Mandrill, Sendgrid, Postmark). To avoid having to create fully styled emails from within the workflow, it's recommended to use these templates and only pass the required variables through. ### Capture/Cancel based on the verification result The "Result received" trigger from Onfido can now be used to handle the various states they support. For this demo use case only "approved" and "declined" will be used. ![Handle verification result](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/use-cases/send-kyc-verification-link/capture-cancel.png) Handle verification result * Trigger: **Result received** from the Onfido app * Utility: **Conditions** * Branches: **Status = `approved`** * Branches: **Status = `declined`** Depending on the status, the payment can now be captured or cancelled. Onfido also supports custom reasons to be returned, so an additional condition utility can be added to alert on Slack for certain cases: * Utility: **Conditions** added after "Cancel payment" * Branch: **Reason** one of (`well known fraudster`, `fraud suspected`) Then a Slack message can be sent letting the team know to review closely. ## Additional ideas Automation can be used to build even more logic and take the use case further: * Add conditional logic to send an SMS instead of an email for users who provided their phone number. * Automatically update a CRM and tag a user if the result indicates fraudulent activity. * Add a counter to be passed through and allow users more than one attempt to get verified. * Handle the "abandoned" outcome from Onfido to create a new link and send a reminder to the user. ## See it in action Here is a video walking through this exact setup and how the workflows were created: [https://www.loom.com/embed/acce7eb33b7048c6aa58b2da9bbfd1b7](https://www.loom.com/embed/acce7eb33b7048c6aa58b2da9bbfd1b7) ## Start automating You now know how to get the most out of Workflows, but there's more that you can do: * Learn about the [Payments App](/docs/workflows/apps/native-apps/primer-payments-app) * Check our guide to [monitor workflows](/docs/workflows/monitor-workflows) * Learn more about Workflows [best practices](/docs/workflows/best-practices) # Split Source: https://primer.io/docs/workflows/utilities/split ![Split Utility](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/split/split-utility.png) Split Utility ## Using the Split Utility While the [Conditions Utility](/docs/workflows/utilities/conditions-block) allows you to create routes based on logic using outputs from previous blocks, the Split Utility can create multiple routes to **distribute load based on percentages**. You can create up to five routes at a time with a flexible distribution depending on your needs, like 50/50, 80/20, 8/15/42/35, etc. This allows for a wide variety of use cases: * **A/B/C/.. testing** of processors, configurations, third-parties, etc. * **Load distribution** for more resilience at high volume. * **Cost optimization**, for example sending 80% of traffic to your main provider, but keeping minimum volume commitments and sending the rest to the secondary provider. * **Traffic shifting**, start with 100/0, and gradually update over time to 95/5, 90/10, 80/20, etc. until you reach 0/100 and have completely shifted traffic over. > [!NOTE] > > Learn how to [analyze A/B test results with Observability](/docs/observability/use-cases/analyze-ab-test). ## Setup What to consider when setting it up the Split Utility: * You can create **up to 5 splits**, but need **at least 2**. * It's mandatory to use the full 100% distribution across all splits, you can't save anything less than 100% or anything more than 100%. * A split can have any value from `0` to `100` - it's possible to assign `0` to a split and use it to (temporarily) disable a split. [https://www.loom.com/embed/866f33f87d6746efae64e943fbbd6f16?sid=c8921656-0f5e-4625-aa84-8b3a9e0753e2](https://www.loom.com/embed/866f33f87d6746efae64e943fbbd6f16?sid=c8921656-0f5e-4625-aa84-8b3a9e0753e2) ### Removing the block If you no longer want to use the Split Utility, you can remove it from your workflow. If you still have blocks assigned to splits, a dialog will ask if you want to retain the blocks from a specific split, or delete the entire utility and all subsequent routes. ![Delete Split Utility](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/utilities/split/delete-split-utility.png) Delete Split Utility ## Good to know: distribution logic Which split gets chosen during the execution of any given workflow is based on a **random number** generated at runtime. This is important to know, as there is no guarantee that the distribution is round robin. The workflow will not keep track of how many requests were routed through any given split or if the percentage that is set up is met **exactly**. The more requests are sent in the closer the distribution nears the splits that are set up (law of large numbers). This also means if only a handful of requests are sent, the distribution can be very different. A setup of 50/50 with only two requests might still send both requests down the first split, making the actual distribution 100/0. Internal tests showed a standard deviation of **0.94%** after **2 500** requests, falling to just **0.12%** after **20 000** requests. If you need an even more precise distribution than this, you can keep track of the various tiers in your backend, send in additional metadata, and branch based on that number using the [Conditions Utility](/docs/workflows/utilities/conditions-block). ## Start automating Now that you know how to use the Split Utility, you can [create and use it within your workflows](/docs/get-started/create-workflow). # Workflow validation Source: https://primer.io/docs/workflows/workflow-validation Ensuring that [Workflow Runs](/docs/workflows/monitor-workflows/overview) can complete as expected. ## Getting services to talk to each other When you are creating workflows to send data between services there are a few concepts to be aware of when it comes to interoperability - the ability of two services to talk to each other. Workflows at Primer are a translation layer between these services and due to the defined contracts for Inputs and Outputs, data can flow freely without much overhead of having to map or convert data yourself. With that in mind, it's almost inevitable that at some point the wrong data could be send to a service, making it impossible for that service to do its designated job. Validation during workflow creation can help you identify these situations early, but can never be an exhaustive preventive measure. In case of problems, the full details of data exchanged between services or error messages received are viewable in the [Workflow Run details](/docs/workflows/monitor-workflows/overview). ## Necessary steps Before you publish your workflow, we validate that all blocks are properly configured. Any incomplete blocks are highlighted so that you can apply the necessary fixes. ![Workflow validation](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/validation/validation-steps.png) ## Types of validation ### Required vs optional fields Any [action](/docs/workflows/apps/overview#actions) or [Utility](/docs/workflows/utilities/workflow-utilities/) might have a minimum required set of information to be set up in order to be able to publish a workflow. You can identify incomplete actions easily, as some [Inputs](/docs/workflows/apps/overview#inputs-and-outputs) are marked as mandatory: ![missing required inputs](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/validation/missing-required-inputs.png) missing required inputs ### Data type validation Any input, be it for a condition, an action, or other utilities, is defined by a data type. This could be a number, a text string, a list of pre-defined values, a date, or even very specific inputs, like e-mail, or web addresses. Primer supports setting up workflows by manually selecting or entering values, as well as mapping previous values to a field, such as using the payment customer phone number as the recipient number for an action sending SMS. When manually entering values, you can see hints in case the input is not valid, such as this invalid e-mail address: ![invalid email](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/validation/email-invalid.png) invalid email Validation will only help partially when mapping fields from previous blocks, as the actual value to be passed is only known when the workflow runs. Here is an example of a customer's e-mail address from the payment created trigger being assigned to the recipient field of a send e-mail action: ![mappedemail](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/validation/email-mapped.png) mapped email Some fields from previous blocks are incompatible with the input you are setting up, so you might not always see all outputs in the variable selector. For example it is not possible to map a `text` field like "customer name" to an `amount` field, or a `currency` to a `country` field. These fields will therefore not show up in the variable selector for that field. However, some ambiguity is allowed to enable more flexible workflows. It is possible to map a `text` output to an `e-mail` field in case the source app has not explicitly defined a field as "text in e-mail format", but only as "text". This increases compatibility between some services where not all data types are always defined as explicit as they could be. Should a workflow encounter problems due to this, you can see which values have been passed and what the third-party response was in the [workflow run details](/docs/workflows/monitor-workflows/overview). ### Blocks without an app connected It is possible to create a workflow without actually having connected to the apps yet. This way you can start exploring automation use cases or discover an app's capabilities without having to have the app set up yet. However, in order to be able to publish your workflow, you have to connect to the app. This is possible right from the canvas by setting up the account from there. ![Add an app right from the canvas](https://goat-assets.production.core.primer.io/marketing/workflows/external-docs/validation/unauthenticated-apps.png) Add an app right from the canvas ### Input with missing source Any value that is assigned to an input keeps a reference to its source block. If that source block is removed, moved, or updated so that this field is no longer available, then you will see a validation hint telling you that this field is no longer available at this step. You can remove that field and revisit what else you need to update to proceed. ### Optional app updates Some validation hints are even optional, such as when there is an [app update](/docs/workflows/apps/overview#managing-updates) available, but you don't have to update to the latest version in order to publish your draft. ## What is not being validated Validation will help you avoid the most obvious mistakes when creating workflows, because they are objectively wrong. On the other hand, it is possible to set up workflows that satisfy all the requirements of the workflow builder but still result in problems. This is where the [workflow run details](/docs/workflows/monitor-workflows/overview) come in handy as they allow you to debug exactly what has happened. Consider a workflow that cancels an order after a fraud check. It could be that the order is actually not known to the service itself due to some **other steps missing, like the order creation**. When you create your workflow and the individual blocks are set up correctly you can publish the workflow. But when the workflow is running, the third-party might respond with "I don't know `order-123`". This is when you should revisit your logic and workflows holistically and ensure that orders are actually created with that third-party prior to any cancellation attempt. ## Start automating Now that you know how to reliably [create workflows](/docs/get-started/create-workflow), check out our guide to [monitor workflows](/docs/workflows/monitor-workflows/overview), or learn more about workflows [best practices](/docs/workflows/best-practices). # Changelog Source: https://primer.io/docs/api-reference/changelog # Dispute Open Source: https://primer.io/docs/api-reference/endpoints/v2.4/dispute-and-chargebacks-webhooks/dispute-open https://api.schemas.primer.io/api-reference/v2.4/webhooks.yaml post /dispute-opened Primer notifies you with a `DISPUTE.OPENED` webhook on newly opened disputes or chargebacks. This notification is unified across all processors. Learn more about [how Primer handles webhooks](/docs/api-reference/get-started/configure-webhooks). ```json Webhook theme={"dark"} Version - 2.4 ``` ```json Example of dispute event theme={"dark"} { "eventType": "DISPUTE.OPENED", "version": "2.4", "primerAccountId": "7fcd50f1-99f2-416e-8013-6ecd1c1285c3", "transactionId": "c3f662ad-d197-492e-b78b-63eefa64a31d", "orderId": "order-123", "processorId": "Adyen", "processorDisputeId": "adyen_ref_123", "paymentId": "ecb8d3bc-805d-4d97-826e-ef8d4cc3d2a2", "raw_processor_callback": { "example": { "raw_callback": "request", "from": "Adyen" } } } ``` # Dispute Status Source: https://primer.io/docs/api-reference/endpoints/v2.4/dispute-and-chargebacks-webhooks/dispute-status https://api.schemas.primer.io/api-reference/v2.4/webhooks.yaml post /dispute-status Primer notifies you with a `DISPUTE.STATUS` webhook that will provide information on retrievals, disputes (also known as chargebacks), and preabritration filings. This notification is supported for Adyen, Airwallex, Braintree, Checkout.com, PayPal, Stripe & Worldpay. The `DISPUTE.STATUS` event can be used to proactively communicate with customers, issue refunds, send disputes to risk tools, or to proactively defend disputes. The `DISPUTE.STATUS` event is currently in an open beta stage, as we continue to add more processors. Learn more about [managing disputes at Primer](/docs/disputes/manage-disputes). ```json Webhook theme={"dark"} Version - 2.4 ``` ```json Example of dispute event theme={"dark"} { "eventType": "DISPUTE.STATUS", "version": "2.4", "type": "DISPUTE", "status": "CHALLENGED", "primerAccountId": "acct_123456789", "transactionId": "txn_987654321", "orderId": "order_12345", "paymentId": "pay_67890", "paymentMethod": { "type": "CARD", "card": { "network": "VISA", "last4": "1234", "expiry": "12/25" } }, "processor": "ADYEN", "processorDisputeId": "dispute_123456789", "receivedAt": "2025-09-23T13:00:00Z", "challengeRequiredBy": "2025-10-07T13:00:00Z", "reason": "Fraudulent transaction", "reasonCode": "4800", "processorReason": "Chargeback reason code 4800", "amount": 1000, "currency": "GBP", "merchantId": "merchant_12345" } ``` # Payment Operation Failure Source: https://primer.io/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-operation-failure https://api.schemas.primer.io/api-reference/v2.4/webhooks.yaml post /payment-operation-failure Every operation you trigger on a payment deserves a clear answer. These webhooks deliver one instantly - so you can act before a missed capture or failed refund becomes a problem you discover too late. Primer notifies you with a failure webhook whenever a payment operation attempt does not succeed and the payment status has not changed as a result. The following event types are supported: - `PAYMENT.CAPTURE.FAILED` - a capture attempt did not succeed - `PAYMENT.REFUND.FAILED` - a refund attempt did not succeed - `PAYMENT.CANCELLATION.FAILED` - a cancellation attempt did not succeed - `PAYMENT.AUTHORIZATION_ADJUSTMENT.FAILED` - an authorization adjustment attempt did not succeed These events are operational signals, not status changes. Receiving a `PAYMENT.CAPTURE.FAILED` event, for example, means the capture attempt was unsuccessful - it does not mean the payment has failed or that the authorization has been lost. **When does a failure webhook fire?** Common scenarios include: - **Amount mismatch** - you attempt to capture £100, but the remaining authorised amount is only £80 - **PSP-side error** - the processor returns a technical error or the request times out before a response is received > **Particularly useful with Primer Workflows.** If you trigger captures or refunds automatically through a Workflow, failure webhooks are the signal you need to keep your own systems in sync. Because the action happened upstream, your backend won't know it failed unless Primer tells you - these events close that gap. A **webhook is emitted for every individual failed attempt**. If the same operation fails multiple times, you will receive a separate event each time. The webhook payload is intentionally minimal. To **retrieve the full context** - including the error reason, timeline, and processor response - **call** `GET /payments/{id}?expand=transactions.events` after receiving the event. **What to do when you receive a failure event** The right action depends on the failure type: for amount mismatches, you may want to retry the capture with a corrected amount; for PSP errors or timeouts, a retry after a short delay is often appropriate. In all cases, make sure your internal systems reflect the outcome - update your order management, notify your operations team if needed, and avoid leaving the payment in an ambiguous state on your end. **Testing failure webhooks in sandbox** The easiest way to trigger each failure event in your sandbox environment is to force a condition that will cause the processor to reject the operation. Because the failures are real processor responses, no special flags or mock modes are needed — you just need to engineer the right conditions. - **`PAYMENT.CAPTURE.FAILED`** — Authorise a payment, then attempt to capture an amount larger than what was authorised. The processor will reject the capture and the event will fire immediately. - **`PAYMENT.REFUND.FAILED`** — Capture a payment, then refund it directly through your processor's dashboard before sending the refund request to Primer. Since the funds have already been returned at the processor level, Primer's refund attempt will fail and the event will fire. - **`PAYMENT.CANCELLATION.FAILED`** — Authorise a payment, then capture it directly through your processor's dashboard (outside of Primer). When you then send a cancel request through Primer, the processor will reject it since the payment is no longer in a cancellable state, since the capture already happened. In all cases, once you receive the webhook, you can retrieve the full error detail by calling `GET /payments/{id}?expand=transactions.events`. The `transactionEvent.id` in the webhook payload corresponds directly to the event entry in the response, where you will find the processor status reason and the full operation timeline. ```json Webhook theme={"dark"} Version - 2.4 ``` ```json Example capture failed notification theme={"dark"} { "eventType": "PAYMENT.CAPTURE.FAILED", "date": "2026-02-19T15:36:16.367687", "notificationConfig": { "id": "cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description": "Payment webhook" }, "version": "2.4", "signedAt": "1689221338", "payment": { "id": "DdRZ6YY0", "amount": 3000, "currencyCode": "GBP", "orderId": "order-123" }, "requestAmount": 1500, "transactionEvent": { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } } ``` Learn more about [how Primer handles webhooks](/docs/api-reference/get-started/configure-webhooks). # Payment Refund Source: https://primer.io/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-refund https://api.schemas.primer.io/api-reference/v2.4/webhooks.yaml post /payment-refund Primer notifies you with a `PAYMENT.REFUND` Webhook when a refund request has been fully processed by a payment processor and the refund has reached a final state. Check the transaction with the most recent `transactionType: "REFUND"` in the `transactions` array: - if `processorStatus` is `SETTLED`, the refund was successful and the funds have been returned to the customer - if `processorStatus` is `FAILED`, the refund was unsuccessful Learn more about [how Primer handles webhooks](/docs/api-reference/get-started/configure-webhooks). ```json Webhook theme={"dark"} Version - 2.4 ``` ```json Example payment refund notification theme={"dark"} { "eventType":"PAYMENT.REFUND", "date":"2021-02-21T15:37:16.367687", "notificationConfig":{ "id":"cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description":"Refund webhook" }, "version":"2.4", "signedAt": "1689221398", "payment":{ "id":"DdRZ6YY0", "date":"2021-02-21T15:34:16.367687", "dateUpdated":"2021-02-21T15:37:16.267687", "amount":3000, "currencyCode":"GBP", "customerId":"cust-123", "orderId":"order-123", "status":"SETTLED", "cardTokenType":"CARD_PAN", "customer": { "emailAddress": "test@primer.io", "mobileNumber": "0123456789", "billingAddress": { "firstName": "John", "postalCode": "CB94BQ", "addressLine1": "10001 Alpha St", "countryCode": "GB", "city": "Cambridge", "state": "Cambridgeshire" } }, "paymentMethod":{ "paymentType":"FIRST_PAYMENT", "paymentMethodToken":"-lcWjvBAAs2DnIRXwxNjUzNTYzNjIy", "isVaulted": "false", "analyticsId":"LUi5pETUaVsdSEamK25L", "paymentMethodType":"PAYMENT_CARD", "paymentMethodData":{ "last4Digits":"1111", "first6Digits": "411111", "firstDigits": "41111111", "expirationMonth":"03", "expirationYear":"2030", "cardholderName":"ADYEN", "network":"Visa", "isNetworkTokenized":false, "binData":{ "network":"VISA", "issuerCountryCode":"US", "issuerName":"JPMORGAN CHASE BANK, N.A.", "regionalRestriction":"UNKNOWN", "accountNumberType":"UNKNOWN", "accountFundingType":"UNKNOWN", "prepaidReloadableIndicator":"NOT_APPLICABLE", "productUsageType":"UNKNOWN", "productCode":"UNKNOWN", "productName":"UNKNOWN" } }, "authorizationType": "FINAL", "threeDSecureAuthentication":{ "responseCode":"NOT_PERFORMED" } }, "processor":{ "name":"STRIPE", "processorMerchantId":"acct_1GORasdasqNWFwi8c", "amountCaptured":3000, "amountRefunded":3000 }, "transactions":[ { "date":"2021-02-21T15:34:16.367687", "amount":3000, "currencyCode":"GBP", "transactionType":"SALE", "orderId":"order-123", "processorTransactionId":"pi_3L3edsGZasdasdc1iget38p", "authorizationCode":"831000", "processorName":"STRIPE", "processorMerchantId":"acct_1GORasvasdNWFwi8c", "processorStatus":"SETTLED", "cardTokenType":"CARD_PAN" }, { "date":"2021-02-21T15:37:16.267687", "amount":3000, "currencyCode":"GBP", "transactionType":"REFUND", "orderId":"order-123", "processorTransactionId":"re_3L3edsGZasdasdc1iget38p", "processorName":"STRIPE", "processorMerchantId":"acct_1GORasvasdNWFwi8c", "processorStatus":"SETTLED", "cardTokenType":"CARD_PAN" } ], "riskData":{ "fraudChecks":{ "source":"riskified", "preAuthorizationResult":"THREE_DS_EXEMPTION", "preAuthorizationRecommendation":"TRANSACTION_RISK_ANALYSIS", "postAuthorizationResult":"ACCEPT" }, "cvvCheck": { "source": "processor", "result": "MATCHED" }, "avsCheck": { "source": "processor", "result": { "streetAddress": "NOT_MATCHED", "postalCode": "NOT_VERIFIED" } } } } } ``` # Payment Status Update Source: https://primer.io/docs/api-reference/endpoints/v2.4/payment-webhooks/payment-status-update https://api.schemas.primer.io/api-reference/v2.4/webhooks.yaml post /payment-status Primer notifies you with a `PAYMENT.STATUS` webhook when a payment's status has been updated. This is especially useful for asyncronous processor Connections, which do not respond with an upfront authorization. The webhook events will arrive in the order that the payment status changes, for example you should expect a status of `PENDING`, then `AUTHORIZED`, then `SETTLED` (depending on how your workflow is set up). The webhook body contains the full payment object. ```json Webhook theme={"dark"} Version - 2.4 ``` ```json Example payment status notification theme={"dark"} { "eventType":"PAYMENT.STATUS", "date":"2021-02-21T15:36:16.367687", "notificationConfig":{ "id":"cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description":"Payment webhook" }, "version":"2.4", "signedAt": "1689221338", "payment":{ "id":"DdRZ6YY0", "date":"2021-02-21T15:34:16.367687", "dateUpdated":"2021-02-21T15:35:16.133701", "amount":3000, "currencyCode":"GBP", "customerId":"cust-123", "orderId":"order-123", "status":"SETTLED", "cardTokenType":"CARD_PAN", "customer": { "emailAddress": "test@primer.io", "mobileNumber": "0123456789", "billingAddress": { "firstName": "John", "postalCode": "CB94BQ", "addressLine1": "10001 Alpha St", "countryCode": "GB", "city": "Cambridge", "state": "Cambridgeshire" } }, "paymentMethod":{ "paymentType":"FIRST_PAYMENT", "paymentMethodToken":"-lcWjvBAAs2DnIRXwxNjUzNTYzNjIy", "isVaulted": "false", "analyticsId":"LUi5pETUaVsdSEamK25L", "paymentMethodType":"PAYMENT_CARD", "paymentMethodData":{ "last4Digits":"1111", "first6Digits": "411111", "firstDigits": "41111111", "expirationMonth":"03", "expirationYear":"2030", "cardholderName":"ADYEN", "network":"Visa", "isNetworkTokenized":false, "binData":{ "network":"VISA", "issuerCountryCode":"US", "issuerName":"JPMORGAN CHASE BANK, N.A.", "regionalRestriction":"UNKNOWN", "accountNumberType":"UNKNOWN", "accountFundingType":"UNKNOWN", "prepaidReloadableIndicator":"NOT_APPLICABLE", "productUsageType":"UNKNOWN", "productCode":"UNKNOWN", "productName":"UNKNOWN" } }, "authorizationType": "FINAL", "threeDSecureAuthentication":{ "responseCode":"NOT_PERFORMED" } }, "processor":{ "name":"STRIPE", "processorMerchantId":"acct_1GORasdasqNWFwi8c", "amountCaptured":3000, "amountRefunded":0 }, "transactions":[ { "date":"2021-02-21T15:34:16.367687", "amount":3000, "currencyCode":"GBP", "transactionType":"SALE", "orderId":"order-123", "processorTransactionId":"pi_3L3edsGZasdasdc1iget38p", "authorizationCode":"831000", "processorName":"STRIPE", "processorMerchantId":"acct_1GORasvasdNWFwi8c", "processorStatus":"SETTLED", "cardTokenType":"CARD_PAN" } ], "riskData":{ "fraudChecks":{ "source":"riskified", "preAuthorizationResult":"THREE_DS_EXEMPTION", "preAuthorizationRecommendation":"TRANSACTION_RISK_ANALYSIS", "postAuthorizationResult":"ACCEPT" }, "cvvCheck": { "source": "processor", "result": "MATCHED" }, "avsCheck": { "source": "processor", "result": { "streetAddress": "NOT_MATCHED", "postalCode": "NOT_VERIFIED" } } } } } ``` Learn more about [how Primer handles webhooks](/docs/api-reference/get-started/configure-webhooks). # Workflow Run Failed Source: https://primer.io/docs/api-reference/endpoints/v2.4/workflow-webhooks/workflow-run-failed https://api.schemas.primer.io/api-reference/v2.4/webhooks.yaml post /workflow-run-failed Primer notifies you with a `WORKFLOW_RUN.FAILED` webhook when a workflow run does not complete successfully. This webhook is recommended if you use Capture or Cancel via Workflows. A workflow failure does not necessarily fail the payment or update the payment status, so this webhook is the signal you need to keep your own systems in sync when an automated capture or cancel does not succeed. For payment workflows, the payload does not contain payment data — only the Payment ID in the `triggerEventId` field. Use the [Payments API](/api-reference/v2.4/api-reference/payments-api/get-a-payment) to retrieve the latest status and payment data for the payment linked to this ID. Learn more about [Workflow Run failed webhooks](/workflows/monitor-workflows/workflow-run-failed-webhook) and [how Primer handles webhooks](/api-reference/get-started/configure-webhooks). ```json Webhook theme={"dark"} Version - 1.0 ``` ```json Example workflow run failed notification theme={"dark"} { "eventType": "WORKFLOW_RUN.FAILED", "version": "1.0", "date": "2024-02-21 15:36:16.167687", "primerAccountId": "123abcde-99f2-416e-8013-6ecd1c1285c3", "triggerEventId": "DdRZ6YY0", "workflow": { "id": "ecb8d3bc-123a-4d56-826e-ef8d4cc3d2a2", "name": "MIT UK Card", "version": 8 }, "run": { "timestamp": "2024-03-07T12:20:14.394429", "id": "bbb1c3cc-805d-4d97-826e-ef8d4cc3d2a2", "status": "FAILED", "lastError": { "applicationId": "PRIMER_PAYMENTS", "actionId": "capture_payment", "diagnosticsId": "1234567890", "message": "Payment ID not found." } } } ``` # API lifecycle Source: https://primer.io/docs/api-reference/get-started/api-lifecycle How Primer versions, supports, and deprecates the Primer API. This page describes the lifecycle of the Primer API: the named stages every version moves through, what Primer commits to at each stage, and the rules that govern transitions. ## Lifecycle stages Every supported version of the API is in one of six stages at any given time. | Stage | Badge | SLA | Support | Breaking changes | Minimum notice before next stage | | - | - | - | - | - | - | | Beta | `BETA` | None — use at own risk. | Best-effort support for our early adopters. | Allowed, documented in the changelog. | — | | Release Candidate | `RC` | None — near-final quality. | Priority support for testers. | Unlikely, but possible. | 30 days before `GA`. | | Generally Available | `GA` | Full production SLA. | Full support: bug fixes, security patches, and new features. | Avoided. A migration path is provided when one is required. | 12 months before deprecation. | | Supported | `Supported` | Reduced — security only. | Critical security patches only. No new features. | None — the version is frozen. | 12 months before end of life. | | Deprecated | `Deprecated` | Reduced. | None. The version still serves traffic and emits deprecation signals. | None. | 12 months before end of life. | | End of Life | `EOL` | None. | None. Calls return `410 Gone`. | — | — | ## How versions move between stages The lifecycle is **time-driven**, with explicit minimum notice periods at each transition. Notice periods are floors, not targets — Primer can stay in any stage for longer than the minimum, but cannot shorten it. * A version in `RC` reaches `GA` no sooner than 30 days after entering `RC`. * A version in `GA` is given at least 12 months of notice before being deprecated. * A version in `Deprecated` remains there for at least 12 months before reaching `EOL`. ```mermaid theme={"dark"} gantt title Example timeline (illustrative) dateFormat YYYY-MM-DD axisFormat %b %Y section vN Beta :vnbeta, 2025-01-01, 60d RC :vnrc, 2025-03-01, 30d GA :vnga, 2025-04-01, 365d Supported :vnsup, 2026-04-01, 365d section vN-1 GA :vmga, 2024-01-01, 455d Supported :vmsup, 2025-04-01, 365d Deprecated :crit, vmdep, 2026-04-01, 365d End of life :milestone, vmeol, 2027-04-01, 0d section vN-2 Supported :vlsup, 2024-04-01, 365d Deprecated :crit, vldep, 2025-04-01, 365d End of life :milestone, vleol, 2026-04-01, 0d ``` ## Current status | Version | Stage | Deprecation | End of life | | - | - | - | - | | `v2.4` | `GA` | — | — | | `v2.3` | `Supported` | 2026-07-01 | 2027-07-01 | | `v2.2` | `Supported` | 2026-07-01 | 2027-07-01 | | `v2.1` | `Supported` | 2026-07-01 | 2027-07-01 | | `v2` | `Supported` | 2026-07-01 | 2027-07-01 | This table is updated as versions transition between stages. For per-version changes, see the [API changelog](/docs/changelogs/api-changelog). ## Machine-readable signals Three HTTP signals communicate the lifecycle state of each request and response: * **`X-Api-Version` request header.** Pin every request to a specific API version. If the header is omitted, requests default to the earliest supported version — which means an unpinned client may silently start hitting an older version as new versions ship. Pinning is strongly recommended. * **`Deprecation` response header.** Emitted from `Deprecated` versions. Carries the date the version was deprecated. Standardised in [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745). * **`Sunset` response header.** Companion to `Deprecation`. Carries the planned end-of-life date. Standardised in the same RFC. Standardised in [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594) Example response from a deprecated version: ```http theme={"dark"} HTTP/1.1 200 OK Deprecation: @1782864000 Sunset: Tue, 01 Jun 2027 00:00:00 GMT Link: ; rel="deprecation" ``` The `Deprecation` and `Sunset` headers are scheduled for rollout alongside this policy. ## End of life behaviour When a version reaches `EOL`, calls to that version return `410 Gone`: ```http theme={"dark"} HTTP/1.1 410 Gone Content-Type: application/json { "error": { "type": "api_version_unsupported", "message": "This API version has reached end of life. Migrate to a supported version." } } ``` To avoid silent breakage, always pin requests to a specific version using the `X-Api-Version` header rather than relying on the default. ## Vocabulary `Supported` is a specific lifecycle stage on this page, not a general adjective. A version in `GA` is actively supported but is not in the `Supported` stage. When referring to a version's state, prefer the badges — `GA`, `Supported`, `Deprecated`, `EOL` — over prose. `Deprecated` and `EOL` are distinct stages. A `Deprecated` version still serves traffic, with deprecation signals attached to every response. An `EOL` version no longer serves traffic and returns `410 Gone`. ## Related * [API changelog](/docs/changelogs/api-changelog) * [SDK lifecycle](/docs/sdk/lifecycle) — the same model applied to the Primer SDKs. # API Responses Source: https://primer.io/docs/api-reference/get-started/api-responses ## Status Codes The following table summarizes the HTTP response codes you may receive from the Primer REST API. | Status Code | Description | | - | - | | `200` | Success | | `400` | Bad Request | | `401` | Unauthorized | | `403` | Forbidden | | `404` | Entity Not Found | | `409` | Entity Already Exists | | `422` | Input Validation Failed | | `429` | Rate Limit Exceeded | ## Error Responses Primer uses conventional HTTP response codes to indicate the success or failure of an API request. HTTP codes in the `2XX` range indicate a successful request, whereas codes in the `4XX` range indicate a failed request usually due to invalid inputs or operations. The format of the payload for all errors is common. When an unsuccessful request occurs, you will receive a payload in the following format: ```json theme={"dark"} { "error": { "errorId": "AnErrorId", "description": "A human description of the error.", "diagnosticsId": "1234567890", "validationErrors": [] } } ``` All error payloads will be comprised of a unique `errorId` which you can use to identify the error, a human description `description`, and a `diagnosticsId` that you can quote when contacting the support team ([support@primer.io](mailto:support@primer.io)). In case of a badly formed request, Primer will also return additional `validationErrors`. > [!NOTE] > > A `403` response with the `SecurityPolicyBlock` error ID does not include a `diagnosticsId`. These requests are blocked before they reach the API, so no diagnostics record is created. When contacting support about these errors, include the source IP address and the time of the failed requests instead. See [Request requirements](/docs/api-reference/get-started/request-requirements). ## Payment Status As the payments are created, processed, and finalised, they go through a number of states that you will get as an API response, through webhook notifications, and in the Dashboard. These states are used across all processors, as processor specific states are mapped to these. An additional message, in the field `processorMessage`, from the processor may also be included that details the reason for the state, primarily on failure states. | Status | Description | | - | - | | PENDING | The payment has been created by Primer but not yet authorized. | | FAILED | The processor failed to process this payment. | | AUTHORIZED | The payment is authorized and awaiting capture. | | SETTLING | The payment has been submitted for settlement and funds will be settled later. | | PARTIALLY\_SETTLED | The payment has been partially settled. | | SETTLED | Funds have been settled into your account. | | DECLINED | This payment was declined by the processor, either at a gateway or acquirer level. See the reason object in your response payload for more details. | | CANCELLED | The payment was cancelled prior to it being settled. | ## Breaking changes Primer commits to not introducing breaking changes in endpoints or API versions without also introducing a minor API version bump. You can expect endpoints that you’re using to not have breaking changes until you upgrade to another version. However, you should expect non-breaking or additive changes, and we encourage you to design your systems to protect against this possibility. Currently, non-breaking changes can happen inside the same minor API version, and breaking changes cannot. Primer considers breaking changes to be changes that can potentially break an integration. Breaking changes include: * removing an entire operation * removing or renaming a parameter * removing or renaming a response field * adding a new required parameter * making a previously optional parameter required * changing the type of a parameter or response field * removing enum values * adding a new validation rule to an existing parameter * changing authentication or authorization requirements Primer considers non-breaking changes to be changes that should not break an integration, and that you should protect against. Additive changes include: * adding an operation * adding an optional parameter * adding an optional request header * adding a response field * adding a response header * adding values to existing enums If, in exceptional circumstances, we do need to introduce a breaking change without bumping the API version, then we will ensure to communicate this ahead of any release, working closely with you to mitigate any possible impact. Don’t hesitate to reach out with any questions or feedback. You can email Primer directly at [support@primer.io](mailto:support@primer.io), or contact your Primer account manager. # Authentication Source: https://primer.io/docs/api-reference/get-started/authentication Primer uses API keys to authenticate requests. You can manage API keys in the [Developers](https://dashboard.primer.io/developers) area of the dashboard. As API keys carry many privileges such as *authorizing payments*, it is important to keep them **private** and **secure**. Do not hardcode or share API keys (particularly in your source version control system), and they should only be used in your backend. > [!NOTE] > > Send server-side requests from a static egress IP address, not a shared or dynamically assigned cloud IP address. See [Request requirements](/docs/api-reference/get-started/request-requirements). Authentication is handled via HTTP headers, specifically the `X-Api-Key` header. ```bash theme={"dark"} curl -X POST 'https://api.primer.io/' \ --header 'X-Api-Key: ' ``` ## Managing API Keys Head up to the [Developers area](https://dashboard.primer.io/developers) on the dashboard to manage your API keys. You will be able to generate or revoke API keys and edit their respective scopes. Be aware that any changes to existing API keys will be reflected immediately and could cause unwanted side effects. ## Available scopes | Scope | Description | | - | - | | `client_tokens:write` | Create client tokens for use with the client SDK. | | `third_party:webhook_trigger` | Allows a third party, typically your payment processor, to post to Primer's callback endpoint. API keys with this scope enable communication between your processor and Primer about important payment lifecycle events. | | `transactions:authorize` | Authorize a payment | | `transactions:cancel` | Cancel a payment. | | `transactions:capture` | Submit a payment for settlement. | | `transactions:read` | Retrieve one or more payments. | | `transactions:refund` | Refund a payment. | | `payment_instrument:read` | Read stored payment methods. | | `payment_instrument:write` | Write stored payment methods. | | `google_pay_merchants:read` | List the Google Pay domains registered through Primer. See [Manage Google Pay domains through Primer](/docs/connections/payment-methods/google-pay/domain-management). | | `google_pay_merchants:write` | Register and remove Google Pay domains through Primer. | # Configure Webhooks Source: https://primer.io/docs/api-reference/get-started/configure-webhooks ## Overview A webhook is a notification sent from Primer to your server using an HTTP `POST` request. You can use webhooks to be notified of: * **Payment status updates**\ Useful for asynchronous processor connections, where you do not get an immediate authorization response. * **Refund completion**\ Notified when a refund reaches a final state. * **Payment operation failures**\ Notified when a capture, cancellation, refund, or authorization adjustment attempt fails without changing the payment status. * **Disputes and chargebacks**\ Notified when a dispute is opened. * **Workflow run failures**\ Recommended if you use Capture or Cancel via Workflows. ## Delivery model (read this first) This section defines the expected behavior of Primer webhooks. ### What counts as a successful delivery A webhook delivery is considered **successful** when Primer receives **any HTTP `2xx`** response from your endpoint. Any response outside the `2xx` range, including `3xx` redirects, is treated as a failure and will trigger retries. ### How fast should my endpoint respond Your endpoint should return a `2xx` response **immediately** upon receiving the webhook. Do **not** perform long or complex processing before responding. A good pattern is: 1. Validate signature and basic payload shape 2. Enqueue the work (or store the event) 3. Respond with a `2xx` status code 4. Process asynchronously ### Timeout Primer uses a **10 second timeout** for webhook delivery attempts.\ If your endpoint does not respond within this window, the attempt is treated as a failure and retries may happen. ### When will I receive webhooks Webhook delivery typically happens **within seconds** of the underlying change (payment status update, refund completion, dispute opened, etc.), but is not guaranteed to be immediate. ## Retries If a delivery attempt fails, Primer retries the webhook up to **5 times** with increasing delays. Typical retry schedule: * \~10 seconds * \~60 seconds * \~5 minutes * \~10 minutes * \~15 minutes Actual retry timings may vary slightly due to random jitter applied to avoid retry bursts, which helps prevent many retries from hitting your server at the same time. The final retry happens approximately **30 minutes** after the first attempt. > [!NOTE] > > After the final retry attempt, the event is dropped and will not be retried again. ## Ordering and event recency Webhook ordering is **not guaranteed**. To detect the latest payment status change, compare `payment.dateUpdated` and keep the newest one. > [!WARNING] > > Never assume the last webhook you received is the newest one. > Always compare timestamps. ## Delivery guarantees and idempotency Primer webhooks are delivered **at least once**. This means that in rare cases, the same webhook event may be delivered more than once. Your system must be able to handle duplicate deliveries safely. To do this, webhook processing should be idempotent. Recommended approaches: * Store a unique key per processed event and ignore duplicates * Use stable identifiers from the payload, for example: * `payment.id` + `payment.dateUpdated` for payment status updates * `payment.id` + latest refund transaction timestamp for refunds * `transactionId` for disputes If a stable identifier cannot be derived, a safe fallback is to store a hash of the payload for a short time window and ignore repeated deliveries. ## Set up webhooks Set up a webhook in the **Developers** area of the Dashboard. Webhooks are sent with a `POST` request to your endpoint. ![](https://mintcdn.com/primer-cc826789/zUtJbc_qshGTc-1X/images/api/add_a_webhook.png?fit=max\&auto=format\&n=zUtJbc_qshGTc-1X\&q=85\&s=9529480da5c84ddca6e1258c8f8871d0) Add a webhook ## Test webhooks Click **Test webhook** to send an example request to your endpoint. ![](https://mintcdn.com/primer-cc826789/2gUFYKfNb_svpxsN/images/api/test_a_webhook.png?fit=max\&auto=format\&n=2gUFYKfNb_svpxsN\&q=85\&s=f15cea8db78b1679a3ec288d78678fc5) Test a webhook Example payload: ```json theme={"dark"} { "message": "Testing your webhook connection" } ``` ## Webhook event types ### Payment status updates Payment status notifications are sent whenever a payment status changes. The webhook payload contains the full payment object. **Example** ```json theme={"dark"} { "eventType": "PAYMENT.STATUS", "date": "2023-02-21T15:36:16.367687", "notificationConfig": { "id": "cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description": "Payment webhook" }, "version": "2.1", "payment": { "id": "DdRZ6YY0", "date": "2023-02-21T15:36:16.167687", "dateUpdated": "2023-02-21T15:36:16.267687", "amount": 3000, "currencyCode": "GBP", "customerId": "cust-123", "orderId": "order-123", "status": "SETTLED", "paymentMethod": { "paymentMethodToken": "-lcWjvBAAs2DnIRXwxNjUzNTYzNjIy", "analyticsId": "LUi5pETUaVsdSEamK25L", "paymentMethodType": "PAYMENT_CARD", "paymentMethodData": { "last4Digits": "1111", "expirationMonth": "03", "expirationYear": "2030", "cardholderName": "ADYEN", "network": "Visa", "isNetworkTokenized": false, "binData": { "network": "VISA", "issuerCountryCode": "US", "issuerName": "JPMORGAN CHASE BANK, N.A.", "regionalRestriction": "UNKNOWN", "accountNumberType": "UNKNOWN", "accountFundingType": "UNKNOWN", "prepaidReloadableIndicator": "NOT_APPLICABLE", "productUsageType": "UNKNOWN", "productCode": "UNKNOWN", "productName": "UNKNOWN" }, "cvvAvailable": true }, "threeDSecureAuthentication": { "responseCode": "NOT_PERFORMED" } }, "processor": { "name": "STRIPE", "processorMerchantId": "acct_1GORasdasqNWFwi8c", "amountCaptured": 3000, "amountRefunded": 0 }, "transactions": [ { "date": "2023-02-21T15:36:16.167687", "amount": 3000, "currencyCode": "GBP", "transactionType": "SALE", "processorTransactionId": "pi_3L3edsGZasdasdc1iget38p", "processorName": "STRIPE", "processorMerchantId": "acct_1GORasvasdNWFwi8c", "processorStatus": "SETTLED" } ] } } ``` > [!NOTE] > > See the [migration guide](/docs/changelogs/migration-guides/payment-status-webhooks) to update to the latest versions of the webhook event. ### Refunds Refund notifications are sent when a refund reaches a final state. Check the most recent `REFUND` transaction in the payment `transactions`: * SETTLED the refund succeeded and funds were returned * FAILED the refund failed **Example** ```json theme={"dark"} { "eventType": "PAYMENT.REFUND", "date": "2023-02-21T15:37:16.367687", "notificationConfig": { "id": "cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description": "Refund webhook" }, "version": "2.1", "payment": { "id": "DdRZ6YY0", "date": "2023-02-21T15:36:16.167687", "dateUpdated": "2023-02-21T15:37:16.267687", "amount": 3000, "currencyCode": "GBP", "customerId": "cust-123", "orderId": "order-123", "status": "SETTLED", "processor": { "name": "STRIPE", "processorMerchantId": "acct_1G2EpYaHgVZqNWFwi8c", "amountCaptured": 3000, "amountRefunded": 3000 }, "transactions": [ { "date": "2023-02-21T15:36:16.167687", "amount": 3000, "currencyCode": "GBP", "transactionType": "SALE", "processorTransactionId": "pi_3L3ed23NWFwiNWFwi8c1iget38p", "processorName": "STRIPE", "processorMerchantId": "acct_1GORcaGv23NWFwi8c", "processorStatus": "SETTLED" }, { "date": "2023-02-21T15:37:16.267687", "amount": 3000, "currencyCode": "GBP", "transactionType": "REFUND", "processorTransactionId": "pi_3L3ed23NWFwiNWFwi8c1iget38p", "processorName": "STRIPE", "processorMerchantId": "acct_1GORcaGv23NWFwi8c", "processorStatus": "SETTLED" } ] } } ``` ### Payment operation failures Failed operation notifications are sent when a capture, cancellation, refund, or authorization adjustment attempt fails but the payment status does not change. These webhooks use a minimal payload. Call `GET /payments/{id}?expand=transactions.events` to retrieve full details. | Event type | Description | | - | - | | `PAYMENT.CAPTURE.FAILED` | A capture attempt failed | | `PAYMENT.CANCELLATION.FAILED` | A cancellation attempt failed | | `PAYMENT.REFUND.FAILED` | A refund attempt failed | | `PAYMENT.AUTHORIZATION_ADJUSTMENT.FAILED` | An authorization adjustment attempt failed | **Example** ```json theme={"dark"} { "eventType": "PAYMENT.CAPTURE.FAILED", "date": "2026-02-19T15:36:16.367687", "notificationConfig": { "id": "cc51f9f0-7e1c-492b-9d37-f83a818f6070", "description": "Payment webhook" }, "version": "2.4", "signedAt": "1689221338", "payment": { "id": "DdRZ6YY0", "amount": 3000, "currencyCode": "GBP", "orderId": "order-123" }, "requestAmount": 1500, "transactionEvent": { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } } ``` ### Disputes and chargebacks Dispute notifications are sent when a dispute or chargeback is opened. | Field | Description | | - | - | | `eventType` | Always `DISPUTE.OPENED` | | `primerAccountId` | Your Primer merchant account id | | `transactionId` | Primer transaction id related to the dispute | | `orderId` | Your order reference | | `processorId` | Processor name | | `processorDisputeId` | Dispute id on the processor side | | `paymentId` | Primer payment id | | **Example** | | ```json theme={"dark"} { "eventType": "DISPUTE.OPENED", "version": "2.1", "primerAccountId": "7fcd50f1-99f2-416e-8013-6ecd1c1285c3", "transactionId": "c3f662ad-d197-492e-b78b-63eefa64a31d", "orderId": "order-123", "processorId": "Adyen", "processorDisputeId": "adyen_ref_123", "paymentId": "ecb8d3bc-805d-4d97-826e-ef8d4cc3d2a2" } ``` ### Workflow run failed This webhook is recommended if you use Capture or Cancel via Workflows. A workflow failure does not necessarily fail the payment or update the payment status. For more details, see the [Automation documentation](/docs/workflows/monitor-workflows/workflow-run-failed-webhook). ```json theme={"dark"} { "eventType": "WORKFLOW_RUN.FAILED", "version": "1.0", "date": "2024-02-21 15:36:16.167687", "primerAccountId": "123abcde-99f2-416e-8013-6ecd1c1285c3", "triggerEventId": "DdRZ6YY0", "workflow": { "id": "ecb8d3bc-123a-4d56-826e-ef8d4cc3d2a2", "name": "MIT UK Card", "version": 8 }, "run": { "timestamp": "2024-03-07T12:20:14.394429", "id": "bbb1c3cc-805d-4d97-826e-ef8d4cc3d2a2", "status": "FAILED", "lastError": { "applicationId": "PRIMER_PAYMENTS", "actionId": "capture_payment", "diagnosticsId": "1234567890", "message": "Payment ID not found." } } } ``` ## Webhook signing Primer can sign webhook events so you can verify that they were sent by Primer. Each webhook request includes the following headers: * `X-Signature-Primary` * `X-Signature-Secondary` only present during signing secret rotation The signature is an HMAC SHA256 of the raw webhook payload using your signing secret, base64 encoded. ### Prevent replay attacks Each webhook payload includes a `signedAt` field, representing the Unix timestamp of when the webhook was signed. When validating a webhook, you should verify that: * the signature is valid * the `signedAt` timestamp is close to your current system time\ Primer recommends a maximum difference of 3 minutes If Primer retries a webhook, it is signed again. Each retry has a new `signedAt` value and a new signature. ### Verify signatures (Python example) ```python theme={"dark"} import base64 import hashlib import hmac def validate_webhook_signature(payload: str, signature: str, secret: str) -> bool: mac = hmac.new( key=secret.encode("utf-8"), msg=payload.encode("utf-8"), digestmod=hashlib.sha256, ) computed = base64.b64encode(mac.digest()).decode("utf-8") return computed == signature ``` ### Set up your signing secret Create a signing secret from the **Webhooks** section of the Primer Dashboard. Signing secrets are environment specific. Each environment (Sandbox and Production) has its own secret. You can only copy the secret once. Make sure to store it securely. ### Rotate your signing secret You can rotate your active signing secret from the Dashboard at any time. When a secret is rotated: * the previous secret remains valid for 24 hours * both signatures are sent during that period Webhook request headers during rotation: * `X-Signature-Primary` signed with the new secret * `X-Signature-Secondary` signed with the previous secret During the transition window, your endpoint should verify the webhook against both signatures. ```python theme={"dark"} @router.post("/my-webhook") async def my_webhook(request: Request, payload: dict): if "X-Signature-Primary" in request.headers: verify(request.headers["X-Signature-Primary"], payload) if "X-Signature-Secondary" in request.headers: verify(request.headers["X-Signature-Secondary"], payload) return {"status": "ok"} ``` ## Checklist If you experience missing or repeated webhook events: * Ensure your endpoint responds with a `2xx` status code quickly * Avoid HTTP redirects * Handle duplicate deliveries safely * Compare `payment.dateUpdated` to determine the latest state * Verify webhook signatures and `signedAt` timestamps # Idempotency Key Source: https://primer.io/docs/api-reference/get-started/idempotency-key ## What is an idempotency key? Primer supports a request idempotency mechanism for our Payments API. This optional feature enables you to safely retry a request without risking the user being charged or refunded multiple times. This is particularly useful when an API call fails due to the request being invalid, due to a network issue, or if Primer is momentarily unavailable. If this is the case, make another request with the same idempotency key: * If a request with the same idempotency key has already been successfully processed by Primer, the new request will be ignored. A `409` error will be returned with an `errorId` set to `IdempotencyKeyAlreadyExists`. * Otherwise, Primer will attempt to process the new request. ## How to use an idempotency key To make an idempotent request, generate an idempotency key and pass it to the header `X-Idempotency-Key`. ```json theme={"dark"} curl -X POST 'https://api.primer.io/' \ --header 'X-Idempotency-Key: ' ``` The way you generate the key is totally up to you, as long as it is unique per request attempt. Keep in mind that a payment request resulting in a declined or failed payment is still considered Successfully processed for the API. Therefore, if you want to allow the user to retry an unsuccessful payment, make sure to not use the same idempotency key. As a such, don’t use anything too restrictive like an `orderId` for the idempotency key as multiple payment attempts and refunds can be made for a single order. # Request requirements Source: https://primer.io/docs/api-reference/get-started/request-requirements Send server-side requests to the Primer API from a static egress IP address so they are not blocked before they reach the API. ## Overview Primer may block API requests based on the IP address they come from. Many cloud platforms send outbound traffic from shared, dynamically assigned IP addresses by default. Other customers of the platform send traffic from the same addresses, so an address can be blocked because of their traffic rather than yours. When that happens, your requests to Primer are blocked, even though your integration has not changed. To avoid this, send all server-side requests to Primer from a static egress IP address that only you use. ## Use a static egress IP address A static egress IP address is a public IP address that you reserve. All outbound traffic from your backend to Primer uses it. This applies to every server-side call, for example: * creating and updating client sessions with `POST /client-session` and `PATCH /client-session` * creating, capturing, cancelling and refunding payments * managing saved payment methods Serverless and container platforms often use shared outbound addresses unless you configure otherwise. Route their traffic through a NAT service with a reserved IP address: | Platform | Configuration | | - | - | | Google Cloud (Cloud Run, Cloud Functions, GKE) | Route outbound traffic through Cloud NAT with a reserved static external IP address. | | AWS (Lambda, ECS, EKS, EC2) | Run the workload in a VPC and route outbound traffic through a NAT gateway with an Elastic IP address. | | Microsoft Azure | Attach a NAT gateway with a static public IP address to the workload's subnet. | Refer to your cloud provider's documentation for the setup steps. > [!NOTE] > > Configure the static egress IP address in your test environment as well as in production. This lets you confirm that requests use the new address before you go live. ## Identify a blocked request When a request is blocked, it does not reach the API and you will receive a `403` response with the `SecurityPolicyBlock` error ID: ```json theme={"dark"} { "error": { "errorId": "SecurityPolicyBlock", "description": "This request has been blocked by a security policy.", "validationErrors": [] } } ``` Blocks depend on the source IP address at the time of the request, so they can start and stop without any change to your integration. If you receive this error: 1. Check which public IP address your backend uses for outbound requests to Primer. 2. If it is a shared or dynamically assigned address, configure a static egress IP address as described above. 3. If the errors continue after you move to a static egress IP address, contact [support@primer.io](mailto:support@primer.io). Include the source IP address and the time of the failed requests. # Forward a request to a PSP, substituting vaulted card data Source: https://primer.io/docs/api-reference/v2.4/api-reference/primer-proxy-api/forward-a-request-to-a-psp-substituting-vaulted-card-data-2 https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml post /{proxyPath} Forwards the request to the host named in `X-Target-Host`, at the given path, substituting any card placeholders in the body first. Any additional headers on the request, including the merchant's own PSP credential (for example `Authorization`), are passed through unchanged. `X-Primer-Api-Key` authenticates you against Primer. A placeholder has the form `{{.}}`, for example `{{tok_abc.CARD_NUMBER}}`, and is substituted anywhere in the body. A placeholder left unresolved fails the request rather than being forwarded. The response is the target PSP's response, relayed byte-for-byte, unless the `X-Primer-Proxy-Error` response header is present, in which case Primer itself raised a fault before or after reaching the PSP. See the `default` response below for both cases. The proxy never retries a request to the PSP. # Forward a request to a PSP, substituting vaulted card data Source: https://primer.io/docs/api-reference/v2.4/api-reference/primer-proxy-api/forward-a-request-to-a-psp-substituting-vaulted-card-data-3 https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml delete /{proxyPath} Forwards the request to the host named in `X-Target-Host`, at the given path, substituting any card placeholders in the body first. Any additional headers on the request, including the merchant's own PSP credential (for example `Authorization`), are passed through unchanged. `X-Primer-Api-Key` authenticates you against Primer. A placeholder has the form `{{.}}`, for example `{{tok_abc.CARD_NUMBER}}`, and is substituted anywhere in the body. A placeholder left unresolved fails the request rather than being forwarded. The response is the target PSP's response, relayed byte-for-byte, unless the `X-Primer-Proxy-Error` response header is present, in which case Primer itself raised a fault before or after reaching the PSP. See the `default` response below for both cases. The proxy never retries a request to the PSP. # Forward a request to a PSP, substituting vaulted card data Source: https://primer.io/docs/api-reference/v2.4/api-reference/primer-proxy-api/forward-a-request-to-a-psp-substituting-vaulted-card-data-4 https://api.schemas.primer.io/api-reference/v2.4/openapi.yaml patch /{proxyPath} Forwards the request to the host named in `X-Target-Host`, at the given path, substituting any card placeholders in the body first. Any additional headers on the request, including the merchant's own PSP credential (for example `Authorization`), are passed through unchanged. `X-Primer-Api-Key` authenticates you against Primer. A placeholder has the form `{{.}}`, for example `{{tok_abc.CARD_NUMBER}}`, and is substituted anywhere in the body. A placeholder left unresolved fails the request rather than being forwarded. The response is the target PSP's response, relayed byte-for-byte, unless the `X-Primer-Proxy-Error` response header is present, in which case Primer itself raised a fault before or after reaching the PSP. See the `default` response below for both cases. The proxy never retries a request to the PSP. # Changelog Source: https://primer.io/docs/api-reference/changelog # Card Field Components Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-field-components Detailed reference for individual card and billing address field composables > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Each `CardFormDefaults` field component handles its own formatting, validation, keyboard configuration, and error display. All fields accept `controller: PrimerCardFormController` and `modifier: Modifier = Modifier`. ## Card detail fields ### CardNumberField | Aspect | Detail | | - | - | | Auto-formatting | Groups digits with spaces (e.g., `4242 4242 4242 4242`) | | Max length | 16-19 digits depending on detected network | | Keyboard type | `KeyboardType.Number` | | Validation | Luhn algorithm check, minimum length per network | | Validation timing | On blur (when user taps another field) | | Trailing icon | Detected card network logo(s) (Visa, Mastercard, Amex, etc.) | | Network detection | Local detection begins after the 1st digit; remote detection begins after the 8th digit | Supported networks: Visa, Mastercard, Amex, Diners Club, Discover, JCB, UnionPay, Maestro, Elo, Mir, Hiper, Hipercard, Cartes Bancaires, Dankort, Eftpos, Other. ### ExpiryField | Aspect | Detail | | - | - | | Auto-formatting | Inserts `/` automatically (typing `1225` → `12/25`) | | Max length | 5 characters (MM/YY) | | Keyboard | `KeyboardType.Number` | | Validation | Valid month (01–12), future date | ### CvvField | Aspect | Detail | | - | - | | Max length | 4 digits for Amex, 3 for other networks | | Keyboard | `KeyboardType.Number` | | Visual | Password masking (dots) | | Dynamic | Max length updates when card network is detected | ### CardholderField | Aspect | Detail | | - | - | | Keyboard | `KeyboardType.Text` with `KeyboardCapitalization.Words` | | Validation | Required (non-empty) when session requires cardholder name | | Visibility | Only rendered when `CARDHOLDER_NAME` is in `state.cardFields` | ### CardNetworkField | Aspect | Detail | | - | - | | Visibility | Only rendered when card has multiple networks (co-badged) | | Interaction | Tapping a chip calls `controller.selectCardNetwork(network)` | | No modifier parameter | Unlike other fields | ## Billing address fields All billing fields are rendered only when required by session configuration. | Field | Keyboard | Validation | Notes | | - | - | - | - | | `CountryCodeField` | — | Required | Read-only; opens picker via `requestCountrySelection()` | | `FirstNameField` | `Text` + `Words` capitalization | Required | — | | `LastNameField` | `Text` + `Words` capitalization | Required | — | | `AddressLine1Field` | `Text` | Required | — | | `AddressLine2Field` | `Text` | Optional | — | | `CityField` | `Text` | Required | — | | `StateField` | `Text` | Required | Label adapts to selected country | | `PostalCodeField` | `Text` | Required, format varies by country | Label adapts to selected country | ## Validation behavior 1. **While typing** — no error messages shown. `isFormValid` updates in real-time. 2. **On blur** — field is validated and any error is added to `state.fieldErrors`. 3. **Error display** — inline error text below the field using theme error color. 4. **Error clearing** — errors clear when corrected and re-validated on next blur. # PrimerCardFormController Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-form-controller Controller interface for managing card form state, field updates, validation, and submission > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Controller interface for the card payment form. Exposes observable state, field update methods, and submission actions. ## Creation ```kotlin theme={"dark"} @Composable fun rememberCardFormController( checkout: PrimerCheckoutController, ): PrimerCardFormController ``` | Parameter | Type | Description | | - | - | - | | `checkout` | `PrimerCheckoutController` | Checkout controller from `rememberPrimerCheckoutController()` | > [!NOTE] > > Must be called inside `PrimerCheckoutHost` content or a `PrimerCheckoutSheet` slot. ## Property | Property | Type | Description | | - | - | - | | `state` | `StateFlow` | Observable state containing field values, validation errors, loading state, and form configuration | ## Methods ### Field update methods | Method | Parameter | Description | | - | - | - | | `updateCardNumber(value: String)` | Raw card number | Updates card number. Triggers network detection. | | `updateCvv(value: String)` | CVV digits | Updates CVV field | | `updateExpiryDate(value: String)` | Raw expiry input | Updates expiry date. Auto-formats to MM/YY. | | `updateCardholderName(value: String)` | Full name | Updates cardholder name | | `updatePostalCode(value: String)` | Postal/ZIP code | Updates billing postal code | | `updateCountryCode(value: String)` | ISO country code | Updates billing country code | | `updateCity(value: String)` | City name | Updates billing city | | `updateState(value: String)` | State/region | Updates billing state | | `updateAddressLine1(value: String)` | Street address | Updates billing address line 1 | | `updateAddressLine2(value: String)` | Apt, suite, etc. | Updates billing address line 2 | | `updatePhoneNumber(value: String)` | Phone number | Updates billing phone number | | `updateFirstName(value: String)` | First name | Updates billing first name | | `updateLastName(value: String)` | Last name | Updates billing last name | ### Action methods | Method | Description | | - | - | | `submit()` | Submits the form for tokenization and payment. Sets `state.isLoading` to `true` during submission. | | `selectCardNetwork(network: PrimerCardNetwork)` | Selects a network for co-badged cards. Only applicable when `state.networkSelection` has multiple networks. | | `onFieldFocusChange(type: PrimerInputElementType, hasFocus: Boolean)` | Notifies controller of field focus changes. Triggers on-blur validation. | | `requestCountrySelection()` | Opens the country selection picker UI | | `setVaultOnSuccess(vault: Boolean)` | Configures whether to save the payment method to vault after success. Requires `customerId` in session. | ## State ```kotlin theme={"dark"} data class State( val cardFields: List, val billingFields: List, val fieldErrors: List?, val data: Map, val isLoading: Boolean, val isFormEnabled: Boolean, val selectedCountry: PrimerCountry?, val networkSelection: NetworkSelection?, val binData: PrimerBinData?, val fieldFocusStates: Map, val isFormValid: Boolean, val vaultOnSuccess: Boolean, ) ``` | Property | Type | Description | | - | - | - | | `cardFields` | `List` | Card input fields required by the session | | `billingFields` | `List` | Billing address fields required by the session. Empty if not required. | | `fieldErrors` | `List?` | Validation errors per field. `null` before first validation. See [Validation](/docs/sdk/android-checkout/v3.0.0-beta/api/common/validation-result). | | `data` | `Map` | Current field values keyed by input element type | | `isLoading` | `Boolean` | `true` while submitting a payment or applying `setVaultOnSuccess` — the client-session updates the card form triggers | | `isFormEnabled` | `Boolean` | `true` when the form accepts input. `false` during submission. | | `selectedCountry` | `PrimerCountry?` | Selected billing country, or `null` | | `networkSelection` | `NetworkSelection?` | Co-badge network selection data. `null` when card is not co-badged. | | `binData` | `PrimerBinData?` | BIN-data lookup result for the entered card number (issuer, funding type, regional debit network, etc.). `null` until the BIN range is recognised. | | `fieldFocusStates` | `Map` | Focus state per field. `FieldState` contains `hasFocus`, `hasBeenFocused`, and `shouldShowError`. | | `isFormValid` | `Boolean` | `true` when all required fields pass validation. Updates in real-time. | | `vaultOnSuccess` | `Boolean` | Whether payment method will be saved to vault on success | ### NetworkSelection ```kotlin theme={"dark"} data class NetworkSelection( val availableNetworks: List, val selectedNetwork: PrimerCardNetwork?, ) ``` | Property | Type | Description | | - | - | - | | `availableNetworks` | `List` | Card networks available for this card | | `selectedNetwork` | `PrimerCardNetwork?` | Currently selected network, or `null` | ## PrimerInputElementType | Value | Field | | - | - | | `CARD_NUMBER` | Card number | | `EXPIRY_DATE` | Expiry date (MM/YY) | | `CVV` | CVV / security code | | `CARDHOLDER_NAME` | Cardholder name | | `POSTAL_CODE` | Billing postal code | | `COUNTRY_CODE` | Billing country | | `CITY` | Billing city | | `STATE` | Billing state/region | | `ADDRESS_LINE_1` | Billing address line 1 | | `ADDRESS_LINE_2` | Billing address line 2 | | `PHONE_NUMBER` | Billing phone number | | `FIRST_NAME` | Billing first name | | `LAST_NAME` | Billing last name | ## SyncValidationError ```kotlin theme={"dark"} class SyncValidationError { val inputElementType: PrimerInputElementType val errorId: String val fieldId: Int val errorResId: Int? val errorFormatId: Int? } ``` | Property | Type | Description | | - | - | - | | `inputElementType` | `PrimerInputElementType` | Field that has the error | | `errorId` | `String` | Error identifier describing the validation failure | | `fieldId` | `Int` | Field identifier | | `errorResId` | `Int?` | Android string resource ID for the error message | | `errorFormatId` | `Int?` | Android string resource ID for the error format | See [Validation](/docs/sdk/android-checkout/v3.0.0-beta/api/common/validation-result) for details. ## FieldState ```kotlin theme={"dark"} data class FieldState( val hasFocus: Boolean, val hasBeenFocused: Boolean, val shouldShowError: Boolean, ) ``` | Property | Type | Description | | - | - | - | | `hasFocus` | `Boolean` | Whether the field currently has focus | | `hasBeenFocused` | `Boolean` | Whether the field has been focused at least once | | `shouldShowError` | `Boolean` | Whether the field should display its validation error | > [!NOTE] > > Validation errors appear on blur (when the user leaves a field), not while typing. Use `isFormValid` for submit button state and `fieldErrors` for error messages. # CardFormDefaults Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-form-defaults Pre-built sub-components for customizing PrimerCardForm slots > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Object providing pre-built composable functions for each part of the card form. Use these to rearrange or selectively replace sections of `PrimerCardForm`. ## Card detail fields | Function | Description | | - | - | | `CardNumberField(controller, modifier)` | Card number input with auto-formatting, Luhn validation, and network icon | | `ExpiryField(controller, modifier)` | Expiry date input with MM/YY auto-formatting | | `CvvField(controller, modifier)` | CVV input with dynamic length based on card network | | `CardholderField(controller, modifier)` | Cardholder name input. Only rendered when required by session. | | `CardNetworkField(controller)` | Co-badge network selector. Only rendered for co-badged cards. | All field functions accept `controller: PrimerCardFormController` and `modifier: Modifier = Modifier` (except `CardNetworkField` which has no modifier). ## Billing address fields | Function | Description | | - | - | | `CountryCodeField(controller, modifier)` | Country selector that opens a picker dialog | | `FirstNameField(controller, modifier)` | Billing first name input | | `LastNameField(controller, modifier)` | Billing last name input | | `AddressLine1Field(controller, modifier)` | Street address line 1 | | `AddressLine2Field(controller, modifier)` | Street address line 2 (optional) | | `CityField(controller, modifier)` | City name input | | `StateField(controller, modifier)` | State or region input | | `PostalCodeField(controller, modifier)` | Postal or ZIP code input | Only rendered when required by the session configuration. ## Content composables ### CardDetailsContent ```kotlin theme={"dark"} @Composable fun CardFormDefaults.CardDetailsContent( controller: PrimerCardFormController, cardNumber: @Composable () -> Unit = { CardNumberField(controller) }, expiryDate: @Composable () -> Unit = { ExpiryField(controller) }, cvv: @Composable () -> Unit = { CvvField(controller) }, cardholderName: @Composable () -> Unit = { CardholderField(controller) }, ) ``` Renders the default card details layout. Each field can be individually replaced via slot parameters. ### BillingAddressContent ```kotlin theme={"dark"} @Composable fun CardFormDefaults.BillingAddressContent( controller: PrimerCardFormController, countryCode: @Composable () -> Unit = { CountryCodeField(controller) }, firstName: @Composable () -> Unit = { FirstNameField(controller) }, lastName: @Composable () -> Unit = { LastNameField(controller) }, addressLine1: @Composable () -> Unit = { AddressLine1Field(controller) }, addressLine2: @Composable () -> Unit = { AddressLine2Field(controller) }, city: @Composable () -> Unit = { CityField(controller) }, state: @Composable () -> Unit = { StateField(controller) }, postalCode: @Composable () -> Unit = { PostalCodeField(controller) }, ) ``` Renders the default billing address layout. Only renders fields required by the session. ## Submit button ### SubmitButton ```kotlin theme={"dark"} @Composable fun CardFormDefaults.SubmitButton( controller: PrimerCardFormController, modifier: Modifier = Modifier, ) ``` Default pay button that displays the formatted amount, disables when invalid or submitting, and shows a loading indicator during submission. # PrimerCardForm Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/primer-card-form Composable component that renders a complete card payment form with customizable slots > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Composable that renders a card payment form with card details, optional billing address, and submit button. Each section is a slot parameter you can replace. ## Signature ```kotlin theme={"dark"} @Composable fun PrimerCardForm( controller: PrimerCardFormController, modifier: Modifier = Modifier, cardDetails: @Composable () -> Unit = { CardFormDefaults.CardDetailsContent(controller) }, billingAddress: @Composable () -> Unit = { CardFormDefaults.BillingAddressContent(controller) }, submitButton: @Composable () -> Unit = { CardFormDefaults.SubmitButton(controller) }, ) ``` ## Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `controller` | [`PrimerCardFormController`](/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-form-controller) | Required | Controller managing form state, validation, and submission | | `modifier` | `Modifier` | `Modifier` | Modifier applied to the root container | | `cardDetails` | `@Composable () -> Unit` | `CardFormDefaults.CardDetailsContent(controller)` | Slot for card input fields (number, expiry, CVV, cardholder name) | | `billingAddress` | `@Composable () -> Unit` | `CardFormDefaults.BillingAddressContent(controller)` | Slot for billing address fields. Only rendered when required by session. | | `submitButton` | `@Composable () -> Unit` | `CardFormDefaults.SubmitButton(controller)` | Slot for the submit/pay button | ## Default layout # PrimerCardNetwork Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-card-network Card network data class used in co-badged card selection > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Represents a card network option for co-badged card selection. Exposed through `PrimerCardFormController.State.networkSelection`. ## Definition ```kotlin theme={"dark"} data class PrimerCardNetwork( val network: CardNetwork.Type, val displayName: String, val allowed: Boolean, ) ``` ## Properties | Property | Type | Description | | - | - | - | | `network` | `CardNetwork.Type` | The card network type | | `displayName` | `String` | Human-readable network name (e.g., `"Visa"`, `"Mastercard"`) | | `allowed` | `Boolean` | Whether this network is allowed for the current transaction | ## CardNetwork.Type ```kotlin theme={"dark"} enum class CardNetwork.Type { OTHER, VISA, MASTERCARD, AMEX, DINERS_CLUB, DISCOVER, JCB, UNIONPAY, MAESTRO, ELO, MIR, HIPER, HIPERCARD, CARTES_BANCAIRES, DANKORT, EFTPOS, } ``` | Value | Display Name | | - | - | | `VISA` | Visa | | `MASTERCARD` | Mastercard | | `AMEX` | American Express | | `DINERS_CLUB` | Diners Club | | `DISCOVER` | Discover | | `JCB` | JCB | | `UNIONPAY` | UnionPay | | `MAESTRO` | Maestro | | `ELO` | Elo | | `MIR` | Mir | | `HIPER` | Hiper | | `HIPERCARD` | Hipercard | | `CARTES_BANCAIRES` | Cartes Bancaires | | `DANKORT` | Dankort | | `EFTPOS` | eftpos | | `OTHER` | Unknown | Each enum value also has a `displayName` property. ## Co-badged card selection When a card supports multiple networks (e.g., Visa + Cartes Bancaires), the card form exposes network selection through the controller state: ```kotlin theme={"dark"} val cardFormController = rememberCardFormController(checkout) val state by cardFormController.state.collectAsStateWithLifecycle() val selection = state.networkSelection selection.availableNetworks // List selection.selectedNetwork // PrimerCardNetwork? selection.isNetworkSelectable // Boolean cardFormController.selectCardNetwork(network) ``` | Property | Type | Description | | - | - | - | | `availableNetworks` | `List` | Networks available for the entered card number | | `selectedNetwork` | `PrimerCardNetwork?` | Currently selected network, or `null` if auto-detected | | `isNetworkSelectable` | `Boolean` | `true` when the user must choose between multiple networks | See [PrimerCardFormController](/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-form-controller) for full card form API. # PrimerCountry Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-country Country data class and selection controller for billing address forms > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Represents a country in the billing address form. Used by `PrimerCardFormController` for country selection. ## Definition ```kotlin theme={"dark"} data class PrimerCountry( val name: String, val code: CountryCode, ) ``` ## Properties | Property | Type | Description | | - | - | - | | `name` | `String` | Human-readable country name (e.g., `"United States"`, `"Germany"`) | | `code` | `CountryCode` | ISO 3166-1 alpha-2 country code enum (249 values) | ## CountryCode ISO 3166-1 alpha-2 enum with 249 country codes. Examples: | Value | Country | | - | - | | `CountryCode.US` | United States | | `CountryCode.GB` | United Kingdom | | `CountryCode.DE` | Germany | | `CountryCode.FR` | France | | `CountryCode.JP` | Japan | | `CountryCode.AU` | Australia | ## Card form integration Country selection is part of the card form billing address flow: ```kotlin theme={"dark"} val cardFormController = rememberCardFormController(checkout) val state by cardFormController.state.collectAsStateWithLifecycle() val selectedCountry: PrimerCountry? = state.selectedCountry cardFormController.requestCountrySelection() ``` Calling `requestCountrySelection()` opens the country picker. The selected country appears in `state.selectedCountry`. See [PrimerCardFormController](/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-form-controller) for full card form API. # PrimerError Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-error Error class containing payment and SDK error details > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Error class carried by [`PrimerCheckoutState.Failure`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state). Contains error details and a diagnostics ID for Primer support. ## Definition ```kotlin theme={"dark"} class PrimerError { val errorId: String val description: String val errorCode: String? val diagnosticsId: String val recoverySuggestion: String? } ``` ## Properties | Property | Type | Description | | - | - | - | | `errorId` | `String` | Unique error identifier for programmatic handling | | `description` | `String` | Human-readable error message (suitable for logging) | | `errorCode` | `String?` | Specific failure reason (e.g., `"card_declined"`, `"insufficient_funds"`). `null` for non-payment errors. | | `diagnosticsId` | `String` | Unique diagnostics ID. Provide to Primer support when investigating issues. | | `recoverySuggestion` | `String?` | Suggested recovery action. `null` when no recovery applies. | # PrimerSettings Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-settings Configuration class for SDK behavior, UI options, and payment method settings > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Configuration class for SDK behavior. Pass to `rememberPrimerCheckoutController()`. ## Definition ```kotlin theme={"dark"} data class PrimerSettings( var paymentHandling: PrimerPaymentHandling = PrimerPaymentHandling.AUTO, var locale: Locale = Locale.getDefault(), var paymentMethodOptions: PrimerPaymentMethodOptions = PrimerPaymentMethodOptions(), var uiOptions: PrimerUIOptions = PrimerUIOptions(), var debugOptions: PrimerDebugOptions = PrimerDebugOptions(), var clientSessionCachingEnabled: Boolean = false, var apiVersion: PrimerApiVersion = PrimerApiVersion.V2_4, ) ``` | Property | Type | Default | Description | | - | - | - | - | | `paymentHandling` | `PrimerPaymentHandling` | `AUTO` | Controls whether the SDK processes payments automatically or delegates to your server | | `locale` | `Locale` | `Locale.getDefault()` | Forces the SDK locale for translations and formatting | | `paymentMethodOptions` | `PrimerPaymentMethodOptions` | `PrimerPaymentMethodOptions()` | Payment method-specific configuration (Google Pay, Klarna, 3DS, Stripe) | | `uiOptions` | `PrimerUIOptions` | `PrimerUIOptions()` | UI behavior settings (screens, dismissal, theming) | | `debugOptions` | `PrimerDebugOptions` | `PrimerDebugOptions()` | Debug and development options | | `clientSessionCachingEnabled` | `Boolean` | `false` | Caches the client session to reduce network requests | | `apiVersion` | `PrimerApiVersion` | `V2_4` | Primer API version used for backend communication | ## Usage ```kotlin theme={"dark"} val settings = PrimerSettings( locale = Locale.GERMANY, uiOptions = PrimerUIOptions( isInitScreenEnabled = false, dismissalMechanism = listOf(DismissalMechanism.CLOSE_BUTTON), ), paymentMethodOptions = PrimerPaymentMethodOptions( redirectScheme = "myapp://primer", googlePayOptions = PrimerGooglePayOptions( merchantName = "My Store", captureBillingAddress = true, ), ), ) val checkout = rememberPrimerCheckoutController( clientToken = clientToken, settings = settings, ) ``` *** ## PrimerUIOptions Controls checkout UI behavior: which screens are shown, how the sheet is dismissed, and theming. ```kotlin theme={"dark"} data class PrimerUIOptions( var isInitScreenEnabled: Boolean = true, var isSuccessScreenEnabled: Boolean = true, var isErrorScreenEnabled: Boolean = true, var dismissalMechanism: List = listOf(DismissalMechanism.GESTURES), var theme: PrimerTheme = PrimerTheme(), var cardFormUIOptions: PrimerCardFormUIOptions = PrimerCardFormUIOptions(), ) ``` | Property | Type | Default | Description | | - | - | - | - | | `isInitScreenEnabled` | `Boolean` | `true` | Shows a loading screen while the checkout initializes | | `isSuccessScreenEnabled` | `Boolean` | `true` | Shows a success screen after payment completes | | `isErrorScreenEnabled` | `Boolean` | `true` | Shows an error screen when a payment fails | | `dismissalMechanism` | `List` | `[GESTURES]` | How the user can dismiss the checkout sheet | | `theme` | `PrimerTheme` | `PrimerTheme.build()` | Visual theme for all SDK components | | `cardFormUIOptions` | `PrimerCardFormUIOptions` | `PrimerCardFormUIOptions()` | Card form-specific UI options | ### DismissalMechanism | Value | Description | | - | - | | `GESTURES` | Dismiss by tapping outside or swiping down | | `CLOSE_BUTTON` | Shows a close button in the sheet header | ### PrimerCardFormUIOptions | Property | Type | Default | Description | | - | - | - | - | | `payButtonAddNewCard` | `Boolean` | `false` | When `true`, the card form button shows "Add new card" instead of "Pay" | | `payButtonText` | `String?` | `null` | The text of the Pay button on the card form. Write `{amount}` where the order total should go. The SDK fills it in, formatted for the shopper and including any card surcharge, and updates it when the surcharge changes. For example, `"Complete order {amount}"` reads "Complete order £11.50". Text without `{amount}` shows no amount, and the SDK leaves the token out while the amount is unknown. Empty or `null` keeps "Pay". Applies to the card form screen of the checkout and to the default `CardFormDefaults.SubmitButton` of a composable `PrimerCardForm`. Drop-in ignores it. | *** ## PrimerPaymentMethodOptions Payment method-specific configuration. Set `redirectScheme` for any flow that redirects to a third-party app (3DS, PayPal, Klarna). ```kotlin theme={"dark"} data class PrimerPaymentMethodOptions( var redirectScheme: String? = null, var googlePayOptions: PrimerGooglePayOptions = PrimerGooglePayOptions(), var klarnaOptions: PrimerKlarnaOptions = PrimerKlarnaOptions(), var threeDsOptions: PrimerThreeDsOptions = PrimerThreeDsOptions(), var stripeOptions: PrimerStripeOptions = PrimerStripeOptions(), ) ``` | Property | Type | Default | Description | | - | - | - | - | | `redirectScheme` | `String?` | `null` | Deep link scheme for returning from third-party apps (e.g., `"myapp://primer"`) | | `googlePayOptions` | `PrimerGooglePayOptions` | `PrimerGooglePayOptions()` | Google Pay configuration. Required when using Google Pay. | | `klarnaOptions` | `PrimerKlarnaOptions` | `PrimerKlarnaOptions()` | Klarna configuration. Required when using Klarna. | | `threeDsOptions` | `PrimerThreeDsOptions` | `PrimerThreeDsOptions()` | 3D Secure configuration | | `stripeOptions` | `PrimerStripeOptions` | `PrimerStripeOptions()` | Stripe ACH configuration. Required when using Stripe ACH. | ### PrimerGooglePayOptions | Property | Type | Default | Description | | - | - | - | - | | `merchantName` | `String?` | `null` | Merchant name displayed in the Google Pay sheet | | `buttonStyle` | `GooglePayButtonStyle` | — | Button appearance: `WHITE` or `BLACK` | | `captureBillingAddress` | `Boolean` | `false` | Requests billing address from Google Pay | | `existingPaymentMethodRequired` | `Boolean` | `false` | Only shows Google Pay if the user has a saved payment method | | `shippingAddressParameters` | `PrimerGoogleShippingAddressParameters?` | `null` | Asks the shopper for a shipping address in the Google Pay sheet (has `phoneNumberRequired`). When you register `onShippingAddressChange` ([Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping)), the SDK asks for the address itself, and this only adds the phone number. | | `requireShippingMethod` | `Boolean` | `false` | Not needed with the [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping) handlers. When you register `onShippingAddressChange`, the SDK ignores this setting. Registering `onShippingOptionChange` as well shows the shipping method selector. If you set this to `true` without `onShippingAddressChange`, the sheet has no shipping options to show, and the SDK logs a warning. | | `emailAddressRequired` | `Boolean` | `false` | Requests email from Google Pay | | `buttonOptions` | `GooglePayButtonOptions` | — | Button customization (`buttonTheme`, `buttonType`) | ### PrimerKlarnaOptions | Property | Type | Default | Description | | - | - | - | - | | `recurringPaymentDescription` | `String?` | `null` | Description shown for recurring Klarna payments | | `returnIntentUrl` | `String?` | `null` | Return URL after Klarna authorization | ### PrimerThreeDsOptions | Property | Type | Default | Description | | - | - | - | - | | `threeDsAppRequestorUrl` | `String?` | `null` | App requestor URL for 3DS2 authentication | ### PrimerStripeOptions | Property | Type | Default | Description | | - | - | - | - | | `mandateData` | `MandateData?` | `null` | ACH mandate text. Use `TemplateMandateData(merchantName)` for a standard template, or `FullMandateStringData(value)` / `FullMandateData(@StringRes value)` for custom text. | | `publishableKey` | `String?` | `null` | Stripe publishable key | *** ## PrimerDebugOptions | Property | Type | Default | Description | | - | - | - | - | | `is3DSSanityCheckEnabled` | `Boolean` | `true` | Enables 3DS security sanity checks. Disable only during development. | *** ## PrimerPaymentHandling | Value | Description | | - | - | | `AUTO` | SDK processes payment end-to-end. Emits `Success` or `Failure` events. | *** ## PrimerApiVersion | Value | Description | | - | - | | `V2_4` | Primer API version 2.4 (latest) | # Validation Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/common/validation-result Field-level validation errors and input element types for form validation > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Field-level validation errors reported through `PrimerCardFormController.State.fieldErrors`. ## SyncValidationError ```kotlin theme={"dark"} class SyncValidationError { val inputElementType: PrimerInputElementType val errorId: String } ``` | Property | Type | Description | | - | - | - | | `inputElementType` | `PrimerInputElementType` | Field that triggered the error | | `errorId` | `String` | Error identifier or message describing the validation failure | ## PrimerInputElementType ```kotlin theme={"dark"} enum class PrimerInputElementType { CARD_NUMBER, EXPIRY_DATE, CVV, CARDHOLDER_NAME, COUNTRY_CODE, FIRST_NAME, LAST_NAME, ADDRESS_LINE_1, ADDRESS_LINE_2, CITY, STATE, POSTAL_CODE, } ``` | Value | Validation | | - | - | | `CARD_NUMBER` | Luhn check + card network detection | | `EXPIRY_DATE` | MM/YY format, future date | | `CVV` | Correct length for card network (3 or 4 digits) | | `CARDHOLDER_NAME` | Non-empty when required | | `COUNTRY_CODE` | ISO 3166-1 alpha-2 | | `FIRST_NAME` | Non-empty | | `LAST_NAME` | Non-empty | | `ADDRESS_LINE_1` | Non-empty | | `ADDRESS_LINE_2` | Optional | | `CITY` | Non-empty | | `STATE` | Non-empty | | `POSTAL_CODE` | Format varies by country | ## Validation timing Fields validate **on blur** (when the user leaves a field), not while typing. > [!NOTE] > > `isFormValid` updates in real-time as the user types. `fieldErrors` only updates on blur. Use `isFormValid` for submit button state and `fieldErrors` for error messages. # API Reference Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/overview Complete API reference for the Primer Checkout Android SDK > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. ## Core API | Component | Description | | - | - | | [`PrimerCheckoutController`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-controller) | Main checkout session controller with state observation and actions | | [`PrimerCheckoutState`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state) | Unified checkout state — lifecycle (`Loading`, `Ready`), session updates, and terminal outcomes (`Success`, `Failure`) | | [`Payment outcomes`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-event) | How `Success` / `Failure` and `PrimerCheckoutData` are surfaced through `PrimerCheckoutState` | | [`PrimerCheckoutSheet`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-sheet) | Modal bottom sheet composable with built-in navigation and screen slots | | [`PrimerCheckoutHost`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-host) | Inline host composable for embedding checkout components in your layout | ## Card Form | Component | Description | | - | - | | [`PrimerCardForm`](/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/primer-card-form) | Card payment form composable with slot-based layout | | [`PrimerCardFormController`](/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-form-controller) | Card form state holder with field data, validation, and submit action | | [`CardFormDefaults`](/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-form-defaults) | Pre-built field components for custom card form layouts | | [Card Field Components](/docs/sdk/android-checkout/v3.0.0-beta/api/card-form/card-field-components) | Individual field composables (`CardNumberField`, `ExpiryField`, `CvvField`, etc.) | ## Payment Methods | Component | Description | | - | - | | [`PrimerPaymentMethods`](/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) | Payment method list composable | | [`PrimerPaymentMethodsController`](/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/payment-methods-controller) | Payment methods state holder with available methods | | [`PaymentMethodsDefaults`](/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/payment-methods-defaults) | Pre-built sub-components for custom payment method layouts | | [`PrimerVaultedPaymentMethodsController`](/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods-controller) | Saved payment methods state holder with select, delete, and management | ## Theming | Component | Description | | - | - | | [`PrimerTheme`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/primer-theme) | Root theme container holding all design token groups | | [`LightColorTokens` / `DarkColorTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/color-tokens) | Color tokens for light and dark mode | | [`SpacingTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/spacing-tokens) | Spacing values for padding and margins | | [`TypographyTokens` / `TypographyStyle`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/typography-tokens) | Font sizes, weights, and line heights | | [`RadiusTokens` / `WidthTokens` / `SizeTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/shape-tokens) | Corner radius, border widths, and component sizes | ## Common Objects | Component | Description | | - | - | | [`PrimerSettings`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-settings) | SDK configuration (payment handling mode, options) | | [`PrimerError`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-error) | Error details with diagnostics ID and recovery suggestion | | [`Validation`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/validation-result) | Field validation result with error details | | [`PrimerCardNetwork`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-card-network) | Card network type for co-badged card selection | | [`PrimerCountry`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-country) | Country data class and selection controller for billing address | ## Controller pattern All stateful components follow the same `remember*` controller pattern: ```kotlin theme={"dark"} val checkout = rememberPrimerCheckoutController(clientToken) val cardFormController = rememberCardFormController(checkout) val paymentMethodsController = rememberPaymentMethodsController(checkout) val vaultedMethodsController = rememberVaultedPaymentMethodsController(checkout) ``` Each controller is created with a `remember*` composable function, exposes state via `StateFlow`, and provides action methods. # PrimerPaymentMethodsController Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/payment-methods-controller Controller interface for accessing and selecting available payment methods > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Controller interface for the payment method list. Exposes available methods as observable state and provides selection. ## Creation ```kotlin theme={"dark"} @Composable fun rememberPaymentMethodsController( checkout: PrimerCheckoutController, ): PrimerPaymentMethodsController ``` | Parameter | Type | Description | | - | - | - | | `checkout` | `PrimerCheckoutController` | Checkout controller from `rememberPrimerCheckoutController()` | > [!NOTE] > > Must be called inside `PrimerCheckoutHost` content or a `PrimerCheckoutSheet` slot. ## Property | Property | Type | Description | | - | - | - | | `methods` | `StateFlow>` | Available payment methods for the current session. Updates on `checkout.refresh()`. | ## Method | Method | Description | | - | - | | `select(method: PrimerPaymentMethod)` | Selects a payment method to begin its payment flow (card form, redirect, native wallet, etc.) | ## PrimerPaymentMethod ```kotlin theme={"dark"} data class PrimerPaymentMethod( val paymentMethodType: String, val paymentMethodName: String?, val surcharge: Surcharge?, val supportedPrimerSessionIntents: List, val paymentMethodManagerCategories: List, ) ``` | Property | Type | Description | | - | - | - | | `paymentMethodType` | `String` | Payment method identifier (e.g., `"PAYMENT_CARD"`, `"PAYPAL"`, `"GOOGLE_PAY"`) | | `paymentMethodName` | `String?` | Human-readable display name | | `surcharge` | `Surcharge?` | Surcharge amount, or `null` if none | | `supportedPrimerSessionIntents` | `List` | Session intents supported by this payment method | | `paymentMethodManagerCategories` | `List` | Manager categories for this payment method | ### Common payment method types | Type | Description | | - | - | | `"PAYMENT_CARD"` | Credit/debit card | | `"PAYPAL"` | PayPal | | `"GOOGLE_PAY"` | Google Pay | | `"KLARNA"` | Klarna | | `"APPLE_PAY"` | Apple Pay | | `"IDEAL"` | iDEAL | | `"BANCONTACT"` | Bancontact | | `"SOFORT"` | Sofort/Klarna Pay Now | # PaymentMethodsDefaults Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/payment-methods-defaults Pre-built sub-components for customizing PrimerPaymentMethods slots > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Object providing pre-built composable functions for each part of the payment methods list. ## Components | Function | Description | | - | - | | `SectionHeader()` | Default "Pay with" header styled with the current theme | | `Method(method: PrimerPaymentMethod, onClick: () -> Unit)` | Payment method item with icon, name, optional surcharge, and chevron | | `EmptyState(modifier: Modifier = Modifier)` | Message displayed when no payment methods are available | ## SectionHeader ```kotlin theme={"dark"} @Composable fun PaymentMethodsDefaults.SectionHeader() ``` Renders "Pay with" text using the current theme's typography and color tokens. ## Method ```kotlin theme={"dark"} @Composable fun PaymentMethodsDefaults.Method( method: PrimerPaymentMethod, onClick: () -> Unit, ) ``` | Parameter | Type | Description | | - | - | - | | `method` | `PrimerPaymentMethod` | Payment method data to display | | `onClick` | `() -> Unit` | Callback when tapped. Typically calls `controller.select(method)`. | ## EmptyState ```kotlin theme={"dark"} @Composable fun PaymentMethodsDefaults.EmptyState( modifier: Modifier = Modifier, ) ``` Rendered automatically by `PrimerPaymentMethods` when the `controller.methods` list is empty. # PrimerPaymentMethods Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods Composable component that renders the available payment methods list with customizable slots > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Composable that renders available payment methods with customizable header and item slots. Handles surcharge grouping automatically. ## Signature ```kotlin theme={"dark"} @Composable fun PrimerPaymentMethods( controller: PrimerPaymentMethodsController, modifier: Modifier = Modifier, header: @Composable () -> Unit = { PaymentMethodsDefaults.SectionHeader() }, method: @Composable (PrimerPaymentMethod, () -> Unit) -> Unit = { paymentMethod, onClick -> PaymentMethodsDefaults.Method(paymentMethod, onClick) }, ) ``` ## Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `controller` | [`PrimerPaymentMethodsController`](/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/payment-methods-controller) | Required | Controller providing available payment methods | | `modifier` | `Modifier` | `Modifier` | Modifier applied to the root container | | `header` | `@Composable () -> Unit` | `PaymentMethodsDefaults.SectionHeader()` | Slot for section header above the list | | `method` | `@Composable (PrimerPaymentMethod, () -> Unit) -> Unit` | `PaymentMethodsDefaults.Method(...)` | Slot for each payment method item. Receives method data and onClick callback. | ## Default behavior Renders a "Pay with" header, a vertical list of methods with icon, name, and optional surcharge, and groups methods by surcharge amount. Shows `PaymentMethodsDefaults.EmptyState()` when no methods are available. # PrimerVaultedPaymentMethodsController Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods-controller Controller interface for managing saved (vaulted) payment methods > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Controller interface for saved payment methods. Exposes vaulted methods as observable state and provides selection, deletion, and management. ## Creation ```kotlin theme={"dark"} @Composable fun rememberVaultedPaymentMethodsController( checkout: PrimerCheckoutController, ): PrimerVaultedPaymentMethodsController ``` | Parameter | Type | Description | | - | - | - | | `checkout` | `PrimerCheckoutController` | Checkout controller from `rememberPrimerCheckoutController()` | > [!NOTE] > > Must be called inside `PrimerCheckoutHost` content or a `PrimerCheckoutSheet` slot. ## Property | Property | Type | Description | | - | - | - | | `methods` | `StateFlow>` | Saved payment methods for the current customer. Empty list while loading or when no methods exist. | > [!NOTE] > > The parent `checkout.state` provides loading/ready state. Use `checkout.state` to distinguish between "loading" and "no saved methods." ## Methods | Method | Description | | - | - | | `select(method: PrimerVaultedPaymentMethod)` | Pay with a saved method. Automatically shows CVV recapture if required by the payment method. | | `delete(method: PrimerVaultedPaymentMethod)` | Delete a saved method. Shows a confirmation dialog before deletion. | | `showAll()` | Open the full vaulted methods management screen. | ## PrimerVaultedPaymentMethod ```kotlin theme={"dark"} data class PrimerVaultedPaymentMethod( val id: String, val analyticsId: String, val paymentInstrumentType: String, val paymentMethodType: String, val paymentInstrumentData: PaymentInstrumentData, val threeDSecureAuthentication: AuthenticationDetails?, ) ``` | Property | Type | Description | | - | - | - | | `id` | `String` | Unique identifier for this vaulted method | | `analyticsId` | `String` | Analytics tracking identifier | | `paymentInstrumentType` | `String` | Instrument type (e.g., `"PAYMENT_CARD"`) | | `paymentMethodType` | `String` | Payment method type identifier | | `paymentInstrumentData` | `PaymentInstrumentData` | Card or payment method details | | `threeDSecureAuthentication` | `AuthenticationDetails?` | 3DS authentication data, if available | ### PaymentInstrumentData | Property | Type | Description | | - | - | - | | `network` | `String?` | Card network (e.g., `"Visa"`, `"Mastercard"`) | | `cardholderName` | `String?` | Cardholder name | | `first6Digits` | `String?` | First 6 digits (BIN) | | `firstDigits` | `String?` | First 6 or 8 digits (BIN) | | `last4Digits` | `String?` | Last 4 digits for display | | `expirationMonth` | `String?` | Expiry month (MM) | | `expirationYear` | `String?` | Expiry year (YYYY) | | `externalPayerInfo` | `ExternalPayerInfo?` | External payer details (e.g., PayPal email) | | `binData` | `BinData?` | BIN data for card routing | | `bankName` | `String?` | Bank name for bank-based methods | ## Composable ```kotlin theme={"dark"} @Composable fun PrimerVaultedPaymentMethods( controller: PrimerVaultedPaymentMethodsController, modifier: Modifier = Modifier, header: @Composable (onShowAll: () -> Unit) -> Unit = { onShowAll -> VaultedPaymentMethodsDefaults.SectionHeader(onShowAll) }, item: @Composable (method: PrimerVaultedPaymentMethod, isSelected: Boolean, onSelect: () -> Unit) -> Unit = { method, isSelected, onSelect -> VaultedPaymentMethodsDefaults.Method(method, isSelected, onSelect) }, submitButton: @Composable (isLoading: Boolean, enabled: Boolean, onSubmit: () -> Unit) -> Unit = { isLoading, enabled, onSubmit -> VaultedPaymentMethodsDefaults.SubmitButton(isLoading, enabled, onSubmit) }, ) ``` | Parameter | Type | Default | Description | | - | - | - | - | | `controller` | `PrimerVaultedPaymentMethodsController` | — | Controller from `rememberVaultedPaymentMethodsController()` | | `modifier` | `Modifier` | `Modifier` | Compose modifier | | `header` | `@Composable (onShowAll: () -> Unit) -> Unit` | `SectionHeader(onShowAll)` | Header composable above the list. Receives callback to show all saved methods. | | `item` | `@Composable (PrimerVaultedPaymentMethod, Boolean, () -> Unit) -> Unit` | `Method(...)` | Composable for each vaulted method row. Receives method, selection state, and select callback. | | `submitButton` | `@Composable (Boolean, Boolean, () -> Unit) -> Unit` | `SubmitButton(...)` | Submit button below the list. Receives loading state, enabled state, and submit callback. | ### VaultedPaymentMethodsDefaults | Function | Description | | - | - | | `SectionHeader(onShowAll: () -> Unit)` | Default section header ("Saved payment methods") with "Show all" action | | `Method(method: PrimerVaultedPaymentMethod, isSelected: Boolean, onSelect: () -> Unit)` | Default method row with card details, network icon, and selection | | `SubmitButton(isLoading: Boolean, enabled: Boolean, onSubmit: () -> Unit)` | Default submit button for vaulted payment | # PrimerCheckoutController Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-controller Main checkout session controller for state observation and session management > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Central interface for managing a checkout session. Create with `rememberPrimerCheckoutController()`. ## Creation ```kotlin theme={"dark"} @Composable fun rememberPrimerCheckoutController( clientToken: String, settings: PrimerSettings = PrimerSettings(), ): PrimerCheckoutController ``` | Parameter | Type | Default | Description | | - | - | - | - | | `clientToken` | `String` | Required | Short-lived token from the [Client Session API](/docs/checkout/client-session) | | `settings` | [`PrimerSettings`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-settings) | `PrimerSettings()` | SDK configuration including payment handling mode | ## Interface ```kotlin theme={"dark"} @Stable interface PrimerCheckoutController { val state: StateFlow fun refresh() fun dismiss() fun onShippingAddressChange(handler: (suspend (PrimerShippingAddressChange) -> List)?) fun onShippingOptionChange(handler: (suspend (PrimerShippingOptionChange) -> Unit)?) } ``` ## Property | Property | Type | Description | | - | - | - | | `state` | `StateFlow` | Unified checkout state — session lifecycle plus terminal payment outcomes (`Success` / `Failure`). Collect with `collectAsStateWithLifecycle()`. See [`PrimerCheckoutState`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state). | ## Methods | Method | Description | | - | - | | `refresh()` | Reinitializes the checkout session. State transitions back to `Loading` while refetching configuration. | | `dismiss()` | Programmatically dismisses the checkout UI. Closes the bottom sheet or triggers cleanup for inline host. | | `onShippingAddressChange(handler)` | Express Checkout: registers the handler that supplies shipping options for the address the shopper entered in the Google Pay sheet. Pass `null` to remove the handler. See [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping). | | `onShippingOptionChange(handler)` | Express Checkout: registers the handler that updates the client session's shipping to the selected option through your backend. Pass `null` to remove the handler. | ## Idempotency key Set the `X-Idempotency-Key` header from the `beforePaymentCreate` gate on [`PrimerCheckoutSheet`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-sheet) or [`PrimerCheckoutHost`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-host). The gate runs once per attempt — just before the SDK creates the payment — and the value you pass to `continuePaymentCreation(idempotencyKey)` is sent on `POST /payments` and every subsequent `POST /payments/{id}/resume` for that attempt. A retry after failure runs the gate again, producing a fresh key. ```kotlin theme={"dark"} val checkout = rememberPrimerCheckoutController(clientToken, settings) PrimerCheckoutSheet( checkout = checkout, beforePaymentCreate = { handler -> LaunchedEffect(Unit) { handler.continuePaymentCreation(idempotencyKey = UUID.randomUUID().toString()) } }, ) ``` ## Express Checkout shipping The two shipping handlers price Google Pay shipping from the address the shopper enters in the Google Pay sheet. Register both before the Google Pay sheet opens. They are `suspend` functions and run on the main thread. They share one 20 second budget per Google Pay callback, and the SDK cancels a handler when the budget runs out. ```kotlin theme={"dark"} val checkout = rememberPrimerCheckoutController(clientToken, settings) LaunchedEffect(checkout) { checkout.onShippingAddressChange { change -> myBackend.shippingRates(change.shippingAddress) } checkout.onShippingOptionChange { change -> myBackend.updateShipping(orderId, change.selectedShippingOption.id) } } ``` | Type | Fields | | - | - | | `PrimerShippingAddressChange` | `paymentMethodType: String`, `shippingAddress: PrimerAddress` | | `PrimerShippingOption` | `id: String`, `name: String`, `description: String`, `amount: Int` (minor units) | | `PrimerShippingOptionChange` | `paymentMethodType: String`, `selectedShippingOption: PrimerShippingOption` | The three types are in the `io.primer.checkout.api.shipping` package. See [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping) for the full flow, the client session patch your backend sends, and the failure modes. ## Extension function ### formatAmount ```kotlin theme={"dark"} fun PrimerCheckoutController.formatAmount(amountInCents: Int): String ``` Formats an amount in minor units (cents) into a locale-aware currency string based on the current session (e.g., `"$10.00"`, `"10,00 EUR"`). Once the checkout has reached `Ready`, it keeps working in every state, including `Loading` during `refresh()`, using the currency of the last `Ready` session. | Parameter | Type | Description | | - | - | - | | `amountInCents` | `Int` | Amount in minor currency units (e.g., `1000` for \$10.00 USD) | # Payment outcomes Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-event Success and failure outcomes, delivered as terminal states of PrimerCheckoutState > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Payment outcomes are terminal states of [`PrimerCheckoutState`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state), observed via `PrimerCheckoutController.state`. There is no separate event callback. > [!NOTE] > > Earlier previews delivered outcomes through a `PrimerCheckoutEvent` type and an `onEvent` lambda on `PrimerCheckoutSheet` / `PrimerCheckoutHost`. Both were removed — `Success` and `Failure` are now cases of `PrimerCheckoutState`. ## Outcomes ```kotlin theme={"dark"} sealed interface PrimerCheckoutState { // ... data class Success(val checkoutData: PrimerCheckoutData) : PrimerCheckoutState data class Failure( val primerError: PrimerError, val checkoutData: PrimerCheckoutData? = null, ) : PrimerCheckoutState } ``` ### Success Reached when payment completes successfully. Only emitted in `AUTO` payment handling mode. | Property | Type | Description | | - | - | - | | `checkoutData` | `PrimerCheckoutData` | Payment result containing payment ID and order ID | ### Failure Reached when a payment fails or an error occurs. | Property | Type | Description | | - | - | - | | `error` | [`PrimerError`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-error) | Error details including description, error code, and diagnostics ID | ## Reacting to outcomes ```kotlin theme={"dark"} val checkout = rememberPrimerCheckoutController(clientToken, settings) val state by checkout.state.collectAsStateWithLifecycle() LaunchedEffect(state) { when (val s = state) { is PrimerCheckoutState.Success -> navigateToConfirmation(s.checkoutData) is PrimerCheckoutState.Failure -> logError(s.primerError) else -> Unit } } PrimerCheckoutSheet(checkout = checkout) ``` The built-in `success` / `error` slots on [`PrimerCheckoutSheet`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-sheet) render the in-sheet result screens; observe `state` when you need to react programmatically (navigate, log, clear the cart). ## PrimerCheckoutData ```kotlin theme={"dark"} data class PrimerCheckoutData( val payment: Payment, ) ``` ### Payment ```kotlin theme={"dark"} data class Payment( val id: String, val orderId: String, ) ``` | Property | Type | Description | | - | - | - | | `id` | `String` | Unique payment identifier assigned by Primer | | `orderId` | `String` | Order identifier from the client session | # PrimerCheckoutHost Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-host Inline host composable for embedding checkout components directly in your layout > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Composable that wraps your custom checkout layout with `PrimerTheme` and required `CompositionLocal` providers. Renders SDK components inline rather than in a modal bottom sheet. Overlay sheets for 3DS and redirect flows are handled automatically. ## Signature ```kotlin theme={"dark"} @Composable fun PrimerCheckoutHost( checkout: PrimerCheckoutController, modifier: Modifier = Modifier, theme: PrimerTheme = PrimerTheme(), beforePaymentCreate: (@Composable (handler: PrimerPaymentCreationDecisionHandler) -> Unit)? = null, content: @Composable () -> Unit, ) ``` > [!NOTE] > > There is no `onEvent` callback. With the inline host you build your own result UI — > observe [`checkout.state`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state) > for `PrimerCheckoutState.Success` / `PrimerCheckoutState.Failure` and render accordingly. ## Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `checkout` | `PrimerCheckoutController` | Required | Checkout controller providing session state to child components | | `modifier` | `Modifier` | `Modifier` | Modifier applied to the host container | | `theme` | [`PrimerTheme`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/primer-theme) | `PrimerTheme()` | Design tokens applied to all SDK components within the host | | `beforePaymentCreate` | `(@Composable (PrimerPaymentCreationDecisionHandler) -> Unit)?` | `null` | Optional gate shown right before payment creation — run last-minute checks or set an idempotency key, then call `handler.continuePaymentCreation(idempotencyKey)` or `handler.abortPaymentCreation(message)`. Omit to let the SDK proceed automatically. | | `content` | `@Composable () -> Unit` | Required | Your custom layout containing SDK components (trailing lambda) | ## What it provides 1. **PrimerTheme** — applies design tokens so child components inherit your styling 2. **CompositionLocal providers** — injects checkout context so `remember*Controller()` functions work 3. **Overlay management** — renders overlays for 3DS challenges and redirect flows automatically Without `PrimerCheckoutHost`, SDK components like `PrimerCardForm` and `PrimerPaymentMethods` will not function. # PrimerCheckoutSheet Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-sheet Modal bottom sheet composable with built-in navigation and customizable screen slots > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Modal bottom sheet composable with built-in navigation between screens (splash, loading, payment methods, card form, success, error). Each screen is a slot parameter you can override. ## Signature ```kotlin theme={"dark"} @Composable fun PrimerCheckoutSheet( checkout: PrimerCheckoutController, modifier: Modifier = Modifier, onDismiss: () -> Unit = {}, theme: PrimerTheme = PrimerTheme(), splash: @Composable () -> Unit = { PrimerCheckoutSheetDefaults.Splash() }, loading: @Composable () -> Unit = { PrimerCheckoutSheetDefaults.Loading() }, paymentMethodSelection: @Composable () -> Unit = { PrimerCheckoutSheetDefaults.PaymentMethodSelection(checkout) }, cardForm: @Composable () -> Unit = { val controller = rememberCardFormController(checkout) PrimerCardForm(controller = controller) }, success: @Composable (PrimerCheckoutData) -> Unit = { data -> PrimerCheckoutSheetDefaults.Success(data) }, error: @Composable (PrimerError, PrimerCheckoutData?) -> Unit = { primerError, _ -> PrimerCheckoutSheetDefaults.Error(primerError) }, beforePaymentCreate: (@Composable (handler: PrimerPaymentCreationDecisionHandler) -> Unit)? = null, ) ``` > [!NOTE] > > There is no `onEvent` callback. The built-in `success` / `error` slots render the > in-sheet result screens; to react programmatically (navigate, log, refresh your > cart), observe [`checkout.state`](/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state) > for `PrimerCheckoutState.Success` / `PrimerCheckoutState.Failure`. ## Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `checkout` | `PrimerCheckoutController` | Required | Checkout controller that drives the sheet lifecycle | | `modifier` | `Modifier` | `Modifier` | Modifier applied to the bottom sheet container | | `onDismiss` | `() -> Unit` | `{}` | Called on swipe down, back press, or auto-dismiss after result screen | | `theme` | [`PrimerTheme`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/primer-theme) | `PrimerTheme()` | Design tokens applied to all components within the sheet | | `splash` | `@Composable () -> Unit` | `Defaults.Splash()` | Slot displayed briefly when the sheet first opens | | `loading` | `@Composable () -> Unit` | `Defaults.Loading()` | Slot displayed during payment processing | | `paymentMethodSelection` | `@Composable () -> Unit` | `Defaults.PaymentMethodSelection(checkout)` | Slot for payment method selection screen | | `cardForm` | `@Composable () -> Unit` | `PrimerCardForm(...)` | Slot for card payment form screen | | `success` | `@Composable (PrimerCheckoutData) -> Unit` | `Defaults.Success(data)` | Slot after successful payment. Auto-dismisses after 3 seconds. | | `error` | `@Composable (PrimerError, PrimerCheckoutData?) -> Unit` | `Defaults.Error(primerError)` | Slot after payment failure. Shows retry and "try other methods" options. `checkoutData` carries the payment id and order id when the payment was created before failing. | | `beforePaymentCreate` | `(@Composable (PrimerPaymentCreationDecisionHandler) -> Unit)?` | `null` | Optional gate shown right before payment creation — run last-minute checks or set an idempotency key, then call `handler.continuePaymentCreation(idempotencyKey)` or `handler.abortPaymentCreation(message)`. Omit to let the SDK proceed automatically. | ## PrimerCheckoutSheetDefaults Pre-built composable implementations for each screen slot. ```kotlin theme={"dark"} object PrimerCheckoutSheetDefaults { @Composable fun Splash() @Composable fun Loading() @Composable fun Success(checkoutData: PrimerCheckoutData) @Composable fun Error(error: PrimerError) @Composable fun PaymentMethodSelection(checkout: PrimerCheckoutController) @Composable fun VaultedMethods(checkout: PrimerCheckoutController) @Composable fun PaymentMethods(checkout: PrimerCheckoutController) } ``` | Function | Description | | - | - | | `Splash()` | Brief splash screen with Primer logo and loading animation | | `Loading()` | Centered circular progress indicator during payment processing | | `Success(checkoutData)` | Checkmark animation and payment confirmation. Auto-dismisses after 3 seconds. | | `Error(error)` | Error message with retry and "try other methods" options | | `PaymentMethodSelection(checkout)` | Vaulted methods (if any) + available payment methods | | `VaultedMethods(checkout)` | Saved payment methods section only | | `PaymentMethods(checkout)` | Available payment methods section only (excluding vaulted) | ## PrimerCheckoutSheet vs PrimerCheckoutHost | Feature | PrimerCheckoutSheet | PrimerCheckoutHost | | - | - | - | | Presentation | Modal bottom sheet | Inline in your layout | | Navigation | Built-in screen transitions | You manage navigation | | Dismissal | Swipe, back press, auto-dismiss | You control visibility | | Success/error screens | Built-in slots (customizable) | You build your own | | 3DS/redirect flows | Handled within the sheet | Overlay sheet appears on top | # PrimerCheckoutState Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/primer-checkout-state Sealed interface representing checkout session lifecycle states > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Single observable snapshot of the checkout session. Covers the session lifecycle (`Loading` / `Ready`), client-session updates, and the terminal payment outcomes (`Success` / `Failure`). Observe via `PrimerCheckoutController.state`. > [!NOTE] > > There is no separate event callback. Payment outcomes that earlier releases delivered through an `onEvent` lambda are now terminal states of this flow — observe `Success` and `Failure` here. ## Definition ```kotlin theme={"dark"} @Immutable sealed interface PrimerCheckoutState { data object Loading : PrimerCheckoutState data class Ready( val clientSession: PrimerClientSession, ) : PrimerCheckoutState data class Success( val checkoutData: PrimerCheckoutData, ) : PrimerCheckoutState data class Failure( val primerError: PrimerError, val checkoutData: PrimerCheckoutData? = null, ) : PrimerCheckoutState } ``` ## States | State | Description | | - | - | | `Loading` | SDK is initializing — fetching configuration and payment methods. Initial state and re-entered on `refresh()`. | | `Ready` | Checkout is fully initialized and ready for payment. Contains `clientSession` data. Emitted again with the updated `clientSession` after each client-session update. | | `Success` | Terminal — payment completed successfully (`AUTO` flow). Sticks until a new attempt starts. | | `Failure` | Terminal — payment failed or an SDK error occurred. Sticks until a new attempt starts. | ### Ready properties | Property | Type | Description | | - | - | - | | `clientSession` | `PrimerClientSession` | Session data containing order details, currency, and customer information | ### Client-session updates When the client session changes during checkout (for example after a billing-address change or `setVaultOnSuccess`), the state goes from `Ready` with the old session to `Ready` with the updated one. Read totals, fees, and surcharges from `Ready.clientSession`. To show progress while the update is in flight, use `isLoading` on the card form state (`rememberCardFormController(checkout).state`). ### Success properties | Property | Type | Description | | - | - | - | | `checkoutData` | `PrimerCheckoutData` | Payment result containing the payment ID and order ID | ### Failure properties | Property | Type | Description | | - | - | - | | `primerError` | [`PrimerError`](/docs/sdk/android-checkout/v3.0.0-beta/api/common/primer-error) | Error details including description, error code, and diagnostics ID | | `checkoutData` | `PrimerCheckoutData?` | Payment ID and order ID when the payment was created before failing, e.g. a decline. `null` when the failure happened before a payment existed | ## Observing state ```kotlin theme={"dark"} val checkout = rememberPrimerCheckoutController(clientToken, settings) val state by checkout.state.collectAsStateWithLifecycle() when (val s = state) { is PrimerCheckoutState.Loading -> CircularProgressIndicator() is PrimerCheckoutState.Ready -> ShowPaymentMethods(s.clientSession) is PrimerCheckoutState.Success -> navigateToConfirmation(s.checkoutData) is PrimerCheckoutState.Failure -> showError(s.primerError) else -> Unit } ``` ## PrimerClientSession ```kotlin theme={"dark"} data class PrimerClientSession( val totalAmount: Int?, val currencyCode: String?, val customerId: String?, val orderId: String?, ) ``` | Property | Type | Description | | - | - | - | | `totalAmount` | `Int?` | Total amount in minor currency units (e.g., `1000` = \$10.00) | | `currencyCode` | `String?` | ISO 4217 currency code (e.g., `"USD"`, `"EUR"`) | | `customerId` | `String?` | Customer identifier from your system | | `orderId` | `String?` | Order identifier from your system | # Color Tokens Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/theming/color-tokens Color token classes for light and dark mode theming > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta). > The API is subject to change before the stable release. Two classes define all color tokens: * **`LightColorTokens`** — open class with 2 base tokens and 29 semantic tokens for light mode * **`DarkColorTokens`** — extends `LightColorTokens` and overrides the internal palette for dark mode. Semantic tokens resolve automatically through inheritance. The raw palette behind the semantic tokens (`primerColorGray*`, `primerColorRed*`, `primerColorBlue*`, `primerColorGreen*`) is internal. To change a color, override the semantic token that uses it. ## Base tokens (2) | Token | Light | Dark | Purpose | | - | - | - | - | | `primerColorBrand` | `#2F98FF` | `#2F98FF` | Primary brand color | | `primerColorBorderTransparentDefault` | transparent | transparent | Transparent border base | ## Semantic tokens (29) Resolve through base tokens and the internal palette. Override the ones you want to change. ### Background | Token | Light | Dark | Resolves to | Purpose | | - | - | - | - | - | | `primerColorBackgroundPrimary` | | | `primerColorGray000` | Sheet and screen background | | `primerColorBackgroundSecondary` | | | `primerColorGray100` | Secondary surfaces | | `primerColorBackgroundOutlinedDefault` | | | `primerColorBackgroundPrimary` | Input field background | | `primerColorBackgroundOutlinedDisabled` | | | `primerColorGray100` | Disabled input field background | ### Text colors | Token | Light | Dark | Resolves to | Purpose | | - | - | - | - | - | | `primerColorTextPrimary` | | | `primerColorGray900` | Main text | | `primerColorTextSecondary` | | | `primerColorGray600` | Labels, descriptions | | `primerColorTextPlaceholder` | | | `primerColorGray500` | Input placeholders | | `primerColorTextDisabled` | | | `primerColorGray400` | Disabled text | | `primerColorTextNegative` | | | `primerColorRed900` | Error messages | | `primerColorTextLink` | | | `primerColorBlue900` | Clickable links | | `primerColorTextOutlinedDefault` | | | `primerColorTextPrimary` | Text inside input fields | ### Border colors (outlined) | Token | Light | Dark | Resolves to | Purpose | | - | - | - | - | - | | `primerColorBorderOutlinedDefault` | | | `primerColorGray300` | Default input border | | `primerColorBorderOutlinedActive` | | | `primerColorGray500` | Active input border | | `primerColorBorderOutlinedFocus` | | | `primerColorFocus` | Focused input border | | `primerColorBorderOutlinedDisabled` | | | `primerColorGray200` | Disabled input border | | `primerColorBorderOutlinedError` | | | `primerColorRed500` | Error input border | | `primerColorBorderOutlinedLoading` | | | `primerColorGray200` | Loading input border | | `primerColorBorderOutlinedSelected` | | | `primerColorBrand` | Selected item border | ### Border colors (transparent) | Token | Light | Dark | Resolves to | Purpose | | - | - | - | - | - | | `primerColorBorderTransparentActive` | transparent | transparent | `primerColorBorderTransparentDefault` | Active | | `primerColorBorderTransparentFocus` | | | `primerColorFocus` | Focused | | `primerColorBorderTransparentDisabled` | transparent | transparent | `primerColorBorderTransparentDefault` | Disabled | | `primerColorBorderTransparentSelected` | transparent | transparent | `primerColorBorderTransparentDefault` | Selected | ### Icon colors | Token | Light | Dark | Resolves to | Purpose | | - | - | - | - | - | | `primerColorIconPrimary` | | | `primerColorGray900` | Default icon | | `primerColorIconDisabled` | | | `primerColorGray400` | Disabled icon | | `primerColorIconNegative` | | | `primerColorRed500` | Error icon | | `primerColorIconPositive` | | | `primerColorGreen500` | Success icon | ### Utility | Token | Light | Dark | Resolves to | Purpose | | - | - | - | - | - | | `primerColorFocus` | | | `primerColorBrand` | Focus ring | | `primerColorLoader` | | | `primerColorBrand` | Loading indicator | | `primerColorOnBrand` | | | `primerColorBackgroundPrimary` | Content on the brand color, such as the pay button label | ## Customization Override tokens by extending `LightColorTokens` or `DarkColorTokens`: ```kotlin theme={"dark"} val theme = PrimerTheme( lightColorTokens = object : LightColorTokens() { override val primerColorBrand: Color = Color(0xFF6C5CE7) override val primerColorBackgroundPrimary: Color = Color(0xFFF8F8F8) }, darkColorTokens = object : DarkColorTokens() { override val primerColorBrand: Color = Color(0xFFA29BFE) }, ) ``` Changing a base token affects all semantic tokens that reference it. Use `PrimerTheme.appearanceMode` to choose whether the light or dark set is used. # PrimerTheme Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/theming/primer-theme Central theming configuration for all Primer Checkout components > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Root theme container holding all design token groups. Pass to `PrimerCheckoutSheet` or `PrimerCheckoutHost` via the `theme` parameter. ## Definition ```kotlin theme={"dark"} data class PrimerTheme( val lightColorTokens: LightColorTokens = LightColorTokens(), val darkColorTokens: DarkColorTokens = DarkColorTokens(), val appearanceMode: PrimerAppearanceMode = PrimerAppearanceMode.SYSTEM, val widthTokens: WidthTokens = WidthTokens(), val radiusTokens: RadiusTokens = RadiusTokens(), val sizeTokens: SizeTokens = SizeTokens(), val spacingTokens: SpacingTokens = SpacingTokens(), val typographyTokens: TypographyTokens = TypographyTokens(), ) ``` ## Properties | Property | Type | Description | | - | - | - | | `lightColorTokens` | [`LightColorTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/color-tokens) | Color tokens for light mode | | `darkColorTokens` | [`DarkColorTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/color-tokens) | Color tokens for dark mode. Extends `LightColorTokens`. | | `appearanceMode` | `PrimerAppearanceMode` | Whether the checkout follows the system theme (`SYSTEM`, default) or is pinned to `LIGHT` or `DARK` | | `widthTokens` | [`WidthTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/shape-tokens) | Border widths for inputs in their default, focus, selected, and error states | | `radiusTokens` | [`RadiusTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/shape-tokens) | Corner radius for cards, inputs, bottom sheets | | `sizeTokens` | [`SizeTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/shape-tokens) | Sizes for icons and touch targets | | `spacingTokens` | [`SpacingTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/spacing-tokens) | Padding and margin values | | `typographyTokens` | [`TypographyTokens`](/docs/sdk/android-checkout/v3.0.0-beta/api/theming/typography-tokens) | Font sizes, weights, and line heights | ## PrimerAppearanceMode ```kotlin theme={"dark"} enum class PrimerAppearanceMode { SYSTEM, LIGHT, DARK, } ``` | Value | Description | | - | - | | `SYSTEM` | Follows the device's light or dark setting. Default. | | `LIGHT` | Always uses `lightColorTokens`. | | `DARK` | Always uses `darkColorTokens`. | ```kotlin theme={"dark"} val theme = PrimerTheme(appearanceMode = PrimerAppearanceMode.DARK) ``` ## Methods ### isDarkAppearance ```kotlin theme={"dark"} @Composable fun isDarkAppearance(): Boolean ``` Returns `true` when the checkout is dark right now, given `appearanceMode` and the system setting. ### colorTokens ```kotlin theme={"dark"} @Composable fun colorTokens(darkTheme: Boolean = isDarkAppearance()): LightColorTokens ``` Returns `darkColorTokens` when `darkTheme` is `true`, `lightColorTokens` otherwise. Defaults to the appearance resolved from `appearanceMode`. ## Material 3 Integration `PrimerTheme` automatically maps color tokens to a Material 3 `ColorScheme`. Material components used within the checkout tree (such as `ModalBottomSheet`) inherit your Primer tokens without additional configuration. Both `PrimerCheckoutSheet` and `PrimerCheckoutHost` wrap content in a `MaterialTheme` that applies this mapping internally. ### Color mapping | M3 Role | Primer Token | Notes | | - | - | - | | `primary` | `primerColorBrand` | | | `onPrimary` | `primerColorOnBrand` | | | `primaryContainer` | `primerColorBlue900` | | | `onPrimaryContainer` | `primerColorOnBrand` | | | `inversePrimary` | `primerColorBlue500` | | | `secondary` | `primerColorGray600` | | | `onSecondary` | `primerColorOnBrand` | | | `secondaryContainer` | `primerColorGray200` | | | `onSecondaryContainer` | `primerColorTextPrimary` | | | `tertiary` | `primerColorBlue500` | | | `onTertiary` | `primerColorOnBrand` | | | `tertiaryContainer` | `primerColorGray200` | | | `onTertiaryContainer` | `primerColorTextPrimary` | | | `background` | `primerColorBackgroundPrimary` | | | `onBackground` | `primerColorTextPrimary` | | | `surface` | `primerColorBackgroundPrimary` | | | `onSurface` | `primerColorTextPrimary` | | | `surfaceVariant` | `primerColorGray100` | | | `onSurfaceVariant` | `primerColorTextSecondary` | | | `surfaceTint` | `primerColorBrand` | | | `inverseSurface` | `primerColorGray900` | | | `inverseOnSurface` | `primerColorGray000` | | | `surfaceBright` | `primerColorGray000` (light) / `primerColorGray300` (dark) | mode-specific | | `surfaceDim` | `primerColorGray100` (light) / `primerColorGray000` (dark) | mode-specific | | `surfaceContainer` | `primerColorGray100` | | | `surfaceContainerHigh` | `primerColorGray200` | | | `surfaceContainerHighest` | `primerColorGray300` | | | `surfaceContainerLow` | `primerColorGray100` | | | `surfaceContainerLowest` | `primerColorBackgroundPrimary` | | | `error` | `primerColorRed500` | | | `onError` | `primerColorOnBrand` | | | `errorContainer` | `primerColorRed100` | | | `onErrorContainer` | `primerColorTextNegative` | | | `outline` | `primerColorBorderOutlinedDefault` | | | `outlineVariant` | `primerColorGray300` | | | `scrim` | `Color.Black` (alpha 0.32) | hardcoded | Overriding a Primer token automatically updates every M3 role that references it. No separate M3 configuration is needed. The `primerColorGray*`, `primerColorRed*`, `primerColorBlue*`, and `primerColorGreen*` palette tokens are internal; override the semantic tokens instead. ## LocalPrimerTheme ```kotlin theme={"dark"} val LocalPrimerTheme = staticCompositionLocalOf { PrimerTheme() } ``` Compose `CompositionLocal` providing the current `PrimerTheme`. Set automatically by `PrimerCheckoutSheet` and `PrimerCheckoutHost`. Access with `LocalPrimerTheme.current` inside the checkout composable tree. # Shape Tokens Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/theming/shape-tokens Radius, border width, and size tokens for component shapes and dimensions > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta). > The API is subject to change before the stable release. ## RadiusTokens ```kotlin theme={"dark"} data class RadiusTokens( val xsmall: Dp = 2.dp, val small: Dp = 4.dp, val medium: Dp = 8.dp, val large: Dp = 12.dp, ) ``` | Token | Preview | Default | Usage | | - | - | - | - | | `xsmall` | | 2.dp | Subtle rounding | | `small` | | 4.dp | Chips, tags | | `medium` | | 8.dp | Input fields, cards | | `large` | | 12.dp | Bottom sheet corners | ## WidthTokens ```kotlin theme={"dark"} data class WidthTokens( val default: Dp = 1.dp, val focus: Dp = 2.dp, val selected: Dp = 2.dp, val error: Dp = 2.dp, ) ``` | Token | Preview | Default | Usage | | - | - | - | - | | `default` | | 1.dp | Input borders at rest | | `focus` | | 2.dp | Focused input borders | | `selected` | | 2.dp | Selected item borders | | `error` | | 2.dp | Input borders in the error state | ## SizeTokens ```kotlin theme={"dark"} data class SizeTokens( val small: Dp = 16.dp, val medium: Dp = 20.dp, val large: Dp = 24.dp, val xlarge: Dp = 32.dp, val xxlarge: Dp = 40.dp, val xxxlarge: Dp = 56.dp, ) ``` | Token | Preview | Default | Usage | | - | - | - | - | | `small` | | 16.dp | Small icons | | `medium` | | 20.dp | Default icons | | `large` | | 24.dp | Large icons | | `xlarge` | | 32.dp | Payment method icons | | `xxlarge` | | 40.dp | Touch targets | | `xxxlarge` | | 56.dp | Large touch targets | Access all shape tokens via `LocalPrimerTheme.current` inside the checkout composable tree. # SpacingTokens Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/theming/spacing-tokens Spacing tokens for padding and margin values across components > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta). > The API is subject to change before the stable release. ## Definition ```kotlin theme={"dark"} data class SpacingTokens( val xxsmall: Dp = 2.dp, val xsmall: Dp = 4.dp, val small: Dp = 8.dp, val medium: Dp = 12.dp, val large: Dp = 16.dp, val xlarge: Dp = 20.dp, val xxlarge: Dp = 24.dp, ) ``` ## Properties | Token | Preview | Default | Usage | | - | - | - | - | | `xxsmall` | | 2.dp | Icon padding, minimal gaps | | `xsmall` | | 4.dp | Chip padding, tight spacing | | `small` | | 8.dp | Between form fields | | `medium` | | 12.dp | Section internal padding | | `large` | | 16.dp | Container padding, major gaps | | `xlarge` | | 20.dp | Between major sections | | `xxlarge` | | 24.dp | Largest gaps | Access via `LocalPrimerTheme.current.spacingTokens` inside the checkout composable tree. # TypographyTokens Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/api/theming/typography-tokens Typography tokens for font styles, sizes, and weights across components > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta). > The API is subject to change before the stable release. ## TypographyTokens ```kotlin theme={"dark"} data class TypographyTokens( @FontRes val brandFont: Int = R.font.inter, val titleXlarge: TypographyStyle = TypographyStyle(size = 24, weight = 550, lineHeight = 32, letterSpacing = -0.6f), val titleLarge: TypographyStyle = TypographyStyle(size = 16, weight = 550, lineHeight = 20, letterSpacing = -0.2f), val bodyLarge: TypographyStyle = TypographyStyle(size = 16, weight = 400, lineHeight = 20, letterSpacing = -0.2f), val bodyMedium: TypographyStyle = TypographyStyle(size = 14, weight = 400, lineHeight = 20, letterSpacing = 0f), val bodySmall: TypographyStyle = TypographyStyle(size = 12, weight = 400, lineHeight = 16, letterSpacing = 0f), val error: TypographyStyle? = null, ) ``` | Token | Size | Weight | Line height | Usage | | - | - | - | - | - | | `titleXlarge` | 24sp | 550 | 32sp | Sheet titles | | `titleLarge` | 16sp | 550 | 20sp | Section headers | | `bodyLarge` | 16sp | 400 | 20sp | Input text, body | | `bodyMedium` | 14sp | 400 | 20sp | Labels, descriptions | | `bodySmall` | 12sp | 400 | 16sp | Helper text, errors | | `error` | -- | -- | -- | Error text. `null` by default, so error text follows `bodySmall` | All styles use `brandFont`, the **Inter** variable font by default. Set `brandFont` in the constructor to use your own font resource for every style, or override `font` on a single style. ```kotlin theme={"dark"} val typography = TypographyTokens(brandFont = R.font.my_brand_font) ``` ### Preview titleXlarge — The quick brown fox jumps over the lazy dog titleLarge — The quick brown fox jumps over the lazy dog bodyLarge — The quick brown fox jumps over the lazy dog bodyMedium — The quick brown fox jumps over the lazy dog bodySmall — The quick brown fox jumps over the lazy dog ## TypographyStyle ```kotlin theme={"dark"} data class TypographyStyle( @FontRes val font: Int, val letterSpacing: Float, val weight: Int, val size: Int, val lineHeight: Int, ) ``` | Property | Type | Description | | - | - | - | | `font` | `Int` | Android font resource ID (`@FontRes`). Defaults to Inter variable font. | | `letterSpacing` | `Float` | Letter spacing in sp | | `weight` | `Int` | Font weight (400 = regular, 550 = semi-bold, 700 = bold) | | `size` | `Int` | Font size in sp | | `lineHeight` | `Int` | Line height in sp | ### toTextStyle() ```kotlin theme={"dark"} fun toTextStyle(): TextStyle ``` Converts to a Compose `TextStyle` for use in composables. # Installation Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/installation Add the Primer Checkout SDK to your Android project > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. ## Prerequisites * Android API level 24+ (minSdk) * Kotlin 2.0+ with the [Compose Compiler Gradle plugin](https://developer.android.com/develop/ui/compose/compiler) * Jetpack Compose enabled in your project * A `clientToken` from your server via the [Client Session API](/docs/checkout/client-session) ## Install the SDK We recommend installing the SDK through the Primer BOM (`io.primer:bom`). The BOM sets the version of the SDK and of every Primer library you add, so you only set one version. Add it to your module-level `build.gradle.kts`: ```kotlin theme={"dark"} dependencies { implementation(platform("io.primer:bom:3.0.0-beta.8")) implementation("io.primer:checkout") } ``` Or without the BOM: ```kotlin theme={"dark"} dependencies { implementation("io.primer:checkout:3.0.0-beta.8") } ``` ## Payment method dependencies `io.primer:checkout` doesn't include the wrappers for 3DS, Klarna or Stripe ACH. Add one for each of these you enable in the Dashboard. Without the 3DS wrapper, card payments that need 3DS fail, and without the Klarna or Stripe wrapper, that method doesn't appear in the checkout. The wrappers ship with the SDK at the same version. With the BOM, leave out the version: ```kotlin theme={"dark"} dependencies { implementation(platform("io.primer:bom:3.0.0-beta.8")) implementation("io.primer:checkout") implementation("io.primer:3ds-android") // 3DS on card payments implementation("io.primer:klarna-android") // Klarna implementation("io.primer:stripe-android") // Stripe ACH } ``` Without the BOM, use the same version as `io.primer:checkout` for each wrapper. ## Compose Setup Ensure Jetpack Compose is enabled in your module-level `build.gradle.kts`. The SDK uses the Kotlin Compose Compiler plugin — add it to your `plugins` block instead of setting `kotlinCompilerExtensionVersion`: ```kotlin theme={"dark"} plugins { id("org.jetbrains.kotlin.plugin.compose") version "" } android { buildFeatures { compose = true } } dependencies { implementation(platform("androidx.compose:compose-bom:2025.12.00")) implementation("androidx.compose.ui:ui") implementation("androidx.compose.material3:material3") implementation("androidx.lifecycle:lifecycle-runtime-compose:2.7.0") } ``` > [!NOTE] > > The Primer SDK is built against a specific Compose BOM version. We recommend aligning your app's BOM version with ours to avoid binary incompatibilities. See the [Compose BOM to library version mapping](https://developer.android.com/develop/ui/compose/bom/bom-mapping) for details. ## Basic Usage Add the checkout to your Composable: ```kotlin theme={"dark"} @Composable fun CheckoutScreen(clientToken: String) { val checkout = rememberPrimerCheckoutController( clientToken = clientToken, ) // The sheet renders its own success/error screens. Observe state to // react programmatically (navigate, log, clear the cart). val state by checkout.state.collectAsStateWithLifecycle() LaunchedEffect(state) { when (val s = state) { is PrimerCheckoutState.Success -> { /* Navigate to confirmation */ } is PrimerCheckoutState.Failure -> { /* Inspect s.primerError */ } else -> Unit } } PrimerCheckoutSheet(checkout = checkout) } ``` ## Verify Installation Build your project to confirm the SDK is resolved correctly: ```bash theme={"dark"} ./gradlew assembleDebug ``` If the build succeeds, the SDK is installed and ready to use. ## ProGuard / R8 The SDK includes its own ProGuard rules. No additional configuration is needed for release builds. ## Next Steps > [card] [First Payment](/docs/checkout/primer-checkout/first-payment) > > Accept your first payment > [card] [Theming](/docs/checkout/primer-checkout/build-your-ui/styling-customization) > > Customize the appearance > [card] [Core Concepts](/docs/checkout/primer-checkout/core-concepts) > > Understand the architecture > [card] [Settings](/docs/checkout/primer-checkout/configuration/sdk-options) > > Configure SDK behavior # Troubleshooting Source: https://primer.io/docs/sdk/android-checkout/v3.0.0-beta/troubleshooting Common issues and solutions for the Primer Checkout SDK > [!WARNING] > > Primer Checkout Android SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. ## Installation issues ### Compose version conflict **Problem**: Build fails with Compose compiler version mismatch. **Solution**: Ensure your Compose compiler version is compatible: ```kotlin theme={"dark"} android { composeOptions { kotlinCompilerExtensionVersion = "1.5.8" } } ``` ## Runtime issues ### Checkout stays in Loading state **Problem**: `PrimerCheckoutState.Loading` never transitions to `Ready`. **Possible causes**: * Invalid or expired client token * Network connectivity issues * Incorrect API key in client session creation **Solution**: Check Logcat for error messages from the SDK. Ensure your client token is fresh and generated correctly. ### Payment methods not showing **Problem**: `PrimerPaymentMethods` shows empty list. **Possible causes**: * No payment methods configured in Primer Dashboard * Client session missing required fields * Payment methods not enabled for the currency/country **Solution**: Verify your [Primer Dashboard](https://dashboard.primer.io) configuration and ensure your client session includes the correct `currencyCode` and `countryCode`. ### Card form fields not appearing **Problem**: Some card form fields (cardholder name, billing address) don't appear. **Explanation**: Fields are configured by your Primer Dashboard settings. Only fields marked as required in the Dashboard will appear in the form. This is expected behavior. ### 3DS challenge not completing **Problem**: Payment gets stuck during 3DS authentication. **Solution**: Ensure your app's Activity has `android:configChanges="orientation|screenSize"` to prevent the WebView from being destroyed during configuration changes. ## Compose-specific issues ### Recomposition causes re-initialization **Problem**: Checkout reinitializes on every recomposition. **Solution**: Use `rememberPrimerCheckoutController()` which survives recomposition. Don't create the controller inside conditionals or callbacks: ```kotlin theme={"dark"} // Correct val checkout = rememberPrimerCheckoutController(clientToken) // Incorrect - creates new controller on recomposition val checkout = PrimerCheckoutController(clientToken) // Don't do this ``` ### State not updating in UI **Problem**: UI doesn't reflect state changes. **Solution**: Use `collectAsStateWithLifecycle()`: ```kotlin theme={"dark"} val state by checkout.state.collectAsStateWithLifecycle() ``` ## Getting help If you encounter an issue not covered here: 1. Check the error's `diagnosticsId` in logs 2. Verify your configuration in the Primer Dashboard 3. Contact Primer support with the `diagnosticsId` ## Next steps > [card] [Best Practices](/docs/checkout/primer-checkout/configuration/best-practices) > > Production-ready tips > [card] [First Payment](/docs/checkout/primer-checkout/first-payment) > > Verify your integration # Card Field Components Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components Individual per-field building blocks for composing custom card form layouts > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `CardFormDefaults` exposes a set of per-field building blocks alongside its full section renderers. Each building block is a static function with the signature `(PrimerCardFormSession) -> CardFieldContent`, except the co-badged network selector `cardNetwork(_:)`, which returns `CardNetworkFieldContent`. Drop any of them into a custom [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) section slot to recompose the form one field at a time, while keeping the SDK's built-in formatting, validation, keyboard configuration, and inline error display. > [!NOTE] > > Every building block except `cardNetwork(_:)` is **self-hiding**: it renders nothing unless its field is part of the active [`CardFormConfiguration`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) for the current session. You can drop every block into a layout without worrying about which fields the current session actually requires — only the configured ones appear. ## How the building blocks work The full-section renderers — `CardFormDefaults.cardDetails(_:)` and `CardFormDefaults.billingAddress(_:)` — produce the complete, config-aware form. The field-level building blocks let you interleave your own content (banners, headings, custom layout) between individual fields instead. Each field block forwards to the same shared, configuration-aware renderer the section helpers use, so a hand-composed layout behaves identically to the default form. The block checks whether its field appears in the session's `configuration.cardFields` or `configuration.billingFields`; if not, it resolves to an `EmptyView`. ```swift theme={"dark"} @available(iOS 15.0, *) public enum CardFormDefaults { public static func cardNumber(_ session: PrimerCardFormSession) -> CardFieldContent public static func expiryDate(_ session: PrimerCardFormSession) -> CardFieldContent // ...one function per field } ``` All field blocks take a single unlabeled [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) parameter and return a concrete `View`. Read `session.state` for rendering and call into the session for mutations and submission. ## Card detail fields These map to the `cardFields` in the active `CardFormConfiguration` (the default configuration is `.cardNumber`, `.expiryDate`, `.cvv`, `.cardholderName`). | Method | Return type | Renders when | Description | | - | - | - | - | | `cardNumber(_:)` | `CardFieldContent` | `.cardNumber` is in `configuration.cardFields` | Card number field with network-aware grouping, Luhn validation, and the detected-network icon. For co-badged cards, it shows the network selector (or a badge for each detected network when the shopper cannot choose) in place of the icon. | | `expiryDate(_:)` | `CardFieldContent` | `.expiryDate` is configured | Expiry field; auto-inserts the `/` separator (MM/YY) and validates for a real month that has not passed (the current month is accepted). | | `cvv(_:)` | `CardFieldContent` | `.cvv` is configured | CVV field; masked input, max length adapts to the detected network (4 for Amex, 3 otherwise). | | `cardholderName(_:)` | `CardFieldContent` | `.cardholderName` is configured | Cardholder name field with word capitalization. | ```swift theme={"dark"} @available(iOS 15.0, *) public static func cardNumber(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func expiryDate(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func cvv(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func cardholderName(_ session: PrimerCardFormSession) -> CardFieldContent ``` ### Co-badged card network selector `cardNetwork(_:)` is a standalone selector for co-badged cards that you place yourself, for a layout that does not render the SDK's card number field. Unlike the other blocks it does **not** read `CardFormConfiguration`; it renders only when more than one network is detected (`session.state.availableNetworks.count > 1`), reusing the SDK's built-in dropdown. Tapping a network commits the choice through `session.selectCardNetwork(_:)`. Unlike the selector built into the card number field, `cardNetwork(_:)` always shows a dropdown. When the shopper cannot choose between the detected networks, the card number field shows a badge for each detected network. `cardNetwork(_:)` still shows the dropdown in that case. | Method | Return type | Renders when | Description | | - | - | - | - | | `cardNetwork(_:)` | `CardNetworkFieldContent` | `availableNetworks.count > 1` | Dropdown selector for co-badged cards (e.g., Cartes Bancaires + Visa). | ```swift theme={"dark"} @available(iOS 15.0, *) public static func cardNetwork(_ session: PrimerCardFormSession) -> CardNetworkFieldContent ``` > [!WARNING] > > The card number field has its own co-badged selector, both in the full `cardDetails(_:)` section and in the `cardNumber(_:)` block. Use `cardNetwork(_:)` only in a layout that contains neither of them. Combining it with either one shows two selectors. ## Billing address fields These map to the `billingFields` in the active `CardFormConfiguration`. They appear only when billing address collection is enabled for the session (`configuration.requiresBillingAddress` and the corresponding field present in `billingFields`). | Method | Return type | Renders when | Description | | - | - | - | - | | `firstName(_:)` | `CardFieldContent` | `.firstName` is in `configuration.billingFields` | First name field with word capitalization. | | `lastName(_:)` | `CardFieldContent` | `.lastName` is configured | Last name field with word capitalization. | | `phoneNumber(_:)` | `CardFieldContent` | `.phoneNumber` is configured | Phone number field with the phone keypad and telephone-number AutoFill; valid with 7–15 digits (spaces, dashes, dots, brackets and `+` are ignored). | | `addressLine1(_:)` | `CardFieldContent` | `.addressLine1` is configured | Primary street address line. | | `addressLine2(_:)` | `CardFieldContent` | `.addressLine2` is configured | Secondary address line (apartment, suite, etc.). | | `city(_:)` | `CardFieldContent` | `.city` is configured | City field. | | `state(_:)` | `CardFieldContent` | `.state` is configured | State field. | | `postalCode(_:)` | `CardFieldContent` | `.postalCode` is configured | Postal/ZIP code field. A valid value contains letters, digits, spaces and hyphens, and is 3–10 characters long. | | `countryCode(_:)` | `CardFieldContent` | `.countryCode` is configured | Country selector field. | ```swift theme={"dark"} @available(iOS 15.0, *) public static func firstName(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func lastName(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func phoneNumber(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func addressLine1(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func addressLine2(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func city(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func state(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func postalCode(_ session: PrimerCardFormSession) -> CardFieldContent @available(iOS 15.0, *) public static func countryCode(_ session: PrimerCardFormSession) -> CardFieldContent ``` ## Composing a custom card detail layout Pass a `@ViewBuilder` closure to the `cardDetails` slot on [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form). Lay out the field blocks in any order, and add your own content between them. Because each block is self-hiding, the extra fields you reference (such as `cardholderName`) appear only if the session's configuration includes them. ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 15.0, *) struct CustomCardDetails: View { var body: some View { PrimerCardForm(cardDetails: { session in VStack(alignment: .leading, spacing: 16) { Text("Card details") .font(.headline) // Includes the co-badged network selector when multiple networks are detected. CardFormDefaults.cardNumber(session) HStack(spacing: 12) { CardFormDefaults.expiryDate(session) CardFormDefaults.cvv(session) } CardFormDefaults.cardholderName(session) } }) } } ``` > [!TIP] > > `CardFormDefaults.cardNumber(session)` already shows the co-badged network selector when multiple networks are detected. A custom layout that includes it needs nothing extra for co-badged cards. ### Recomposing billing fields too The `billingAddress` slot works the same way. Group billing blocks into your own layout; only the configured fields render. The slot itself always renders, so check `requiresBillingAddress` first. Your heading then stays hidden when the session collects no billing address. ```swift theme={"dark"} @available(iOS 15.0, *) struct CustomBilling: View { var body: some View { PrimerCardForm(billingAddress: { session in if session.state.configuration.requiresBillingAddress { VStack(alignment: .leading, spacing: 16) { Text("Billing address") .font(.headline) HStack(spacing: 12) { CardFormDefaults.firstName(session) CardFormDefaults.lastName(session) } CardFormDefaults.addressLine1(session) CardFormDefaults.addressLine2(session) HStack(spacing: 12) { CardFormDefaults.city(session) CardFormDefaults.state(session) } CardFormDefaults.postalCode(session) CardFormDefaults.countryCode(session) } } }) } } ``` ## Reacting to field state Each building block manages its own input and inline error display, so you don't have to wire bindings manually. When you need to react to the form as a whole — for example to drive your own submit button — read the published `session.state`: ```swift theme={"dark"} @available(iOS 15.0, *) struct CustomSubmit: View { @ObservedObject var session: PrimerCardFormSession var body: some View { Button("Pay now") { session.submit() } .disabled(!session.state.isValid || session.state.isLoading) } } ``` While a payment is processing (`session.state.isLoading` is `true`), every card and billing field rendered by a building block is disabled and grayed out. The focused field also loses focus. The `cardNetwork(_:)` selector and your own controls between the blocks stay enabled. Disable them yourself while `session.state.isLoading` is `true`. Per-field errors are available on `session.state` via `fieldErrors`, `hasError(for:)`, and `errorMessage(for:)`. See [Card Form Session](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) for the full state surface. ## See also > [card] [Card Form Defaults](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-defaults) > > The full section renderers and submit button these blocks complement. > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > The composable form view and its `@ViewBuilder` section slots. > [card] [Card Form Session](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) > > Observable state, field updates, and submission for the card form. # CardFormDefaults Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-defaults Pre-built section slot bodies for custom card form layouts > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `CardFormDefaults` is the namespace that holds the default content for [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form)'s slots. When you create a card form without supplying a slot, `PrimerCardForm` falls back to the matching `CardFormDefaults` helper. You can also call these helpers yourself inside a custom slot to keep the default rendering while wrapping it with your own layout. ```swift theme={"dark"} @available(iOS 15.0, *) public enum CardFormDefaults ``` > [!NOTE] > > `CardFormDefaults` is an empty enum used purely as a namespace for static factory methods. You never instantiate it; you call its `static func` members and embed the views they return. ## How the defaults are wired `PrimerCardForm` declares each `@ViewBuilder` slot with a default argument that points at the matching `CardFormDefaults` helper: ```swift theme={"dark"} public init( @ViewBuilder cardDetails: @escaping (PrimerCardFormSession) -> CardDetails = { CardFormDefaults.cardDetails($0) }, @ViewBuilder billingAddress: @escaping (PrimerCardFormSession) -> Billing = { CardFormDefaults.billingAddress($0) }, @ViewBuilder submitButton: @escaping (PrimerCardFormSession) -> Submit = { CardFormDefaults.submitButton($0) } ) ``` Each helper receives the [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) for the current checkout and returns a concrete, config-aware view. Because they return concrete view types, they can satisfy `PrimerCardForm`'s generic view parameters (`CardDetails`, `Billing`, `Submit`) at the default-value site, where an opaque `some View` cannot. ## Section helpers These three helpers produce the bodies of `PrimerCardForm`'s three slots. | Method | Returns | Description | | - | - | - | | `cardDetails(_:)` | `CardDetailsContent` | Default card-details section (number, expiry, CVV, cardholder name). | | `billingAddress(_:)` | `BillingAddressContent` | Default billing-address section. Renders only when the configuration requires billing fields. | | `submitButton(_:)` | `CardSubmitButton` | Default submit button, enabled when the form is valid and not loading. | ```swift theme={"dark"} public static func cardDetails(_ session: PrimerCardFormSession) -> CardDetailsContent public static func billingAddress(_ session: PrimerCardFormSession) -> BillingAddressContent public static func submitButton(_ session: PrimerCardFormSession) -> CardSubmitButton ``` > [!NOTE] > > `billingAddress(_:)` and the individual billing fields render nothing unless the API-driven form configuration includes billing fields, so it is always safe to include the section. The decision is made for you from the session's configuration. ### `unavailable()` `PrimerCardForm` shows this placeholder when no checkout session is present in the environment — that is, when the `.primerCheckoutSession(_:theme:onCompletion:)` modifier has not been applied, or the session is not yet ready. ```swift theme={"dark"} public static func unavailable() -> some View ``` It returns an `EmptyView`, so an unconfigured form occupies no space rather than crashing or showing partial UI. ## Returned section views The section helpers return concrete `View` types. You rarely name these directly — you embed them inside your own layout — but they are public so you can store and compose them. | Type | Description | | - | - | | `CardDetailsContent` | The shared, config-aware card-details renderer (number, expiry, CVV, cardholder name, and the co-badged network selector when multiple networks are detected). | | `BillingAddressContent` | The shared, config-aware billing-address renderer. Renders only the fields the configuration requires. | | `CardSubmitButton` | The default pay button, labeled with the localized "Pay" title. Disabled when the form is invalid or a payment is loading. | All three are annotated `@available(iOS 15.0, *)` and conform to `View`. > [!NOTE] > > While a payment is loading, VoiceOver reads the value "Processing payment, please wait" on the default `CardSubmitButton`. When the form is invalid and no payment is loading, VoiceOver reads the hint "Button disabled. Complete all required fields to enable payment". The SDK localizes both strings. ## Wrapping the default in a custom slot The most common reason to call `CardFormDefaults` directly is to keep the SDK's rendering while adding your own chrome around it. Pass a slot closure to `PrimerCardForm`, then call the matching helper inside it. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } var body: some View { ScrollView { PrimerCardForm( cardDetails: { formSession in VStack(alignment: .leading, spacing: 16) { Text("Card details") .font(.headline) // Keep the default fields, wrapped in your own layout. CardFormDefaults.cardDetails(formSession) Text("Your card is encrypted and never stored on this device.") .font(.footnote) .foregroundColor(.secondary) } .padding() } ) } .primerCheckoutSession(session) { state in handle(state) } } } ``` > [!TIP] > > Because each helper returns a concrete view, you can place it anywhere a SwiftUI view is expected — inside a `VStack`, a `GroupBox`, a card-styled container, or alongside your own promotional content. ## Replacing only the submit button To keep the default fields but swap the pay button, supply only the `submitButton` slot and leave the other two at their defaults: ```swift theme={"dark"} PrimerCardForm( submitButton: { formSession in Button { formSession.submit() } label: { Text("Pay now") .frame(maxWidth: .infinity) } .buttonStyle(.borderedProminent) .disabled(!formSession.state.isValid || formSession.state.isLoading) } ) ``` Read `formSession.state.isValid` and `formSession.state.isLoading` to mirror the enablement logic of the default `CardSubmitButton`. A custom button does not get the default button's VoiceOver value and hint, so set your own accessibility value and hint from the same two flags. See [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) for the full state surface. ## Recomposing individual fields The section helpers are coarse-grained: they render an entire section. For fine-grained layouts, `CardFormDefaults` also exposes per-field building blocks (`cardNumber(_:)`, `cvv(_:)`, `firstName(_:)`, and so on) on the same namespace. Compose those inside your `cardDetails` or `billingAddress` slot to arrange fields exactly how you want. ```swift theme={"dark"} PrimerCardForm( cardDetails: { formSession in VStack(spacing: 12) { CardFormDefaults.cardNumber(formSession) HStack(spacing: 12) { CardFormDefaults.expiryDate(formSession) CardFormDefaults.cvv(formSession) } CardFormDefaults.cardholderName(formSession) } } ) ``` > [!WARNING] > > When more than one network is detected, `CardFormDefaults.cardNumber(_:)` shows the co-badged network selector inside the card number field. The full `cardDetails(_:)` section does the same. When the shopper cannot choose between the detected networks, the field shows a badge for each detected network instead. Do not add `CardFormDefaults.cardNetwork(_:)` next to `cardNumber(_:)` or `cardDetails(_:)`, or the shopper sees two selectors. The per-field building blocks are documented in full on [Card field components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components). ## See also > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > The card form view and its three section slots. > [card] [Card field components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components) > > Per-field building blocks for fully custom layouts. > [card] [PrimerCardFormSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) > > The observable session that drives form state and submission. # PrimerCardFormSession Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session Observable card form session: field updates, validation, network selection, and submission > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerCardFormSession` is the observable session for the card payment form. It publishes the current [`PrimerCardFormState`](#primercardformstate) and exposes field update methods, co-badge network selection, and submission controls. The session is created by the SDK and injected into every [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) slot closure. Read `state` to render your UI and call the session's methods to mutate the form. ```swift theme={"dark"} @available(iOS 15.0, *) @MainActor public final class PrimerCardFormSession: ObservableObject ``` > [!NOTE] > > You never instantiate `PrimerCardFormSession` yourself. Each `PrimerCardForm` slot > (`cardDetails`, `billingAddress`, `submitButton`) receives the session as a closure parameter. > Observe it with `@ObservedObject`. ## Accessing the session The session is passed to each `PrimerCardForm` slot. Capture it and observe `state` to drive your UI: ```swift theme={"dark"} PrimerCardForm( submitButton: { session in Button("Pay") { session.submit() } .disabled(!session.state.isValid || session.state.isLoading) } ) ``` To observe state changes inside a custom subview, mark the captured session as `@ObservedObject`: ```swift theme={"dark"} struct SubmitButton: View { @ObservedObject var session: PrimerCardFormSession var body: some View { Button("Pay") { session.submit() } .disabled(!session.state.isValid || session.state.isLoading) } } ``` ## Property | Property | Type | Description | | - | - | - | | `state` | `PrimerCardFormState` | The latest card form state. `@Published private(set)` — read-only, observe it through `@ObservedObject`. Contains field values, validation errors, loading state, network selection, and surcharge information. | ## Methods ### Field update methods Each setter forwards a raw string to the form and the session republishes `state`. The setters do not validate. Validation runs in the SDK-rendered field for that type, a `CardFormDefaults` field or a default slot body, while it is on screen. The SDK never validates a field you render yourself, so setter calls alone never make `state.isValid` `true`. Updating the card number triggers network detection and may populate `state.availableNetworks` and `state.binData`. | Method | Description | | - | - | | `updateCardNumber(_ value: String)` | Updates the card number. Triggers network detection. | | `updateCvv(_ value: String)` | Updates the CVV / security code. | | `updateExpiryDate(_ value: String)` | Updates the expiry date (MM/YY). | | `updateCardholderName(_ value: String)` | Updates the cardholder name. | | `updatePostalCode(_ value: String)` | Updates the billing postal / ZIP code. | | `updateCountryCode(_ value: String)` | Updates the billing country code (ISO 3166-1 alpha-2). | | `updateCity(_ value: String)` | Updates the billing city. | | `updateState(_ value: String)` | Updates the billing state / region. | | `updateAddressLine1(_ value: String)` | Updates billing address line 1. | | `updateAddressLine2(_ value: String)` | Updates billing address line 2. | | `updatePhoneNumber(_ value: String)` | Updates the billing phone number. | | `updateFirstName(_ value: String)` | Updates the billing first name. | | `updateLastName(_ value: String)` | Updates the billing last name. | Every setter drives the SDK-rendered field the customer sees. The value you set becomes what that field displays. When that field is on screen, the form re-validates the value, so a prefilled field does not hold back the submit button. While the field has focus, the customer's typing wins and the setter does not change the visible text. The card number shows formatted, the same way typing it would. `updateCountryCode` also resolves the country picker's selection from the ISO code. See [Pre-fill cardholder name](/docs/checkout/primer-checkout/guides-and-recipes/prefill-cardholder-name). Writes and reads are asymmetric on purpose. `updateCardNumber` and `updateCvv` accept a raw value and show it in the SDK-rendered field, but the card number and CVV are never handed back to your code: `state.data` carries a masked card number and an empty CVV. > [!WARNING] > > If your code passes a card number or CVV to these setters, your application handles cardholder > data, and your PCI DSS obligations can change. Confirm your scope with your acquirer or a > qualified assessor before you collect card data in your own UI. If you use only the SDK-rendered > card fields and never call these two setters, this warning does not apply to you. ### Network selection | Method | Description | | - | - | | `selectCardNetwork(_ network: PrimerCardNetwork)` | Selects a network for co-badged cards. Applicable only when `state.availableNetworks` contains more than one network. The picked network is sent as the card's preferred network while it is still the one shown. Without a pick, no preferred network is sent. The surcharge follows the network shown either way. See [PrimerCardNetwork](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-card-network). | ### Saving the card | Method | Description | | - | - | | `setVaultOnSuccess(_ enabled: Bool) async throws` | Updates the client session so a successful card payment saves the card (`true`) or does not save it (`false`). Use it for a shopper-facing "save card" control. The client session must have a customer ID. Throws when the client session update fails. | ```swift theme={"dark"} Toggle("Save card for next time", isOn: $saveCard) .onChange(of: saveCard) { enabled in Task { try? await session.setVaultOnSuccess(enabled) } } ``` ### Lifecycle | Method | Description | | - | - | | `submit()` | Tokenizes the card and creates the payment. If you set `onBeforePaymentCreate`, it runs first and can abort the payment. `state.isLoading` is `true` from the call until the payment succeeds or fails. Calls made while `state.isLoading` is `true` are ignored, so a double tap starts only one payment. `submit()` does not check `state.isValid`: gate your button on it. | | `cancel()` | Leaves the card form. If the form was opened from the payment method list, it returns to that list (no outcome is delivered). Otherwise it dismisses the checkout and `.dismissed` is delivered. Ignored while a payment runs (`state.isLoading` is `true`) and while `onBeforePaymentCreate` waits for your decision, because the payment cannot be stopped. | When wiring custom `TextField`s, drive each field with the matching `update*` method. You can round-trip through `session.state.data` for every field except the card number and the CVV: that map is the merchant-facing state, so the card number reads back **masked** (`424242••••••4242`) and the CVV reads back **empty**. Binding a custom card-number field to it would feed the mask straight back into the form on the next keystroke. > [!WARNING] > > Never bind a custom card number or CVV field to `session.state.data`. Hold your own `@State` for those > two and write one way, into the session. The SDK validates only the fields it renders. When you replace a card field with your own, `state.isValid` stays `false` and the default submit button stays disabled. Validate your fields yourself and provide your own `submitButton`. Pass the expiry date to `updateExpiryDate` as `MM/YY`. ```swift theme={"dark"} struct CustomCardFields: View { @State private var cardNumber = "" @State private var cvv = "" var body: some View { PrimerCardForm( cardDetails: { session in // Card number and CVV: one-way. Your own state is the source of truth. TextField("Card number", text: $cardNumber) .onChange(of: cardNumber) { session.updateCardNumber($0) } TextField("CVV", text: $cvv) .onChange(of: cvv) { session.updateCvv($0) } // Non-PCI fields can round-trip through the form state. TextField("MM/YY", text: Binding( get: { session.state.data[.expiryDate] }, set: { session.updateExpiryDate($0) } )) TextField("Name on card", text: Binding( get: { session.state.data[.cardholderName] }, set: { session.updateCardholderName($0) } )) }, // The SDK validates only the fields it renders, so `state.isValid` stays `false` // with custom fields. Gate your own button on your own validation. submitButton: { session in Button("Pay") { session.submit() } .disabled(!isComplete(session.state) || session.state.isLoading) } ) } private func isComplete(_ state: PrimerCardFormState) -> Bool { cardNumber.count >= 12 && cvv.count >= 3 && !state.data[.expiryDate].isEmpty && !state.data[.cardholderName].isEmpty } } ``` ## PrimerCardFormState ```swift theme={"dark"} @available(iOS 15.0, *) public struct PrimerCardFormState: Equatable ``` The complete state of the card payment form: configuration, current field values, validation errors, loading and validity flags, co-badge network selection, and surcharge information. ### Properties | Property | Type | Description | | - | - | - | | `configuration` | `CardFormConfiguration` | Which fields the form requires. See [CardFormConfiguration](#cardformconfiguration). | | `data` | `FormData` | Current field values keyed by `PrimerInputElementType`. See [FormData](#formdata). | | `fieldErrors` | `[FieldError]` | Validation errors per field. Empty when there are no errors. See [FieldError](#fielderror). | | `isLoading` | `Bool` | `true` while a payment is being submitted. | | `isValid` | `Bool` | `true` when the card number, expiry date, CVV and cardholder name pass validation in their SDK-rendered fields. Billing address fields do not affect it. The SDK never validates a field you render yourself, so it keeps `isValid` `false`. | | `selectedCountry` | `PrimerCountry?` | Selected billing country, or `nil`. See [PrimerCountry](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-country). | | `selectedNetwork` | `PrimerCardNetwork?` | The network the form shows: the one picked with the co-badge selector or `selectCardNetwork(_:)` while it is still available, otherwise the first detected network. `nil` when no network is detected. | | `availableNetworks` | `[PrimerCardNetwork]` | Card networks detected from the card number. More than one indicates a co-badged card. | | `surchargeAmountRaw` | `Int?` | Surcharge amount in the smallest currency unit (e.g. cents), or `nil`. | | `surchargeAmount` | `String?` | Formatted surcharge amount for display, or `nil`. | | `binData` | `PrimerBinData?` | BIN metadata detected from the card number, or `nil`. `preferred` is the first of the detected networks that your client session's ordered allowed card networks list contains, or `nil` if none is allowed. `alternatives` holds the other detected networks: allowed ones in that order, then any that are not allowed. | ### Convenience properties | Property | Type | Description | | - | - | - | | `displayFields` | `[PrimerInputElementType]` | All fields that should be rendered (card fields plus billing fields when enabled). | ### Helper methods | Method | Description | | - | - | | `hasError(for fieldType: PrimerInputElementType) -> Bool` | Returns `true` when the given field currently has a validation error. | | `errorMessage(for fieldType: PrimerInputElementType) -> String?` | Returns the human-readable error message for the field, or `nil` when there is none. | ```swift theme={"dark"} PrimerCardForm( cardDetails: { session in VStack(alignment: .leading) { CardFormDefaults.cardNumber(session) if session.state.hasError(for: .cardNumber), let message = session.state.errorMessage(for: .cardNumber) { Text(message).foregroundColor(.red) } } } ) ``` > [!NOTE] > > Validation errors surface in `fieldErrors` after the form evaluates a field. Use `isValid` to > gate the submit button and `errorMessage(for:)` to display per-field messages. See > [ValidationResult](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/validation-result). ## CardFormConfiguration ```swift theme={"dark"} @available(iOS 15.0, *) public struct CardFormConfiguration: Equatable ``` Declares which fields the card form requires. | Property | Type | Description | | - | - | - | | `cardFields` | `[PrimerInputElementType]` | Card-specific fields (card number, expiry, CVV, cardholder name). | | `billingFields` | `[PrimerInputElementType]` | Billing address fields. Empty when billing address collection is disabled. | | `requiresBillingAddress` | `Bool` | `true` when billing address collection is enabled. | | `allFields` | `[PrimerInputElementType]` | Computed: `cardFields + billingFields`. | ```swift theme={"dark"} public init( cardFields: [PrimerInputElementType], billingFields: [PrimerInputElementType] = [], requiresBillingAddress: Bool = false ) ``` The static `CardFormConfiguration.default` requires `[.cardNumber, .expiryDate, .cvv, .cardholderName]` with no billing fields. ## FormData ```swift theme={"dark"} @available(iOS 15.0, *) public struct FormData: Equatable ``` Type-safe container for field values keyed by `PrimerInputElementType`. Subscript access returns an empty string for unset fields. | Member | Type | Description | | - | - | - | | `subscript(fieldType: PrimerInputElementType)` | `String` | Reads or writes the value for a field. Returns `""` when unset. | | `dictionary` | `[PrimerInputElementType: String]` | All current field values as a dictionary. | ```swift theme={"dark"} let cardNumber = session.state.data[.cardNumber] let allValues = session.state.data.dictionary ``` ## FieldError ```swift theme={"dark"} @available(iOS 15.0, *) public struct FieldError: Equatable, Identifiable ``` A validation error for a specific form field. | Property | Type | Description | | - | - | - | | `id` | `PrimerInputElementType` | Stable identifier (the field type) for SwiftUI diffing. | | `fieldType` | `PrimerInputElementType` | The field that has the error. | | `message` | `String` | Human-readable error message to display. | | `errorCode` | `String?` | Machine-readable error code for programmatic handling, or `nil`. | ```swift theme={"dark"} ForEach(session.state.fieldErrors) { error in Text(error.message) } ``` ## PrimerInputElementType The field identifier used throughout `PrimerCardFormState` (in `configuration`, `data`, and `fieldErrors`). | Case | Field | | - | - | | `.cardNumber` | Card number | | `.expiryDate` | Expiry date (MM/YY) | | `.cvv` | CVV / security code | | `.cardholderName` | Cardholder name | | `.postalCode` | Billing postal code | | `.countryCode` | Billing country | | `.city` | Billing city | | `.state` | Billing state / region | | `.addressLine1` | Billing address line 1 | | `.addressLine2` | Billing address line 2 | | `.phoneNumber` | Billing phone number | | `.firstName` | Billing first name | | `.lastName` | Billing last name | | `.email` | Email address | | `.otp` | One-time passcode | | `.retailer` | Retailer | | `.all` | All fields | | `.unknown` | Unknown / unspecified | ## See also > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > The card form component and its customizable slots. > [card] [Card field components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components) > > Prebuilt field views from CardFormDefaults. > [card] [ValidationResult](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/validation-result) > > Field validation model and error handling. > [card] [PrimerCountry](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-country) > > Country model for billing address selection. # PrimerCardForm Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form SwiftUI card payment form view with slot-based layout > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerCardForm` is a SwiftUI `View` that renders a complete card payment form, composed from three section slots: card details, billing address, and submit button. Each section is a `@ViewBuilder` slot you can replace. The form resolves its [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) from the environment. The `.primerCheckoutSession(_:theme:onCompletion:)` modifier provides it, so you can embed the form anywhere in your own SwiftUI layout. The modal [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) renders its own card screen and does not take composable views. > [!NOTE] > > Requires iOS 15.0+. `PrimerCardForm` is `@available(iOS 15.0, *)`. ## Signature ```swift theme={"dark"} @available(iOS 15.0, *) public struct PrimerCardForm: View { public init( @ViewBuilder cardDetails: @escaping (PrimerCardFormSession) -> CardDetails = { CardFormDefaults.cardDetails($0) }, @ViewBuilder billingAddress: @escaping (PrimerCardFormSession) -> Billing = { CardFormDefaults.billingAddress($0) }, @ViewBuilder submitButton: @escaping (PrimerCardFormSession) -> Submit = { CardFormDefaults.submitButton($0) } ) } ``` ## Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `cardDetails` | `(PrimerCardFormSession) -> CardDetails` | `{ CardFormDefaults.cardDetails($0) }` | Slot for the card input fields (number, expiry, CVV, cardholder name). | | `billingAddress` | `(PrimerCardFormSession) -> Billing` | `{ CardFormDefaults.billingAddress($0) }` | Slot for the billing address fields. The default content renders nothing unless the session's configuration requires billing fields. A custom slot is always shown. To hide it, check `session.state.configuration.requiresBillingAddress` yourself. | | `submitButton` | `(PrimerCardFormSession) -> Submit` | `{ CardFormDefaults.submitButton($0) }` | Slot for the submit/pay button. | Each slot receives the active [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session), which exposes the published `state` and the field-update and `submit()` methods you need to drive custom UI. > [!NOTE] > > Every slot is generic and defaults to a [`CardFormDefaults`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-defaults) builder. Because the defaults are supplied per-parameter, you can override any single slot and leave the rest at their default styling — you never have to re-implement the whole form. ## Default layout The default form stacks the three slots vertically: | Order | Slot | Default content | | - | - | - | | 1 | `cardDetails` | `CardFormDefaults.cardDetails` — card number, expiry, CVV, cardholder name | | 2 | `billingAddress` | `CardFormDefaults.billingAddress` — billing address fields, rendered only when the session requires them | | 3 | `submitButton` | `CardFormDefaults.submitButton` — the pay button | When no card-form session is available, the form renders `CardFormDefaults.unavailable()` (an empty view) instead. This happens when the `.primerCheckoutSession(_:theme:onCompletion:)` modifier is missing, or when the checkout session is still initializing (its `phase` is not yet `.ready`). It also happens when the checkout session has no card payment method. While a payment is processing, the default submit button and the input fields rendered by `CardFormDefaults` are disabled automatically. This covers the `cardDetails` and `billingAddress` sections and the per-field builders, except `cardNetwork(_:)`. The `cardNetwork(_:)` selector and views of your own inside a slot stay enabled, so disable them with `session.state.isLoading`. ## Usage ### Default form Render the fully styled default card form with no arguments: ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CardPaymentScreen: View { var body: some View { PrimerCardForm() } } ``` > [!TIP] > > Place `PrimerCardForm()` inside a view that has the `.primerCheckoutSession(_:theme:onCompletion:)` modifier applied, so the form can resolve its `PrimerCardFormSession` from the environment. ### Overriding a single slot To customize one section, pass a **labeled** argument and leave the others at their defaults. Here only the submit button is replaced — `cardDetails` and `billingAddress` keep the default styling: ```swift theme={"dark"} PrimerCardForm(submitButton: { session in MyPayButton(isLoading: session.state.isLoading) { session.submit() } }) ``` > [!WARNING] > > Always pass slots with their labels (`cardDetails:`, `billingAddress:`, `submitButton:`). Which slot a bare trailing closure such as `PrimerCardForm { session in ... }` fills depends on your Swift language mode. In Swift 6 mode it fills the first slot, `cardDetails`. In Swift 5 mode it fills the last slot, `submitButton`, and the compiler shows a trailing-closure matching warning. ### Recomposing the card section from building blocks You don't have to discard the default fields when customizing a slot. Compose the default content with your own views using the per-field builders on [`CardFormDefaults`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-defaults): ```swift theme={"dark"} PrimerCardForm(cardDetails: { session in VStack { CardFormDefaults.cardDetails(session) MyPromoBanner() } }) ``` You can also assemble the card section from the individual field building blocks — `CardFormDefaults.cardNumber`, `expiryDate`, `cvv`, and `cardholderName`: ```swift theme={"dark"} PrimerCardForm(cardDetails: { session in VStack(spacing: 16) { CardFormDefaults.cardNumber(session) HStack(spacing: 16) { CardFormDefaults.expiryDate(session) CardFormDefaults.cvv(session) } CardFormDefaults.cardholderName(session) } }) ``` See [Card field components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components) for the full set of field building blocks. ## See also > [card] [PrimerCardFormSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) > > State, field-update methods, and `submit()` passed into every slot. > [card] [CardFormDefaults](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-defaults) > > Default section and field builders used by each slot. > [card] [Card field components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components) > > Individual field building blocks for recomposing the card section. > [card] [PrimerPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) > > Render the list of available payment methods alongside the card form. # PrimerCardNetwork Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-card-network Card network type used for co-badged card selection > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerCardNetwork` represents a single card network (card scheme) detected from a card number, together with the display information needed to render it. It is the model used in **co-badged card** scenarios — when one physical card carries more than one network (for example Cartes Bancaires + Visa) and the shopper, or your UI, must choose which network to route the payment through. You read `PrimerCardNetwork` values from [`PrimerCardFormState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) (`availableNetworks`, `selectedNetwork`, and the BIN metadata in `binData.preferred` / `binData.alternatives`) and commit a choice with [`PrimerCardFormSession.selectCardNetwork(_:)`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session). ## Definition ```swift theme={"dark"} @objc public final class PrimerCardNetwork: NSObject ``` > [!NOTE] > > You never construct `PrimerCardNetwork` yourself. The SDK detects networks from the entered card number and publishes them on `PrimerCardFormState.availableNetworks`. Use those instances directly when calling `selectCardNetwork(_:)`. ## Properties | Property | Type | Description | | - | - | - | | `displayName` | `String` | Human-readable network name for display (e.g. `"Visa"`, `"Mastercard"`, `"Cartes Bancaires"`). | | `network` | `CardNetwork` | The underlying card network value. See [CardNetwork](#cardnetwork). | | `allowed` | `Bool` | `true` when this network is enabled for the current merchant configuration. | | `allowsUserSelection` | `Bool` | `true` when the shopper may choose this network in a co-badged selector. `false` for networks that auto-route (e.g. EFTPOS). | | `issuerCountryCode` | `String?` | ISO country code of the card issuer, when known. | | `issuerName` | `String?` | Name of the card issuer, when known. | | `accountFundingType` | `String?` | Account funding type (e.g. credit/debit), when known. | | `prepaidReloadableIndicator` | `String?` | Indicator describing whether a prepaid card is reloadable, when known. | | `productUsageType` | `String?` | Product usage type reported by the network, when known. | | `productCode` | `String?` | Network product code, when known. | | `productName` | `String?` | Network product name, when known. | | `issuerCurrencyCode` | `String?` | ISO currency code associated with the issuer, when known. | | `regionalRestriction` | `String?` | Regional restriction reported by the network, when known. | | `accountNumberType` | `String?` | Account number type reported by the network, when known. | > [!NOTE] > > `displayName`, `network`, `allowed`, and `allowsUserSelection` are the properties you need for co-badge selection. The other `String?` properties hold issuer/BIN metadata. They are always `nil` on the instances in `availableNetworks` and `selectedNetwork`. They are filled only on the instances in `PrimerCardFormState.binData` (`preferred` and `alternatives`) after a remote BIN lookup (`binData.status == .complete`). Read issuer details from there. ## CardNetwork `network` is a `CardNetwork` — a `String`-backed enum identifying the scheme. Its raw value matches the network's canonical uppercase identifier. ```swift theme={"dark"} public enum CardNetwork: String, Codable, CaseIterable ``` > [!NOTE] > > The source declaration also conforms to `LogReporter`, an SDK logging marker protocol that is not meant for merchant use; it is omitted here. | Case | Raw value | Display name | | - | - | - | | `.amex` | `AMEX` | American Express | | `.bancontact` | `BANCONTACT` | Bancontact | | `.cartesBancaires` | `CARTES_BANCAIRES` | Cartes Bancaires | | `.diners` | `DINERS_CLUB` | Diners | | `.discover` | `DISCOVER` | Discover | | `.eftpos` | `EFTPOS` | EFTPOS | | `.elo` | `ELO` | Elo | | `.hiper` | `HIPER` | Hiper | | `.hipercard` | `HIPERCARD` | Hiper | | `.jcb` | `JCB` | JCB | | `.maestro` | `MAESTRO` | Maestro | | `.masterCard` | `MASTERCARD` | Mastercard | | `.mir` | `MIR` | Mir | | `.visa` | `VISA` | Visa | | `.unionpay` | `UNIONPAY` | UnionPay | | `.unknown` | `OTHER` | Unknown | The enum exposes these public members: | Member | Type | Description | | - | - | - | | `displayName` | `String` | Human-readable network name. | | `icon` | `UIImage?` | Branded network icon, or `nil` when none is bundled. | | `traits` | `PrimerCardNetworkTraits?` | PAN length, gap pattern, and CVV metadata for the network, or `nil`. | | `init(cardNumber: String)` | — | Detects the network from a card number, falling back to `.unknown`. | | `init(cardNetworkStr: String)` | — | Resolves a network from a string identifier, falling back to `.unknown`. | ## Co-badged card selection When the entered card number resolves to more than one network, the card form publishes those options on `PrimerCardFormState`. Read them inside any [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) slot through the injected [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session): | State property | Type | Description | | - | - | - | | `availableNetworks` | `[PrimerCardNetwork]` | Networks detected from the card number. More than one indicates a co-badged card. | | `selectedNetwork` | `PrimerCardNetwork?` | The network the card form currently applies. This is the network you passed to `selectCardNetwork(_:)`, or the shopper selected, while it stays in `availableNetworks`. Otherwise it is the first available network. `nil` while no network is detected. | To commit a choice, pass one of the `availableNetworks` instances to the session: | Method | Description | | - | - | | `selectCardNetwork(_ network: PrimerCardNetwork)` | Selects a network for a co-badged card. Applicable only when `availableNetworks` contains more than one network. Only a network picked this way or in the built-in selector is sent as the card's preferred network. When nothing is picked, no preferred network is sent. | > [!TIP] > > Show a selector only when there is a real choice to make — gate it on `availableNetworks.count > 1`. For a single detected network the SDK routes automatically and no selection is needed. ### Building a custom selector ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 15.0, *) struct CoBadgedNetworkPicker: View { @ObservedObject var session: PrimerCardFormSession var body: some View { let networks = session.state.availableNetworks if networks.count > 1 { VStack(alignment: .leading, spacing: 8) { Text("Choose card network") .font(.subheadline) ForEach(networks, id: \.network) { network in Button { session.selectCardNetwork(network) } label: { HStack { Text(network.displayName) Spacer() if session.state.selectedNetwork?.network == network.network { Image(systemName: "checkmark") } } } .disabled(!network.allowed) } } } } } ``` > [!NOTE] > > Render only networks where `allowsUserSelection` is `true` (and that are `allowed`). Networks that auto-route — such as EFTPOS — are resolved by the SDK and should not appear as a manual choice. ### Using the built-in selector If you don't need a fully custom picker, the SDK ships a ready-made selector inside the card number field. Both the default `cardDetails` section and the `CardFormDefaults.cardNumber(_:)` building block show it automatically when a co-badged card is detected. When one of the networks disallows shopper selection (for example EFTPOS), the field shows both network badges and offers no choice. `CardFormDefaults.cardNetwork(_:)` is a standalone dropdown for layouts that do not use `CardFormDefaults.cardNumber(_:)`. It renders only when `availableNetworks.count > 1` and calls `selectCardNetwork(_:)` for you. Do not combine it with `CardFormDefaults.cardNumber(_:)` or the full `cardDetails` section, or two selectors appear. See [Card field components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components). ```swift theme={"dark"} PrimerCardForm(cardDetails: { session in VStack(alignment: .leading, spacing: 16) { // The card number field shows the network selector for co-badged cards. CardFormDefaults.cardNumber(session) HStack(spacing: 12) { CardFormDefaults.expiryDate(session) CardFormDefaults.cvv(session) } CardFormDefaults.cardholderName(session) } }) ``` ## See also > [card] [Card Form Session](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) > > State, network selection, and submission for the card form. > [card] [Card field components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components) > > The built-in co-badge selector and other per-field building blocks. > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > The card form view and its slots. # PrimerCountry Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-country Country data type for billing address selection > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Represents a country in the card form's billing address flow. `PrimerCountry` carries the ISO code, display name, flag emoji, and dial code, and is surfaced through [`PrimerCardFormState.selectedCountry`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) once the buyer selects a country. `PrimerCountry` is a `public struct` conforming to `Equatable` and `Identifiable`, where `id` is the ISO `code`. The stable identifier makes it safe to use directly in SwiftUI `List` and `ForEach`. ## Definition ```swift theme={"dark"} @available(iOS 15.0, *) public struct PrimerCountry: Equatable, Identifiable { public var id: String { code } public let code: String public let name: String public let flag: String? public let dialCode: String? public init(code: String, name: String, flag: String? = nil, dialCode: String? = nil) } ``` ## Properties | Property | Type | Description | | - | - | - | | `id` | `String` | Deterministic identifier based on country code for stable SwiftUI diffing. Equal to `code`. | | `code` | `String` | ISO 3166-1 alpha-2 country code (e.g., `"US"`, `"GB"`, `"DE"`). | | `name` | `String` | Country name for display. In `state.selectedCountry` this is the English name from the SDK's dial-code table (for example `"United States"`), not a localized name. When you create a `PrimerCountry` yourself, it is the value you pass. | | `flag` | `String?` | Flag emoji for the country (e.g., `"🇺🇸"`). `nil` when unavailable. | | `dialCode` | `String?` | International dialing code (e.g., `"+1"` for US). `nil` when unavailable. | > [!NOTE] > > `PrimerCountry` requires iOS 15.0+, matching the minimum deployment target for the Checkout Components framework. ## Initializer | Parameter | Type | Default | Description | | - | - | - | - | | `code` | `String` | — | ISO 3166-1 alpha-2 country code. | | `name` | `String` | — | Country name for display. | | `flag` | `String?` | `nil` | Flag emoji for the country. | | `dialCode` | `String?` | `nil` | International dialing code. | ## Reading the selected country When billing address collection is enabled, the buyer's chosen country is exposed on the card form state. Observe [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) and read `state.selectedCountry`: ```swift theme={"dark"} struct BillingCountryLabel: View { @ObservedObject var session: PrimerCardFormSession var body: some View { if let country = session.state.selectedCountry { HStack { Text(country.flag ?? "") Text(country.name) Text("(\(country.code))") .foregroundStyle(.secondary) } } else { Text("Select a country") } } } ``` ## Updating the selected country To set the billing country programmatically, call `updateCountryCode(_:)` on the card form session with an ISO 3166-1 alpha-2 code. When the code is a supported country code with a dial-code entry, the session resolves `state.selectedCountry` into a full `PrimerCountry`. Otherwise, `state.selectedCountry` keeps its previous value. The codes BQ, BV, CW, EH, HM, SX, TF and UM have no dial-code entry. The buyer can pick them in the country picker, but `state.selectedCountry` keeps its previous value: ```swift theme={"dark"} session.updateCountryCode("US") ``` | Method | Description | | - | - | | `updateCountryCode(_ value: String)` | Updates the billing country by ISO 3166-1 alpha-2 code. Updates `state.selectedCountry` when the code is a supported country code with a dial-code entry; otherwise `state.selectedCountry` keeps its previous value. | > [!TIP] > > Pass the same ISO code you read from `country.code` to round-trip a selection, for example when restoring a saved billing address. ## Equatable behavior Two `PrimerCountry` values are equal when all four properties (`code`, `name`, `flag`, `dialCode`) match. This makes `PrimerCountry` safe to compare when diffing card form state in `Equatable`-driven SwiftUI views. ## See also > [card] [PrimerCardFormSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) > > Observe the card form state and update the billing country. > [card] [Validation](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/validation-result) > > Field-level validation errors (`FieldError`) for billing address inputs. # PrimerError Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error Error details with a diagnostics ID and recovery suggestion > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerError` is the error type delivered when a payment or checkout fails. Every error carries a stable `errorId` for programmatic handling, a `diagnosticsId` to share with Primer support, and (where applicable) a `recoverySuggestion` describing how to recover. ```swift theme={"dark"} public enum PrimerError: PrimerErrorProtocol { public var errorId: String { get } public var diagnosticsId: String { get } public var recoverySuggestion: String? { get } public var plainDescription: String? { get } public var errorDescription: String? { get } public var errorUserInfo: [String: Any] { get } public var underlyingErrorCode: String? { get } } ``` > [!NOTE] > > `PrimerError` conforms to `LocalizedError` and `CustomNSError`, so you also get `localizedDescription` for free and can bridge it to `NSError` when needed. ## How errors are delivered You never construct a `PrimerError` yourself. The SDK delivers it to you through one of two channels, depending on how you present checkout. | Channel | Where the error arrives | | - | - | | SwiftUI state | [`PrimerCheckoutState.failure(PrimerError, checkoutData:)`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state), delivered to the completion closure of the `.primerCheckoutSession(session) { state in ... }` modifier (or `PrimerCheckout(clientToken:) { state in ... }`). Switch on `.failure`. Once checkout is ready, `.failure` arrives once per failed payment attempt and the checkout stays open so the shopper can retry. `.success` or `.dismissed` follows exactly once. A failure while the session is still initializing, before the checkout is ready, ends the `.primerCheckoutSession` session, and nothing more is delivered. `PrimerCheckout(clientToken:)` also reports a failed initialization through the closure while it shows its error screen with a retry. | | Presenter delegate | [`PrimerCheckoutPresenterDelegate`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` for UIKit / presenter-driven integrations. It is called once per failed attempt, including a failed initialization. While the SDK error screen is enabled, the sheet stays open for a retry, and `primerCheckoutPresenterDidCompleteWithSuccess(_:)` or `primerCheckoutPresenterDidDismiss()` follows exactly once. When `isErrorScreenEnabled` is `false`, the sheet closes on the failure. | See [Handle the payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) for the full success / failure / dismissed flow. ## Properties | Property | Type | Description | | - | - | - | | `errorId` | `String` | Stable, kebab-case identifier for the error category (for example `"invalid-client-token"`, `"payment-cancelled"`, `"apple-pay-no-cards-in-wallet"`). Use this for programmatic branching. | | `diagnosticsId` | `String` | Unique per-occurrence diagnostics ID. Log it and provide it to Primer support when investigating an issue. | | `recoverySuggestion` | `String?` | Suggested recovery action when one applies (for example "Check if the token you have provided is a valid token"). `nil` when no recovery is available (for example a user-cancelled payment). | | `plainDescription` | `String?` | The error message without the `errorId` and `diagnosticsId` wrapper. This is the text the SDK's default error screen shows. | | `errorDescription` | `String?` | Message for logging: `"[] (diagnosticsId: )"`. Also surfaced as `localizedDescription` via `LocalizedError`. | | `errorUserInfo` | `[String: Any]` | `NSError` user-info dictionary. Includes `"diagnosticsId"` and a `"createdAt"` timestamp. | | `underlyingErrorCode` | `String?` | Reserved for NOL Pay provider errors, which CheckoutComponents does not produce. Always `nil` for errors delivered by CheckoutComponents. | > [!WARNING] > > `errorDescription` and `localizedDescription` include the error and diagnostics IDs and are meant for logs. The SDK's default error screen shows `plainDescription`. In your own UI, show your own localized, branded message. ## Handling an error Receive the checkout state through the completion closure and, in the `.failure` branch, log the `diagnosticsId` and `errorId`. Branch on `errorId` only when you need behavior specific to a category (for example `"payment-failed"` for a declined payment versus a configuration error such as `"invalid-client-token"`). > [!NOTE] > > A shopper who cancels a payment method (closing the Apple Pay sheet or PayPal, leaving a redirect) is not a failure. Tapping PayPal's "Cancel and return" link is also a cancel. For Klarna, closing the consent alert or the web sheet is a cancel, and so is a decline from Klarna. CheckoutComponents returns to the payment method list, or delivers `.dismissed` when there is no list to return to. Klarna SDK errors (`"klarna-sdk-error"`) reach `.failure`. `"payment-cancelled"` reaches `.failure` only in rare edge cases. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutScreen: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } var body: some View { ScrollView { PrimerCardForm() } .primerCheckoutSession(session) { state in handle(state) } } private func handle(_ state: PrimerCheckoutState) { switch state { case let .failure(error, _): handle(error) case let .success(result): print("Payment completed: \(result.paymentId)") case .dismissed, .initializing, .ready: break @unknown default: break } } private func handle(_ error: PrimerError) { // Always log the diagnostics ID — share it with Primer support. print("Checkout failed [\(error.errorId)]: \(error.localizedDescription)") print("Diagnostics ID: \(error.diagnosticsId)") switch error.errorId { case "payment-cancelled": // Rarely delivered here: the shopper backed out, so no message is needed. break default: // Show your own branded, localized error message here. showRetryAlert(suggestion: error.recoverySuggestion) } } } ``` For a UIKit / presenter integration, the same `PrimerError` arrives through the delegate: ```swift theme={"dark"} extension CheckoutCoordinator: PrimerCheckoutPresenterDelegate { func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) { print("Checkout failed [\(error.errorId)] — diagnosticsId: \(error.diagnosticsId)") // Present your own error UI; use error.recoverySuggestion to decide whether to offer a retry. } } ``` > [!TIP] > > When filing a support ticket, include the `diagnosticsId`. It lets Primer trace the exact occurrence of the failure across SDK and backend logs. ## See also > [card] [PrimerCheckoutState](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) > > The checkout state that delivers `.failure(PrimerError, checkoutData:)`. > [card] [Handle the payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) > > Handle success, failure, and dismissal end to end. > [card] [PrimerCheckoutPresenter](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) > > Receive failures through the presenter delegate. > [card] [ValidationResult](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/validation-result) > > Inline field validation, distinct from checkout errors. # PrimerSettings Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings SDK configuration: payment handling, payment method options, UI, and debug options > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerSettings` is the SDK's top-level configuration object. Create it once and pass it to your checkout entry point, either as `primerSettings:` on [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) or as `settings:` on [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). ## Definition ```swift theme={"dark"} public final class PrimerSettings: Codable { public init( paymentHandling: PrimerPaymentHandling = .auto, localeData: PrimerLocaleData? = nil, paymentMethodOptions: PrimerPaymentMethodOptions? = nil, uiOptions: PrimerUIOptions? = nil, threeDsOptions: PrimerThreeDsOptions? = nil, debugOptions: PrimerDebugOptions? = nil, clientSessionCachingEnabled: Bool = false, apiVersion: PrimerApiVersion = .V2_4 ) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `paymentHandling` | `PrimerPaymentHandling` | `.auto` | Keep the default. Primer Checkout creates the payment after tokenization. `.manual` fails the checkout at start, see [PrimerPaymentHandling](#primerpaymenthandling). | | `localeData` | `PrimerLocaleData?` | `nil` | Locale used to format amounts. Its `localeCode` is also sent with Klarna, redirect, QR code, form redirect and Stripe ACH payment requests. Defaults to the device locale. It does not change the language of the SDK's own UI text, which follows the app's language. | | `paymentMethodOptions` | `PrimerPaymentMethodOptions?` | `nil` | Payment method-specific configuration (Apple Pay, Klarna, 3DS, Stripe ACH, redirect scheme). | | `uiOptions` | `PrimerUIOptions?` | `nil` | UI behavior settings: which screens are shown, dismissal mechanisms, and appearance mode. | | `threeDsOptions` | `PrimerThreeDsOptions?` | `nil` | Ignored. The SDK does not read this parameter. Set 3D Secure options through `paymentMethodOptions: PrimerPaymentMethodOptions(threeDsOptions:)` instead. | | `debugOptions` | `PrimerDebugOptions?` | `nil` | Debug and development options. | | `clientSessionCachingEnabled` | `Bool` | `false` | Caches client session data to reduce network requests. | | `apiVersion` | `PrimerApiVersion` | `.V2_4` | Primer API version used for backend communication. | > [!NOTE] > > Each option group is optional. Pass `nil` (the default) to use the SDK defaults, or supply a configured object to override behavior for that group. ## Usage ```swift theme={"dark"} let settings = PrimerSettings( paymentHandling: .auto, localeData: PrimerLocaleData(languageCode: "de", regionCode: "DE"), paymentMethodOptions: PrimerPaymentMethodOptions( urlScheme: "myapp://primer", applePayOptions: PrimerApplePayOptions( merchantIdentifier: "merchant.com.myapp", merchantName: nil ) ), uiOptions: PrimerUIOptions( isInitScreenEnabled: false, dismissalMechanism: [.gestures, .closeButton], appearanceMode: .system ) ) PrimerCheckout( clientToken: clientToken, primerSettings: settings, onCompletion: { state in // Handle the checkout result } ) ``` > [!TIP] > > Define your settings outside the SwiftUI view body (for example, as a stored property) so they are not re-created on every render cycle. ```swift theme={"dark"} private let primerSettings = PrimerSettings(paymentHandling: .auto) struct CheckoutView: View { let clientToken: String var body: some View { PrimerCheckout( clientToken: clientToken, primerSettings: primerSettings ) } } ``` *** ## PrimerPaymentHandling Primer Checkout supports `.auto` only. The SDK tokenizes the payment method, creates the payment, and delivers the result through the completion handler. ```swift theme={"dark"} public enum PrimerPaymentHandling: String, Codable { case auto = "AUTO" case manual = "MANUAL" } ``` | Case | Description | | - | - | | `.auto` | The SDK creates the payment after tokenization. Results are delivered through the completion handler. | | `.manual` | Not supported in Primer Checkout. The checkout fails at start with a `PrimerError` whose `errorId` is `invalid-value`, before the shopper sees any payment method. | > [!WARNING] > > The `.manual` case exists because `PrimerSettings` is shared with the Drop-In and Headless SDKs. Primer Checkout does not support it, and the checkout fails at start. To pass an idempotency key or to abort a payment before the SDK creates it, use `idempotencyKey` or `onBeforePaymentCreate` on [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). See [Handle the payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) for how results reach your app. *** ## PrimerLocaleData Sets the locale that formats amounts, instead of the device locale. The SDK also sends its `localeCode` with Klarna, redirect, QR code, form redirect and Stripe ACH payment requests. It does not change the language of the SDK's own UI text, which follows the app's language. ```swift theme={"dark"} public struct PrimerLocaleData: Codable, Equatable { public let languageCode: String public let localeCode: String public let regionCode: String? public init(languageCode: String? = nil, regionCode: String? = nil) } ``` | Property | Type | Description | | - | - | - | | `languageCode` | `String` | ISO 639-1 language code (for example `"en"`, `"de"`, `"fr"`). Defaults to the device language. | | `localeCode` | `String` | Combined `language-region` code (for example `"en-US"`). Computed from the language and region codes. | | `regionCode` | `String?` | ISO 3166-1 alpha-2 region code (for example `"US"`, `"GB"`). `nil` when only the language is provided. | > [!NOTE] > > If you pass only `languageCode`, `regionCode` is `nil` and `localeCode` is the language code alone, for example `"de"`. Pass `regionCode` as well to get a `language-region` code. *** ## PrimerPaymentMethodOptions Payment method-specific configuration. Set `urlScheme` for flows that leave your app and return to it: PayPal, redirect-based payment methods, Adyen Klarna and Stripe ACH. Without a valid scheme, these flows fail with a `PrimerError` whose `errorId` is `invalid-value`. 3D Secure returns to your app through `threeDsOptions.threeDsAppRequestorUrl` instead. ```swift theme={"dark"} public final class PrimerPaymentMethodOptions: Codable { public init( urlScheme: String? = nil, applePayOptions: PrimerApplePayOptions? = nil, klarnaOptions: PrimerKlarnaOptions? = nil, threeDsOptions: PrimerThreeDsOptions? = nil, stripeOptions: PrimerStripeOptions? = nil ) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `urlScheme` | `String?` | `nil` | Deep link scheme for returning from third-party apps (for example `"myapp://primer"`). Must be a valid URL scheme. | | `applePayOptions` | `PrimerApplePayOptions?` | `nil` | Apple Pay configuration. Required when using Apple Pay. | | `klarnaOptions` | `PrimerKlarnaOptions?` | `nil` | Klarna configuration for recurring Klarna sessions. Not needed for Klarna payments in Primer Checkout, which creates one-off Klarna sessions. | | `threeDsOptions` | `PrimerThreeDsOptions?` | `nil` | 3D Secure configuration. | | `stripeOptions` | `PrimerStripeOptions?` | `nil` | Stripe ACH configuration. Required when using Stripe ACH. | ### PrimerApplePayOptions ```swift theme={"dark"} public final class PrimerApplePayOptions: Codable { public init( merchantIdentifier: String, merchantName: String?, isCaptureBillingAddressEnabled: Bool = false, showApplePayForUnsupportedDevice: Bool = true, checkProvidedNetworks: Bool = true, shippingOptions: ShippingOptions? = nil, billingOptions: BillingOptions? = nil, allowedCardTypes: [CardType]? = nil ) } public enum CardType: String, Codable { case credit, debit } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `merchantIdentifier` | `String` | — | Your Apple Pay merchant identifier (for example `"merchant.com.myapp"`). | | `merchantName` | `String?` | — | Fallback merchant name for the Apple Pay sheet. The merchant name from the [client session](/docs/checkout/client-session) takes precedence. Pass `nil` if the client session provides it. | | `isCaptureBillingAddressEnabled` | `Bool` | `false` | When `true` and `billingOptions` sets no fields, the sheet requests the billing postal address. Use `billingOptions` to configure required billing fields. | | `showApplePayForUnsupportedDevice` | `Bool` | `true` | Not used by Primer Checkout. Apple Pay is always listed when it is configured. On a device that cannot pay, selecting it shows an "Apple Pay Unavailable" screen. | | `checkProvidedNetworks` | `Bool` | `true` | Whether to verify the device can pay using the provided networks before presenting Apple Pay. | | `shippingOptions` | `ShippingOptions?` | `nil` | Extra shipping contact fields to request on the Apple Pay sheet. `requireShippingMethod` has no effect in Primer Checkout. | | `billingOptions` | `BillingOptions?` | `nil` | Required billing contact fields. | | `allowedCardTypes` | `[CardType]?` | `nil` | Card funding types the Apple Pay sheet offers (`.credit`, `.debit`). `nil` or empty allows all types. | `PrimerApplePayOptions.ShippingOptions` and `PrimerApplePayOptions.BillingOptions` are nested types that set the contact fields the Apple Pay sheet asks for. When the Express Checkout shipping handlers run, the SDK requests the postal address itself. Use `ShippingOptions` only to request extra shipping contact fields. ```swift theme={"dark"} public final class PrimerApplePayOptions: Codable { public struct ShippingOptions: Codable { public let shippingContactFields: [RequiredContactField]? public let requireShippingMethod: Bool public init(shippingContactFields: [RequiredContactField]? = nil, requireShippingMethod: Bool) } public struct BillingOptions: Codable { public let requiredBillingContactFields: [RequiredContactField]? public init(requiredBillingContactFields: [RequiredContactField]? = nil) } public enum RequiredContactField: String, Codable { case name, emailAddress, phoneNumber, postalAddress } } ``` See [Apple Pay integration](/docs/sdk/ios-checkout/v3.0.0-beta/guides/apple-pay-integration) for end-to-end setup. ### PrimerKlarnaOptions ```swift theme={"dark"} public final class PrimerKlarnaOptions: Codable { public init(recurringPaymentDescription: String) } ``` | Parameter | Type | Description | | - | - | - | | `recurringPaymentDescription` | `String` | Description sent for recurring Klarna sessions. Primer Checkout creates one-off Klarna payments and does not read it. | ### PrimerStripeOptions ```swift theme={"dark"} public final class PrimerStripeOptions: Codable, Equatable { public enum MandateData: Codable, Equatable { case fullMandate(text: String) case templateMandate(merchantName: String) } public init(publishableKey: String, mandateData: MandateData? = nil) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `publishableKey` | `String` | — | Stripe publishable key. | | `mandateData` | `MandateData?` | `nil` | ACH mandate text shown before the shopper confirms. Required for Stripe ACH: without it, the ACH payment fails at the mandate step. Use `.templateMandate(merchantName:)` for the standard template, or `.fullMandate(text:)` for your own text. | ### PrimerThreeDsOptions ```swift theme={"dark"} public struct PrimerThreeDsOptions: Codable, Equatable { public init(threeDsAppRequestorUrl: String? = nil) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `threeDsAppRequestorUrl` | `String?` | `nil` | URL that an out-of-band 3DS challenge, such as a banking app, uses to return to your app. Must start with `https`, typically a universal link of your app. Set it through `paymentMethodOptions.threeDsOptions`. Used for 3DS protocol versions above 2.1. Without a usable URL, the SDK logs a warning and the challenge cannot redirect back. | *** ## PrimerUIOptions Controls checkout UI behavior: which screens are shown, how the sheet is dismissed, and appearance mode. ```swift theme={"dark"} public final class PrimerUIOptions: Codable { public internal(set) var isInitScreenEnabled: Bool public internal(set) var isSuccessScreenEnabled: Bool public internal(set) var isErrorScreenEnabled: Bool public internal(set) var dismissalMechanism: [DismissalMechanism] public internal(set) var cardFormUIOptions: PrimerCardFormUIOptions? public internal(set) var appearanceMode: PrimerAppearanceMode public var theme: PrimerTheme public init( isInitScreenEnabled: Bool? = nil, isSuccessScreenEnabled: Bool? = nil, isErrorScreenEnabled: Bool? = nil, dismissalMechanism: [DismissalMechanism]? = [.gestures], cardFormUIOptions: PrimerCardFormUIOptions? = nil, appearanceMode: PrimerAppearanceMode? = nil, theme: PrimerTheme? = nil ) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `isInitScreenEnabled` | `Bool?` | `true` | Managed checkout only (`PrimerCheckout`, `PrimerCheckoutPresenter`). Shows the splash screen while payment methods load, and holds it for at least 0.5 s. With `false`, the SDK skips the pause and shows an empty screen while payment methods load. The splash screen always shows while the SDK initializes. The inline `.primerCheckoutSession` integration never shows a splash and never pauses. | | `isSuccessScreenEnabled` | `Bool?` | `true` | Shows a success screen after the payment completes. | | `isErrorScreenEnabled` | `Bool?` | `true` | Shows the SDK error screen when a payment or the checkout initialization fails. After a failed payment attempt the screen offers a retry and can offer to choose another payment method. A failed initialization shows a retry. A failure before any payment attempt, such as a load failure, shows no retry. With `false`, the SDK shows no error view. It reports the failure only through `onCompletion` as `.failure`. With `PrimerCheckoutPresenter`, it reports through `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` and closes the sheet. | | `dismissalMechanism` | `[DismissalMechanism]?` | `[.gestures]` | How the user can dismiss the checkout modal. | | `cardFormUIOptions` | `PrimerCardFormUIOptions?` | `nil` | Card form-specific UI options. | | `appearanceMode` | `PrimerAppearanceMode?` | `.system` | Sets the color scheme of the SDK UI. With `.light` or `.dark`, the SDK screens, sheets, and design tokens use that scheme. Light mode reads `colors` from `PrimerCheckoutTheme`, and dark mode reads `darkColors`. With the inline `.primerCheckoutSession` modifier, your own views keep their color scheme. With `.system`, the SDK follows the color scheme of the host view. Klarna's payment view also follows this setting. | | `theme` | `PrimerTheme?` | `PrimerTheme()` | Drop-In theme. Primer Checkout ignores it. Style the checkout with [`PrimerCheckoutTheme`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme), passed as `primerTheme:` on `PrimerCheckout` / `PrimerCheckoutPresenter` or `theme:` on `.primerCheckoutSession`. | ### DismissalMechanism ```swift theme={"dark"} public enum DismissalMechanism: String, Codable { case gestures = "GESTURES" case closeButton = "CLOSE_BUTTON" } ``` | Case | Description | | - | - | | `.gestures` | Lets the shopper swipe down to dismiss the sheet that `PrimerCheckoutPresenter` presents, and shows the sheet's grabber. Without it, the presenter hides the grabber and disables the swipe. This option has no effect when you present `PrimerCheckout` or the inline flow in your own SwiftUI sheet. The SDK blocks swipe dismissal while the processing screen is shown. | | `.closeButton` | Display a close button in the navigation area. | ### PrimerAppearanceMode ```swift theme={"dark"} public enum PrimerAppearanceMode: String, Codable { case system = "SYSTEM" case light = "LIGHT" case dark = "DARK" } ``` | Case | Description | | - | - | | `.system` | Follows the color scheme of the host view, which is the device appearance setting unless your app overrides it. Default. | | `.light` | Forces light appearance. | | `.dark` | Forces dark appearance. | ### PrimerCardFormUIOptions ```swift theme={"dark"} public struct PrimerCardFormUIOptions: Codable { public let payButtonAddNewCard: Bool public let payButtonText: String? public init(payButtonAddNewCard: Bool = false, payButtonText: String? = nil) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `payButtonAddNewCard` | `Bool` | `false` | When `true`, the button of the SDK card form screen reads "Add card" instead of "Pay". This applies in `PrimerCheckout`, `PrimerCheckoutPresenter` and the sheet that `.primerCheckoutSession` opens for card. The button of a composable `PrimerCardForm` is not affected. | | `payButtonText` | `String?` | `nil` | The text of the Pay button on the card form. Write `{amount}` where the order total should go. The SDK fills it in, formatted for the shopper and including any card surcharge, and updates it when the surcharge changes. For example, `"Complete order {amount}"` reads "Complete order £11.50". Text without `{amount}` shows no amount, and the SDK leaves the token out while the amount is unknown. Empty or `nil` keeps "Pay". Applies to the card form screen of the checkout and to the default `CardSubmitButton` of a composable `PrimerCardForm`. Drop-in ignores it. | *** ## PrimerDebugOptions ```swift theme={"dark"} public struct PrimerDebugOptions: Codable { public init(is3DSSanityCheckEnabled: Bool? = nil) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `is3DSSanityCheckEnabled` | `Bool?` | `true` | Enables 3DS security sanity checks. Disable only during development. | *** ## PrimerApiVersion ```swift theme={"dark"} public enum PrimerApiVersion: String, Codable { case V2_4 = "2.4" public static let latest: PrimerApiVersion = .V2_4 } ``` | Case | Description | | - | - | | `V2_4` | Primer API version 2.4 (latest). | *** ## See also > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > The managed checkout view that accepts these settings > [card] [PrimerCheckoutPresenter](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) > > Present checkout from UIKit with PrimerSettings > [card] [PrimerError](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) > > Error type surfaced through the completion handler > [card] [PrimerCheckoutTheme](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) > > Theme the checkout UI with design tokens via primerTheme # Validation Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/common/validation-result Field validation results and helpers for the card form > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. The card form's built-in field views validate each field and surface the results through `PrimerCardFormState`. A field shows an error when the shopper leaves it with an invalid value. The CVV field also validates as soon as it reaches its full length. The error clears when the shopper focuses that field again. Empty fields never show an error message. Values you write with the session's `update*` methods never produce a `FieldError`. They count toward `isValid` only while the matching SDK field view is on screen. Read validation state from the `PrimerCardFormSession` inside your custom slots to display targeted messages and gate submission. ## FieldError A `FieldError` represents a validation error for a single form field. It is `Equatable` and `Identifiable` (its `id` is the `fieldType`), so it works directly with SwiftUI's `ForEach`. ```swift theme={"dark"} @available(iOS 15.0, *) public struct FieldError: Equatable, Identifiable { public var id: PrimerInputElementType { fieldType } public let fieldType: PrimerInputElementType public let message: String public let errorCode: String? public init( fieldType: PrimerInputElementType, message: String, errorCode: String? = nil ) } ``` | Property | Type | Description | | - | - | - | | `id` | `PrimerInputElementType` | Deterministic identifier based on `fieldType` for stable SwiftUI diffing. | | `fieldType` | `PrimerInputElementType` | The type of field that has the error. | | `message` | `String` | Human-readable error message to display to the user. | | `errorCode` | `String?` | Machine-readable error code for programmatic handling. | ## Validation surfaces on PrimerCardFormState Validation is exposed through the form state held by `PrimerCardFormSession`. Observe the session your slot receives with `@ObservedObject` and read `session.state`. | Member | Type | Description | | - | - | - | | `fieldErrors` | `[FieldError]` | Field-specific validation errors currently present in the form. | | `isValid` | `Bool` | `true` when the card number, expiry date, CVV and cardholder name fields are all valid. Billing address fields don't affect it. Use this to enable or disable your submit button. | | `hasError(for:)` | `(PrimerInputElementType) -> Bool` | Returns `true` when the given field currently has an error. | | `errorMessage(for:)` | `(PrimerInputElementType) -> String?` | Returns the first error message for the given field, or `nil` if the field has no error. | ```swift theme={"dark"} @available(iOS 15.0, *) public struct PrimerCardFormState: Equatable { public internal(set) var fieldErrors: [FieldError] public internal(set) var isValid: Bool public func hasError(for fieldType: PrimerInputElementType) -> Bool public func errorMessage(for fieldType: PrimerInputElementType) -> String? } ``` > [!NOTE] > > `isValid` is `true` while the SDK's card number, expiry date, CVV and cardholder name fields all hold valid values. Billing address fields don't count toward it. While `isValid` is `true`, the SDK keeps `fieldErrors` empty. It clears every entry whenever a field's validity updates, billing errors included. Use `isValid` to drive the enabled state of your submit button, and use `fieldErrors` / `errorMessage(for:)` to render per-field messages. ## Reading a field error inside a slot Validation runs inside the SDK's own field views (the `CardFormDefaults` building blocks), which also show the field's error message. The `update*` methods on `PrimerCardFormSession` store a value but never produce a validation error. A `TextField` of your own never produces a `FieldError`. Keep the SDK field and use the helpers on `session.state` to add your own UI around it. The example below adds a hint under the CVV field while it has an error. ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 15.0, *) struct CvvField: View { @ObservedObject var session: PrimerCardFormSession var body: some View { VStack(alignment: .leading, spacing: 4) { CardFormDefaults.cvv(session) if session.state.hasError(for: .cvv) { Text("You can find the security code on the back of your card.") .font(.footnote) .foregroundColor(.secondary) } } } } ``` To enumerate every error currently present in the form, iterate `fieldErrors` directly — `FieldError` is `Identifiable`, so it slots into `ForEach`. ```swift theme={"dark"} ForEach(session.state.fieldErrors) { error in Text("\(error.fieldType.stringValue): \(error.message)") .font(.footnote) .foregroundColor(.red) } ``` ## Gating submission with isValid Bind your submit button's enabled state to `session.state.isValid` so it activates only once the form passes validation. ```swift theme={"dark"} Button("Pay") { session.submit() } .disabled(!session.state.isValid) ``` ## PrimerInputElementType `PrimerInputElementType` identifies the type of input field referenced by a `FieldError` (and used throughout the card form). Each case has a `stringValue` returning the canonical string identifier. ```swift theme={"dark"} @objc public enum PrimerInputElementType: Int { case cardNumber case expiryDate case cvv case cardholderName case otp case postalCode case phoneNumber case retailer case unknown case countryCode case firstName case lastName case addressLine1 case addressLine2 case city case state case email case all public var stringValue: String { get } } ``` | Case | `stringValue` | Description | | - | - | - | | `cardNumber` | `CARD_NUMBER` | Credit/debit card number (e.g., "4242 4242 4242 4242"). | | `expiryDate` | `EXPIRY_DATE` | Card expiration date in MM/YY format. | | `cvv` | `CVV` | Card verification value (3-4 digit security code). | | `cardholderName` | `CARDHOLDER_NAME` | Name as printed on the card. | | `otp` | `OTP` | One-time password for verification flows. | | `postalCode` | `POSTAL_CODE` | Postal or ZIP code for billing address. | | `phoneNumber` | `PHONE_NUMBER` | Phone number for contact or verification. | | `retailer` | `RETAILER` | Retail outlet selection for cash payment methods. | | `unknown` | `UNKNOWN` | Unknown or unrecognized field type. | | `countryCode` | `COUNTRY_CODE` | ISO country code (e.g., "US", "GB"). | | `firstName` | `FIRST_NAME` | First name for billing address. | | `lastName` | `LAST_NAME` | Last name for billing address. | | `addressLine1` | `ADDRESS_LINE_1` | Primary street address line. | | `addressLine2` | `ADDRESS_LINE_2` | Secondary address line (apartment, suite, etc.). | | `city` | `CITY` | City name for billing address. | | `state` | `STATE` | State or province for billing address. | | `email` | `EMAIL` | Email address for receipts and notifications. | | `all` | `ALL` | Represents all fields collectively (used for bulk operations). | > [!TIP] > > You typically don't construct `FieldError` yourself. The SDK's field views populate `fieldErrors` when the shopper leaves a field. Read it through `session.state` and use `hasError(for:)` / `errorMessage(for:)` to drive your UI. ## See also > [card] [Card form session](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) > > The observable session that exposes form state, mutation methods, and submission. > [card] [Card field components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components) > > Built-in field views you can compose inside the card form slots. # API Reference Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/overview Complete API reference for the Primer Checkout iOS SDK > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. ## Core API | Component | Description | | - | - | | [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) | Managed SwiftUI view that renders the SDK's default checkout screens | | [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) | Observable session that owns the checkout lifecycle for composable, inline checkout | | [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) | Enum representing checkout lifecycle states (`initializing`, `ready`, `success`, `failure`, `dismissed`) | | [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) | UIKit entry point that presents the managed checkout modally with a delegate | ## Card Form | Component | Description | | - | - | | [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) | Card payment form view with `@ViewBuilder` slots for card details, billing address, and submit | | [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) | Observable session exposing card-form state, field mutations, and the submit action | | [`CardFormDefaults`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-defaults) | Pre-built slot bodies and per-field building blocks for custom card form layouts | | [Card Field Components](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-field-components) | Individual field building blocks (`cardNumber`, `expiryDate`, `cvv`, `cardholderName`, etc.) | ## Payment Methods | Component | Description | | - | - | | [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) | Payment method list view with `@ViewBuilder` slots for header, method row, and empty state | | [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) | Observable session exposing the selection state and selection actions | | [`PaymentMethodsDefaults`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-defaults) | Pre-built slot bodies for custom payment method layouts | | [`VaultedPaymentMethodsDefaults`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) | Pre-built header, item, and submit bodies for `PrimerVaultedPaymentMethods` | | [`PrimerVaultedPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) | Saved payment methods view with slots for header, item, and submit | ## Theming | Component | Description | | - | - | | [`PrimerCheckoutTheme`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) | Root theme container holding all design token override groups | | [`ColorOverrides`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens) | Color token overrides, passed as `colors` (light mode) and `darkColors` (dark mode) | | [`SpacingOverrides`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens) | Spacing values for padding and margins | | [`TypographyOverrides`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/typography-tokens) | Font sizes, weights, and line heights | | [`RadiusOverrides` / `WidthOverrides` / `SizeOverrides`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) | Corner radius, border widths per field state, and component sizes | ## Common Objects | Component | Description | | - | - | | [`PrimerSettings`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings) | SDK configuration (payment handling mode, options) | | [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) | Error details with diagnostics ID and recovery suggestion | | [`FieldError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/validation-result) | Validation error for a single card-form field, read from `PrimerCardFormState` | | [`PrimerCardNetwork`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-card-network) | Card network type for co-badged card selection | | [`PrimerCountry`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-country) | Country data used for billing address selection | ## Session pattern The iOS SDK offers a managed checkout and a composable one. The managed checkout, [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) in SwiftUI or [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) from UIKit, builds its own checkout and needs no session. An observable [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) drives the composable views and owns the checkout lifecycle. It loads the [client session](/docs/checkout/client-session) and tracks the lifecycle [`Phase`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). In SwiftUI, outcomes reach your `onCompletion` handler as [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state). `.failure` arrives once per failed attempt. `.success` or `.dismissed` arrives at most once and ends the checkout. With the default error screen, the shopper can retry after a failed payment. If initialization fails, an inline `PrimerCheckoutSession` ends after that single `.failure`. ### Composable (inline) Hold a `PrimerCheckoutSession` as a `@StateObject`, then attach it to your view hierarchy with the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. The composable views — [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form), [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods), and [`PrimerVaultedPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) — resolve their per-feature session from the SwiftUI environment and expose slots you can override. `PrimerCardForm` and `PrimerPaymentMethods` take `@ViewBuilder` slots. `PrimerVaultedPaymentMethods` slots return `AnyView`, so wrap your custom content in `AnyView`. ```swift theme={"dark"} @StateObject private var session: PrimerCheckoutSession init(token: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: token)) } var body: some View { ScrollView { PrimerCardForm() PrimerPaymentMethods() } .primerCheckoutSession(session) { state in handle(state) } } ``` The `PrimerCardForm` slots, the `PrimerPaymentMethods` `header` and `emptyState` slots, and the `PrimerVaultedPaymentMethods` `header` slot receive their session as a parameter. Use it to read state and call actions from your custom UI. The `PrimerPaymentMethods` `method` slot and the `PrimerVaultedPaymentMethods` `item` and `submitButton` slots receive only row data and callbacks. | Session | Provided by | Exposes | | - | - | - | | [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) | `.primerCheckoutSession(_:theme:onCompletion:)` | `phase`, `clientSession`, `cardForm`, `selection`, `onBeforePaymentCreate`, `onShippingAddressChange`, `onShippingOptionChange`, `idempotencyKey`, `formatAmount(_:)`, `refresh()`, `cancel()` | | [`PrimerCardFormSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) | `PrimerCardForm` slots | `state`, card field mutations, `selectCardNetwork(_:)`, `setVaultOnSuccess(_:)`, `submit()`, `cancel()` | | [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) | `PrimerPaymentMethods` / `PrimerVaultedPaymentMethods` slots | `select(_:)`, `selectVaulted(_:)` (pays), `delete(_:)`, `showAll()`, `cancel()` | > [!NOTE] > > Sessions are `@MainActor` `ObservableObject`s. Observe them with `@StateObject` (when you own them) or `@ObservedObject` (when they are passed into a slot), and read their `@Published` `state`/`phase` directly in your views. ### Managed (modal) For a turnkey flow that renders the SDK's default screens, use [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) in SwiftUI, or [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) from UIKit. ```swift theme={"dark"} PrimerCheckout(clientToken: token) { state in handle(state) } ``` ```swift theme={"dark"} PrimerCheckoutPresenter.shared.delegate = self PrimerCheckoutPresenter.presentCheckout(clientToken: token, from: self) ``` > [!TIP] > > Start with the managed `PrimerCheckout` view to get a working checkout quickly, then move to the composable views and `@ViewBuilder` slots when you need full control over the UI. ## See also > [card] [PrimerCheckoutSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) > > Own the checkout lifecycle for inline, composable checkout. > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > Drop in the managed SwiftUI checkout view. > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > Build a custom card form with @ViewBuilder slots. > [card] [Handle payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) > > React to the final PrimerCheckoutState. # PaymentMethodsDefaults Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-defaults Pre-built sub-components for custom payment method layouts > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PaymentMethodsDefaults` is a public enum (used as a namespace) providing the pre-built `@ViewBuilder` content that [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) renders when you omit a slot. Use these helpers inside your own slots to mix custom and default content, or as a reference for the default look and feel. ```swift theme={"dark"} @available(iOS 15.0, *) public enum PaymentMethodsDefaults ``` > [!NOTE] > > Each helper is the default value for the matching `PrimerPaymentMethods` slot. The component falls back to `PaymentMethodsDefaults.header($0)`, `PaymentMethodsDefaults.method($0, onSelect: $1)`, and `PaymentMethodsDefaults.emptyState($0)` when those slots are not supplied. ## Builders | Builder | Description | | - | - | | `header(_:)` | Default "Choose payment method" header styled with the current theme | | `method(_:onSelect:)` | Default tappable row for one payment method, styled per payment method type, that calls `onSelect` when tapped | | `emptyState(_:)` | Message displayed when no payment methods are available | | `unavailable()` | Empty placeholder rendered when no `PrimerSelectionSession` is in the environment | ## header ```swift theme={"dark"} public static func header(_ session: PrimerSelectionSession) -> PaymentMethodsHeaderContent ``` Renders the section title using the theme's [typography](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/typography-tokens) and [color tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens), with the header accessibility trait applied. | Parameter | Type | Description | | - | - | - | | `session` | `PrimerSelectionSession` | The active selection session. Accepted to match the slot closure signature; the default header is static. | The `session` parameter exists only so this helper matches the `header` slot's closure signature — the default header does not read from it. ## method ```swift theme={"dark"} public static func method( _ method: CheckoutPaymentMethod, onSelect: @escaping () -> Void ) -> PaymentMethodRowContent ``` Renders a tappable row for a single payment method. The row's content and VoiceOver label depend on the payment method type: | Payment method type | Row content | VoiceOver label | | - | - | - | | Card | The card icon and the localized "Pay with card" title | "Pay with card" | | Apple Pay | Apple's native Apple Pay button | The system Apple Pay label | | Klarna | The Klarna logo inside the localized "Pay with Klarna" text | "Pay with Klarna" | | Any other method | Its backend logo. Without a logo, the row shows `method.buttonText`, or `method.name` when there is no button text. | "Pay with" followed by `method.buttonText`, or `method.name` when there is no button text | The default row does not display a surcharge. To show one, read `method.formattedSurcharge` in your own `method` slot, as in the [example below](#using-defaults-inside-custom-slots). | Parameter | Type | Description | | - | - | - | | `method` | `CheckoutPaymentMethod` | The payment method data to display | | `onSelect` | `@escaping () -> Void` | Callback invoked when the row is tapped. `PrimerPaymentMethods` wires this to `session.select(method)`. | ## emptyState ```swift theme={"dark"} public static func emptyState(_ session: PrimerSelectionSession) -> PaymentMethodsEmptyContent ``` Rendered automatically by [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) when `session.state.paymentMethods` is empty. | Parameter | Type | Description | | - | - | - | | `session` | `PrimerSelectionSession` | The active selection session. Accepted to match the slot closure signature; the default empty state is static. | ## unavailable ```swift theme={"dark"} public static func unavailable() -> some View ``` Rendered by [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) instead of its slots when no [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) is in the environment. That is the case when the view is not inside `.primerCheckoutSession(_:)`, or when the session has not reached `.ready` yet. It returns an `EmptyView`, so the list occupies no space. ## Return types Each slot builder returns a concrete public view type so it can serve as a `@ViewBuilder` default argument. These types have no public initializer. To get an instance, call the matching builder. You can still use the type name, for example as a property type or a return type. | Type | Returned by | Description | | - | - | - | | `PaymentMethodsHeaderContent` | `header(_:)` | The default section header view | | `PaymentMethodRowContent` | `method(_:onSelect:)` | A single default payment method row | | `PaymentMethodsEmptyContent` | `emptyState(_:)` | The default empty-state view | ```swift theme={"dark"} @available(iOS 15.0, *) public struct PaymentMethodsHeaderContent: View @available(iOS 15.0, *) public struct PaymentMethodRowContent: View @available(iOS 15.0, *) public struct PaymentMethodsEmptyContent: View ``` ## Using defaults inside custom slots Reuse a default builder for one part of the list while customizing another. Here the default header and empty state are kept, but each row is replaced with a branded row: ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CustomPaymentMethodsView: View { var body: some View { PrimerPaymentMethods( method: { method, onSelect in Button(action: onSelect) { HStack { if let icon = method.icon { Image(uiImage: icon) .resizable() .scaledToFit() .frame(width: 24, height: 24) } Text(method.name) Spacer() if let surcharge = method.formattedSurcharge { Text(surcharge) .foregroundColor(.secondary) } } .padding() } } ) } } ``` Because the `header` and `emptyState` slots are omitted, `PrimerPaymentMethods` falls back to `PaymentMethodsDefaults.header` and `PaymentMethodsDefaults.emptyState`. You can also call a default builder explicitly — for example, to render the default row while wrapping it in your own container: ```swift theme={"dark"} PrimerPaymentMethods( method: { method, onSelect in PaymentMethodsDefaults.method(method, onSelect: onSelect) .padding(.horizontal) .background(Color(.secondarySystemBackground)) .cornerRadius(12) } ) ``` > [!TIP] > > The `header` and `emptyState` slots pass you the [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session), so you can branch on `session.state` to show custom content while still falling back to a default builder when appropriate. ## See also > [card] [PrimerPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) > > The slot-based payment method list these defaults power. > [card] [PrimerSelectionSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) > > Session that exposes the available methods and the select action. > [card] [VaultedPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) > > Saved payment methods and their own default sub-components. > [card] [CardFormDefaults](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-defaults) > > The equivalent default sub-components for the card form. # PrimerSelectionSession Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session Observable payment-method selection session backing the list and vaulted views > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerSelectionSession` is the observable session that drives payment-method selection. It publishes the selection `state` (available methods, current selection and saved-method state) and the customer's saved `vaultedPaymentMethods`, and provides the methods that act on them. The SDK raises the CVV recapture screen when a saved card needs one. A single `PrimerSelectionSession` backs **both** [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) (the list of available methods) and [`PrimerVaultedPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) (saved methods). Both views resolve the same session from the environment supplied by the `.primerCheckoutSession(_:)` modifier, so you rarely construct or hold it yourself — you read it from the `header` and `emptyState` slots those views hand you. > [!NOTE] > > `PrimerSelectionSession` is a `@MainActor`, `ObservableObject` final class available on iOS 15.0 and later (`@available(iOS 15.0, *)`). Observe it with `@ObservedObject` and call its methods from the main actor. ## Declaration ```swift theme={"dark"} @available(iOS 15.0, *) @MainActor public final class PrimerSelectionSession: ObservableObject { @Published public private(set) var state: PrimerPaymentMethodSelectionState @Published public private(set) var vaultedPaymentMethods: [PrimerHeadlessUniversalCheckout.VaultedPaymentMethod] } ``` The session is created and injected by the SDK, so you do not initialize it yourself. The `header` slot of `PrimerPaymentMethods` and of `PrimerVaultedPaymentMethods`, and the `emptyState` slot of `PrimerPaymentMethods`, receive it directly. The row and submit slots do not receive it. To use the session in those slots, read it with `@Environment(\.primerSelectionSession)`. ## Properties | Property | Type | Description | | - | - | - | | `state` | `PrimerPaymentMethodSelectionState` | The latest selection state, bridged from the underlying selection scope. Read-only (`@Published public private(set)`) — drive UI from it and call the session's methods to change it. | | `vaultedPaymentMethods` | `[PrimerHeadlessUniversalCheckout.VaultedPaymentMethod]` | Read-only (`@Published public private(set)`). The customer's saved (vaulted) payment methods. Published, so a list you build yourself re-renders when the set changes, after `delete(_:)` or when the SDK's own saved-methods screen deletes one. Empty when none are available. | > [!NOTE] > > `state` is the snapshot you render from; `vaultedPaymentMethods` is the list of saved cards. Which card the SDK's own screens act on is reflected back through `state.selectedVaultedPaymentMethod`. Keep the highlight in your own view state. ## Methods | Method | Description | | - | - | | `select(_ method: CheckoutPaymentMethod)` | Selects a payment method, starting its flow (card form, redirect, native wallet, etc.). | | `cancel()` | Ends the checkout. `onCompletion` receives `.dismissed`. | | `selectVaulted(_ method: PrimerHeadlessUniversalCheckout.VaultedPaymentMethod)` | Pays with a saved payment method. Call it from your pay button, not from a row tap. | | `delete(_ method:) async throws` | Deletes a saved payment method, then refreshes `vaultedPaymentMethods`. | | `showAll()` | Presents the SDK's saved-payment-methods screen, where the customer can pick a different method or delete one. | ### select(\_:) ```swift theme={"dark"} public func select(_ method: CheckoutPaymentMethod) ``` Selects a payment method to begin its payment flow. Call this from a method row's tap handler. The selected method is reflected in `state.selectedPaymentMethod`. | Parameter | Type | Description | | - | - | - | | `method` | `CheckoutPaymentMethod` | The payment method the user chose. Typically the value passed into the `method` slot of `PrimerPaymentMethods`. | ### cancel() ```swift theme={"dark"} public func cancel() ``` Ends the checkout, as if the customer dismissed it. The checkout state moves to `.dismissed`. The `onCompletion` of `.primerCheckoutSession(_:theme:onCompletion:)` or `PrimerCheckout` receives `.dismissed` once, and nothing is delivered after that. Do not use it as a back or deselect action. ### selectVaulted(\_:) ```swift theme={"dark"} public func selectVaulted(_ method: PrimerHeadlessUniversalCheckout.VaultedPaymentMethod) ``` Pays with a saved payment method. This is the pay verb, so call it from your pay button rather than from a row tap. A card that needs CVV recapture raises the CVV recapture screen first, and that screen finishes the payment. The outcome arrives through `.primerCheckoutSession(_:theme:onCompletion:)`. Keep which row looks selected in your own view state. Returns immediately; the payment runs on. A call made while `state.isVaultPaymentLoading` is `true` does not start another payment. When the payment starts, it first passes through your [`onBeforePaymentCreate`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) handler, as for every other payment method. If the handler aborts, the session reports a failure through `onCompletion`. > [!WARNING] > > This method starts a payment. A row tap wired to it will charge the customer. | Parameter | Type | Description | | - | - | - | | `method` | `PrimerHeadlessUniversalCheckout.VaultedPaymentMethod` | The saved method to pay with. | ### delete(\_:) ```swift theme={"dark"} public func delete(_ method: PrimerHeadlessUniversalCheckout.VaultedPaymentMethod) async throws ``` Deletes a saved payment method. Once the deletion succeeds, the method leaves `vaultedPaymentMethods` at once. If it was the selected one, `state.selectedVaultedPaymentMethod` moves to the first remaining method. The SDK then re-fetches the saved methods. If that re-fetch fails, the deleted method still stays out of the list. Throws if the deletion itself fails, leaving the list unchanged. | Parameter | Type | Description | | - | - | - | | `method` | `PrimerHeadlessUniversalCheckout.VaultedPaymentMethod` | The saved method to remove. | > [!WARNING] > > Deletion is immediate — there is no confirmation step. Add your own if you want one. (The SDK's own saved-methods screen, reached via `showAll()`, does confirm before it deletes.) ```swift theme={"dark"} Button("Delete", role: .destructive) { Task { do { try await session.delete(method) } catch { showError(error) } } } ``` ### showAll() ```swift theme={"dark"} public func showAll() ``` Presents the SDK's saved-payment-methods screen: the full list, where the customer can select a different method for payment or delete one. Works in both the managed `PrimerCheckout` modal and the inline integration. > [!TIP] > > `PrimerVaultedPaymentMethods` already wires this into its default header, so you only need to call it directly if you have replaced the header slot or built your own saved-methods UI. ## PrimerPaymentMethodSelectionState `PrimerPaymentMethodSelectionState` is the immutable snapshot published by `state`. It conforms to `Equatable`. Every stored property is `public internal(set)` — readable from your code but mutated only by the SDK, so treat it as read-only and call the session's methods to change selection. The public initializer exists for previews and tests. ```swift theme={"dark"} @available(iOS 15.0, *) public struct PrimerPaymentMethodSelectionState: Equatable { public internal(set) var paymentMethods: [CheckoutPaymentMethod] = [] public internal(set) var isLoading: Bool = false public internal(set) var selectedPaymentMethod: CheckoutPaymentMethod? public internal(set) var searchQuery: String = "" public internal(set) var filteredPaymentMethods: [CheckoutPaymentMethod] = [] public internal(set) var error: String? public internal(set) var selectedVaultedPaymentMethod: PrimerHeadlessUniversalCheckout.VaultedPaymentMethod? public internal(set) var isVaultPaymentLoading: Bool = false public internal(set) var isPaymentMethodsExpanded: Bool = true public init( paymentMethods: [CheckoutPaymentMethod] = [], isLoading: Bool = false, selectedPaymentMethod: CheckoutPaymentMethod? = nil, searchQuery: String = "", filteredPaymentMethods: [CheckoutPaymentMethod] = [], error: String? = nil, selectedVaultedPaymentMethod: PrimerHeadlessUniversalCheckout.VaultedPaymentMethod? = nil, isVaultPaymentLoading: Bool = false, isPaymentMethodsExpanded: Bool = true ) } ``` ### Properties | Property | Type | Description | | - | - | - | | `paymentMethods` | `[CheckoutPaymentMethod]` | All available payment methods for the current session. | | `isLoading` | `Bool` | Reserved. The SDK never sets it, so the state the session publishes keeps it `false`. Do not drive a loading indicator from it. For a loading placeholder, use the checkout session's `phase` (`.initializing`). The selection session exists only once `phase` is `.ready`, and `paymentMethods` fills right after. | | `selectedPaymentMethod` | `CheckoutPaymentMethod?` | The currently selected available method, or `nil`. | | `searchQuery` | `String` | Reserved. No public API sets a search query, so it is always empty. | | `filteredPaymentMethods` | `[CheckoutPaymentMethod]` | The same list as `paymentMethods`, because no search can be applied. To filter, filter `paymentMethods` in your own view. | | `error` | `String?` | An error message for the selection flow, or `nil`. | | `selectedVaultedPaymentMethod` | `PrimerHeadlessUniversalCheckout.VaultedPaymentMethod?` | The saved method the SDK's own screens act on. Once saved methods load, the SDK selects the first one. It changes when the customer picks another on the saved-methods screen or you call `selectVaulted(_:)`. If the selected method is deleted, it moves to the first remaining method. `nil` only while saved methods are loading or when there are none. | | `isVaultPaymentLoading` | `Bool` | Whether a payment with the selected vaulted method is in progress. | | `isPaymentMethodsExpanded` | `Bool` | Whether the payment methods section is expanded (showing all methods). Defaults to `true`. Becomes `false` when the customer picks a saved method on the SDK's saved-methods screen (`showAll()`). Becomes `true` again when they tap the SDK's "Show other ways to pay" button. `selectVaulted(_:)` does not change it. | > [!TIP] > > Drive your custom rows and empty states directly from these properties rather than caching copies. ## CheckoutPaymentMethod `paymentMethods` and `filteredPaymentMethods` are arrays of `CheckoutPaymentMethod`, the model describing a single selectable method. It is documented in full on the [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) page; the key fields are `id`, `type`, `name`, `icon`, and the surcharge and styling properties. ## Usage ### Reading state and selecting a method `PrimerPaymentMethods` hands each `method` slot a `CheckoutPaymentMethod` and an `onSelect` closure that calls `select(_:)` for you. To select outside a slot — for example from a custom header — call `select(_:)` on the session directly. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutScreen: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } var body: some View { ScrollView { PrimerPaymentMethods( method: { paymentMethod, onSelect in Button(action: onSelect) { HStack { if let icon = paymentMethod.icon { Image(uiImage: icon) .resizable() .scaledToFit() .frame(width: 28, height: 28) } Text(paymentMethod.buttonText ?? paymentMethod.name) Spacer() if let surcharge = paymentMethod.formattedSurcharge { Text(surcharge).foregroundColor(.secondary) } } .padding() } .buttonStyle(.plain) } ) } .primerCheckoutSession(session) { state in handle(state) } } } ``` ### Working with vaulted methods and CVV recapture When rendering saved methods, iterate `vaultedPaymentMethods`, keep the highlight in your own view state, and call `selectVaulted(_:)` from your pay button. A card that needs CVV recapture raises the CVV recapture screen on submit, and that screen finishes the payment. ```swift theme={"dark"} struct SavedMethods: View { @ObservedObject var session: PrimerSelectionSession @State private var highlighted: String? var body: some View { VStack(alignment: .leading, spacing: 8) { ForEach(session.vaultedPaymentMethods, id: \.id) { method in HStack { Text(method.paymentMethodType) Spacer() Button("Select") { highlighted = method.id } Button("Delete", role: .destructive) { Task { try? await session.delete(method) } } } } Button("Pay") { guard let method = session.vaultedPaymentMethods .first(where: { $0.id == highlighted }) else { return } session.selectVaulted(method) } .disabled(session.state.isVaultPaymentLoading) } } } ``` > [!WARNING] > > Never mutate `state` directly — every property is `internal(set)`. Change selection only through `select(_:)`, `selectVaulted(_:)`, `delete(_:)`, and `showAll()`. ## See also > [card] [PrimerPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) > > The slot-based view that renders the available payment methods. > [card] [PrimerVaultedPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) > > Render and select saved (vaulted) payment methods. > [card] [PaymentMethodsDefaults](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-defaults) > > Default slot bodies used by the payment-method views. > [card] [PrimerCheckoutSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) > > The top-level session injected via .primerCheckoutSession(\_:). # PrimerPaymentMethods Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods Payment method list composable with slot-based rows > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerPaymentMethods` is the SwiftUI view that renders the list of available payment methods. It is composed from three `@ViewBuilder` slots — a `header`, a per-method `method` row, and an `emptyState` — and resolves its [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) from the environment supplied by the `.primerCheckoutSession(_:)` modifier. Each slot defaults to the matching helper on [`PaymentMethodsDefaults`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-defaults), so calling `PrimerPaymentMethods()` with no arguments renders the SDK's built-in UI. Override any one slot to customize that part of the list while keeping the defaults for the rest. > [!NOTE] > > `PrimerPaymentMethods` is available on iOS 15.0 and later (`@available(iOS 15.0, *)`). ## Signature ```swift theme={"dark"} @available(iOS 15.0, *) public struct PrimerPaymentMethods: View { public init( @ViewBuilder header: @escaping (PrimerSelectionSession) -> Header = { PaymentMethodsDefaults.header($0) }, @ViewBuilder method: @escaping (CheckoutPaymentMethod, @escaping () -> Void) -> Method = { PaymentMethodsDefaults.method($0, onSelect: $1) }, @ViewBuilder emptyState: @escaping (PrimerSelectionSession) -> Empty = { PaymentMethodsDefaults.emptyState($0) } ) } ``` ## Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `header` | `(PrimerSelectionSession) -> Header` | `PaymentMethodsDefaults.header($0)` | Slot for the section header rendered above the list. Receives the [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session). | | `method` | `(CheckoutPaymentMethod, @escaping () -> Void) -> Method` | `PaymentMethodsDefaults.method($0, onSelect: $1)` | Slot rendered once per available method. Receives the `CheckoutPaymentMethod` and an `onSelect` closure to invoke when the row is tapped. | | `emptyState` | `(PrimerSelectionSession) -> Empty` | `PaymentMethodsDefaults.emptyState($0)` | Slot shown when no payment methods are available. Receives the [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session). | ## Default behavior By default `PrimerPaymentMethods` arranges its slots in a vertical stack: * Renders the default header. * When `session.state.paymentMethods` is non-empty, renders one default row per method. Each row's tap triggers `session.select(paymentMethod)`, starting that method's flow. * When `session.state.paymentMethods` is empty, renders the default empty state. `PrimerPaymentMethods` applies the spacing between its slots itself, so the spacing stays the same when you override a slot. `primerSpaceMedium` (12pt by default) separates the header from the list of methods, or from the empty state when there are no methods. `primerSpaceSmall` (8pt by default) separates the method rows. You can change both through [`SpacingOverrides`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens) in `PrimerCheckoutTheme`. `PrimerPaymentMethods` renders nothing while no `PrimerSelectionSession` is in the environment. This happens while the checkout session is still initializing, and when the view is used outside `.primerCheckoutSession(_:)`. The list appears once `session.phase` reaches `.ready`. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutScreen: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } var body: some View { ScrollView { PrimerPaymentMethods() } .primerCheckoutSession(session) { state in handle(state) } } } ``` > [!NOTE] > > Wire the view hierarchy with `.primerCheckoutSession(_:)`. `PrimerPaymentMethods` reads its session from the environment — you do not pass the session into the view directly. ## CheckoutPaymentMethod `CheckoutPaymentMethod` describes a single payment method available for selection. It contains the method's display information and optional custom styling. The `method` slot receives one instance per available method, and selecting a method is also surfaced through `session.state.selectedPaymentMethod`. ```swift theme={"dark"} @available(iOS 15.0, *) public struct CheckoutPaymentMethod: Equatable, Identifiable { public let id: String public let type: String public let name: String public let icon: UIImage? public let surcharge: Int? public let hasUnknownSurcharge: Bool public let formattedSurcharge: String? public let backgroundColor: UIColor? public let buttonText: String? public let textColor: UIColor? public let borderColor: UIColor? public let borderWidth: CGFloat? public let cornerRadius: CGFloat? public init( id: String, type: String, name: String, icon: UIImage? = nil, surcharge: Int? = nil, hasUnknownSurcharge: Bool = false, formattedSurcharge: String? = nil, backgroundColor: UIColor? = nil, buttonText: String? = nil, textColor: UIColor? = nil, borderColor: UIColor? = nil, borderWidth: CGFloat? = nil, cornerRadius: CGFloat? = nil ) } ``` ### Properties | Property | Type | Description | | - | - | - | | `id` | `String` | Unique identifier for this payment method instance. | | `type` | `String` | The payment method type identifier (e.g., `"PAYMENT_CARD"`, `"PAYPAL"`, `"APPLE_PAY"`). | | `name` | `String` | Human-readable display name for the payment method. | | `icon` | `UIImage?` | Icon image to display for this payment method. | | `surcharge` | `Int?` | Surcharge amount in minor currency units (e.g., cents), if applicable. | | `hasUnknownSurcharge` | `Bool` | Indicates whether the surcharge amount is unknown (e.g., varies by card network). | | `formattedSurcharge` | `String?` | Pre-formatted surcharge string for display (e.g., `"+ $0.50"`). | | `backgroundColor` | `UIColor?` | Custom background color for the payment method button. | | `buttonText` | `String?` | Custom button text from display metadata (e.g., `"Pay with Klarna"`). | | `textColor` | `UIColor?` | Custom text color for the payment method button. | | `borderColor` | `UIColor?` | Custom border color for the payment method button. The SDK's default row ignores it; only a custom `method` slot can use it. | | `borderWidth` | `CGFloat?` | Custom border width for the payment method button. The SDK's default row ignores it; only a custom `method` slot can use it. | | `cornerRadius` | `CGFloat?` | Custom corner radius for the payment method button. The SDK's default row ignores it; only a custom `method` slot can use it. | > [!TIP] > > `CheckoutPaymentMethod` conforms to `Identifiable` via `id`, so you can iterate methods directly with `ForEach` when building a custom list. > [!NOTE] > > `CheckoutPaymentMethod` equality compares only `id`, `type`, `name`, `surcharge`, `hasUnknownSurcharge`, `formattedSurcharge` and `backgroundColor`. Background colors are compared in both light and dark mode. The display-only properties `icon`, `buttonText`, `textColor`, `borderColor`, `borderWidth` and `cornerRadius` are ignored, so a change to them alone does not make two methods unequal. ## Customization ### Custom method row Override the `method` slot to render your own row. The slot receives the `CheckoutPaymentMethod` and an `onSelect` closure — call `onSelect` when the user taps your row to start that method's flow. ```swift theme={"dark"} PrimerPaymentMethods( method: { paymentMethod, onSelect in Button(action: onSelect) { HStack { if let icon = paymentMethod.icon { Image(uiImage: icon) .resizable() .scaledToFit() .frame(width: 28, height: 28) } Text(paymentMethod.buttonText ?? paymentMethod.name) Spacer() if let surcharge = paymentMethod.formattedSurcharge { Text(surcharge) .foregroundColor(.secondary) } } .padding() } .buttonStyle(.plain) } ) ``` ### Custom empty state Override the `emptyState` slot to control what appears when no methods are available. The slot receives the [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) so you can read selection state if needed. ```swift theme={"dark"} PrimerPaymentMethods( emptyState: { _ in VStack(spacing: 12) { Image(systemName: "creditcard.and.123") .font(.largeTitle) Text("No payment methods are available right now.") .multilineTextAlignment(.center) .foregroundColor(.secondary) } .frame(maxWidth: .infinity) .padding() } ) ``` ### Custom header Override the `header` slot to replace the default section title. ```swift theme={"dark"} PrimerPaymentMethods( header: { _ in Text("Choose how to pay") .font(.title2.weight(.semibold)) .frame(maxWidth: .infinity, alignment: .leading) } ) ``` > [!WARNING] > > The generic parameters `Header`, `Method`, and `Empty` are inferred from the slots you provide. When overriding only some slots, the remaining slots keep their `PaymentMethodsDefaults` bodies — you do not need to re-specify them. ## See also > [card] [PrimerSelectionSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) > > The observable session that drives the method list and selection. > [card] [PaymentMethodsDefaults](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-defaults) > > Default slot bodies used by PrimerPaymentMethods. > [card] [PrimerVaultedPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods) > > Render and select saved (vaulted) payment methods. > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > The slot-based card entry composable. # PrimerVaultedPaymentMethods Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/vaulted-payment-methods Saved (vaulted) payment method shortcut composable with header, row and submit slots > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerVaultedPaymentMethods` is the returning-customer shortcut: it renders the **selected** saved payment method — the first saved one until the customer picks another — with a header and a submit button that pays with it. It is composed from three slots: header, item row, and submit button. The header's "Show all" action opens the SDK's saved-payment-methods screen, which lists every saved method and is the only place a customer can delete one. > [!NOTE] > > This is a one-row shortcut, not a full list. If you want every saved method visible inline, build that yourself — iterate [`PrimerSelectionSession.vaultedPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session), keep the highlight in your own view state, and call `selectVaulted(_:)` from your pay button and `delete(_:)` to remove one. The view resolves its [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) from the environment. Paying and deletion are driven through that session — `PrimerVaultedPaymentMethods` only composes the UI. CVV recapture is a screen the SDK raises for itself. > [!NOTE] > > This view reads its session from the environment injected by the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. Place it inside a view hierarchy that applies that modifier. When no session is present it renders an empty placeholder, and when the customer has **no** saved methods it renders nothing at all — so you do not need to hide it yourself. ## PrimerVaultedPaymentMethods ```swift theme={"dark"} @available(iOS 15.0, *) public struct PrimerVaultedPaymentMethods: View { public typealias VaultedMethod = PrimerHeadlessUniversalCheckout.VaultedPaymentMethod public init( header: @escaping (PrimerSelectionSession) -> AnyView = { AnyView(VaultedPaymentMethodsDefaults.header($0)) }, item: @escaping (VaultedMethod, _ isSelected: Bool, _ onSelect: @escaping () -> Void) -> AnyView = { AnyView(VaultedPaymentMethodsDefaults.item($0, isSelected: $1, onSelect: $2)) }, submitButton: @escaping (_ isLoading: Bool, _ isEnabled: Bool, _ onSubmit: @escaping () -> Void) -> AnyView = { AnyView(VaultedPaymentMethodsDefaults.submitButton(isLoading: $0, isEnabled: $1, onSubmit: $2)) } ) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `header` | `(PrimerSelectionSession) -> AnyView` | `VaultedPaymentMethodsDefaults.header($0)` | Header shown above the row. The default renders the section title plus a "Show all" button wired to `session.showAll()`. Receives the session so custom headers can read state or trigger session actions — **if you replace this slot, call `showAll()` yourself or the customer loses the route to deleting a saved method.** | | `item` | `(VaultedMethod, _ isSelected: Bool, _ onSelect: @escaping () -> Void) -> AnyView` | `VaultedPaymentMethodsDefaults.item(...)` | The row for the selected method. Called once, with `isSelected: true`. | | `submitButton` | `(_ isLoading: Bool, _ isEnabled: Bool, _ onSubmit: @escaping () -> Void) -> AnyView` | `VaultedPaymentMethodsDefaults.submitButton(...)` | Submit button below the row. Receives loading state, enabled state (`false` while a saved-method payment is in flight), and a callback that pays with the selected method. | > [!NOTE] > > Slots are type-erased to `AnyView` rather than using opaque return types. The three-argument `item` and `submitButton` builders hit Swift's generic-default inference limits, so this view trades the opaque-return ergonomics of [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) for guaranteed composition. Wrap any custom slot content in `AnyView`. ### VaultedMethod typealias ```swift theme={"dark"} public typealias VaultedMethod = PrimerHeadlessUniversalCheckout.VaultedPaymentMethod ``` `VaultedMethod` is a convenience alias for `PrimerHeadlessUniversalCheckout.VaultedPaymentMethod`, the model passed to the `item` slot. ```swift theme={"dark"} public final class VaultedPaymentMethod: Codable { public let id: String public let paymentMethodType: String public let paymentInstrumentType: PaymentInstrumentType public let paymentInstrumentData: Response.Body.Tokenization.PaymentInstrumentData public let analyticsId: String } ``` | Property | Type | Description | | - | - | - | | `id` | `String` | Unique identifier for this vaulted method. Use it to drive selection and deletion. | | `paymentMethodType` | `String` | Payment method type (e.g. `"PAYMENT_CARD"`, `"PAYPAL"`). | | `paymentInstrumentType` | `PaymentInstrumentType` | Type of payment instrument (e.g. card, bank account). | | `paymentInstrumentData` | `Response.Body.Tokenization.PaymentInstrumentData` | Detailed instrument data: card network, masked digits, expiry, external payer info, BIN data. | | `analyticsId` | `String` | Identifier used for analytics tracking. | ## Usage The default slots produce a complete, themed saved-method shortcut — no slot arguments are required: ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 15.0, *) struct SavedMethodsView: View { var body: some View { PrimerVaultedPaymentMethods() } } ``` Wrap the view in a hierarchy that injects a checkout session: ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 15.0, *) struct CheckoutScreen: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } var body: some View { ScrollView { PrimerVaultedPaymentMethods() .padding() } .primerCheckoutSession(session) { state in // Handle the checkout state (.success, .failure, .dismissed) } } } ``` ## Customizing slots Provide any combination of slots; omitted slots fall back to their defaults. Custom content must be wrapped in `AnyView`. ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 15.0, *) struct CustomVaultedMethods: View { var body: some View { PrimerVaultedPaymentMethods( header: { session in AnyView( HStack { Text("Pay faster with a saved card") .font(.headline) Spacer() // Keep a route to the SDK's saved-methods screen — it is where // the customer switches methods or deletes one. Button("Manage") { session.showAll() } } ) }, item: { method, isSelected, onSelect in AnyView( Button(action: onSelect) { HStack { Text(method.paymentMethodType) Spacer() if isSelected { Image(systemName: "checkmark.circle.fill") } } .padding() } .buttonStyle(.plain) ) } ) } } ``` > [!TIP] > > The `item` slot renders the currently selected method, so it always receives `isSelected: true`. Use it to keep the same selection affordances (checkmarks, borders, highlights) as your other rows. Calling `onSelect` keeps this same method as the selected one. It does not switch to another method and does not pay. To let the customer change which saved method is used, keep a route to `session.showAll()`, which opens the SDK's saved-methods screen. Or build your own list from `session.vaultedPaymentMethods` and keep the highlighted method in your own view state. Then call `session.selectVaulted(_:)` with that method from your pay button. `selectVaulted(_:)` pays immediately, so don't call it from a row tap. ## Driving payment and deletion `PrimerVaultedPaymentMethods` delegates all behavior to [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session). Read `vaultedPaymentMethods` and call the session methods directly from custom slots. | Member | Signature | Description | | - | - | - | | `vaultedPaymentMethods` | `@Published public private(set) var vaultedPaymentMethods: [PrimerHeadlessUniversalCheckout.VaultedPaymentMethod]` | Saved methods for the current customer. Published, so a list you build yourself re-renders when the set changes. Empty while loading or when none exist. | | `selectVaulted(_:)` | `func selectVaulted(_ method: PrimerHeadlessUniversalCheckout.VaultedPaymentMethod)` | Pays with a saved method. It returns at once and the payment keeps running. As with every other payment method, your [`onBeforePaymentCreate`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) handler runs before the payment is created and can abort it. For a card that needs CVV recapture, that happens once the customer submits the CVV screen. The outcome arrives through the `onCompletion` of `.primerCheckoutSession(_:theme:onCompletion:)`. A repeat call while a payment is in flight is ignored. Backs the `submitButton` slot's `onSubmit`, not the `item` slot's `onSelect`. | | `delete(_:)` | `func delete(_ method: PrimerHeadlessUniversalCheckout.VaultedPaymentMethod) async throws` | Deletes a saved method immediately, with no confirmation (add your own if you want one). Once the delete succeeds, the method is removed from `vaultedPaymentMethods` and from the selection right away, even if the follow-up refresh of saved methods fails. | | `showAll()` | `func showAll()` | Presents the SDK's saved-payment-methods screen, where the customer can pick a different method or delete one. Backs the default header's "Show all". | The selection state read by the slots lives on `session.state` (`PrimerPaymentMethodSelectionState`): | Property | Type | Description | | - | - | - | | `selectedVaultedPaymentMethod` | `PrimerHeadlessUniversalCheckout.VaultedPaymentMethod?` | The currently selected vaulted method, or `nil`. Compare its `id` to highlight the selected row. | | `isVaultPaymentLoading` | `Bool` | `true` while a vaulted payment is in flight. Backs the submit slot's `isLoading`. | > [!NOTE] > > CVV recapture is handled entirely by the SDK. When the saved card requires a CVV, `selectVaulted(_:)` raises the CVV recapture screen, and that screen finishes the payment. Nothing is inserted into your layout, so a merchant-owned pay button needs no field and no disabled state for it. ## VaultedPaymentMethodsDefaults The default slot content. Because `PrimerVaultedPaymentMethods` erases its slots to `AnyView`, these helpers return `some View`. Compose them inside custom slots to keep the default look while overriding only part of the layout. ```swift theme={"dark"} @available(iOS 15.0, *) public enum VaultedPaymentMethodsDefaults { public static func header(_ session: PrimerSelectionSession) -> some View public static func item( _ method: PrimerHeadlessUniversalCheckout.VaultedPaymentMethod, isSelected: Bool, onSelect: @escaping () -> Void ) -> some View public static func submitButton( isLoading: Bool, isEnabled: Bool, onSubmit: @escaping () -> Void ) -> some View public static func unavailable() -> some View } ``` | Method | Description | | - | - | | `header(_:)` | Default section header: the title "Saved payment methods" plus a "Show all" button that calls `session.showAll()`. | | `item(_:isSelected:onSelect:)` | Default saved-method row: brand icon and the masked value (or the brand name when none is available), inside a rounded border. When selected, the row shows a checkmark and a thicker border, both in `primerColorBorderOutlinedSelected`. Otherwise the border uses `primerColorBorderOutlinedDefault` at the default width. VoiceOver announces the selected row as selected. | | `submitButton(isLoading:isEnabled:onSubmit:)` | Default "Pay" button, styled like the card form's pay button (brand fill, medium radius, 44pt minimum height). While `isLoading` it keeps its colors, shows a spinner and ignores taps. When disabled it uses the theme's disabled colors. | | `unavailable()` | Empty placeholder rendered when no [`PrimerSelectionSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) is available in the environment. | Reuse a default while customizing a sibling slot: ```swift theme={"dark"} PrimerVaultedPaymentMethods( submitButton: { isLoading, isEnabled, onSubmit in AnyView(VaultedPaymentMethodsDefaults.submitButton( isLoading: isLoading, isEnabled: isEnabled, onSubmit: onSubmit )) } ) ``` ## See also > [card] [PrimerSelectionSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-session) > > Paying and deletion actions for payment methods and vaulted methods. > [card] [PrimerPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) > > Slot-based list of available (non-vaulted) payment methods. > [card] [PaymentMethodsDefaults](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/payment-methods-defaults) > > Default slot content for the payment methods list. > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > Slot-based card entry form for new cards. # PrimerCheckout Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout SwiftUI managed-modal checkout view that renders Primer’s default screens > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerCheckout` is the prebuilt, fully managed SwiftUI flow. Drop it into your view hierarchy with a client token and it renders Primer's default screens end to end — splash, payment method selection, card form, processing, and the success and error results — including 3DS and redirect handling. This is the fastest way to integrate. You do not compose any screens or wire up sessions yourself; the view manages its own lifecycle and reports the outcome through `onCompletion`. When the client session offers only one payment method and the shopper has no saved payment methods, `PrimerCheckout` skips the selection screen and starts that method directly. A card opens the card form, and PayPal launches at once. If the shopper has saved payment methods, the selection screen opens so they can pay with one. > [!NOTE] > > `PrimerCheckout` renders the SDK's default screens and does not expose the composable views or their `@ViewBuilder` slots. For full UI customization, embed views such as [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) and [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) in your own layout and wire them up with [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). ## Declaration ```swift theme={"dark"} @available(iOS 15.0, *) @MainActor public struct PrimerCheckout: View ``` ## Initializer ```swift theme={"dark"} public init( clientToken: String, primerSettings: PrimerSettings = PrimerSettings(), primerTheme: PrimerCheckoutTheme = PrimerCheckoutTheme(), onCompletion: ((PrimerCheckoutState) -> Void)? = nil, onShippingAddressChange: ShippingAddressChangeHandler? = nil, onShippingOptionChange: ShippingOptionChangeHandler? = nil ) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `clientToken` | `String` | Required | The client token obtained from your backend. See [Client session](/docs/checkout/client-session). | | `primerSettings` | [`PrimerSettings`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings) | `PrimerSettings()` | Configuration settings including payment options and UI preferences. | | `primerTheme` | [`PrimerCheckoutTheme`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) | `PrimerCheckoutTheme()` | Theme configuration for design tokens applied across all default screens. | | `onCompletion` | `((PrimerCheckoutState) -> Void)?` | `nil` | Optional callback for the checkout outcome. It receives `.failure` once for each failed attempt, including a failed initialization. `.success` or `.dismissed` arrives exactly once and ends the flow. The lifecycle states (`.initializing`, `.ready`) are not delivered here. See [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state). | | `onShippingAddressChange` | `ShippingAddressChangeHandler?` | `nil` | Express Checkout: supplies the shipping options for the address the shopper entered in the wallet sheet. See [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping). | | `onShippingOptionChange` | `ShippingOptionChangeHandler?` | `nil` | Express Checkout: commits the option the shopper selected, through your backend. | > [!NOTE] > > `PrimerCheckout` requires iOS 15.0 or later and must be used on the main actor, like any SwiftUI `View`. ## Usage ### Minimal Present the managed flow with just a client token. All other parameters use their defaults. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutView: View { let clientToken: String var body: some View { PrimerCheckout(clientToken: clientToken) } } ``` ### With settings and theme Customize payment options and design tokens by passing `primerSettings` and `primerTheme`. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutView: View { let clientToken: String var body: some View { PrimerCheckout( clientToken: clientToken, primerSettings: PrimerSettings(), primerTheme: PrimerCheckoutTheme() ) } } ``` ### Handling the result Pass an `onCompletion` closure and switch over the [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) it delivers. `.failure` arrives once for each failed attempt. With the default error screen, the shopper can retry, so do not close the checkout on it. `.success` or `.dismissed` ends the flow and arrives exactly once. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutView: View { let clientToken: String @Environment(\.dismiss) private var dismiss var body: some View { PrimerCheckout(clientToken: clientToken) { state in switch state { case let .success(result): print("Payment succeeded: \(result.paymentId)") dismiss() case let .failure(error, _): print("Payment failed: \(error.localizedDescription)") case .dismissed: dismiss() default: break } } } } ``` > [!NOTE] > > By default, a failure shows the SDK error screen, and the shopper can retry from there. If you turn it off with `primerSettings: PrimerSettings(uiOptions: PrimerUIOptions(isErrorScreenEnabled: false))`, `PrimerCheckout` shows nothing after a failed initialization or a failed payment. Your app only receives `.failure` and must close the checkout or show its own UI. > [!TIP] > > See [Handle the payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) for a full walkthrough of consuming each `PrimerCheckoutState` case. ## Presenting modally `PrimerCheckout` is an ordinary SwiftUI `View`, so present it however your navigation pattern prefers — for example, in a `.sheet`. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct StorefrontView: View { @State private var isCheckoutPresented = false let clientToken: String var body: some View { Button("Pay") { isCheckoutPresented = true } .sheet(isPresented: $isCheckoutPresented) { PrimerCheckout(clientToken: clientToken) { state in if case .dismissed = state { isCheckoutPresented = false } if case .success = state { isCheckoutPresented = false } } } } } ``` While a payment is processing, the shopper cannot swipe the sheet away. At other times the shopper can swipe it away, and SwiftUI resets `isCheckoutPresented`. A swipe does not report `.dismissed`. `.dismissed` is delivered when the shopper closes the checkout from the SDK's own screens, such as the close button. To show the close button, pass `primerSettings: PrimerSettings(uiOptions: PrimerUIOptions(dismissalMechanism: [.closeButton]))`. The default is `[.gestures]`, which shows no close button. Apple Pay, Stripe ACH and QR code methods such as PromptPay do not show the processing screen, so the sheet can still be swiped away during those payments. ## Customizing the UI `PrimerCheckout` does not accept screen slots. When you need to control layout, styling, or which fields appear, build your own UI from the composable views and drive them with a session instead. | Goal | Use | | - | - | | Fastest integration, default screens | `PrimerCheckout` (this page) | | Custom SwiftUI layout and slots | [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) + [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) / [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) | | UIKit apps | [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) | For the composable approach, create a `PrimerCheckoutSession` as a `@StateObject`, place the composable views in your layout, and attach the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. The modifier injects the session that those views resolve from the environment. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CustomCheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } var body: some View { ScrollView { PrimerPaymentMethods() PrimerCardForm() } .primerCheckoutSession(session) { state in handle(state) } } private func handle(_ state: PrimerCheckoutState) { // .failure after .ready arrives once per failed payment attempt, then .success or .dismissed arrives once. // A failed initialization is final: .failure arrives and nothing follows. } } ``` ## See also > [card] [PrimerCheckoutSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) > > Compose custom UI from the SwiftUI views. > [card] [PrimerCheckoutPresenter](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) > > Present the managed flow from UIKit. > [card] [PrimerCheckoutState](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) > > The states delivered to onCompletion. > [card] [PrimerCheckoutTheme](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) > > Style the default screens with design tokens. # PrimerCheckoutPresenter Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter UIKit entry point for presenting the managed checkout and receiving delegate callbacks > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerCheckoutPresenter` is the UIKit entry point for the managed checkout. It presents the CheckoutComponents UI from a `UIViewController` and delivers results through a delegate, acting as a bridge between UIKit apps and the underlying SwiftUI implementation. > [!NOTE] > > For pure SwiftUI apps, use [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > directly instead of this class. `PrimerCheckoutPresenter` exists for view-controller based > navigation. Objective-C code can call `dismiss` and the two `presentCheckout` overloads that take > no settings. `PrimerCheckoutPresenterDelegate` is a Swift protocol, so a Swift object must receive > the results. ## Declaration ```swift theme={"dark"} @available(iOS 15.0, *) @MainActor @objc public final class PrimerCheckoutPresenter: NSObject ``` The presenter is a `@MainActor` singleton: call its static methods from the main thread (the default for UIKit lifecycle callbacks). It is also exposed to Objective-C via `@objc`. ## Properties | Property | Type | Description | | - | - | - | | `shared` | `PrimerCheckoutPresenter` | The shared singleton instance. Use it to assign the `delegate`. Exposed to Objective-C. | | `delegate` | `PrimerCheckoutPresenterDelegate?` | The object that receives checkout result and lifecycle callbacks. Held weakly. | | `isAvailable` | `Bool` | `static`. `true` when CheckoutComponents can be presented on the current OS version. | | `isPresenting` | `Bool` | `static`. `true` while a checkout is being presented or is currently on screen. Check it before calling `presentCheckout`. | ```swift theme={"dark"} @objc public static let shared = PrimerCheckoutPresenter() public weak var delegate: PrimerCheckoutPresenterDelegate? @objc public static var isAvailable: Bool @objc public static var isPresenting: Bool ``` > [!NOTE] > > `delegate` is a `weak` reference. Retain the object you assign (for example the presenting view > controller) for as long as checkout is on screen, otherwise callbacks will not fire. ## Presenting checkout `presentCheckout` has five overloads. They differ only in how much you configure and whether you supply the presenting view controller yourself. All overloads accept an optional trailing `completion` closure that runs once the checkout UI has finished presenting. If the automatic overloads cannot find a presenting view controller, `completion` does not run. While a previous checkout is still animating in, the call presents nothing and `completion` runs immediately. A checkout that is already on screen does not stop a new call. Check `isPresenting`, and do not call `presentCheckout` while it is `true`. `primerSettings` and `primerTheme` have no Swift defaults; `completion` and the two Express Checkout shipping handlers default to `nil`. The overloads that omit settings or theme apply the SDK's current global `PrimerSettings` and a default `PrimerCheckoutTheme()` internally. For the shipping handlers, see [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping). ### From an explicit view controller ```swift theme={"dark"} @objc public static func presentCheckout( clientToken: String, from viewController: UIViewController, completion: (() -> Void)? = nil ) public static func presentCheckout( clientToken: String, from viewController: UIViewController, primerSettings: PrimerSettings, completion: (() -> Void)? = nil, onShippingAddressChange: ShippingAddressChangeHandler? = nil, onShippingOptionChange: ShippingOptionChangeHandler? = nil ) public static func presentCheckout( clientToken: String, from viewController: UIViewController, primerSettings: PrimerSettings, primerTheme: PrimerCheckoutTheme, completion: (() -> Void)? = nil, onShippingAddressChange: ShippingAddressChangeHandler? = nil, onShippingOptionChange: ShippingOptionChangeHandler? = nil ) ``` ### With automatic view controller detection These overloads locate the top-most presenting view controller for you, which is convenient when you do not have a view controller reference at hand. ```swift theme={"dark"} @objc public static func presentCheckout( clientToken: String, completion: (() -> Void)? = nil ) public static func presentCheckout( clientToken: String, primerSettings: PrimerSettings, completion: (() -> Void)? = nil, onShippingAddressChange: ShippingAddressChangeHandler? = nil, onShippingOptionChange: ShippingOptionChangeHandler? = nil ) ``` > [!WARNING] > > If no presenting view controller can be found, the automatic overloads report a > [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) through > `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` and do not call `completion`. Assign the > `delegate` before calling these methods. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `clientToken` | `String` | — | The client token for the session. Generate it from your backend with the [client session](/docs/checkout/client-session) API. | | `viewController` | `UIViewController` | — | The view controller to present from. Omitted in the automatic-detection overloads. | | `primerSettings` | `PrimerSettings` | — | Configuration applied to this checkout session. Overloads that omit it use the SDK's current global `PrimerSettings`. See [`PrimerSettings`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings). | | `primerTheme` | `PrimerCheckoutTheme` | — | Theme configuration for the [design tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme). Overloads that omit it use a default `PrimerCheckoutTheme()`. | | `completion` | `(() -> Void)?` | `nil` | Optional closure invoked once the checkout UI has finished presenting. If the automatic overloads find no presenting view controller, it is not called. While a previous checkout is still animating in, the call presents nothing and `completion` is invoked immediately. | | `onShippingAddressChange` | `ShippingAddressChangeHandler?` | `nil` | Express Checkout: supplies the shipping options for the address the shopper entered in the wallet sheet. Available on the overloads that take `primerSettings`. See [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping). | | `onShippingOptionChange` | `ShippingOptionChangeHandler?` | `nil` | Express Checkout: commits the option the shopper selected, through your backend. Runs only when `onShippingAddressChange` is also set. Available on the overloads that take `primerSettings`. | > [!NOTE] > > The overloads that take `primerSettings` or `primerTheme` are **not** `@objc` compatible because of > those Swift-only parameter types. From Objective-C, you can call only > `presentCheckout(clientToken:completion:)`, `presentCheckout(clientToken:from:completion:)` and > `dismiss(animated:completion:)`. These two `presentCheckout` overloads use the SDK's global > `PrimerSettings`. `PrimerCheckoutPresenterDelegate` is not exposed to Objective-C, so implement the > delegate in Swift. ## Dismissing checkout ```swift theme={"dark"} @objc public static func dismiss( animated: Bool = true, completion: (() -> Void)? = nil ) ``` | Parameter | Type | Default | Description | | - | - | - | - | | `animated` | `Bool` | `true` | Has no effect. The checkout always dismisses with animation. | | `completion` | `(() -> Void)?` | `nil` | Optional closure invoked after dismissal completes. With no checkout on screen, it is invoked immediately. | When a checkout is on screen, `dismiss` closes it. It then calls `primerCheckoutPresenterDidDismiss()` on the delegate, unless that checkout already delivered its final result. With no checkout on screen, `dismiss` does nothing and `completion` runs immediately. The checkout also closes itself when a payment succeeds. It closes after the success screen finishes, or right away when `uiOptions.isSuccessScreenEnabled` is `false`. Then it calls `primerCheckoutPresenterDidCompleteWithSuccess(_:)`. When a payment fails and `uiOptions.isErrorScreenEnabled` is `true` (the default), the delegate gets `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` right away. The sheet stays open on the SDK error screen, so the shopper can retry or choose another payment method where available. When `uiOptions.isErrorScreenEnabled` is `false`, the sheet closes on failure. The delegate then gets the failure after the sheet has closed. See [`PrimerSettings`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings). ### Swipe to dismiss The checkout is shown as a sheet. When `uiOptions.dismissalMechanism` contains `.gestures` (the default), the shopper can swipe it away. Without `.gestures`, the sheet is modal and shows no grabber. The swipe is blocked while a payment is processing, so the sheet stays until the result is known. What the delegate receives for a swipe depends on the screen: | Screen when the shopper swipes | Delegate callback | | - | - | | Success screen | `primerCheckoutPresenterDidCompleteWithSuccess(_:)` | | Error screen | `primerCheckoutPresenterDidDismiss()`. The failure was already reported when it happened. | | Any other screen | `primerCheckoutPresenterDidDismiss()` | ## PrimerCheckoutPresenterDelegate ```swift theme={"dark"} @available(iOS 15.0, *) public protocol PrimerCheckoutPresenterDelegate: AnyObject ``` Conform to this protocol to receive checkout results. All three methods are required. A failed 3-D Secure challenge is reported through `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` like any other failure. ### Methods | Method | Description | | - | - | | `primerCheckoutPresenterDidCompleteWithSuccess(_:)` | Called when payment is successful, with the [`PaymentResult`](#paymentresult). | | `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` | Called once for each failed attempt, including a failed initialization, with a [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error). While the SDK error screen is enabled, the sheet stays open for a retry. This callback can then fire more than once, and a success or a dismissal can follow. `checkoutData` carries the payment id and order id when the payment was created before the failure, and is `nil` otherwise. See [`PrimerCheckoutState.failure`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state#failure-associated-values). | | `primerCheckoutPresenterDidDismiss()` | Called when checkout is dismissed without completion. | ```swift theme={"dark"} func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) func primerCheckoutPresenterDidDismiss() ``` ## PaymentResult The success callback delivers a `PaymentResult` value. ```swift theme={"dark"} public struct PaymentResult: Sendable, Equatable { public let paymentId: String public let status: PaymentStatus public let token: String? public let redirectUrl: String? public let errorMessage: String? public let amount: Int? public let currencyCode: String? public let paymentMethodType: String? } ``` | Property | Type | Description | | - | - | - | | `paymentId` | `String` | The unique identifier of the payment. | | `status` | `PaymentStatus` | The final status of the payment. | | `token` | `String?` | The payment token, when available. | | `redirectUrl` | `String?` | A redirect URL, when the flow involved one. | | `errorMessage` | `String?` | A human-readable error message, when available. | | `amount` | `Int?` | The payment amount in minor units. | | `currencyCode` | `String?` | The ISO 4217 currency code. | | `paymentMethodType` | `String?` | The payment method type used for the payment. | ### PaymentStatus ```swift theme={"dark"} public enum PaymentStatus: Sendable { case pending case success case failed } ``` | Case | Description | | - | - | | `pending` | The payment is still being processed. | | `success` | The payment completed successfully. | | `failed` | The payment failed. | > [!TIP] > > When switching on `PaymentStatus`, always include a `default` case so your code stays > forward-compatible with future status values. ## UIKit usage example ```swift theme={"dark"} import PrimerSDK import UIKit final class CheckoutViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() PrimerCheckoutPresenter.shared.delegate = self } @IBAction func payButtonTapped(_ sender: UIButton) { PrimerCheckoutPresenter.presentCheckout( clientToken: clientToken, from: self ) } } extension CheckoutViewController: PrimerCheckoutPresenterDelegate { func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) { switch result.status { case .success: showReceipt(paymentId: result.paymentId) case .pending: showPendingState(paymentId: result.paymentId) case .failed: showError(message: result.errorMessage) default: break } } func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) { showError(message: error.errorDescription, paymentReference: checkoutData?.payment?.id) } func primerCheckoutPresenterDidDismiss() { // The shopper closed checkout without completing a payment. } } ``` To apply custom settings or theming, use the richer overload: ```swift theme={"dark"} PrimerCheckoutPresenter.presentCheckout( clientToken: clientToken, from: self, primerSettings: settings, primerTheme: theme ) ``` > [!NOTE] > > `PrimerCheckoutPresenter.shared.delegate` is `weak`. Keep the conforming object (here, the view > controller) alive for the duration of checkout so the callbacks are delivered. ## See also > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > The SwiftUI view for embedding checkout directly in a SwiftUI hierarchy. > [card] [PrimerCheckoutState](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) > > The state model that drives the managed checkout flow. > [card] [PrimerError](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) > > The error type delivered to the failure callback. > [card] [UIKit integration](/docs/sdk/ios-checkout/v3.0.0-beta/guides/uikit-integration) > > A guide to integrating the managed checkout in UIKit apps. # PrimerCheckoutSession Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session Session owner for composable, inline checkout with the .primerCheckoutSession modifier > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerCheckoutSession` is the owner of a CheckoutComponents session. You hold it (typically as a `@StateObject`) and wire it into your SwiftUI view hierarchy with the [`.primerCheckoutSession(_:theme:onCompletion:)`](#view-modifier) modifier. The session builds the SDK, runs client-token initialization, creates the checkout scope, and bridges per-method scopes into observable session objects that the composable views (such as [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) and [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods)) consume from the environment. Any Primer composable view placed under the modifier resolves its session from the environment. The managed modal [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) does not use a session: it builds its own checkout and needs neither `PrimerCheckoutSession` nor the modifier. While the session is `.ready`, the SDK presents its own follow-up screens (processing, success and failure, plus saved-method management and CVV recapture) in a sheet over your layout. See [What the modifier provides](#what-the-modifier-provides). > [!NOTE] > > This is the iOS analog of the Android `PrimerCheckoutHost`. Where Android wraps your layout in a composable host, iOS wires the session into the environment with a view modifier — child composable views read their per-feature session from `EnvironmentValues`. ## Declaration ```swift theme={"dark"} @available(iOS 15.0, *) @MainActor public final class PrimerCheckoutSession: ObservableObject ``` ## Initializer ```swift theme={"dark"} public init( clientToken: String, settings: PrimerSettings = PrimerSettings(), theme: PrimerCheckoutTheme = PrimerCheckoutTheme(), idempotencyKey: @escaping @Sendable () -> String? = { nil }, onShippingAddressChange: ShippingAddressChangeHandler? = nil, onShippingOptionChange: ShippingOptionChangeHandler? = nil ) ``` | Parameter | Type | Default | Description | | - | - | - | - | | `clientToken` | `String` | Required | The client token from your `POST /client-session` call. See [Client session](/docs/checkout/client-session). | | `settings` | [`PrimerSettings`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings) | `PrimerSettings()` | SDK configuration applied to this session. | | `theme` | [`PrimerCheckoutTheme`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) | `PrimerCheckoutTheme()` | Design tokens applied to all SDK components within the session. | | `idempotencyKey` | `@Sendable () -> String?` | `{ nil }` | Declarative idempotency-key provider, invoked once per payment attempt just before the SDK creates the payment. Return `nil` to opt out. Used when `onBeforePaymentCreate` is not set, or when its decision continues without a key. | | `onShippingAddressChange` | `ShippingAddressChangeHandler?` | `nil` | Express Checkout: supplies the shipping options for the address the shopper entered in the Apple Pay sheet. See [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping). | | `onShippingOptionChange` | `ShippingOptionChangeHandler?` | `nil` | Express Checkout: commits the option the shopper selected, through your backend. Set it together with `onShippingAddressChange`. | ## Phase The lifecycle phase of the session. Terminal outcomes (success, failure, dismissed) are **not** delivered here — they are delivered through the modifier's `onCompletion`. ```swift theme={"dark"} public enum Phase: Equatable { case initializing case ready } ``` | Case | Description | | - | - | | `initializing` | The session is building the SDK and running client-token initialization. Child sessions (`cardForm`, `selection`) are `nil`. | | `ready` | Initialization completed. Child sessions resolve and the composable views render. | ## Published properties | Property | Type | Description | | - | - | - | | `phase` | `Phase` | The current lifecycle phase. Declared `@Published public private(set)` — observe it, but only the session mutates it. | | `clientSession` | [`PrimerClientSession?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state#primerclientsession) | The resolved client session — order total, currency, line items, customer, fees. `nil` until the session reaches `.ready`. It is a snapshot from the last time the session reached `.ready`, and each successful `refresh()` replaces it. A client-session update made mid-checkout, for example a surcharge or a billing address, does not change it. Call `refresh()` to pick up the latest values. `cancel()` sets it to `nil`. The modifier calls `cancel()` when the view disappears, so it is `nil` again until the restarted session reaches `.ready`. Declared `@Published public private(set)`. | This is how you read the order the customer is paying for: ```swift theme={"dark"} struct OrderSummary: View { @ObservedObject var session: PrimerCheckoutSession var body: some View { if let clientSession = session.clientSession { VStack(alignment: .leading) { if let amount = clientSession.totalAmount, let formatted = session.formatAmount(amount) { Text("Total: \(formatted)") } ForEach(clientSession.lineItems ?? [], id: \.itemId) { item in Text(item.itemDescription ?? "") } } } } } ``` ## Properties | Property | Type | Description | | - | - | - | | `onBeforePaymentCreate` | `BeforePaymentCreateHandler?` | Called before a payment is created. Use the decision handler to provide an idempotency key or abort payment creation. Mutations are forwarded to the checkout scope immediately, so assigning after the session reaches `.ready` still takes effect for the next payment attempt. | | `idempotencyKey` | `@Sendable () -> String?` | Declarative idempotency-key provider, invoked once per payment attempt just before the SDK creates the payment. Return `nil` (default) to opt out. Used when `onBeforePaymentCreate` is not set, or when its decision continues without a key. Mutations are forwarded to the checkout scope immediately, so post-`.ready` assignment still applies. | | `onShippingAddressChange` | `ShippingAddressChangeHandler?` | Express Checkout: supplies the shipping options while the Apple Pay sheet is open. Mutations are forwarded to the checkout scope immediately, so post-`.ready` assignment still applies. | | `onShippingOptionChange` | `ShippingOptionChangeHandler?` | Express Checkout: commits the option the shopper selected. Mutations are forwarded to the checkout scope immediately, so post-`.ready` assignment still applies. | | `cardForm` | [`PrimerCardFormSession?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session) | The card-form sub-session, lazily created and cached. Non-`nil` only once `phase == .ready`. | | `selection` | `PrimerSelectionSession?` | The payment-method-selection sub-session, lazily created and cached. Non-`nil` only once `phase == .ready`. | > [!NOTE] > > `onBeforePaymentCreate` uses the `BeforePaymentCreateHandler` type: > > ```swift theme={"dark"} > public typealias BeforePaymentCreateHandler = @Sendable ( > _ data: PrimerCheckoutPaymentMethodData, > _ decisionHandler: @escaping (PrimerPaymentCreationDecision) -> Void > ) -> Void > ``` > > If you set `onBeforePaymentCreate`, the key you pass to `.continuePaymentCreation(withIdempotencyKey:)` wins. When your decision continues without a key, the SDK falls back to the `idempotencyKey` provider. The SDK calls `onBeforePaymentCreate` before every payment, including payments with a saved payment method. It waits until you call `decisionHandler`, and there is no timeout. If you have not answered after 5 seconds, the SDK logs a warning. While it waits, the SDK ignores Back, Cancel and "Choose other payment methods" on its own screens. Your own layout stays interactive, so disable your pay button and payment-method list until you call `decisionHandler`. If the checkout is closed before you answer, a later `decisionHandler` call starts no payment. > [!NOTE] > > The two shipping handlers are for Express Checkout. They run while the Apple Pay sheet is open and must return within 20 seconds: > > ```swift theme={"dark"} > public typealias ShippingAddressChangeHandler = @Sendable ( > _ change: PrimerShippingAddressChange > ) async throws -> [PrimerShippingOption] > > public typealias ShippingOptionChangeHandler = @Sendable ( > _ change: PrimerShippingOptionChange > ) async throws -> Void > ``` > > See [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping) for the full flow. ## Methods | Method | Description | | - | - | | `start() async` | Builds the SDK and drives the session to `.ready`. Calls made once the session is `.ready` are ignored. Do not call it again while the session is still initializing. The modifier calls this for you on appear, and again after `cancel()` when the view reappears. | | `refresh() async` | Re-fetches configuration and payment methods from the backend and returns the session to `.ready`. No-op unless the session has finished initializing; concurrent calls are ignored. A failure arrives in `onCompletion` as `.failure` but does not end the session. `phase` returns to `.ready`, you can call `refresh()` again, and a later `.success` or `.dismissed` still arrives. | | `cancel()` | Tears the session down: dismisses the checkout scope, clears resources, drops cached sub-sessions, sets `clientSession` to `nil` and resets `phase` to `.initializing`. The next `start()` rebuilds the session. Idempotent. The modifier wires this to `onDisappear`, which also fires on a transient disappearance, such as a tab switch or a navigation push. The session is then rebuilt when the view reappears. | | `formatAmount(_ amountInMinorUnits: Int) -> String?` | Formats an amount in minor units the way the SDK's own screens do. `nil` before the session reaches `.ready`, when no currency is known yet. | ### formatAmount(\_:) ```swift theme={"dark"} public func formatAmount(_ amountInMinorUnits: Int) -> String? ``` Formats an amount in minor units for display, so a total you print yourself matches what the SDK prints on its own screens. The currency comes from the client session. Its decimal digits come from the backend and cannot be worked out from [`PrimerClientSession.currencyCode`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state#primerclientsession) alone, because some currencies have none and some have three. The locale is the one in [`PrimerSettings.localeData`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings), which defaults to the device. ```swift theme={"dark"} if let total = session.clientSession?.totalAmount, let formatted = session.formatAmount(total) { Text("Pay \(formatted)") } ``` | Parameter | Type | Description | | - | - | - | | `amountInMinorUnits` | `Int` | The amount in the currency's minor units, for example cents. | Returns `nil` before the session reaches `.ready`. > [!TIP] > > You normally never call `start()` or `cancel()` yourself — the `.primerCheckoutSession` modifier handles the lifecycle. Call `refresh()` when you need to reload after a client-session update (for example, an amount or currency change). ## View modifier The `View.primerCheckoutSession(_:theme:onCompletion:)` modifier wires a `PrimerCheckoutSession` into the SwiftUI environment, bootstraps it on appear, and tears it down on disappear. Apply it once around the Primer composable views you embed inline in your own layout. The managed modal [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) does not use it. ```swift theme={"dark"} @available(iOS 15.0, *) public extension View { func primerCheckoutSession( _ session: PrimerCheckoutSession, theme: PrimerCheckoutTheme? = nil, onCompletion: ((PrimerCheckoutState) -> Void)? = nil ) -> some View } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `session` | `PrimerCheckoutSession` | Required | The session injected into the environment for child composable views to resolve. | | `theme` | [`PrimerCheckoutTheme?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) | `nil` | Overrides the theme the session was created with, re-applied whenever the value changes. Use it to follow a theme your own view state owns, for example a brand or colour-scheme switch. | | `onCompletion` | `((PrimerCheckoutState) -> Void)?` | `nil` | Receives the outcome states. `.success` and `.dismissed` arrive at most once and end the session. A `.failure` while `start()` is initializing the session also ends it. Any other `.failure`, such as a failed payment attempt or a failed `refresh()`, does not end the session, so `onCompletion` can be called again. A session that restarts after `cancel()`, for example when the view reappears, delivers its own outcome. See [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state). | ### What the modifier provides 1. **Environment injection** — exposes the `PrimerCheckoutSession`, the derived `PrimerCardFormSession`, and the `PrimerSelectionSession` through `EnvironmentValues`, so child views like `PrimerCardForm` and `PrimerPaymentMethods` resolve their per-feature session automatically. 2. **Lifecycle bootstrapping** — calls `start()` on appear and `cancel()` on disappear. 3. **Overlay management** — once the session is `.ready`, the modifier presents the SDK's own follow-up screens in a sheet over your layout: processing, success and failure after any payment you start, the screens of payment methods that need one, the saved-methods list opened by `showAll()` with its delete confirmation, and the CVV recapture screen that `selectVaulted(_:)` raises when a saved card needs it. 3DS challenges and web redirects open their own system UI. Do not present a sheet of your own while one of these is up. The customer cannot swipe the SDK's sheet away while the processing screen is showing or while your `onBeforePaymentCreate` handler has not yet called `decisionHandler`. At any other time, swiping the sheet away closes it and returns to your layout without ending the session. > [!WARNING] > > Without the `.primerCheckoutSession` modifier above them in the hierarchy, composable views such as `PrimerCardForm` and `PrimerPaymentMethods` cannot resolve a session and will not function. ## Usage Hold the session as a `@StateObject`, place the composable views in a `ScrollView`, and attach the modifier with your completion handler. ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 15.0, *) struct CheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject( wrappedValue: PrimerCheckoutSession(clientToken: clientToken) ) } var body: some View { ScrollView { VStack(spacing: 24) { PrimerCardForm() PrimerPaymentMethods() } .padding() } .primerCheckoutSession(session) { state in switch state { case .success(let data): print("Payment complete: \(data)") case let .failure(error, _): print("Payment failed: \(error)") case .dismissed: print("Checkout dismissed") default: break } } } } ``` The child composable views resolve their per-feature session from the environment — you do not pass a session into them. Behind the scenes the modifier injects `PrimerCardFormSession` and `PrimerSelectionSession`, which `PrimerCardForm` and `PrimerPaymentMethods` bind to once the session reaches `.ready`. ### Supplying an idempotency key Provide the declarative `idempotencyKey` provider at construction, or assign `onBeforePaymentCreate` for full control over the payment-creation decision. Either may be assigned after `.ready` — the change applies to the next payment attempt. ```swift theme={"dark"} let session = PrimerCheckoutSession( clientToken: token, idempotencyKey: { UUID().uuidString } ) ``` ## See also > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > The managed modal entry point. It builds its own checkout and does not use a session. > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > Composable card form that resolves its session from the environment. > [card] [PrimerPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) > > Composable payment-method selection list for inline layouts. > [card] [PrimerCheckoutState](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) > > The terminal outcome delivered to onCompletion. # PrimerCheckoutState Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state Checkout lifecycle and outcome states, with the payment result model > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerCheckoutState` is a public, `Equatable` enum that represents the current state of the checkout flow. It captures both the **lifecycle** of the session (initializing, ready) and its **outcome** (success, failure, dismissed). Your `onCompletion` closure on [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) or on the `.primerCheckoutSession(_:theme:onCompletion:)` modifier receives the **outcome** states `.success`, `.failure` and `.dismissed`. To follow the **lifecycle** states `.initializing` and `.ready`, read [`PrimerCheckoutSession.phase`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). `.success` and `.dismissed` end the session and are delivered at most once. `.failure` depends on when it happens: **once the checkout is ready, a failed payment attempt does not end the session** — the SDK shows its error screen, offers a retry, and your closure is called again with the outcome of each further attempt. An initialization failure (before the checkout becomes ready) ends an inline `PrimerCheckoutSession`. `PrimerCheckout` keeps its initialization error view open with a Retry button, so a later outcome can still arrive. With `uiOptions.isErrorScreenEnabled` set to `false`, the SDK shows no error view and your app decides what to show. `PrimerCheckoutPresenter` closes its sheet on the failure instead. > [!WARNING] > > Do not treat a `.failure` after the checkout is ready as the end of the session. If you tear down your checkout UI on it, a customer who retries after a decline and then succeeds will never reach your success handling. Tear down on `.success` and `.dismissed`. On an inline `PrimerCheckoutSession`, also tear down on a `.failure` that arrives before the session first becomes ready. > [!NOTE] > > On iOS, a single `PrimerCheckoutState` enum covers what the Android SDK splits across `PrimerCheckoutState` (lifecycle) and `PrimerCheckoutEvent` (outcomes). The `.initializing` and `.ready` cases mirror the lifecycle; `.success`, `.failure`, and `.dismissed` mirror the outcome events delivered to `onCompletion`. ## Definition ```swift theme={"dark"} @available(iOS 15.0, *) public enum PrimerCheckoutState: Equatable { case initializing case ready(clientSession: PrimerClientSession) case success(PaymentResult) case dismissed case failure(PrimerError, checkoutData: PrimerCheckoutData? = nil) } ``` ## States | State | Associated values | Description | | - | - | - | | `.initializing` | — | Initial state while loading configuration and payment methods. The SDK is fetching the client session and preparing available payment methods. | | `.ready` | [`PrimerClientSession`](#primerclientsession) | Checkout is fully initialized and payment methods are loaded. Carries the client session — order total, currency, line items, customer, fees. | | `.success` | [`PaymentResult`](#paymentresult) | Payment completed successfully. Carries the full payment result with payment ID, status, and other details. | | `.dismissed` | — | Terminal state. The shopper closed the checkout without completing a payment. | | `.failure` | [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error), [`checkoutData`](#failure-associated-values) | Payment or checkout failed. Carries the specific error with diagnostics information for debugging, and the payment when one was created before the failure. | ### `.ready` associated values | Parameter | Type | Description | | - | - | - | | `clientSession` | [`PrimerClientSession`](#primerclientsession) | The resolved client session: order total, currency, line items, order and customer details, allowed card networks, and fees. | To read the client session, use [`PrimerCheckoutSession.clientSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). It is `@Published` and becomes non-`nil` as soon as the checkout is ready: ```swift theme={"dark"} @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } ... if let clientSession = session.clientSession { Text(formatted(clientSession.totalAmount, clientSession.currencyCode)) } ``` `refresh()` renews `clientSession`, and `cancel()` sets it back to `nil`. The value is a snapshot. A client-session update during checkout, such as a surcharge or a billing address, does not update it. > [!NOTE] > > This requires the inline integration. `PrimerCheckout` — the managed modal — renders the SDK's own screens and exposes no session object, so the client session is not reachable from it. ### `.failure` associated values | Parameter | Type | Description | | - | - | - | | (first) | [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) | Error details including description, error ID, and diagnostics ID | | `checkoutData` | `PrimerCheckoutData?` | Set when the payment was created before failing, for example on a decline. `checkoutData?.payment` has the payment `id`, `orderId`, and the `status` from the last Payments API response. `nil` when the failure happened before a payment existed (initialization, tokenization, connectivity). | ## Lifecycle A checkout session progresses from the lifecycle states to an outcome. `.success` and `.dismissed` end it. A `.failure` ends it only when initialization fails on an inline `PrimerCheckoutSession`, or when `PrimerCheckoutPresenter` closes its sheet with the error screen off: ``` initializing → ready → success | dismissed (session over) ↑ ↓ failure (retryable — session continues) ``` | Transition | When | Ends the session | | - | - | - | | `.initializing` → `.ready` | Configuration and payment methods have loaded. | — | | `.initializing` → `.failure` | Initialization fails (bad client token, network, configuration). | Inline `PrimerCheckoutSession`: yes. `PrimerCheckout`: no, its error view offers Retry (shown while `uiOptions.isErrorScreenEnabled` is `true`, the default). With the error screen off, `PrimerCheckout` shows nothing and offers no retry, and `PrimerCheckoutPresenter` closes its sheet. | | `.ready` → `.success` | Payment is confirmed by the processor (automatic payment handling). | Yes | | `.ready` → `.failure` | A payment attempt fails. With the SDK error screen on (`uiOptions.isErrorScreenEnabled`, the default), the shopper can retry the failed payment method. When another payment method is available, the shopper can choose it instead. A further attempt delivers another outcome. With the error screen off, the SDK shows no error view and only reports `.failure`, so you decide what to show. `PrimerCheckoutPresenter` also closes its sheet. | No, except `PrimerCheckoutPresenter` with the error screen off, which closes the sheet | | `→ .dismissed` | The shopper closes the checkout without completing a payment, or you call `PrimerSelectionSession.cancel()`. `PrimerCheckoutSession.cancel()` tears the session down without delivering `.dismissed`. | Yes | > [!NOTE] > > `.success` and `.dismissed` are delivered at most once per session. `.failure` is delivered once per failed attempt. A failure before `.ready` ends an inline `PrimerCheckoutSession`. With the error screen off, any failure ends a `PrimerCheckoutPresenter` checkout. The lifecycle states `.initializing` and `.ready` are never passed to `onCompletion`. ## Handling completion Pass an `onCompletion` closure when you present checkout. It receives the outcome states — `.success`, `.failure`, or `.dismissed` — and may be called more than once if a payment attempt fails and the customer retries. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } var body: some View { ScrollView { PrimerCardForm() } .primerCheckoutSession(session) { state in handle(state) } } private func handle(_ state: PrimerCheckoutState) { switch state { case let .success(result): print("Payment \(result.paymentId) succeeded") case let .failure(error, _): print("Checkout failed: \(error.localizedDescription)") case .dismissed: print("Checkout dismissed") default: break } } } ``` > [!TIP] > > `onCompletion` only delivers outcome states, but a `switch` on `PrimerCheckoutState` must still be exhaustive. Cover the lifecycle cases `.initializing` and `.ready` with a `default:` case. `@unknown default:` does not cover them: it matches only cases added in a future version, so the compiler still warns that the switch is not exhaustive. ## PaymentResult `PaymentResult` is the value carried by `.success`. It is a public, `Sendable`, `Equatable` struct describing the completed payment. ```swift theme={"dark"} public struct PaymentResult: Sendable, Equatable { public let paymentId: String public let status: PaymentStatus public let token: String? public let redirectUrl: String? public let errorMessage: String? public let amount: Int? public let currencyCode: String? public let paymentMethodType: String? } ``` | Property | Type | Description | | - | - | - | | `paymentId` | `String` | Unique payment identifier assigned by Primer. | | `status` | [`PaymentStatus`](#paymentstatus) | The final status of the payment. | | `token` | `String?` | A token that depends on the payment method, or `nil`. For card and saved payment methods, it equals `paymentId`. To identify the payment, use `paymentId`. | | `redirectUrl` | `String?` | Always `nil`. The SDK does not set it. | | `errorMessage` | `String?` | Always `nil`. The SDK does not set it. Read failure details from the `PrimerError` in `.failure`. | | `amount` | `Int?` | The payment amount in minor units, when available. | | `currencyCode` | `String?` | The ISO 4217 currency code, when available. | | `paymentMethodType` | `String?` | The payment method type identifier used for the payment (e.g., `"PAYMENT_CARD"`). | ## PaymentStatus `PaymentStatus` is a public, `Sendable` enum describing the final status of a payment. ```swift theme={"dark"} public enum PaymentStatus: Sendable { case pending case success case failed } ``` | Case | Description | | - | - | | `.pending` | The payment is pending and awaiting further processing or confirmation. | | `.success` | The payment completed successfully. | | `.failed` | The payment failed. | > [!NOTE] > > Always include a `default:` (or `@unknown default:`) case when switching on `PaymentStatus` to handle future additions. ## Handling the result Use the `.success` payload to read the payment details and route your UI: ```swift theme={"dark"} private func handleCompletion(_ state: PrimerCheckoutState) { switch state { case let .success(result): switch result.status { case .success: showReceipt(paymentId: result.paymentId) case .pending: showPendingScreen(paymentId: result.paymentId) default: break } case let .failure(error, _): // Not the end of the session: the customer can retry, and this // closure will be called again with the next attempt's outcome. showErrorScreen(message: error.localizedDescription) case .dismissed: dismiss() default: break } } ``` For a full integration walkthrough, see [Handle payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result). ## PrimerClientSession The resolved client session, carried by `.ready` and published on [`PrimerCheckoutSession.clientSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). ```swift theme={"dark"} @objc public final class PrimerClientSession: NSObject, Codable { public let customerId: String? public let orderId: String? public let currencyCode: String? public let totalAmount: Int? public let lineItems: [PrimerLineItem]? public let orderDetails: PrimerOrder? public let customer: PrimerCustomer? public let paymentMethod: PrimerClientSession.PaymentMethod? public let fees: [PrimerFee]? } ``` | Property | Type | Description | | - | - | - | | `customerId` | `String?` | Customer identifier from your system. | | `orderId` | `String?` | Order identifier from your system. | | `currencyCode` | `String?` | ISO 4217 currency code (e.g., `"USD"`, `"EUR"`). | | `totalAmount` | `Int?` | Total amount in minor currency units (e.g., `1000` = \$10.00). | | `lineItems` | `[PrimerLineItem]?` | The order's line items. | | `orderDetails` | `PrimerOrder?` | Country code and shipping details. | | `customer` | `PrimerCustomer?` | Customer contact details, billing and shipping address. | | `paymentMethod` | [`PrimerClientSession.PaymentMethod?`](#primerclientsessionpaymentmethod) | Payment-method options, a nested struct. Currently the allowed card networks. | | `fees` | `[PrimerFee]?` | Fees applied to the order, such as surcharges. | > [!NOTE] > > Every property is optional because the client session itself is merchant-configured — a session created without line items has none. Read them defensively rather than assuming a shape. ### PrimerLineItem | Property | Type | Description | | - | - | - | | `itemId` | `String?` | Your identifier for the item. | | `itemDescription` | `String?` | Human-readable description. | | `amount` | `Int?` | Unit amount in minor units. | | `discountAmount` | `Int?` | Discount applied to this item, in minor units. | | `quantity` | `Int?` | Number of units. | | `taxCode` | `String?` | Tax code for this item. | | `taxAmount` | `Int?` | Tax charged on this item, in minor units. | > [!WARNING] > > `taxCode` and `taxAmount` are per line item. Do not read the order's total tax from them — a three-item order reports each item's own tax, and the values will not sum to a field you can find elsewhere on the session unless your client session was configured that way. ### PrimerOrder | Property | Type | Description | | - | - | - | | `countryCode` | `String?` | The order's ISO 3166-1 alpha-2 country code. | | `shipping` | `PrimerShipping?` | Shipping `amount`, plus the selected method's `methodId`, `methodName`, and `methodDescription`. | ### PrimerCustomer | Property | Type | Description | | - | - | - | | `emailAddress` | `String?` | Customer email. | | `mobileNumber` | `String?` | Customer phone number. | | `firstName` / `lastName` | `String?` | Customer name. | | `billingAddress` | [`PrimerAddress?`](#primeraddress) | Billing address. | | `shippingAddress` | [`PrimerAddress?`](#primeraddress) | Shipping address. | ### PrimerAddress | Property | Type | Description | | - | - | - | | `firstName` / `lastName` | `String?` | Name on the address. | | `addressLine1` / `addressLine2` | `String?` | Street address. | | `city` | `String?` | City. | | `state` | `String?` | State, province, or region. | | `countryCode` | `String?` | ISO 3166-1 alpha-2 country code. | | `postalCode` | `String?` | Postal or ZIP code. | ### PrimerClientSession.PaymentMethod A `Codable`, `Equatable` struct nested in `PrimerClientSession`, so name it as `PrimerClientSession.PaymentMethod`. | Property | Type | Description | | - | - | - | | `orderedAllowedCardNetworks` | [`[CardNetwork]`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-card-network) | Card networks the client session allows, in the configured order. A network the SDK does not recognize becomes `.unknown` rather than being dropped, so the list always matches what the session declared. | ### PrimerFee | Property | Type | Description | | - | - | - | | `type` | `String` | The fee type, currently always `"SURCHARGE"`. If the client session contains a fee of a type the SDK does not recognize, `fees` is `nil`. | | `amount` | `Int` | The fee amount in minor units. | ## See also > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > Present checkout and receive the final state through `onCompletion`. > [card] [PrimerError](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) > > Error details carried by the `.failure` state. > [card] [Handle payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) > > Route your UI based on the checkout outcome. > [card] [PrimerCheckoutSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) > > Drive the inline checkout lifecycle from your own layout. # Color Tokens Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens Color override tokens for the checkout UI > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `ColorOverrides` lets you override individual color tokens used across the checkout UI. You pass one instance to [`PrimerCheckoutTheme`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) as `colors` for light mode and, optionally, another as `darkColors` for dark mode. Every property is an optional `Color?`. Any token you leave `nil` keeps the SDK's default for that appearance. `colors` applies only in light mode and `darkColors` only in dark mode. A token you set in `colors` does not carry over to dark mode: anything you leave `nil` in `darkColors` uses Primer's dark default. The tables list the light and dark defaults as `#RRGGBBAA` hex values. ```swift theme={"dark"} @available(iOS 15.0, *) public struct ColorOverrides: Equatable { public init( primerColorBrand: Color? = nil, // ... all tokens below, each defaulting to nil ) } ``` > [!NOTE] > > Override `primerColorBrand` to recolor buttons, focus borders, loaders and selected states in one change. It applies to light mode through `colors` and to dark mode through `darkColors`. Override a more specific token only when one element must differ from the token it follows. ## Brand and primary | Token | Type | Light default | Dark default | Description | | - | - | - | - | - | | `primerColorBrand` | `Color?` | `#2f98ffff` | `#2f98ffff` | Primary brand color. Fills the pay and primary buttons and tints the keyboard Done button. Focus borders, loaders and selected borders follow it unless you set them. The text cursor follows the focus border. | | `primerColorOnBrand` | `Color?` | None (follows `primerColorBackgroundPrimary`) | None (follows `primerColorBackgroundPrimary`) | Label and spinner on brand-filled buttons. | ## Background and text | Token | Type | Light default | Dark default | Description | | - | - | - | - | - | | `primerColorBackgroundPrimary` | `Color?` | `#ffffffff` | `#171619ff` | Sheet and screen background. | | `primerColorBackgroundSecondary` | `Color?` | `#2121210a` | `#efefef0a` | Subtle panels: ACH mandate box, country picker search bar, surcharge badge on the card number field, card network fallback badge on saved cards, and the vault section. | | `primerColorBackgroundOutlinedDefault` | `Color?` | `#ffffffff` | `#171619ff` | Input field and Pay with card row fill. Follows `primerColorBackgroundPrimary` unless set. | | `primerColorBackgroundOutlinedDisabled` | `Color?` | `#2121210a` | `#efefef0a` | Disabled input fill and disabled button fill. | | `primerColorTextPrimary` | `Color?` | `#212121ff` | `#efefefff` | Main text and outlined button label. | | `primerColorTextSecondary` | `Color?` | `#2121219e` | `#efefef9e` | Labels and descriptions. | | `primerColorTextPlaceholder` | `Color?` | `#21212170` | `#efefef70` | Input placeholders. | | `primerColorTextDisabled` | `Color?` | `#2121214d` | `#efefef4d` | Disabled button label and disabled field text. | | `primerColorTextNegative` | `Color?` | `#b4324bff` | `#f6bfbfff` | Field error messages. | | `primerColorTextLink` | `Color?` | `#2270f4ff` | `#4aaeffff` | Reserved. No component reads this token. | | `primerColorTextOutlinedDefault` | `Color?` | `#212121ff` | `#efefefff` | Text typed into inputs. Follows `primerColorTextPrimary` unless set. | ## Border colors (outlined) Borders of inputs, payment method rows, saved cards and outlined buttons, per state. | Token | Type | Light default | Dark default | Description | | - | - | - | - | - | | `primerColorBorderOutlinedDefault` | `Color?` | `#21212124` | `#efefef24` | Resting border of inputs, the Pay with card row, saved cards, outlined buttons and the card network badge. | | `primerColorBorderOutlinedActive` | `Color?` | `#21212170` | `#efefef70` | Reserved. No component reads this token. | | `primerColorBorderOutlinedFocus` | `Color?` | `#2f98ffff` | `#2f98ffff` | Focused input border. Follows `primerColorFocus` unless set. | | `primerColorBorderOutlinedDisabled` | `Color?` | `#21212112` | `#efefef12` | Disabled input and outlined button border. | | `primerColorBorderOutlinedError` | `Color?` | `#ff7279ff` | `#e46d70ff` | Border of an input in error. Also colors the error message shown under the payment method list. | | `primerColorBorderOutlinedSelected` | `Color?` | `#2f98ffff` | `#2f98ffff` | Selected saved card, payment method row, Klarna category, card network and country check mark. Follows `primerColorBrand` unless set. | | `primerColorBorderOutlinedLoading` | `Color?` | `#21212112` | `#efefef12` | Reserved. No component reads this token. | ## Border colors (transparent) Reserved for elements with a transparent border. No component reads these tokens. | Token | Type | Light default | Dark default | Description | | - | - | - | - | - | | `primerColorBorderTransparentDefault` | `Color?` | `#ffffff00` | `#ffffff00` | Reserved. | | `primerColorBorderTransparentActive` | `Color?` | `#ffffff00` | `#ffffff00` | Reserved. | | `primerColorBorderTransparentFocus` | `Color?` | `#2f98ffff` | `#2f98ffff` | Reserved. Follows `primerColorFocus` unless set. | | `primerColorBorderTransparentDisabled` | `Color?` | `#ffffff00` | `#ffffff00` | Reserved. | | `primerColorBorderTransparentSelected` | `Color?` | `#ffffff00` | `#ffffff00` | Reserved. | ## Icon colors | Token | Type | Light default | Dark default | Description | | - | - | - | - | - | | `primerColorIconPrimary` | `Color?` | `#212121ff` | `#efefefff` | Back and close buttons, the card icon on the card payment method row, chevrons, and the saved card delete mark. | | `primerColorIconDisabled` | `Color?` | `#2121214d` | `#efefef4d` | Reserved. No component reads this token. | | `primerColorIconNegative` | `Color?` | `#ff7279ff` | `#e46d70ff` | Field error icon, error screen icon, and the QR code failure icon. | | `primerColorIconPositive` | `Color?` | `#3eb68fff` | `#27b17dff` | Success screen check mark and the QR code success icon. | ## Utility | Token | Type | Light default | Dark default | Description | | - | - | - | - | - | | `primerColorFocus` | `Color?` | `#2f98ffff` | `#2f98ffff` | Focus color. Not drawn directly: the SDK copies it into `primerColorBorderOutlinedFocus` and `primerColorBorderTransparentFocus` unless you set those. Follows `primerColorBrand` unless set. | | `primerColorLoader` | `Color?` | `#2f98ffff` | `#2f98ffff` | Loading spinners on screens and lists. A loading button shows its spinner in the button label color instead. Follows `primerColorBrand` unless set. | ## Overriding colors Pass a `ColorOverrides` instance as `colors` for light mode and another as `darkColors` for dark mode. Tokens you omit keep the SDK default for that appearance. ```swift theme={"dark"} import SwiftUI import PrimerSDK let brand = Color(red: 0.42, green: 0.36, blue: 0.91) let theme = PrimerCheckoutTheme( colors: ColorOverrides( primerColorBrand: brand, primerColorBackgroundPrimary: .white, primerColorTextPrimary: Color(red: 0.10, green: 0.10, blue: 0.12), primerColorBorderOutlinedError: .red ), darkColors: ColorOverrides( primerColorBrand: brand, primerColorBackgroundPrimary: Color(red: 0.09, green: 0.09, blue: 0.10), primerColorTextPrimary: Color(red: 0.94, green: 0.94, blue: 0.94), primerColorBorderOutlinedError: .red ) ) struct CheckoutScreen: View { let clientToken: String var body: some View { PrimerCheckout( clientToken: clientToken, primerTheme: theme, onCompletion: { state in // handle the final PrimerCheckoutState } ) } } ``` > [!TIP] > > Dark mode reads only `darkColors`. To change a token in both appearances, set it in both `colors` and `darkColors`. A dynamic `Color`, such as an asset catalog color set, shows only its value for the appearance of its group. A dynamic `Color` in `colors` always shows its light value. Some tokens follow another token unless you set them too, so one change can recolor several elements. Within the same group (`colors` or `darkColors`): * `primerColorBrand` also moves `primerColorFocus`, `primerColorLoader`, `primerColorBorderOutlinedSelected`, `primerColorBorderOutlinedFocus` and `primerColorBorderTransparentFocus`. * `primerColorFocus` moves `primerColorBorderOutlinedFocus` and `primerColorBorderTransparentFocus`. * `primerColorBackgroundPrimary` moves `primerColorBackgroundOutlinedDefault`. * `primerColorTextPrimary` moves `primerColorTextOutlinedDefault`. * A `nil` `primerColorOnBrand` uses `primerColorBackgroundPrimary`. A token you set explicitly always wins over the token it follows. ## See also > [card] [PrimerTheme](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) > > The container that bundles color, shape, spacing, and typography overrides. > [card] [Shape Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) > > Override corner radius and border width tokens. > [card] [Typography Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/typography-tokens) > > Override font, size, weight, and line height per text style. > [card] [Spacing Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens) > > Override spacing and size scale tokens. # PrimerCheckoutTheme Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme Root design-token override container for the checkout UI > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `PrimerCheckoutTheme` is the single container for design-token overrides. Pass it to the entry-point APIs to restyle the checkout UI without replacing Primer's internal token system. Internally, the SDK ships auto-generated `DesignTokens` that remain the source of truth, with a light and a dark set of defaults. When you supply a `PrimerCheckoutTheme`, the SDK merges your overrides on top of those defaults, and any `nil` value falls back to the internal default. Colors are the exception: `colors` applies in light mode only, and dark mode reads `darkColors` alone. A color you leave out of `darkColors` uses Primer's dark default, not the matching `colors` value. To change a color in both modes, set it in both groups. `radius`, `spacing`, `sizes`, `typography`, and `width` apply in both modes. You only set the tokens you want to change. > [!NOTE] > > Every override property is optional. A `PrimerCheckoutTheme()` with no arguments applies the SDK's default appearance, so you can start from the defaults and override one group, or one token, at a time. ## Declaration ```swift theme={"dark"} @available(iOS 15.0, *) public struct PrimerCheckoutTheme: Equatable ``` ## Initializer ```swift theme={"dark"} public init( colors: ColorOverrides? = nil, darkColors: ColorOverrides? = nil, radius: RadiusOverrides? = nil, spacing: SpacingOverrides? = nil, sizes: SizeOverrides? = nil, typography: TypographyOverrides? = nil, width: WidthOverrides? = nil ) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `colors` | [`ColorOverrides?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens) | `nil` | Color token overrides applied in light mode. `nil` uses internal defaults. | | `darkColors` | [`ColorOverrides?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens) | `nil` | Color token overrides applied in dark mode only. Any color left `nil` here uses Primer's dark default, not the matching `colors` value. | | `radius` | [`RadiusOverrides?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) | `nil` | Corner radius token overrides. `nil` uses internal defaults. | | `spacing` | [`SpacingOverrides?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens) | `nil` | Spacing (padding and margin) token overrides. `nil` uses internal defaults. | | `sizes` | [`SizeOverrides?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) | `nil` | Size token overrides for icons and touch targets. `nil` uses internal defaults. | | `typography` | [`TypographyOverrides?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/typography-tokens) | `nil` | Typography token overrides (font, weight, size, line height, letter spacing). `nil` uses internal defaults. | | `width` | [`WidthOverrides?`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) | `nil` | Border width token overrides for the default, focus, error, and selected states. `nil` uses internal defaults. | A NaN or infinite radius, spacing, size, width, or typography number is ignored with a warning, and that token keeps its default. ## Properties `PrimerCheckoutTheme` is `Equatable` and exposes one immutable property per initializer parameter. Each is the optional value you passed to the initializer. | Property | Type | Description | | - | - | - | | `colors` | `ColorOverrides?` | The light-mode color token overrides, or `nil` for defaults. | | `darkColors` | `ColorOverrides?` | The dark-mode color token overrides, or `nil` for Primer's dark defaults. | | `radius` | `RadiusOverrides?` | The radius token overrides, or `nil` for defaults. | | `spacing` | `SpacingOverrides?` | The spacing token overrides, or `nil` for defaults. | | `sizes` | `SizeOverrides?` | The size token overrides, or `nil` for defaults. | | `typography` | `TypographyOverrides?` | The typography token overrides, or `nil` for defaults. | | `width` | `WidthOverrides?` | The border width token overrides, or `nil` for defaults. | ## Token groups A theme is made up of six override groups. `ColorOverrides` is used twice, for `colors` (light mode) and `darkColors` (dark mode). Each group is its own optional struct whose properties are all optional, so you only specify the tokens you want to change. The four documentation pages below cover the full property list, types, and defaults for every group. | Group | Override type | Covers | Reference | | - | - | - | - | | Colors | `ColorOverrides` (`colors`, `darkColors`) | Brand, on-brand, background, text, border, icon, focus, and loader colors | [Color tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens) | | Spacing | `SpacingOverrides` | Padding and margin scale | [Spacing tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens) | | Typography | `TypographyOverrides` | Brand font family, title and body text styles, and the field error style | [Typography tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/typography-tokens) | | Radius | `RadiusOverrides` | Corner radius scale | [Shape tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) | | Sizes | `SizeOverrides` | Icon and touch-target sizes | [Shape tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) | | Border width | `WidthOverrides` | Border widths for the default, focus, error, and selected states | [Shape tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) | > [!NOTE] > > The [Shape tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) page documents three groups together: `RadiusOverrides`, `SizeOverrides`, and `WidthOverrides`. ## Applying a theme `PrimerCheckoutTheme` is accepted by all three entry points. The managed view and the UIKit presenter take it as `primerTheme`; the session takes it as `theme`. The `.primerCheckoutSession(_:theme:onCompletion:)` modifier also takes an optional `theme`. When you pass one, it replaces the session's theme and applies again each time the value changes, so you can switch appearance at runtime. | Entry point | Parameter | Reference | | - | - | - | | `PrimerCheckout` (SwiftUI managed view) | `primerTheme` | [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) | | `PrimerCheckoutSession` (custom SwiftUI layout) | `theme` | [PrimerCheckoutSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) | | `PrimerCheckoutPresenter` (UIKit) | `primerTheme` | [PrimerCheckoutPresenter](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) | ### With the managed view ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutView: View { let clientToken: String var body: some View { PrimerCheckout( clientToken: clientToken, primerTheme: brandTheme ) } } ``` ### With a custom layout ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CustomCheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject( wrappedValue: PrimerCheckoutSession( clientToken: clientToken, theme: brandTheme ) ) } var body: some View { ScrollView { PrimerPaymentMethods() PrimerCardForm() } .primerCheckoutSession(session) { state in // React to the terminal state. } } } ``` ## Theme example Build a theme by composing the override groups. Each group only sets the tokens you care about; everything else inherits the SDK defaults. ```swift theme={"dark"} import SwiftUI import PrimerSDK let brandTheme = PrimerCheckoutTheme( colors: ColorOverrides( primerColorBrand: Color(red: 0.91, green: 0.51, blue: 0.47), primerColorBackgroundPrimary: .white, primerColorTextPrimary: Color(white: 0.1) ), darkColors: ColorOverrides( primerColorBrand: Color(red: 0.95, green: 0.62, blue: 0.58) ), radius: RadiusOverrides( primerRadiusMedium: 12, primerRadiusLarge: 16 ), spacing: SpacingOverrides( primerSpaceMedium: 16, primerSpaceLarge: 20 ), typography: TypographyOverrides( titleLarge: TypographyOverrides.TypographyStyle( font: "Inter", weight: .semibold, size: 18, lineHeight: 24 ), bodyMedium: TypographyOverrides.TypographyStyle( font: "Inter", weight: .regular, size: 14, lineHeight: 20 ) ), width: WidthOverrides( primerWidthDefault: 1, primerWidthFocus: 2 ) ) ``` > [!TIP] > > Start small. Override `primerColorBrand` alone and Primer's default tokens fill in the rest of the palette. Focus borders, spinners, and selected borders follow your brand color unless you set them. If your app supports dark mode, set `primerColorBrand` in `darkColors` too. Then add more tokens as your branding requires. ## See also > [card] [Color tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens) > > Override brand, background, text, border, and icon colors for light and dark mode. > [card] [Typography tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/typography-tokens) > > Customize title and body text styles. > [card] [Spacing tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens) > > Tune padding and margin values. > [card] [Shape tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) > > Radius, size, and border-width overrides. # Shape Tokens Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens Corner radius, border width, and component size override tokens > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Shape tokens control the geometry of Primer Checkout components: how rounded their corners are, how thick their borders are, and how large their fixed-dimension elements (icons, touch targets) render. There are three override structs, each passed to the matching parameter of [`PrimerCheckoutTheme`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme): | Struct | `PrimerCheckoutTheme` parameter | Controls | | - | - | - | | `RadiusOverrides` | `radius` | Corner radius scale | | `WidthOverrides` | `width` | Border / stroke thickness | | `SizeOverrides` | `sizes` | Fixed component dimensions | Every property is an optional `CGFloat?`. Values you leave as `nil` fall back to the SDK's internal design tokens, so you only override what you need. > [!NOTE] > > All three structs are `Equatable` and annotated `@available(iOS 15.0, *)`, matching the platform minimum for Primer Checkout. ## RadiusOverrides Corner radius scale, in points. Property names match the SDK's internal `DesignTokens`. ```swift theme={"dark"} @available(iOS 15.0, *) public struct RadiusOverrides: Equatable { public let primerRadiusXsmall: CGFloat? public let primerRadiusSmall: CGFloat? public let primerRadiusMedium: CGFloat? public let primerRadiusLarge: CGFloat? public init( primerRadiusXsmall: CGFloat? = nil, primerRadiusSmall: CGFloat? = nil, primerRadiusMedium: CGFloat? = nil, primerRadiusLarge: CGFloat? = nil ) } ``` | Token | Type | Default | Description | | - | - | - | - | | `primerRadiusXsmall` | `CGFloat?` | 2 | Subtle rounding for the smallest elements | | `primerRadiusSmall` | `CGFloat?` | 4 | Input fields, the saved-card CVV field, the inline card network selector, the country picker's search field, the ACH mandate box and the QR code | | `primerRadiusMedium` | `CGFloat?` | 8 | Buttons, payment method rows, saved-card rows, the error screen button and Klarna options | | `primerRadiusLarge` | `CGFloat?` | 12 | Container of the saved payment methods section | ## WidthOverrides Border and stroke thickness, in points. Each token is named for the field state it styles. ```swift theme={"dark"} @available(iOS 15.0, *) public struct WidthOverrides: Equatable { public let primerWidthDefault: CGFloat? public let primerWidthFocus: CGFloat? public let primerWidthError: CGFloat? public let primerWidthSelected: CGFloat? public init( primerWidthDefault: CGFloat? = nil, primerWidthFocus: CGFloat? = nil, primerWidthError: CGFloat? = nil, primerWidthSelected: CGFloat? = nil ) } ``` | Token | Type | Default | Description | | - | - | - | - | | `primerWidthDefault` | `CGFloat?` | 1 | Resting border of input fields (also when disabled), payment method rows, saved-card rows, outlined buttons, the inline card network selector, the error screen button, the QR code view and Klarna options | | `primerWidthFocus` | `CGFloat?` | 2 | Border of a focused input field, including the saved-card CVV field | | `primerWidthError` | `CGFloat?` | 2 | Border of an input field in error, including the saved-card CVV field | | `primerWidthSelected` | `CGFloat?` | 2 | Border of a selected saved payment method and the selected Klarna category | ## SizeOverrides Fixed component dimensions, in points. Used for icons, touch targets, and other elements with an intrinsic size. ```swift theme={"dark"} @available(iOS 15.0, *) public struct SizeOverrides: Equatable { public let primerSizeSmall: CGFloat? public let primerSizeMedium: CGFloat? public let primerSizeLarge: CGFloat? public let primerSizeXlarge: CGFloat? public let primerSizeXxlarge: CGFloat? public let primerSizeXxxlarge: CGFloat? public init( primerSizeSmall: CGFloat? = nil, primerSizeMedium: CGFloat? = nil, primerSizeLarge: CGFloat? = nil, primerSizeXlarge: CGFloat? = nil, primerSizeXxlarge: CGFloat? = nil, primerSizeXxxlarge: CGFloat? = nil ) } ``` | Token | Type | Default | Description | | - | - | - | - | | `primerSizeSmall` | `CGFloat?` | 16 | Card icon in the card payment method button and the minimum height of the surcharge badge in the card number field | | `primerSizeMedium` | `CGFloat?` | 20 | Field error icon, Klarna option selection indicator and the saved-card delete icon | | `primerSizeLarge` | `CGFloat?` | 24 | Brand icon in a saved payment method row of `PrimerVaultedPaymentMethods` | | `primerSizeXlarge` | `CGFloat?` | 32 | Not used by any component | | `primerSizeXxlarge` | `CGFloat?` | 40 | Tap target of the saved-card delete button (never smaller than 44, so values under 44 have no visible effect) | | `primerSizeXxxlarge` | `CGFloat?` | 56 | Size of the success screen's checkmark icon | ## Overriding shape tokens Pass any combination of the three structs to `PrimerCheckoutTheme`. Unset properties inherit the SDK defaults. ```swift theme={"dark"} import SwiftUI import PrimerSDK let theme = PrimerCheckoutTheme( radius: RadiusOverrides( primerRadiusMedium: 12, primerRadiusLarge: 20 ), sizes: SizeOverrides( primerSizeLarge: 28, primerSizeXxlarge: 48 ), width: WidthOverrides( primerWidthDefault: 1.5, primerWidthFocus: 2.5 ) ) ``` Apply the theme on the prebuilt modal by passing it to `primerTheme`: ```swift theme={"dark"} struct CheckoutView: View { let clientToken: String var body: some View { PrimerCheckout( clientToken: clientToken, primerTheme: theme ) { state in handle(state) } } } ``` When you embed the composable views inline, pass the theme to the [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) instead. The composable views resolve the merged tokens from the session. ```swift theme={"dark"} struct InlineCheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject( wrappedValue: PrimerCheckoutSession(clientToken: clientToken, theme: theme) ) } var body: some View { ScrollView { PrimerCardForm() } .primerCheckoutSession(session) { state in handle(state) } } } ``` > [!TIP] > > Because every token is optional, you can override a single value, for example `RadiusOverrides(primerRadiusMedium: 12)`, and leave the rest of the scale untouched. Combine shape overrides with [color tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens) and the other override structs on `PrimerCheckoutTheme` to build a complete custom appearance. ## See also > [card] [PrimerTheme](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) > > Assemble shape, color, spacing, and typography overrides into a theme. > [card] [Color Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens) > > Override brand, semantic, text, border, and icon colors. > [card] [Spacing Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens) > > Override the spacing scale used for layout and padding. > [card] [Typography Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/typography-tokens) > > Override font family, weight, size, and line height per text style. # Spacing Tokens Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens Spacing override tokens for padding and layout > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `SpacingOverrides` lets you override the spacing scale the Primer iOS SDK uses for padding, gaps, and layout rhythm across the prebuilt screens and the composable views. You pass it through the `spacing` parameter of [`PrimerCheckoutTheme`](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme). Every property is optional. A `nil` value falls back to the internal default token, so you only set the values you want to change. ```swift theme={"dark"} @available(iOS 15.0, *) public struct SpacingOverrides: Equatable ``` > [!NOTE] > > Internal `DesignTokens` (auto-generated from JSON) remain the source of truth for spacing. `SpacingOverrides` merges your values on top of those defaults — any token you leave `nil` keeps its internal default. ## Properties All properties are `CGFloat?` and measured in points. The default column shows the internal token value used when you leave the property `nil`. | Property | Type | Default | Description | | - | - | - | - | | `primerSpaceXxsmall` | `CGFloat?` | 2 | Gap between the country name and its code line in the country picker. | | `primerSpaceXsmall` | `CGFloat?` | 4 | Gap between an input field's label, box and error message, and other small icon-and-text gaps, such as in the header buttons. | | `primerSpaceSmall` | `CGFloat?` | 8 | Gaps between closely related elements, such as payment method rows, saved payment method rows, the billing address title and its fields, and the text and icons inside an input field. | | `primerSpaceMedium` | `CGFloat?` | 12 | Space below each input field and between side-by-side fields, the inner horizontal padding of input fields, the pay button's horizontal padding, the padding inside saved payment method rows, and the gap between the payment method list and its heading. Other screens, such as the error screen, use it for spacing too. It also sets input field height. | | `primerSpaceLarge` | `CGFloat?` | 16 | Container padding, major gaps. | | `primerSpaceXlarge` | `CGFloat?` | 20 | Spacing between major sections. | | `primerSpaceXxlarge` | `CGFloat?` | 24 | Largest section spacing. | > [!NOTE] > > Input field height is `max(44, 2 × primerSpaceMedium + bodyLarge line height)`. With the default 20pt body line height, `primerSpaceMedium: 16` gives 52pt fields. Fields grow with Dynamic Type. ## Initializer Every parameter defaults to `nil`, so you can construct an override that touches only the tokens you care about. ```swift theme={"dark"} public init( primerSpaceXxsmall: CGFloat? = nil, primerSpaceXsmall: CGFloat? = nil, primerSpaceSmall: CGFloat? = nil, primerSpaceMedium: CGFloat? = nil, primerSpaceLarge: CGFloat? = nil, primerSpaceXlarge: CGFloat? = nil, primerSpaceXxlarge: CGFloat? = nil ) ``` ## Overriding spacing Build a `PrimerCheckoutTheme` with a `SpacingOverrides` value and pass it to your checkout. The example below loosens the spacing between fields, payment method rows, and sections. Because `primerSpaceMedium` also sets the field padding, input fields are 52pt tall. ```swift theme={"dark"} import SwiftUI import PrimerSDK let theme = PrimerCheckoutTheme( spacing: SpacingOverrides( primerSpaceSmall: 12, primerSpaceMedium: 16, primerSpaceLarge: 20 ) ) ``` Apply the theme on the prebuilt modal by passing it to `primerTheme`: ```swift theme={"dark"} struct CheckoutView: View { let clientToken: String var body: some View { PrimerCheckout( clientToken: clientToken, primerTheme: theme ) { state in handle(state) } } } ``` When you embed the composable views inline, pass the theme to the [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) instead. The composable views resolve the merged tokens from the session. ```swift theme={"dark"} struct InlineCheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { _session = StateObject( wrappedValue: PrimerCheckoutSession(clientToken: clientToken, theme: theme) ) } var body: some View { ScrollView { PrimerCardForm() } .primerCheckoutSession(session) { state in handle(state) } } } ``` > [!TIP] > > Spacing tokens form a scale. Overriding `primerSpaceSmall`, `primerSpaceMedium`, and `primerSpaceLarge` together keeps the rhythm consistent; changing a single step in isolation can make the layout feel uneven. > [!NOTE] > > These tokens control the spacing used inside Primer's own views. They do not affect the padding you add around the SDK in your own layout — use standard SwiftUI modifiers such as `.padding()` for that. ## See also > [card] [PrimerTheme](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) > > The theme container that carries spacing and the other override groups. > [card] [Shape Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) > > Corner-radius and border-width override tokens. # Typography Tokens Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/typography-tokens Typography override tokens for text styles > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. `TypographyOverrides` lets you override the typography tokens used across Primer Checkout text styles. Pass it to a `PrimerCheckoutTheme` through the `typography` parameter. Every token is optional — any token you leave `nil` falls back to the internal default, and within a token any `nil` property falls back to its default value. > [!NOTE] > > Every style uses the `brand` font family, which defaults to **Inter**. Set `brand` to change the typeface of the whole checkout in one place. Set `font` on a single style to change only that style. A `bodySmall` font also applies to `error` unless you set `error.font`, and to the text in card network badges. You only override the tokens and properties you want to change. ## TypographyOverrides ```swift theme={"dark"} @available(iOS 15.0, *) public struct TypographyOverrides: Equatable { public let brand: String? public let titleXlarge: TypographyStyle? public let titleLarge: TypographyStyle? public let bodyLarge: TypographyStyle? public let bodyMedium: TypographyStyle? public let bodySmall: TypographyStyle? public let error: TypographyStyle? public init( brand: String? = nil, titleXlarge: TypographyStyle? = nil, titleLarge: TypographyStyle? = nil, bodyLarge: TypographyStyle? = nil, bodyMedium: TypographyStyle? = nil, bodySmall: TypographyStyle? = nil, error: TypographyStyle? = nil ) } ``` | Token | Type | Default | Description | | - | - | - | - | | `brand` | `String?` | `nil` | Font family that every style below falls back to (default Inter), so one typeface covers the whole checkout. A style that sets its own `font` wins over it. A value written in token syntax (for example `"{...}"`) is ignored and an error is logged. | | `titleXlarge` | `TypographyStyle?` | `nil` | Title extra large: Inter, -0.6 letter spacing, weight 550, size 24, line height 32. Used for screen titles. | | `titleLarge` | `TypographyStyle?` | `nil` | Title large: Inter, -0.2 letter spacing, weight 550, size 16, line height 20. Used for section headers, header buttons such as Back, button labels and payment method rows. | | `bodyLarge` | `TypographyStyle?` | `nil` | Body large: Inter, -0.2 letter spacing, weight 400, size 16, line height 20. Used for input text and body copy. | | `bodyMedium` | `TypographyStyle?` | `nil` | Body medium: Inter, 0 letter spacing, weight 400, size 14, line height 20. Used for body copy on status, loading and Apple Pay screens. | | `bodySmall` | `TypographyStyle?` | `nil` | Body small: Inter, 0 letter spacing, weight 400, size 12, line height 16. Used for field labels and helper text. | | `error` | `TypographyStyle?` | `nil` | Field error text. Defaults to the body small values (Inter, 0 letter spacing, weight 400, size 12, line height 16). Any property you leave `nil` follows your `bodySmall` override. Set it only to style errors on their own. | ### Preview titleXlarge — The quick brown fox jumps over the lazy dog titleLarge — The quick brown fox jumps over the lazy dog bodyLarge — The quick brown fox jumps over the lazy dog bodyMedium — The quick brown fox jumps over the lazy dog bodySmall — The quick brown fox jumps over the lazy dog error — The quick brown fox jumps over the lazy dog ## TypographyStyle A single typography style. All properties are optional — any `nil` property falls back to the token default. ```swift theme={"dark"} @available(iOS 15.0, *) public struct TypographyStyle: Equatable { public let font: String? public let letterSpacing: CGFloat? public let weight: Font.Weight? public let size: CGFloat? public let lineHeight: CGFloat? public init( font: String? = nil, letterSpacing: CGFloat? = nil, weight: Font.Weight? = nil, size: CGFloat? = nil, lineHeight: CGFloat? = nil ) } ``` > [!NOTE] > > `TypographyStyle` is nested inside `TypographyOverrides`, so refer to it as `TypographyOverrides.TypographyStyle` when you need the fully qualified name. | Property | Type | Default | Description | | - | - | - | - | | `font` | `String?` | `nil` | Custom font family name (e.g., `"Inter"`) | | `letterSpacing` | `CGFloat?` | `nil` | Letter spacing in points, scaled with Dynamic Type. On iOS 16 and later it applies to all text except card network badge text. On iOS 15 only the `bodyLarge` value applies, and only to the card form, billing address and ACH user details fields. | | `weight` | `Font.Weight?` | `nil` | SwiftUI font weight, for example `.regular`, `.semibold` or `.bold`. Weights map to the numeric steps 100 to 900. To override the 550 default of `titleXlarge` or `titleLarge`, use `.medium` (500) or `.semibold` (600). | | `size` | `CGFloat?` | `nil` | Font size in points | | `lineHeight` | `CGFloat?` | `nil` | Line height in points, scaled with Dynamic Type. It adds space around the text, except in card network badges. A value smaller than the font's natural line height has no effect on the text. The `bodyLarge` line height also sets the input field height: `max(44, 2 × primerSpaceMedium + line height)`, which is 44pt at the defaults. | ## Override example Override only the tokens and properties you need. Anything you omit keeps its default. ```swift theme={"dark"} import SwiftUI import PrimerSDK let theme = PrimerCheckoutTheme( typography: TypographyOverrides( brand: "Inter", titleXlarge: .init( font: "Inter", weight: .bold, size: 28, lineHeight: 36 ), bodyLarge: .init( letterSpacing: 0, size: 17 ), bodySmall: .init( weight: .medium, size: 13 ), error: .init(weight: .semibold) ) ) ``` Pass the theme to your checkout the same way you pass any `PrimerCheckoutTheme`. See [PrimerTheme](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) for how to apply it. ## See also > [card] [PrimerTheme](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) > > Assemble and apply a complete theme with all token overrides. > [card] [Color Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/color-tokens) > > Override the color tokens used across the checkout UI. > [card] [Spacing Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/spacing-tokens) > > Adjust spacing tokens for padding and layout. > [card] [Shape Tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/shape-tokens) > > Customize corner radius and border width tokens. # Apple Pay integration Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/guides/apple-pay-integration Configure and accept Apple Pay in the Primer Checkout iOS SDK > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Apple Pay is configured through [`PrimerSettings`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings) — there is no separate Apple Pay view or scope to wire up. When Apple Pay is enabled on your Primer Dashboard, it appears automatically. It surfaces as a `CheckoutPaymentMethod` (with `type == "APPLE_PAY"`) in [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods), or as one of the managed screens in [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout). The merchant identifier you provide in `paymentMethodOptions` is required to pay. Without it, selecting Apple Pay fails with a `PrimerError`. > [!NOTE] > > Apple Pay requires a physical device with a card in the Wallet, the Apple Pay capability enabled in your app, and a configured merchant identifier. The iOS Simulator can list Apple Pay, but you cannot complete a payment there. ## Setup overview There are three steps to accept Apple Pay, in order: > [card] 1. Apple Pay capability > > Add the Apple Pay capability to your app target in Xcode. > [card] 2. Merchant ID > > Create a merchant identifier in the Apple Developer portal. > [card] 3. PrimerSettings > > Pass the merchant identifier to the SDK via PrimerApplePayOptions. ## 1. Enable the Apple Pay capability In Xcode, select your app target, open the **Signing & Capabilities** tab, and add the **Apple Pay** capability. This generates the `com.apple.developer.in-app-payments` entitlement and lets you attach merchant identifiers to the app. ## 2. Create a merchant identifier In the [Apple Developer portal](https://developer.apple.com/account/resources/identifiers/list/merchant), create a merchant identifier (for example `merchant.com.myapp`). Then return to Xcode and select that merchant identifier under the Apple Pay capability you added in step 1. > [!NOTE] > > You also need a payment processing certificate associated with the merchant identifier, and Apple Pay must be configured for the processor on your Primer Dashboard. See the [Apple Pay payment method documentation](https://primer.io/docs) for backend configuration. ## 3. Configure PrimerSettings Provide the merchant identifier through [`PrimerApplePayOptions`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings#primerapplepayoptions), nested inside `paymentMethodOptions` on [`PrimerSettings`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings). The `merchantIdentifier` must exactly match the identifier you created in step 2. ```swift theme={"dark"} import PrimerSDK let settings = PrimerSettings( paymentMethodOptions: PrimerPaymentMethodOptions( applePayOptions: PrimerApplePayOptions( merchantIdentifier: "merchant.com.myapp", merchantName: nil ) ) ) ``` > [!WARNING] > > Set the merchant name through the [client session](/docs/checkout/client-session). The SDK uses `merchantName` only when the client session sets none, so you can pass `nil`. ### PrimerApplePayOptions ```swift theme={"dark"} public final class PrimerApplePayOptions: Codable { public init( merchantIdentifier: String, merchantName: String?, isCaptureBillingAddressEnabled: Bool = false, showApplePayForUnsupportedDevice: Bool = true, checkProvidedNetworks: Bool = true, shippingOptions: ShippingOptions? = nil, billingOptions: BillingOptions? = nil, allowedCardTypes: [CardType]? = nil ) } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `merchantIdentifier` | `String` | — | Your Apple Pay merchant identifier (for example `"merchant.com.myapp"`). Must match the identifier configured in Xcode. | | `merchantName` | `String?` | — | Merchant name shown on the Apple Pay sheet when the client session sets none. Prefer the [client session](/docs/checkout/client-session). | | `isCaptureBillingAddressEnabled` | `Bool` | `false` | Requests the billing postal address when `billingOptions` sets no required billing fields. Prefer `billingOptions` to declare required billing fields. | | `showApplePayForUnsupportedDevice` | `Bool` | `true` | Not used by Primer Checkout: Apple Pay stays in the payment method list on every device. If the device cannot present Apple Pay, selecting it shows an "Apple Pay Unavailable" screen with the reason. The screen has a "Choose Another Payment Method" button that returns to the payment method list. If the shopper has no other payment method and no saved one, the button does nothing. | | `checkProvidedNetworks` | `Bool` | `true` | Whether to verify the device can pay using the provided networks before presenting Apple Pay. | | `shippingOptions` | `ShippingOptions?` | `nil` | Shipping contact requirements collected on the Apple Pay sheet. | | `billingOptions` | `BillingOptions?` | `nil` | Required billing contact fields collected on the Apple Pay sheet. | | `allowedCardTypes` | `[CardType]?` | `nil` | Card types the Apple Pay sheet accepts: `.credit`, `.debit`, or both. `nil` or an empty array accepts all card types. | ### Collecting contact details Use `ShippingOptions` and `BillingOptions` to require contact fields on the Apple Pay sheet. Both accept `RequiredContactField` values. `ShippingOptions` also takes a required `requireShippingMethod` argument. Primer Checkout ignores it, so pass `false` unless you share these settings with Drop-In. > [!NOTE] > > To price shipping from the address the shopper enters, see [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping). When you set the shipping handlers, the SDK turns shipping on and requests the postal address itself. `requireShippingMethod` has no effect. If you set `ShippingOptions` to request other contact fields, pass `requireShippingMethod: false`, because the parameter has no default. ```swift theme={"dark"} let applePayOptions = PrimerApplePayOptions( merchantIdentifier: "merchant.com.myapp", merchantName: nil, shippingOptions: PrimerApplePayOptions.ShippingOptions( shippingContactFields: [.name, .postalAddress], requireShippingMethod: false ), billingOptions: PrimerApplePayOptions.BillingOptions( requiredBillingContactFields: [.name, .postalAddress] ) ) ``` ```swift theme={"dark"} public struct ShippingOptions: Codable { public let shippingContactFields: [RequiredContactField]? public let requireShippingMethod: Bool public init(shippingContactFields: [RequiredContactField]? = nil, requireShippingMethod: Bool) } public struct BillingOptions: Codable { public let requiredBillingContactFields: [RequiredContactField]? public init(requiredBillingContactFields: [RequiredContactField]? = nil) } public enum RequiredContactField: String, Codable { case name, emailAddress, phoneNumber, postalAddress } ``` | Case | Description | | - | - | | `.name` | Collect the contact's name. | | `.emailAddress` | Collect the contact's email address. | | `.phoneNumber` | Collect the contact's phone number. | | `.postalAddress` | Collect the contact's postal address. | ## Showing Apple Pay Once configured, Apple Pay appears wherever payment methods are rendered. You do not present or initiate the Apple Pay sheet yourself — selecting the method starts the SDK-managed flow. ### Managed checkout With [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout), pass the settings and the SDK renders Apple Pay among its default screens. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutView: View { let clientToken: String private let settings = PrimerSettings( paymentMethodOptions: PrimerPaymentMethodOptions( applePayOptions: PrimerApplePayOptions( merchantIdentifier: "merchant.com.myapp", merchantName: nil ) ) ) var body: some View { PrimerCheckout( clientToken: clientToken, primerSettings: settings ) { state in // Handle the checkout result. } } } ``` ### Composable checkout When you build your own UI, pass the same settings into [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). Apple Pay then appears as a `CheckoutPaymentMethod` in [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods), alongside the other available methods. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutScreen: View { @StateObject private var session: PrimerCheckoutSession init(clientToken: String) { let settings = PrimerSettings( paymentMethodOptions: PrimerPaymentMethodOptions( applePayOptions: PrimerApplePayOptions( merchantIdentifier: "merchant.com.myapp", merchantName: nil ) ) ) _session = StateObject( wrappedValue: PrimerCheckoutSession(clientToken: clientToken, settings: settings) ) } var body: some View { ScrollView { PrimerPaymentMethods() } .primerCheckoutSession(session) { state in // Handle the checkout result. } } } ``` > [!TIP] > > The default `method` slot renders Apple Pay as Apple's native Apple Pay button. The button follows light and dark mode and has its own VoiceOver label. To single out Apple Pay in a custom layout, override the `method` slot on `PrimerPaymentMethods` and branch on `paymentMethod.type == "APPLE_PAY"`. In that branch, call `PaymentMethodsDefaults.method` so the shopper still sees the native button. Selecting it starts the Apple Pay flow, and the SDK presents the Apple Pay sheet for you. ```swift theme={"dark"} PrimerPaymentMethods( method: { paymentMethod, onSelect in if paymentMethod.type == "APPLE_PAY" { VStack(spacing: 8) { PaymentMethodsDefaults.method(paymentMethod, onSelect: onSelect) Text("Fastest checkout") .font(.footnote) .foregroundColor(.secondary) } } else { PaymentMethodsDefaults.method(paymentMethod, onSelect: onSelect) } } ) ``` ## Troubleshooting | Symptom | Likely cause | | - | - | | Apple Pay does not appear | Apple Pay is not enabled for your processor on the Primer Dashboard, so the client session does not include it. The SDK lists the methods your client session returns. | | Selecting Apple Pay ends in a failure | `PrimerSettings` has no `PrimerApplePayOptions`, or the client session has no `order.countryCode`. If your app is not entitled to the merchant identifier in Xcode, the SDK cannot present the Apple Pay sheet. | | Selecting Apple Pay shows "Apple Pay Unavailable" | The device does not support Apple Pay, or `checkProvidedNetworks` is `true` and the Wallet has no card on a supported network. To present the sheet whenever the device supports Apple Pay, set `checkProvidedNetworks` to `false`. | | Apple Pay payments cannot be completed in the Simulator | Use a physical device with a card in the Wallet and the Apple Pay capability enabled. | > [!NOTE] > > Apple Pay failures are reported through the standard result handling path. See [Handle the payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) and [PrimerError](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error). ## See also > [card] [PrimerSettings](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings) > > Where Apple Pay options live, alongside the other SDK settings. > [card] [PrimerPaymentMethods](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) > > Render Apple Pay as a method row in a custom layout. > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > The managed flow that shows Apple Pay automatically. > [card] [Express Checkout shipping](/docs/checkout/primer-checkout/guides-and-recipes/express-checkout-shipping) > > Price shipping from the address the shopper enters in the sheet. > [card] [Handle the payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) > > Consume the checkout outcome after an Apple Pay payment. # Handle the payment result Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result Receive and handle checkout outcomes in SwiftUI and UIKit > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Every checkout ends in one of three outcomes: the payment **succeeds**, it **fails**, or the user **dismisses** the flow. This guide shows how to receive and react to that outcome in both SwiftUI and UIKit. The outcome is always delivered as a [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) value: | Case | Associated value | Meaning | | - | - | - | | `.success` | [`PaymentResult`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) | The payment completed. | | `.failure` | [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error), `checkoutData: PrimerCheckoutData?` | The payment or checkout failed. `checkoutData` carries the payment ID and order ID when a payment was created before the failure (for example, a decline). | | `.dismissed` | — | The user closed the checkout without completing a payment. | > [!NOTE] > > The same `PrimerCheckoutState` also has lifecycle cases (`.initializing`, `.ready`). `onCompletion` never receives them. With [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session), observe its `phase` for the lifecycle instead. Always include a `default` case when switching, so future enum additions stay source-compatible. ## SwiftUI ### Using PrimerCheckout The prebuilt [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) view accepts an `onCompletion` closure. It receives `.failure` once per failed attempt, including a failed initialization. While the SDK error screen is enabled (`uiOptions.isErrorScreenEnabled`, the default), the checkout stays open so the customer can retry. It then receives `.success` or `.dismissed` exactly once, and nothing after that. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct CheckoutView: View { let clientToken: String @State private var paymentResult: PaymentResult? var body: some View { if let paymentResult { ConfirmationView(result: paymentResult) } else { PrimerCheckout(clientToken: clientToken) { state in switch state { case let .success(result): paymentResult = result case let .failure(error, _): print("Checkout failed: \(error.errorId) — \(error.diagnosticsId)") case .dismissed: break default: break } } } } } ``` ### Using the .primerCheckoutSession modifier When you embed the composable views (for example [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form)) inline in your own layout, hold a [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) as a `@StateObject` and receive the outcome through the `onCompletion` parameter of the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct InlineCheckoutView: View { @StateObject private var session: PrimerCheckoutSession @State private var paymentResult: PaymentResult? init(clientToken: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) } var body: some View { Group { if let paymentResult { ConfirmationView(result: paymentResult) } else { ScrollView { PrimerCardForm() } } } .primerCheckoutSession(session) { state in switch state { case let .success(result): paymentResult = result case let .failure(error, _): print("Checkout failed: \(error.errorId) — \(error.diagnosticsId)") case .dismissed: break default: break } } } } ``` > [!NOTE] > > `.success` and `.dismissed` are delivered at most once — the session latches the first state that ends it, so a later `.dismissed` produced by a view-lifecycle teardown is ignored. > > `.failure` is different. Once checkout is ready, a failed payment attempt does **not** end the session: the SDK shows its error screen, the customer can retry, and `onCompletion` is called again with the next attempt's outcome. Only a failure *before* the checkout becomes ready is terminal. Keep your checkout UI alive on `.failure` — otherwise a customer who retries after a decline and then succeeds never reaches your success handling. ### Navigating on success Use the `PaymentResult` to drive navigation. `PaymentResult` is `Equatable` but not `Hashable`, so it cannot be appended to a `NavigationPath` or used with `navigationDestination(for:)` directly. Instead, store the result in `@State` and present the confirmation screen with `navigationDestination(isPresented:)`. `NavigationStack` and `navigationDestination(isPresented:)` require iOS 16. On iOS 15, use `NavigationView` with a `NavigationLink(isActive:)` instead. ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 16.0, *) struct CheckoutFlowView: View { let clientToken: String @State private var paymentResult: PaymentResult? private var showsConfirmation: Binding { Binding( get: { paymentResult != nil }, set: { if !$0 { paymentResult = nil } } ) } var body: some View { NavigationStack { PrimerCheckout(clientToken: clientToken) { state in if case let .success(result) = state { paymentResult = result } } .navigationDestination(isPresented: showsConfirmation) { if let paymentResult { ConfirmationView(result: paymentResult) } } } } } ``` ## UIKit In UIKit, present the checkout with [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) and adopt `PrimerCheckoutPresenterDelegate` to receive the outcome. The presenter closes its own sheet, so you don't dismiss it yourself. It finishes dismissing the sheet before it calls `primerCheckoutPresenterDidCompleteWithSuccess(_:)`. `primerCheckoutPresenterDidDismiss()` is called when the customer closes the checkout without completing a payment. `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` is called once per failed attempt, including a failed initialization. The sheet stays open on the SDK error screen so the customer can retry. It closes on failure only when `uiOptions.isErrorScreenEnabled` is `false`. ```swift theme={"dark"} import UIKit import PrimerSDK final class CheckoutViewController: UIViewController { let clientToken: String init(clientToken: String) { self.clientToken = clientToken super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func startCheckout() { PrimerCheckoutPresenter.shared.delegate = self PrimerCheckoutPresenter.presentCheckout(clientToken: clientToken, from: self) } } extension CheckoutViewController: PrimerCheckoutPresenterDelegate { func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) { let confirmation = ConfirmationViewController(result: result) navigationController?.pushViewController(confirmation, animated: true) } func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) { print("Checkout failed: \(error.errorId) — \(error.diagnosticsId)") } func primerCheckoutPresenterDidDismiss() { // User closed the checkout without completing a payment. } } ``` > [!TIP] > > Set the `delegate` before calling `presentCheckout`. If no delegate is set when checkout completes, the outcome is logged and otherwise dropped. The delegate maps one-to-one onto the SwiftUI `PrimerCheckoutState` cases: | Delegate method | Equivalent state | | - | - | | `primerCheckoutPresenterDidCompleteWithSuccess(_:)` | `.success(PaymentResult)` | | `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` | `.failure(PrimerError, checkoutData:)` | | `primerCheckoutPresenterDidDismiss()` | `.dismissed` | ## Reading the PaymentResult On success you receive a `PaymentResult`. Read its properties to build your confirmation UI, send analytics, or reconcile against your backend. | Property | Type | Description | | - | - | - | | `paymentId` | `String` | The Primer payment ID. | | `status` | `PaymentStatus` | The payment status: `.pending`, `.success`, or `.failed`. | | `token` | `String?` | An identifier for the payment. For card and saved payment methods, this is the payment ID. For other methods, it is the payment method token when the method returns one, otherwise `nil`. | | `redirectUrl` | `String?` | Reserved. Always `nil`. | | `errorMessage` | `String?` | Reserved. Always `nil`. | | `amount` | `Int?` | The amount in minor units (for example, cents for USD), when the payment response includes it. `nil` for card, saved and Stripe ACH payment methods. | | `currencyCode` | `String?` | The ISO 4217 currency code (for example, `"USD"`), when available. `nil` for card, saved and Stripe ACH payment methods. | | `paymentMethodType` | `String?` | The payment method type used (for example, `"PAYMENT_CARD"`). | `amount` and `currencyCode` can be `nil`, and they are always `nil` for card, saved and Stripe ACH payment methods. If you need them, read them from your own order or from your backend, using `paymentId`. The `Charged` line in the sample below only shows when both values are present. ```swift theme={"dark"} import SwiftUI import PrimerSDK struct ConfirmationView: View { let result: PaymentResult var body: some View { VStack(spacing: 12) { Text("Payment confirmed") .font(.title2.bold()) Text("Payment ID: \(result.paymentId)") if let amount = result.amount, let currency = result.currencyCode { Text("Charged: \(amount) \(currency)") } } } } ``` > [!NOTE] > > `status` is always `.success` for card, saved and Stripe ACH payment methods in a `.success(PaymentResult)` outcome. Other payment methods report the status from the Payments API response. It can be `.pending` until the processor confirms the payment, as with some Klarna, PayPal, web redirect or QR code payments. Check `status` before you fulfill an order. Primer Checkout creates the payment for you, so `PrimerSettings(paymentHandling: .manual)` is not supported. ## Handling the PrimerError On failure you receive a [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error). The SDK already surfaces failures inside the checkout UI, so you typically use the error for logging, analytics, and support workflows rather than for displaying a message yourself. | Property | Type | Description | | - | - | - | | `errorId` | `String` | A stable, machine-readable identifier for the error category. | | `diagnosticsId` | `String` | A unique ID for this specific occurrence — include it in support requests. | | `errorDescription` | `String?` | A formatted description combining the error ID, message, and diagnostics ID. | | `recoverySuggestion` | `String?` | A suggested recovery action, when one is available. | Together with the error, you receive `checkoutData: PrimerCheckoutData?`. In SwiftUI, bind it with `case let .failure(error, checkoutData)`. In UIKit, it is the `checkoutData` parameter of `primerCheckoutPresenterDidFailWithError(_:checkoutData:)`. If a payment was created before the failure, for example on a decline, use `checkoutData?.payment?.id` and `checkoutData?.payment?.orderId` to find it on your backend. `checkoutData` is `nil` if the failure happened before a payment existed, for example during initialization or tokenization, or after a connectivity error. ```swift theme={"dark"} func report(_ error: PrimerError) { analytics.track("checkout_failed", properties: [ "error_id": error.errorId, "diagnostics_id": error.diagnosticsId ]) if let suggestion = error.recoverySuggestion { print("Recovery: \(suggestion)") } } ``` > [!WARNING] > > Always log `diagnosticsId`. Primer support uses it to trace the exact failed request when you raise an issue. ## See also > [card] [PrimerCheckoutState](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) > > The full state enum and the PaymentResult model. > [card] [PrimerError](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) > > Error categories, IDs, and diagnostics. > [card] [PrimerCheckoutPresenter](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) > > The UIKit entry point and delegate callbacks. > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > The prebuilt SwiftUI checkout view. # SwiftUI navigation Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/guides/swiftui-navigation Present and embed checkout within SwiftUI navigation > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. Primer Checkout is built entirely in SwiftUI, so it slots into any navigation pattern you already use. There are two integration shapes: * **Modal flow** — drop `PrimerCheckout` into a `.sheet`, `.fullScreenCover`, or `NavigationStack` destination and let the SDK render its prebuilt screens. * **Inline embedding** — hold a `PrimerCheckoutSession` as `@StateObject`, apply the `.primerCheckoutSession(_:theme:onCompletion:)` modifier, and place composable views such as `PrimerCardForm` and `PrimerPaymentMethods` directly in your own layout. Both shapes deliver outcomes through a `PrimerCheckoutState` callback, so you drive navigation from the same `.success` / `.dismissed` / `.failure` cases regardless of how checkout is presented. > [!NOTE] > > Primer Checkout requires iOS 15.0 or later — all checkout views and sessions are annotated `@available(iOS 15.0, *)`, and `PrimerCheckout` and the session classes (`PrimerCheckoutSession`, `PrimerCardFormSession`, `PrimerSelectionSession`) are also `@MainActor`. Some SwiftUI navigation hosts shown below require a newer OS than the SDK floor: `NavigationStack` and `.navigationDestination(for:)` require iOS 16.0+, and the `.navigationDestination(item:)` overload requires iOS 17.0+. On an iOS 15 deployment target, present checkout with `.sheet` or `.fullScreenCover` instead. ## Reading the completion state Both SwiftUI shapes report their outcome through `onCompletion` with a `PrimerCheckoutState`. UIKit's `PrimerCheckoutPresenter` uses `PrimerCheckoutPresenterDelegate` instead. The callback receives `.failure` once per failed attempt, and `.success` or `.dismissed` once the checkout ends. After `.success` or `.dismissed`, it delivers nothing more. For an inline session, a failure during initialization is the last callback. The callback never receives the lifecycle cases `.initializing` and `.ready(clientSession:)`. For an inline session, read the lifecycle from `PrimerCheckoutSession.phase` and `clientSession`. Switch on the state to decide how navigation should react. | Case | Associated value | Drives | | - | - | - | | `success` | `PaymentResult` | Dismiss and push a confirmation | | `dismissed` | — | User closed checkout; restore prior screen | | `failure` | `PrimerError`, `checkoutData: PrimerCheckoutData?` | With the default `isErrorScreenEnabled: true` in `PrimerUIOptions`, the SDK shows its error screen and checkout stays open. This applies to a failed payment attempt, and to a failed initialization in `PrimerCheckout`. After a failed payment attempt, the screen offers a retry. When another payment method is available, it also offers that method. A later attempt delivers another outcome. For an inline `PrimerCheckoutSession`, an initialization failure ends the session and the SDK shows nothing, so show your own error UI. With `isErrorScreenEnabled: false` in `PrimerUIOptions`, the SDK shows nothing, so show your own error UI or close checkout. `checkoutData` carries the payment and order IDs when a payment was created before the failure. It is `nil` when the failure happened earlier (initialization, tokenization, connectivity). Match it with `case let .failure(error, checkoutData)`. | > [!WARNING] > > `PrimerCheckoutState` is an evolving enum. Always include a `default` case when switching on it so future cases compile without breaking your navigation logic. ## Modal flow with `PrimerCheckout` `PrimerCheckout` is a self-contained `View` that renders the SDK's default screens. Use it whenever you want the fastest integration and do not need to recompose the UI. ```swift theme={"dark"} public init( clientToken: String, primerSettings: PrimerSettings = PrimerSettings(), primerTheme: PrimerCheckoutTheme = PrimerCheckoutTheme(), onCompletion: ((PrimerCheckoutState) -> Void)? = nil, onShippingAddressChange: ShippingAddressChangeHandler? = nil, onShippingOptionChange: ShippingOptionChangeHandler? = nil ) ``` ### Sheet presentation ```swift theme={"dark"} struct CartView: View { @State private var showCheckout = false let clientToken: String var body: some View { Button("Pay now") { showCheckout = true } .sheet(isPresented: $showCheckout) { PrimerCheckout( clientToken: clientToken, onCompletion: { state in switch state { case .success, .dismissed: showCheckout = false default: break } } ) } } } ``` While a payment is processing, the customer cannot swipe the sheet away. Apple Pay and Stripe ACH show no processing screen, so the sheet is not locked while they run. ### Pushing onto a `NavigationStack` Use a `NavigationStack` when checkout is one step inside a longer flow and you want a back button rather than a modal. `NavigationStack(path:)` and `.navigationDestination(for:)` require iOS 16.0+; on an iOS 15 target, use the sheet presentation above. ```swift theme={"dark"} struct ShopFlow: View { @State private var path = NavigationPath() let clientToken: String var body: some View { NavigationStack(path: $path) { CartScreen(onCheckout: { path.append(Route.checkout) }) .navigationDestination(for: Route.self) { route in switch route { case .checkout: PrimerCheckout( clientToken: clientToken, onCompletion: { state in if case .success(let result) = state { path.append(Route.confirmation(result.paymentId)) } } ) .navigationTitle("Payment") .navigationBarTitleDisplayMode(.inline) case .confirmation(let paymentId): ConfirmationScreen(paymentId: paymentId) } } } } enum Route: Hashable { case checkout case confirmation(String) } } ``` > [!TIP] > > On a `.success`, append a confirmation route and pass `result.paymentId` along — `PaymentResult` also exposes `status`, `amount`, `currencyCode`, and `paymentMethodType` for your receipt screen. ## Inline embedding with `PrimerCheckoutSession` To recompose the UI — for example, to place `PrimerCardForm` inside your own scroll view alongside an order summary — hold a `PrimerCheckoutSession` and wire it in with the `.primerCheckoutSession(_:theme:onCompletion:)` modifier. The modifier injects the session into the environment, so any Primer composable placed under it resolves automatically. ```swift theme={"dark"} public init( clientToken: String, settings: PrimerSettings = PrimerSettings(), theme: PrimerCheckoutTheme = PrimerCheckoutTheme(), idempotencyKey: @escaping @Sendable () -> String? = { nil }, onShippingAddressChange: ShippingAddressChangeHandler? = nil, onShippingOptionChange: ShippingOptionChangeHandler? = nil ) ``` ```swift theme={"dark"} @available(iOS 15.0, *) public extension View { func primerCheckoutSession( _ session: PrimerCheckoutSession, theme: PrimerCheckoutTheme? = nil, onCompletion: ((PrimerCheckoutState) -> Void)? = nil ) -> some View } ``` Hold the session with `@StateObject` so it survives view updates. The modifier bootstraps it on appear and tears it down on disappear. ```swift theme={"dark"} struct InlineCheckoutScreen: View { @StateObject private var session: PrimerCheckoutSession let onPaid: (PaymentResult) -> Void init(clientToken: String, onPaid: @escaping (PaymentResult) -> Void) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken)) self.onPaid = onPaid } var body: some View { ScrollView { VStack(spacing: 24) { OrderSummary() PrimerCardForm() } .padding() } .primerCheckoutSession(session) { state in if case .success(let result) = state { onPaid(result) } } } } ``` > [!NOTE] > > The modifier wires `session.cancel()` to `onDisappear`, which also fires on transient disappearance (tab switch, push/pop, parent sheet re-present). The session resets to a restartable state and rebuilds itself when the view reappears — no extra handling required. ### Embedding the payment-method list `PrimerPaymentMethods` resolves the same session from the environment, so you can compose a full selection-plus-card layout under a single modifier. ```swift theme={"dark"} ScrollView { VStack(spacing: 24) { PrimerPaymentMethods() PrimerCardForm() } .padding() } .primerCheckoutSession(session) { state in handle(state) } ``` ## Driving navigation from the completion state Whether modal or inline, route on the same `PrimerCheckoutState` cases: dismiss on `.dismissed`, advance on `.success`, and leave checkout in place on a payment `.failure` while the SDK error screen is enabled (the default). An inline session that fails to initialize ends, so show your own error UI. ```swift theme={"dark"} struct CheckoutContainer: View { @State private var showCheckout = false @State private var confirmation: String? let clientToken: String var body: some View { NavigationStack { Button("Checkout") { showCheckout = true } .sheet(isPresented: $showCheckout) { PrimerCheckout( clientToken: clientToken, onCompletion: { state in switch state { case .success(let result): showCheckout = false confirmation = result.paymentId case .dismissed: showCheckout = false case .failure: break default: break } } ) } .navigationDestination(item: $confirmation) { paymentId in ConfirmationScreen(paymentId: paymentId) } } } } ``` > [!NOTE] > > The `.navigationDestination(item:)` overload used above requires iOS 17.0+. On earlier targets, drive the same `confirmation` value through an `isPresented`-based `.sheet` or a `.navigationDestination(isPresented:)` binding instead. For the inline shape, the same `onCompletion` closure on `.primerCheckoutSession(_:theme:onCompletion:)` drives the navigation in identical fashion — pop the embedding screen on `.dismissed`, push a confirmation on `.success`. > [!WARNING] > > Do not dismiss checkout on a payment `.failure` while the SDK error screen is enabled (`isErrorScreenEnabled` in `PrimerUIOptions`, which defaults to `true`). The SDK shows the error inside checkout so the customer can retry or, where available, choose another payment method. Dismissing would discard that recoverable state. If you pass `PrimerSettings(uiOptions: PrimerUIOptions(isErrorScreenEnabled: false))`, the SDK shows no error UI and leaves the failure to you. Show your own error or dismiss checkout. An inline session that fails to initialize shows no SDK error, so handle that failure yourself. ## See also > [card] [PrimerCheckoutSession](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) > > Own the inline session lifecycle and sub-sessions > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > The prebuilt modal checkout view > [card] [PrimerCardForm](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) > > Compose the card form inline with slots > [card] [Handle payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) > > React to checkout outcomes # UIKit integration Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/guides/uikit-integration Integrate the Primer Checkout iOS SDK in a UIKit app > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. The Primer Checkout iOS SDK is built with SwiftUI, but it ships a UIKit entry point so you can integrate it from view-controller based apps without rewriting your navigation. [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) presents the managed checkout as a modal sheet from any `UIViewController` and delivers the result through a delegate. For most UIKit apps, the presenter is all you need. If you want full control over the layout, you can also embed the SwiftUI composable views ([`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) and [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods)) inside a `UIHostingController` — see [Embedding the composable views](#embedding-the-composable-views). > [!NOTE] > > `PrimerCheckoutPresenter` is `@available(iOS 15.0, *)` and `@MainActor`. Call its static methods from the main thread — the default for UIKit lifecycle callbacks. For pure SwiftUI apps, use [`PrimerCheckout`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) directly instead. ## Present checkout There are three steps: 1. Assign the [`delegate`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) on `PrimerCheckoutPresenter.shared`. 2. Call `presentCheckout(...)`, passing the client token and the view controller to present from. 3. Implement `PrimerCheckoutPresenterDelegate` to handle the result. ```swift theme={"dark"} import PrimerSDK import UIKit final class CheckoutViewController: UIViewController { private let clientToken: String init(clientToken: String) { self.clientToken = clientToken super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() PrimerCheckoutPresenter.shared.delegate = self } @IBAction func payButtonTapped(_ sender: UIButton) { PrimerCheckoutPresenter.presentCheckout( clientToken: clientToken, from: self ) } } extension CheckoutViewController: PrimerCheckoutPresenterDelegate { func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) { let confirmationVC = ConfirmationViewController(result: result) navigationController?.pushViewController(confirmationVC, animated: true) } func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) { print("Payment \(checkoutData?.payment?.id ?? "-") failed: \(error.localizedDescription)") } func primerCheckoutPresenterDidDismiss() { // The shopper closed checkout without completing a payment. } } ``` > [!NOTE] > > `PrimerCheckoutPresenter.shared.delegate` is a `weak` reference. Keep the conforming object (here, the view controller) alive for as long as checkout is on screen, otherwise the callbacks will not fire. Generate the `clientToken` from your backend with the [client session](/docs/checkout/client-session) API. ## Presentation overloads `presentCheckout` has several overloads that differ in how much you configure and whether you supply the presenting view controller yourself. Every overload accepts an optional `completion` closure (trailing-closure syntax works) that runs once the checkout UI has finished presenting. ```swift theme={"dark"} // Minimal — automatic view controller detection, no settings. PrimerCheckoutPresenter.presentCheckout(clientToken: clientToken) // From an explicit view controller. PrimerCheckoutPresenter.presentCheckout(clientToken: clientToken, from: self) // With custom settings. PrimerCheckoutPresenter.presentCheckout( clientToken: clientToken, from: self, primerSettings: PrimerSettings(uiOptions: PrimerUIOptions(isSuccessScreenEnabled: false)) ) // With custom settings and theme. PrimerCheckoutPresenter.presentCheckout( clientToken: clientToken, from: self, primerSettings: PrimerSettings(), primerTheme: PrimerCheckoutTheme() ) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `clientToken` | `String` | — | The client token for the session. Generate it from your backend with the [client session](/docs/checkout/client-session) API. | | `viewController` | `UIViewController` | — | The view controller to present from. Omitted in the automatic-detection overloads. | | `primerSettings` | `PrimerSettings` | — | Configuration applied to this checkout session. Overloads that omit it use the settings most recently registered in this app session, or `PrimerSettings()` if none were. A previous checkout or `Primer.shared.configure(settings:)` registers settings. See [`PrimerSettings`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings). | | `primerTheme` | `PrimerCheckoutTheme` | — | Theme configuration for the [design tokens](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme). Only on the overload that also takes `from:` and `primerSettings`, where it is required. The other overloads use `PrimerCheckoutTheme()`. | | `completion` | `(() -> Void)?` | `nil` | Optional closure invoked once the checkout UI has finished presenting. If a presentation is already in progress, the call is ignored and the closure runs immediately. It is not called when automatic detection finds no view controller. | | `onShippingAddressChange` | `ShippingAddressChangeHandler?` | `nil` | Apple Pay Express Checkout: returns the shipping options for the shopper's address. Only on the overloads that take `primerSettings`. | | `onShippingOptionChange` | `ShippingOptionChangeHandler?` | `nil` | Apple Pay Express Checkout: commits the shipping option the shopper selected. Only on the overloads that take `primerSettings`. | > [!WARNING] > > The automatic-detection overloads (no `from:` parameter) locate the top-most presenting view controller for you. If no presenting view controller can be found, they report a [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) through `primerCheckoutPresenterDidFailWithError(_:checkoutData:)`. Assign the `delegate` before calling them. > [!NOTE] > > The overloads that take `primerSettings` or `primerTheme` are **not** `@objc` compatible because of those Swift-only parameter types. From Objective-C, use the `clientToken:` / `clientToken:from:` overloads. They use the same fallback settings as the other overloads that omit `primerSettings`. They also cannot take the shipping handlers. ## Implement the delegate Conform to `PrimerCheckoutPresenterDelegate` to receive the checkout result. All three methods are required. A failed 3-D Secure challenge is reported like any other failure, through `primerCheckoutPresenterDidFailWithError(_:checkoutData:)`. | Method | Description | | - | - | | `primerCheckoutPresenterDidCompleteWithSuccess(_:)` | Called when payment is successful, with the [`PaymentResult`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state#paymentresult). | | `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` | Called once per failed attempt, with a [`PrimerError`](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error). `checkoutData` carries the payment id and order id when the payment was created before the failure, and is `nil` otherwise. | | `primerCheckoutPresenterDidDismiss()` | Called when checkout is dismissed without completing a payment. | ```swift theme={"dark"} func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) func primerCheckoutPresenterDidFailWithError(_ error: PrimerError, checkoutData: PrimerCheckoutData?) func primerCheckoutPresenterDidDismiss() ``` The success callback delivers a `PaymentResult`. Switch on its `status` to route your UI: ```swift theme={"dark"} func primerCheckoutPresenterDidCompleteWithSuccess(_ result: PaymentResult) { switch result.status { case .success: showReceipt(paymentId: result.paymentId) case .pending: showPendingState(paymentId: result.paymentId) case .failed: showError(message: result.errorMessage) default: break } } ``` > [!TIP] > > The checkout dismisses itself before it delivers `primerCheckoutPresenterDidCompleteWithSuccess(_:)`, so push your own confirmation screen from that callback. `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` fires once per failed attempt, including a failed initialization. The checkout stays open while the SDK error screen offers a retry, and closes on the failure only when `isErrorScreenEnabled` is `false`. For the full payment-result model, see [Handle payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result). > [!NOTE] > > The shopper can swipe the sheet down when `PrimerSettings.uiOptions.dismissalMechanism` contains `.gestures` (the default), except while a payment is processing. A swipe on the success screen delivers `primerCheckoutPresenterDidCompleteWithSuccess(_:)`. A swipe anywhere else, including the error screen after a failure was reported, delivers `primerCheckoutPresenterDidDismiss()`. ## Dismiss programmatically Call `dismiss(animated:completion:)` to close checkout from your own code (for example, after a timeout). This triggers `primerCheckoutPresenterDidDismiss()` on the delegate. ```swift theme={"dark"} PrimerCheckoutPresenter.dismiss(animated: true) { print("Checkout dismissed") } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `animated` | `Bool` | `true` | Accepted for API compatibility. The sheet always dismisses with animation, whatever value you pass. | | `completion` | `(() -> Void)?` | `nil` | Optional closure invoked after dismissal completes. If no checkout is on screen, it runs immediately and `primerCheckoutPresenterDidDismiss()` is not called. | ## Check availability Use the static properties to guard presentation: ```swift theme={"dark"} // Check if checkout can be presented on the current OS version. guard PrimerCheckoutPresenter.isAvailable else { return } // Avoid presenting twice. guard !PrimerCheckoutPresenter.isPresenting else { return } PrimerCheckoutPresenter.presentCheckout(clientToken: clientToken, from: self) ``` | Property | Type | Description | | - | - | - | | `isAvailable` | `Bool` | `static`. `true` when CheckoutComponents can be presented on the current OS version. | | `isPresenting` | `Bool` | `static`. `true` while a checkout is being presented or is currently on screen. | ## Embedding the composable views If the managed sheet does not match your UI, you can embed the SwiftUI composable views directly inside a UIKit screen with `UIHostingController`. Hold a [`PrimerCheckoutSession`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) as a `@StateObject`, place [`PrimerCardForm`](/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/primer-card-form) and [`PrimerPaymentMethods`](/docs/sdk/ios-checkout/v3.0.0-beta/api/payment-methods/primer-payment-methods) under the `.primerCheckoutSession(_:theme:onCompletion:)` modifier, and host that SwiftUI view in your view controller. First, define the SwiftUI content: ```swift theme={"dark"} import SwiftUI import PrimerSDK @available(iOS 15.0, *) struct EmbeddedCheckoutView: View { @StateObject private var session: PrimerCheckoutSession let onCompletion: (PrimerCheckoutState) -> Void init(clientToken: String, onCompletion: @escaping (PrimerCheckoutState) -> Void) { _session = StateObject( wrappedValue: PrimerCheckoutSession(clientToken: clientToken) ) self.onCompletion = onCompletion } var body: some View { ScrollView { VStack(spacing: 24) { PrimerCardForm() PrimerPaymentMethods() } .padding() } .primerCheckoutSession(session, onCompletion: onCompletion) } } ``` Then host it from your view controller and add it as a child: ```swift theme={"dark"} import SwiftUI import PrimerSDK import UIKit @available(iOS 15.0, *) final class EmbeddedCheckoutViewController: UIViewController { private let clientToken: String init(clientToken: String) { self.clientToken = clientToken super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let checkoutView = EmbeddedCheckoutView(clientToken: clientToken) { [weak self] state in self?.handle(state) } let hostingController = UIHostingController(rootView: checkoutView) addChild(hostingController) hostingController.view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(hostingController.view) NSLayoutConstraint.activate([ hostingController.view.topAnchor.constraint(equalTo: view.topAnchor), hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) hostingController.didMove(toParent: self) } private func handle(_ state: PrimerCheckoutState) { switch state { case let .success(result): showReceipt(paymentId: result.paymentId) case let .failure(error, _): showError(message: error.localizedDescription) case .dismissed: navigationController?.popViewController(animated: true) case .initializing, .ready: break @unknown default: break } } } ``` > [!WARNING] > > The `.primerCheckoutSession(_:theme:onCompletion:)` modifier must sit above the composable views in the hierarchy. It injects the per-feature sessions into the environment and bootstraps the session lifecycle (`start()` on appear, `cancel()` on disappear). Without it, `PrimerCardForm` and `PrimerPaymentMethods` cannot resolve a session and will not function. > [!TIP] > > With embedded composables you receive the outcome as a [`PrimerCheckoutState`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) in the modifier's `onCompletion`, rather than through the presenter delegate. The state-driven model is identical to a pure SwiftUI integration. ## See also > [card] [PrimerCheckoutPresenter](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) > > The full UIKit entry-point API: overloads, delegate, and result types. > [card] [PrimerCheckoutState](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state) > > The state model returned to embedded composable integrations. > [card] [Handle payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) > > Route your UI based on the checkout outcome. > [card] [SwiftUI navigation](/docs/sdk/ios-checkout/v3.0.0-beta/guides/swiftui-navigation) > > Presentation patterns for pure SwiftUI apps. # Installation Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/installation Add the Primer Checkout iOS SDK to your project > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. ## Prerequisites * iOS 15.0+ deployment target * Swift 6.0+ * Xcode 16.0+ * A `clientToken` from your server via the [Client Session API](/docs/checkout/client-session) > [!NOTE] > > The Primer Checkout SDK uses SwiftUI. You can drop it into a SwiftUI view hierarchy directly, or present it from UIKit with [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter). ## Install the SDK Choose CocoaPods or Swift Package Manager. Both install the same `PrimerSDK` framework, which includes the Checkout Components UI. > [!NOTE] > > This is a beta release line. The current version is `3.0.0-beta.8`. Pin to the exact beta version so a new beta tag does not change your build without you opting in. ### With CocoaPods Add the following to your `Podfile`: ```ruby RUBY theme={"dark"} use_frameworks! target 'MyApp' do # 👇 Add this line pod 'PrimerSDK', '3.0.0-beta.8' # ... end ``` Then run `pod install` to install `PrimerSDK` into your workspace: ```bash theme={"dark"} pod install ``` Open the generated `.xcworkspace` (not the `.xcodeproj`) from now on. > [!NOTE] > > If Xcode reports that a resource bundle target needs signing, add the following post-install script to your `Podfile`. > > ```ruby RUBY theme={"dark"} > post_install do |installer| > installer.pods_project.targets.each do |target| > if target.respond_to?(:product_type) and target.product_type == "com.apple.product-type.bundle" > target.build_configurations.each do |config| > config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' > end > end > end > end > ``` ### With Swift Package Manager Swift Package Manager is integrated into Xcode. To add `PrimerSDK`: 1. Select your project, then navigate to **Package Dependencies**. 2. Click the **+** button at the bottom-left of the **Packages** section. 3. Paste [https://github.com/primer-io/primer-sdk-ios.git](https://github.com/primer-io/primer-sdk-ios.git) into the search bar. 4. Under **Dependency Rule**, choose **Exact Version** and enter the beta tag `3.0.0-beta.8`. 5. Press **Add Package** and let Xcode resolve and link the dependency. Or declare it directly in your `Package.swift`: ```swift theme={"dark"} dependencies: [ .package( url: "https://github.com/primer-io/primer-sdk-ios.git", exact: "3.0.0-beta.8" ) ] ``` ### Optional: Klarna Native Klarna appears in the payment method list only when your app includes the `PrimerKlarnaSDK` pod. Adyen Klarna does not need it. With CocoaPods, add `PrimerKlarnaSDK` next to `PrimerSDK` in your `Podfile`, then run `pod install`: ```ruby RUBY theme={"dark"} target 'MyApp' do pod 'PrimerSDK', '3.0.0-beta.8' # 👇 Add this line pod 'PrimerKlarnaSDK' end ``` The `PrimerSDK` Swift package does not include `PrimerKlarnaSDK`, so native Klarna requires CocoaPods. ## Basic Usage Import `PrimerSDK` and present `PrimerCheckout` with a `clientToken`. This renders the SDK's default screens as a managed modal and reports the outcome through `onCompletion`: ```swift theme={"dark"} import SwiftUI import PrimerSDK struct ContentView: View { let clientToken: String var body: some View { PrimerCheckout(clientToken: clientToken) { state in switch state { case .success(let result): print("Payment complete: \(result)") case let .failure(error, _): print("Checkout failed: \(error)") case .dismissed: print("Checkout dismissed") default: break } } } } ``` `PrimerCheckout` requires iOS 15.0+ and runs on the main actor. Its initializer also accepts `primerSettings` and `primerTheme`, plus two optional Apple Pay Express Checkout shipping handlers: ```swift theme={"dark"} PrimerCheckout( clientToken: clientToken, primerSettings: PrimerSettings(), primerTheme: PrimerCheckoutTheme(), onCompletion: { state in // .failure per failed attempt, then .success or .dismissed once } ) ``` | Parameter | Type | Default | Description | | - | - | - | - | | `clientToken` | `String` | — | The client token obtained from your backend via the Client Session API. | | `primerSettings` | `PrimerSettings` | `PrimerSettings()` | Configuration settings including payment options and UI preferences. | | `primerTheme` | `PrimerCheckoutTheme` | `PrimerCheckoutTheme()` | Theme configuration for design tokens. | | `onCompletion` | `((PrimerCheckoutState) -> Void)?` | `nil` | Receives `.failure` once per failed attempt, including a failed initialization. With the default error screen, the checkout stays open for a retry. Then receives `.success` or `.dismissed` exactly once. | | `onShippingAddressChange` | `ShippingAddressChangeHandler?` | `nil` | Express Checkout: returns the shipping options for the shopper's address. | | `onShippingOptionChange` | `ShippingOptionChangeHandler?` | `nil` | Express Checkout: commits the shipping option the shopper selected. | > [!TIP] > > Building a UIKit app? Present the checkout from a `UIViewController` with [`PrimerCheckoutPresenter`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-presenter) instead of embedding the SwiftUI view. ## Verify Installation Build and run your app to confirm the SDK is resolved and links correctly: ```bash theme={"dark"} xcodebuild -scheme MyApp -destination 'generic/platform=iOS' build ``` If the build succeeds and `import PrimerSDK` resolves, the SDK is installed and ready to use. ## Next Steps > [card] [API Overview](/docs/sdk/ios-checkout/v3.0.0-beta/api/overview) > > Tour the Checkout Components API surface > [card] [PrimerCheckout](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout) > > The managed modal entry point in depth > [card] [Theming](/docs/sdk/ios-checkout/v3.0.0-beta/api/theming/primer-theme) > > Customize the appearance with design tokens > [card] [Handle Payment Result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) > > Respond to success, failure, and dismissal # Troubleshooting Source: https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/troubleshooting Common issues and solutions for the Primer Checkout iOS SDK > [!WARNING] > > Primer Checkout iOS SDK is currently in **beta** (v3.0.0-beta.8). > The API is subject to change before the stable release. ## Installation issues ### Swift Package Manager fails to resolve **Problem**: Xcode reports that it cannot resolve `primer-sdk-ios`, or the package gets stuck while resolving versions. **Solution**: Confirm the package URL is `https://github.com/primer-io/primer-sdk-ios.git` and that the dependency rule targets the `3.0.0-beta.8` beta. Then reset Xcode's cached package state: 1. **File ▸ Packages ▸ Reset Package Caches** 2. **File ▸ Packages ▸ Resolve Package Versions** If resolution still fails, close Xcode and clear the derived data and SPM caches: ```bash theme={"dark"} rm -rf ~/Library/Developer/Xcode/DerivedData rm -rf ~/Library/Caches/org.swift.swiftpm ``` > [!NOTE] > > The Primer Checkout iOS SDK requires **iOS 15.0+**. If your target's deployment version is lower, SPM cannot satisfy the platform requirement and resolution fails. ### CocoaPods: bundle code-signing error on Xcode 14 **Problem**: After `pod install`, the build fails with an error stating that a resource bundle needs to be code signed. **Solution**: Add the following `post_install` script to your `Podfile`, then run `pod install` again. It disables code signing on the SDK's resource bundles, which do not require signing: ```ruby theme={"dark"} post_install do |installer| installer.pods_project.targets.each do |target| if target.respond_to?(:product_type) and target.product_type == "com.apple.product-type.bundle" target.build_configurations.each do |config| config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' end end end end ``` After editing the `Podfile`, always run `pod install` again and reopen the generated `.xcworkspace` rather than the `.xcodeproj`. See the [Installation](/docs/sdk/ios-checkout/v3.0.0-beta/installation) guide for the full setup steps. ## Runtime issues ### Checkout stays in the initializing phase **Problem**: `PrimerCheckoutSession.phase` never transitions from `.initializing` to `.ready`, so your composable views show only the loading state. **Possible causes**: | Cause | What to check | | - | - | | Invalid or expired client token | Generate a fresh client token immediately before presenting checkout. Tokens are short-lived. | | Network connectivity | Confirm the device has connectivity and that your backend can reach Primer's API. | | Incorrect API key | Verify the API key used to create the [client session](/docs/checkout/client-session) belongs to the correct environment (sandbox vs. production). | **Solution**: When initialization fails, the session delivers a `.failure` with a `PrimerError` through the `onCompletion` closure on `.primerCheckoutSession(_:theme:onCompletion:)`. Inspect that error and log its `diagnosticsId`: ```swift theme={"dark"} .primerCheckoutSession(session) { state in if case let .failure(error, _) = state { print("Checkout failed: \(error.localizedDescription)") print("Diagnostics ID: \(error.diagnosticsId)") } } ``` ### Checkout fails at start with an invalid-value error **Problem**: The checkout shows the error screen right away, or `onCompletion` receives a `.failure` whose `PrimerError` has `errorId` `invalid-value`. The description names the key `paymentHandling`. **Cause**: `PrimerSettings(paymentHandling: .manual)`. Primer Checkout creates the payment itself and does not support manual payment handling. **Solution**: Use the default `.auto`. To pass an idempotency key or to abort a payment before the SDK creates it, set [`onBeforePaymentCreate`](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session). See [PrimerPaymentHandling](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-settings#primerpaymenthandling). ### Payment methods not showing **Problem**: No payment methods appear, or a payment method you enabled is missing from the list. If no method is available, the session never reaches `.ready`, `PrimerPaymentMethods` renders nothing, and `onCompletion` receives a `.failure`. Its `PrimerError` has `errorId` `misconfigured-payment-methods` or `missing-configuration`. **Possible causes**: * No payment methods are configured in the Primer Dashboard. * The client session is missing required fields. * Payment methods are not enabled for the requested currency or country. * The payment method is not supported by Primer Checkout on iOS. Primer Checkout hides payment methods it cannot present. * Klarna is missing. Primer Checkout lists Klarna only if your app adds the `PrimerKlarnaSDK` pod. See the [Installation](/docs/sdk/ios-checkout/v3.0.0-beta/installation) guide. Adyen Klarna does not need it. **Solution**: Verify your [Primer Dashboard](https://dashboard.primer.io) configuration, and ensure the [client session](/docs/checkout/client-session) includes the correct `currencyCode` and `countryCode`. Primer filters payment methods server-side based on these values, and the SDK then keeps only the methods it supports. If Primer returns no payment methods, checkout fails with `misconfigured-payment-methods`. If Primer Checkout supports none of the returned methods, checkout fails with `missing-configuration`. ### Card form fields not appearing **Problem**: Some card form fields — such as cardholder name or billing address fields — do not appear in `PrimerCardForm`. **Explanation**: The visible fields are driven by your Primer Dashboard configuration, surfaced through the session's published state. Each default field building block self-hides unless its field is present in that configuration, so only fields enabled in the Dashboard appear. This is expected behavior, not a bug. > [!TIP] > > To branch on the active configuration inside a slot, read it from the session state, for example `session.state.configuration.requiresBillingAddress`. ### 3DS challenge not completing **Problem**: A payment gets stuck during 3D Secure authentication. **Solution**: 3DS is handled automatically by the SDK. Make sure you do not dismiss or recreate the hosting view while the challenge is on screen — tearing down the view tears down the session (see below). The SDK does not apply its own timeout to the payment, so it keeps waiting while the challenge is on screen. A challenge that fails arrives like any other failed attempt: a `.failure(error, checkoutData)` in `onCompletion` (SwiftUI) or `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` (UIKit). The payment was created before the challenge started, so `checkoutData` carries its payment id. See the [Handle payment result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) guide. ## SwiftUI-specific issues ### Session re-created on every render **Problem**: Checkout reinitializes repeatedly, flickering back to `.initializing`, because a new `PrimerCheckoutSession` is allocated each time the view's `body` is evaluated. **Solution**: Own the session with `@StateObject` so SwiftUI keeps a single instance across re-renders. Never construct it inline in `body`, inside a conditional, or in a callback: ```swift theme={"dark"} // Correct — one session for the lifetime of the view struct CheckoutView: View { @StateObject private var session: PrimerCheckoutSession init(token: String) { _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: token)) } var body: some View { ScrollView { PrimerPaymentMethods() PrimerCardForm() } .primerCheckoutSession(session) { state in handle(state) } } } ``` ```swift theme={"dark"} // Incorrect — allocates a new session on every render struct CheckoutView: View { var body: some View { let session = PrimerCheckoutSession(clientToken: token) // Don't do this return ScrollView { PrimerCardForm() } .primerCheckoutSession(session) } } ``` > [!WARNING] > > The `.primerCheckoutSession(_:theme:onCompletion:)` modifier bootstraps the session on appear and tears it down on disappear. If a fresh session is allocated on each render, that teardown-and-rebuild cycle prevents checkout from ever reaching `.ready`. ### UI not updating **Problem**: Your custom slot content does not reflect changes such as validation errors, surcharge updates, or the loading state. **Solution**: The Primer composable views observe their session's `@Published` state automatically — you do not need a manual subscription. Drive your custom UI by reading from the session state inside the slot closure: ```swift theme={"dark"} PrimerCardForm(submitButton: { session in Button("Pay \(session.state.surchargeAmount ?? "")") { session.submit() } .disabled(!session.state.isValid || session.state.isLoading) }) ``` Because each slot closure receives the observed session directly, capturing it in an external `@State` or copying its values into local variables breaks observation — always read `session.state` at the point of use. ## Getting help If you encounter an issue not covered here: 1. Capture the `diagnosticsId` from the `PrimerError` delivered in `onCompletion` (SwiftUI) or `primerCheckoutPresenterDidFailWithError(_:checkoutData:)` (UIKit). 2. Verify your configuration in the [Primer Dashboard](https://dashboard.primer.io). 3. Contact Primer support and include the `diagnosticsId` so the team can trace your request. ```swift theme={"dark"} .primerCheckoutSession(session) { state in if case let .failure(error, _) = state { // Share this value with Primer support print("Diagnostics ID: \(error.diagnosticsId)") } } ``` ## See also > [card] [Installation](/docs/sdk/ios-checkout/v3.0.0-beta/installation) > > Add the SDK via SPM or CocoaPods > [card] [Handle Payment Result](/docs/sdk/ios-checkout/v3.0.0-beta/guides/handle-payment-result) > > Process success, failure, and dismissal > [card] [Primer Error](/docs/sdk/ios-checkout/v3.0.0-beta/api/common/primer-error) > > Inspect errors and the diagnosticsId > [card] [Checkout Session](/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-session) > > Own and observe the session lifecycle # Klarna via Adyen options Source: https://primer.io/docs/sdk/primer-checkout-web/adyen-klarna Configuration options for Klarna via Adyen payment integration Klarna via Adyen enables customers to pay using Klarna's buy now, pay later options, processed through your Adyen connection. Klarna allows multiple payment options depending on the country in which the order is created. ## Quick reference | Option | Type | Default | Description | | - | - | - | - | | `buttonOptions.text` | `string` | — | Custom text next to the Klarna logo | ```javascript theme={"dark"} checkout.options = { adyenKlarna: { buttonOptions: { text: 'Pay with Klarna', }, }, }; ``` *** ## Button customization Customize the text displayed on the Klarna via Adyen payment button. | Option | Type | Default | Description | | - | - | - | - | | `buttonOptions.text` | `string` | — | Text displayed next to the Klarna logo. Replaces the default "Pay with" text. | ```javascript theme={"dark"} adyenKlarna: { buttonOptions: { text: 'Pay with Klarna', }, } ``` > [!TIP] > > Use button text that reflects the Klarna payment options available in your customer's region (e.g., "Pay later with Klarna" if only offering Pay Later). *** ## How it works Klarna via Adyen uses a redirect-based payment flow: 1. Customer selects Klarna as their payment method 2. If multiple Klarna payment types are available, the customer selects one (e.g., Pay Now, Pay Later) 3. Customer is redirected to Klarna to authorize the payment 4. After authorization, the customer is redirected back to your checkout > [!TIP] > > If Klarna via Adyen only provides a single payment type for the customer's context, no selection list is displayed. The Klarna button will show the available payment type directly. *** ## Client session requirements Klarna via Adyen requires specific data in the client session to process payments. Pass these when creating the client session on your server. | Parameter | Required | Description | | - | - | - | | `currencyCode` | Yes | 3-letter ISO 4217 currency code (e.g., `USD`, `EUR`, `GBP`) | | `order.lineItems` | Yes | Details of the line items of the order | | `order.countryCode` | Yes | Country code of the customer | | `customer.emailAddress` | No | Pre-fills the Klarna payment form | | `customer.mobileNumber` | No | Pre-fills the Klarna payment form | | `customer.shippingAddress` | No | Pre-fills the Klarna payment form | | `customer.billingAddress` | No | Pre-fills the Klarna payment form | > [!WARNING] > > When passing `customer.billingAddress`, ensure that Klarna has payment method categories configured for the given address. If Klarna is not supported for the given billing address, no Klarna button will be rendered. > [!TIP] > > Learn more about supported countries and currencies in the [Klarna documentation](https://docs.klarna.com/klarna-payments/in-depth-knowledge/puchase-countries-currencies-locales/). *** ## Redirect configuration Klarna via Adyen uses Primer's redirect payment flow. By default, the SDK opens a popup overlay for the Klarna redirect. If popups are blocked or the user is in a WebView, it falls back to a full-page redirect. You can configure redirect behavior through the `redirect` options: ```javascript theme={"dark"} checkout.options = { redirect: { returnUrl: 'https://your-site.com/checkout/complete', forceRedirect: false, }, adyenKlarna: { buttonOptions: { text: 'Pay with Klarna', }, }, }; ``` See [redirect options](/docs/sdk/primer-checkout-web/sdk-options-reference#redirect-options) for full configuration details. *** ## Testing ### Sandbox testing Use Primer's TEST environment to test Klarna via Adyen payments without processing real transactions. Visit the [Klarna Sample Data Page](https://docs.klarna.com/resources/test-environment/sample-customer-data/) for test credentials and sample customer data. ### Production No special configuration is required to go live — use your production credentials and ensure your Adyen account has Klarna enabled. *** ## Troubleshooting > [accordion] Klarna button not appearing > > **Possible causes:** > > * Klarna via Adyen not configured in Primer Dashboard > * Adyen connection not set up or Klarna not enabled on your Adyen account > * Required client session data missing (`currencyCode`, `order.lineItems`, `order.countryCode`) > * Klarna does not support the customer's billing address or country > > **Debug steps:** > > 1. Check browser console for errors > 2. Verify `ADYEN_KLARNA` is in your `enabledPaymentMethods` (if specified) > 3. Verify all required client session parameters are provided > 4. Check that your Adyen account has Klarna enabled for the relevant markets > [accordion] Redirect popup blocked > > **Possible causes:** > > * Browser popup blocker is active > * Running inside a WebView that blocks popups > > **Resolution:** > The SDK automatically falls back to a full-page redirect when popups are blocked. You can also force full-page redirect with `redirect.forceRedirect: true`. > [accordion] Payment types not showing > > **Possible causes:** > > * Klarna does not offer payment types for the customer's country or order amount > * Adyen configuration limits available Klarna payment types > > **Debug steps:** > > 1. Check Klarna's [supported countries and currencies](https://docs.klarna.com/klarna-payments/in-depth-knowledge/puchase-countries-currencies-locales/) > 2. Verify your Adyen account's Klarna configuration > 3. Verify order amount meets Klarna's minimum requirements *** ## Complete example ```html theme={"dark"} ``` *** ## See also > [card] [SDK options reference](/docs/sdk/primer-checkout-web/sdk-options-reference) > > All configuration options > [card] [Klarna options (direct)](/docs/sdk/primer-checkout-web/klarna) > > Klarna direct integration options > [card] [Klarna documentation](https://docs.klarna.com/klarna-payments/) > > Official Klarna documentation # Apple Pay options Source: https://primer.io/docs/sdk/primer-checkout-web/apple-pay Configuration options for Apple Pay payment integration Apple Pay enables customers to pay using payment methods saved to their Apple Wallet. The SDK provides configuration options for button styling and contact information capture. ## Client session requirements Apple Pay requires `currencyCode` and `order.countryCode` in the client session. > [!NOTE] > > `order.countryCode` is the merchant's country (ISO 3166-1 alpha-2) — where the transaction is processed, not the buyer's country. This maps to Apple Pay's [`PKPaymentRequest.countryCode`](https://developer.apple.com/documentation/passkit/pkpaymentrequest/countrycode): "the two-letter ISO 3166 code for the country or region of the merchant's principle place of business." ## Quick reference | Option | Type | Default | Description | | - | - | - | - | | `buttonOptions.type` | `string` | `'plain'` | Button label | | `buttonOptions.buttonStyle` | `string` | — | Button color | | `billingOptions.requiredBillingContactFields` | `string[]` | `[]` | Billing fields to capture | | `shippingOptions.requiredShippingContactFields` | `string[]` | `[]` | Shipping fields to capture | | `shippingOptions.requireShippingMethod` | `boolean` | `false` | Enable shipping method selection | ```javascript theme={"dark"} checkout.options = { applePay: { buttonOptions: { type: 'buy', buttonStyle: 'black', }, billingOptions: { requiredBillingContactFields: ['postalAddress'], }, }, }; ``` *** ## Button options Customize the appearance of the Apple Pay button through the `buttonOptions` configuration. | Option | Type | Default | Description | | - | - | - | - | | `buttonOptions.type` | `string` | `'plain'` | Button label text (see [values](#button-type) below). Automatically localized. | | `buttonOptions.buttonStyle` | `string` | — | `'black'` for black with white text, `'white'` for white with black text, `'white-outline'` for white with black outline. If not set, Apple Pay uses its default styling. | ### Button type Set `buttonOptions.type` to control the label displayed on the Apple Pay button. Text is automatically localized. | Type | Description | | - | - | | `'plain'` | Apple Pay logo only (default) | | `'buy'` | "Buy with Apple Pay" | | `'book'` | "Book with Apple Pay" | | `'check-out'` | "Check Out with Apple Pay" | | `'donate'` | "Donate with Apple Pay" | | `'order'` | "Order with Apple Pay" | | `'pay'` | "Pay with Apple Pay" | | `'set-up'` | "Set Up with Apple Pay" | | `'subscribe'` | "Subscribe with Apple Pay" | | `'add-money'` | "Add Money with Apple Pay" | | `'continue'` | "Continue with Apple Pay" | | `'contribute'` | "Contribute with Apple Pay" | | `'reload'` | "Reload with Apple Pay" | | `'rent'` | "Rent with Apple Pay" | | `'support'` | "Support with Apple Pay" | | `'tip'` | "Tip with Apple Pay" | | `'top-up'` | "Top Up with Apple Pay" | ### Examples ```javascript theme={"dark"} // Standard black button for purchasing applePay: { buttonOptions: { type: 'buy', buttonStyle: 'black', }, } // White button for dark backgrounds applePay: { buttonOptions: { type: 'pay', buttonStyle: 'white', }, } // Donation button with outline applePay: { buttonOptions: { type: 'donate', buttonStyle: 'white-outline', }, } ``` > [!TIP] > > The SDK renders buttons according to [Apple's Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/apple-pay). *** ## Billing options Capture billing information from the customer's Apple Wallet. ```javascript theme={"dark"} applePay: { billingOptions: { requiredBillingContactFields: ['postalAddress'], }, } ``` ### Required billing contact fields Set `requiredBillingContactFields` to specify which billing details to capture from the customer's Apple Wallet. | Field | Description | | - | - | | `'postalAddress'` | Billing address (street, city, state, postal code, country) | *** ## Shipping options Capture shipping information from the customer's Apple Wallet and enable shipping method selection. ```javascript theme={"dark"} applePay: { shippingOptions: { requiredShippingContactFields: ['postalAddress', 'name', 'email', 'phone'], requireShippingMethod: true, }, } ``` ### Required shipping contact fields Set `requiredShippingContactFields` to specify which shipping details to capture from the customer's Apple Wallet. | Field | Description | | - | - | | `'postalAddress'` | Shipping address | | `'name'` | Recipient's name | | `'phoneticName'` | Phonetic representation of name | | `'phone'` | Phone number | | `'email'` | Email address | ### Shipping method selection Set `requireShippingMethod` to `true` to display available shipping methods in the Apple Pay sheet. This requires a shipping module to be configured in your Primer dashboard. ```javascript theme={"dark"} applePay: { shippingOptions: { requiredShippingContactFields: ['postalAddress'], requireShippingMethod: true, }, } ``` When enabled, customers can select from your configured shipping methods directly within the Apple Pay sheet. *** ## Domain configuration If your checkout is hosted on a different domain than your registered Apple Pay domain, set `merchantDomain`: ```javascript theme={"dark"} checkout.options = { merchantDomain: 'merchant.example.com', applePay: { buttonOptions: { type: 'buy', buttonStyle: 'black', }, }, }; ``` See [merchantDomain](/docs/sdk/primer-checkout-web/sdk-options-reference#merchantdomain) in the SDK Options Reference. *** ## Complete example ```html theme={"dark"} ``` *** ## Supported card networks | Network | Description | | - | - | | VISA | Visa cards | | MASTERCARD | Mastercard cards | | AMEX | American Express cards | | DISCOVER | Discover cards | | JCB | JCB cards | | MAESTRO | Maestro cards | | CARTES\_BANCAIRES | Cartes Bancaires (France) | | DANKORT | Dankort (Denmark) | | ELO | Elo (Brazil) | | EFTPOS | eftpos (Australia) | | INTERAC | Interac (Canada) | | MIR | Mir (Russia) | | UNIONPAY | China UnionPay | The SDK filters networks based on your Primer configuration. If `orderedAllowedCardNetworks` is set in your client session, only those networks are available. *** ## Display items The Apple Pay sheet displays line items from your order: * **Line items** — Products from `order.lineItems` * **Fees** — All fees from `order.fees` * **Shipping** — Shipping cost when shipping options are enabled The total amount is calculated from `merchantAmount` if set, otherwise from `totalOrderAmount`. *** ## Testing ### Development 1. Use Safari on macOS or iOS. To test a third-party browser, scan the code in the Apple Pay sheet with an iPhone running iOS 18 or later. 2. Add a test card to your Apple Wallet 3. Use Primer's TEST environment ### Production 1. Register your domain in the [Apple Developer Portal](https://developer.apple.com/) 2. Configure your merchant identifier 3. Verify your domain > [!NOTE] > > Apple Pay works in Safari and in third-party browsers such as Chrome, Edge and Firefox (v1.0.2 and later). In a third-party browser, the Apple Pay sheet shows a code the customer scans with an iPhone running iOS 18 or later to complete the payment. Apple Pay is not available on Android devices, and third-party browser support is not available in mainland China. > > In Safari, the button appears only when the device supports Apple Pay and the customer has payment methods configured. In a third-party browser, the customer needs an iPhone or iPad to complete the payment. *** ## See also > [card] [SDK options reference](/docs/sdk/primer-checkout-web/sdk-options-reference) > > All configuration options > [card] [Apple Pay on the web](https://developer.apple.com/documentation/applepayontheweb) > > Official Apple documentation > [card] [Apple Pay button types](https://developer.apple.com/documentation/applepayontheweb/applepaybuttontype) > > Complete button type reference # Billing Address Source: https://primer.io/docs/sdk/primer-checkout-web/components/primer-card-form/primer-billing-address Collects billing address information for card payments. ## \ Collects customer billing address during card payment flows. Validates based on your Dashboard configuration. ## Quick Reference | | | | - | - | | **Parent** | `` | | **Requires** | Dashboard configuration | | **Properties** | None | *** ## Examples ### In Custom Layout ```html theme={"dark"}
Pay
``` *** ## Configuration Configure in your Primer Dashboard: * Required vs optional fields * Validation rules * Country restrictions * Field display order See [Capturing Billing Address](/docs/checkout/capture-billing-address) for setup. > **Note:** Component only renders if enabled in Dashboard. *** ## Modes | Mode | Behavior | | - | - | | **Drop-in** | Automatically included if Dashboard enabled | | **Custom layout** | Must be explicitly added in `card-form-content` slot | *** ## Events `` does not emit its own events. Validation is triggered by the parent `` during submission. ### Relevant Parent Events | Event | Emitted by | How it affects this component | | - | - | - | | `primer:card-submit` | `` or external dispatch | Triggers validation of all billing address fields — invalid fields display error messages | | `primer:card-error` | `` | Emitted when any card or billing field fails validation — payload includes all validation errors | | `primer:card-success` | `` | Emitted when the form (including billing address) submits successfully | *** ## CSS Properties | Property | Description | | - | - | | `--primer-space-small` | Title bottom margin | | `--primer-space-medium` | Gap between fields | | `--primer-space-large` | Title top margin | | `--primer-color-text-primary` | Title color | *** ## States | State | Description | Visual Change | | - | - | - | | **Hidden** | Not enabled in Dashboard | Not rendered | | **Default** | Ready for input | Standard input appearance | | **Filled** | Address entered | Standard appearance | | **Error** | Validation failed | Error states on invalid fields | | **Disabled** | Form disabled | All fields disabled | *** ## Usage Guidelines ### Do * Place inside `` * Configure required fields in Dashboard * Enable in Dashboard before using ### Don't * Don't expect rendering without Dashboard configuration * Don't place outside card form context *** ## Content Guidelines ### Labels | Do | Don't | | - | - | | "Address line 1" | "Street address" (not universal) | | "City" | "Town/City" (pick one per locale) | | "Postal code" or "ZIP code" (locale-aware) | "Zip" (informal) | ### International considerations | Do | Don't | | - | - | | Use locale-appropriate field labels | Hard-code US-centric labels like "State" for all regions | | Let the SDK adapt field order by country | Force a single address format globally | ### Error messages | Do | Don't | | - | - | | "Enter your billing address" | "Required" | | "Enter a valid postal code" | "Invalid format" | *** ## See also > [card] [primer-card-form](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form) > > Parent container > [card] [Capturing billing address](/docs/checkout/capture-billing-address) > > Dashboard setup # Card form Source: https://primer.io/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form Container for secure card payment inputs with validation and submission handling. ## \ Container for card payment inputs. Provides context to child components, handles validation, and manages form submission. Uses secure iframes for PCI compliance. ## Quick reference | | | | - | - | | **Parent** | `` | | **Properties** | `disabled`, `hide-labels` | | **Slot** | `card-form-content` | | **Emits** | `primer:card-success`, `primer:card-error` | | **Listens for** | `primer:card-submit` | *** ## Examples ### Default layout Renders all card inputs automatically: ```html theme={"dark"} ``` **Renders:** Card number, expiry, CVV, cardholder name, and submit button. ### Disabled state ```html theme={"dark"} ``` ### Hidden labels ```html theme={"dark"} ``` ### Custom layout ```html theme={"dark"}
``` ### With error container ```html theme={"dark"}
``` *** ## Properties | Property | Attribute | Type | Default | Description | | - | - | - | - | - | | `disabled` | `disabled` | `boolean` | `false` | Prevents form submission | | `hideLabels` | `hide-labels` | `boolean` | `false` | Hides labels on all inputs | *** ## Events ### Emitted events | Event | Description | Payload | | - | - | - | | `primer:card-success` | Form submitted successfully | `{ result: unknown }` | | `primer:card-error` | Validation errors occurred | `{ errors: ValidationError[] }` | ### Listened events | Event | Description | | - | - | | `primer:card-submit` | Triggers form submission | **External submit example:** ```javascript theme={"dark"} document.getElementById('my-button').addEventListener('click', () => { document.dispatchEvent( new CustomEvent('primer:card-submit', { bubbles: true, composed: true }) ); }); ``` > **Note:** `bubbles: true` and `composed: true` are required for shadow DOM traversal. *** ## Slots | Slot | Description | | - | - | | `card-form-content` | Custom layout for card inputs. Replaces default when provided. | *** ## Methods | Method | Description | | - | - | | `submit()` | Programmatically submit the form | | `focus()` | Focus the first field in render order, including custom fields slotted above the card inputs | ```javascript theme={"dark"} const cardForm = document.querySelector('primer-card-form'); await cardForm.submit(); cardForm.focus(); ``` *** ## CSS properties | Property | Description | Default | | - | - | - | | `--primer-space-small` | Gap between inline elements | `8px` | | `--primer-space-medium` | Gap between block elements | `16px` | *** ## Dependencies Internally uses: | Component | Purpose | | - | - | | [primer-input-card-number](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-number) | Card number input | | [primer-input-card-expiry](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-expiry) | Expiry date input | | [primer-input-cvv](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-cvv) | CVV input | | [primer-input-card-holder-name](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-holder-name) | Cardholder name input | | [primer-card-form-submit](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form-submit) | Submit button | *** ## Cardholder name configuration ```javascript theme={"dark"} checkout.options = { card: { cardholderName: { visible: true, // Show field (default: true) required: true, // Make required (default: true) defaultValue: '' // Pre-fill value } } }; ``` *** ## Co-branded card schemes Supports co-branded cards like Cartes Bancaires (CB). Network switcher displays automatically when detected. No configuration needed. *** ## Submit options | Method | Example | | - | - | | `` | Built-in, localized | | `` | | Primer button | `Pay` | | `data-submit` | `` | | Event | `document.dispatchEvent(new CustomEvent('primer:card-submit', { bubbles: true, composed: true }))` | *** ## CSS Properties ### Typography | Property | Description | Default | | - | - | - | | `--primer-typography-title-large-size` | Button text size | `16px` | | `--primer-typography-title-large-weight` | Button text weight | `550` | ### Colors (Primary Variant) | Property | Description | | - | - | | `--primer-color-brand` | Button background color | | `--primer-color-gray-000` | Button text color (white) | ### Colors (Secondary Variant) | Property | Description | | - | - | | `--primer-color-background-outlined-default` | Default background | | `--primer-color-background-outlined-hover` | Hover background | | `--primer-color-border-outlined-default` | Default border | | `--primer-color-text-primary` | Button text color | ### Border & Shape | Property | Description | Default | | - | - | - | | `--primer-radius-medium` | Button border radius | `8px` | | `--primer-space-medium` | Horizontal padding | `12px` | ### States | Property | Description | | - | - | | `--primer-color-background-outlined-disabled` | Disabled background | | `--primer-color-text-disabled` | Disabled text | | `--primer-color-background-outlined-loading` | Loading background | ### Animation | Property | Description | Default | | - | - | - | | `--primer-animation-duration` | Transition duration | `200ms` | | `--primer-animation-easing` | Transition easing | `cubic-bezier(0.44, 0, 0.4, 1)` | *** ## States | State | Description | Visual Change | | - | - | - | | **Default** | Ready for click | Brand color background (primary) or outlined (secondary) | | **Hover** | Mouse over button | Slightly darker background | | **Active** | Button pressed | Further darkened background | | **Focus** | Keyboard focused | Focus ring visible | | **Loading** | Form submitting | Spinner displayed, text hidden | | **Disabled** | `disabled` attribute set | Muted colors, no interaction | *** ## Content Guidelines | Do | Don't | | - | - | | "Pay now" | "Submit" | | "Complete payment" | "Pay" | | "Pay \$49.99" | "OK" | *** ## Usage Guidelines ### Do * Use for consistent, localized submit buttons * Place inside `` ### Don't * Don't set `buttonText` to empty string (reverts to default) *** ## See also > [card] [primer-card-form](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form) > > Parent container > [card] [Events guide](/docs/checkout/primer-checkout/configuration/events) > > Submission events # Card Expiry Input Source: https://primer.io/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-expiry Secure input for card expiration dates with automatic formatting. ## \ Secure, PCI-compliant input for card expiration dates. Automatically formats as MM/YY and validates date. ## Quick Reference | | | | - | - | | **Parent** | `` | | **Properties** | `label`, `placeholder`, `aria-label` | | **Features** | Auto-formatting, date validation | *** ## Examples ### Default ```html theme={"dark"} ``` ### Custom Labels ```html theme={"dark"} ``` ### Inline with CVV ```html theme={"dark"}
``` *** ## Properties | Property | Attribute | Type | Default | Description | | - | - | - | - | - | | `label` | `label` | `string` | `"Expiry Date"` | Label text | | `placeholder` | `placeholder` | `string` | `"MM/YY"` | Placeholder text | | `ariaLabel` | `aria-label` | `string` | Value of `label` | Screen reader label | *** ## Validation Validates: * Format is MM/YY * Month is 01-12 * Date is not in the past Errors display automatically on submit or invalid input. *** ## Methods | Method | Description | | - | - | | `focus()` | Moves keyboard focus into the input | ```javascript theme={"dark"} document.querySelector('primer-input-card-expiry').focus(); ``` *** ## Events `` does not emit its own events. Validation and submission are managed by the parent ``. ### Relevant Parent Events | Event | Emitted by | How it affects this input | | - | - | - | | `primer:card-submit` | `` or external dispatch | Triggers validation — if this input is invalid, an error message displays below it | | `primer:card-error` | `` | Emitted when any card input fails validation — payload includes all validation errors | | `primer:card-success` | `` | Emitted when the form submits successfully | ### Reacting to card validation errors ```javascript theme={"dark"} const cardForm = document.querySelector('primer-card-form'); cardForm.addEventListener('primer:card-error', (event) => { const { errors } = event.detail; errors.forEach(err => console.log(err.field, err.message)); }); ``` *** ## CSS Properties This component uses the shared [Input Styling Tokens](/docs/sdk/primer-checkout-web/styling-variables#input-styling-tokens). ### Typography | Property | Description | Default | | - | - | - | | `--primer-typography-body-large-size` | Input text size | `16px` | | `--primer-typography-body-large-weight` | Input text weight | `400` | | `--primer-typography-body-small-size` | Label text size | `12px` | ### Colors | Property | Description | | - | - | | `--primer-color-text-primary` | Input text color | | `--primer-color-text-placeholder` | Placeholder text color | | `--primer-color-text-disabled` | Disabled text color | | `--primer-color-text-negative` | Error message color | ### Border & Background | Property | Description | | - | - | | `--primer-radius-small` | Input border radius | | `--primer-color-border-outlined-default` | Default border | | `--primer-color-border-outlined-focus` | Focus border | | `--primer-color-border-outlined-error` | Error border | | `--primer-color-background-outlined-default` | Default background | ### Spacing | Property | Description | Default | | - | - | - | | `--primer-space-xsmall` | Gap between label and input | `4px` | | `--primer-space-medium` | Input padding | `12px` | ### Animation | Property | Description | Default | | - | - | - | | `--primer-animation-duration` | Transition duration | `200ms` | | `--primer-animation-easing` | Transition easing | `cubic-bezier(0.44, 0, 0.4, 1)` | *** ## States | State | Description | Visual Change | | - | - | - | | **Default** | Initial state | Standard border and background | | **Hover** | Mouse over input | Border darkens slightly | | **Focus** | Input is focused | Blue border, increased width | | **Filled** | Valid date entered | Standard appearance | | **Error** | Invalid or expired date | Red border, error message below | | **Disabled** | Form or input disabled | Muted colors, no interaction | *** ## Usage Guidelines ### Do * Place inside `` * Pair with `` in a flex row ### Don't * Don't place outside card form context *** ## Content Guidelines ### Label | Do | Don't | | - | - | | "Expiry date" | "Expiration" (overly formal) | | "Exp. date" (space-constrained layouts) | "MM/YY" as a label (that's a format, not a label) | ### Placeholder | Do | Don't | | - | - | | `MM/YY` (shows expected format) | "Enter expiry" (redundant with label) | | Empty placeholder (clean look) | `00/00` (could be mistaken for a value) | ### Error messages | Do | Don't | | - | - | | "Enter a valid expiry date" | "Invalid" | | "This card has expired" | "Date is in the past" | *** ## See also > [card] [primer-card-form](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form) > > Parent container > [card] [primer-input-cvv](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-cvv) > > CVV input > [card] [primer-input-card-number](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-number) > > Card number input # Cardholder Name Input Source: https://primer.io/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-holder-name Input for cardholder name on payment forms. ## \ Input for collecting the cardholder's name. Updates card form context in real-time as user types. ## Quick Reference | | | | - | - | | **Parent** | `` | | **Properties** | `label`, `placeholder`, `aria-label` | | **Configuration** | Via SDK options | *** ## Examples ### Default ```html theme={"dark"} ``` ### Custom Labels ```html theme={"dark"} ``` ### In Custom Layout ```html theme={"dark"}
``` *** ## Properties | Property | Attribute | Type | Default | Description | | - | - | - | - | - | | `label` | `label` | `string` | `"Cardholder Name"` | Label text | | `placeholder` | `placeholder` | `string` | `"Name on card"` | Placeholder text | | `ariaLabel` | `aria-label` | `string` | Value of `label` | Screen reader label | *** ## Configuration Control visibility and requirement via SDK options: ```javascript theme={"dark"} checkout.options = { card: { cardholderName: { visible: true, // Show field (default: true) required: true, // Make required (default: true) defaultValue: '' // Pre-fill value } } }; ``` *** ## Pre-filling ### Via SDK options (recommended) ```javascript theme={"dark"} checkout.options = { card: { cardholderName: { defaultValue: 'John Doe' } } }; ``` ### Via primer:ready event ```javascript theme={"dark"} checkout.addEventListener('primer:ready', (event) => { const primer = event.detail; primer.setCardholderName('John Doe'); }); ``` *** ## Methods | Method | Description | | - | - | | `focus()` | Moves keyboard focus into the input | ```javascript theme={"dark"} document.querySelector('primer-input-card-holder-name').focus(); ``` *** ## Events `` does not emit its own events. Validation and submission are managed by the parent ``. ### Relevant Parent Events | Event | Emitted by | How it affects this input | | - | - | - | | `primer:card-submit` | `` or external dispatch | Triggers validation — if this field is required and empty, an error message displays below it | | `primer:card-error` | `` | Emitted when any card input fails validation — payload includes all validation errors | | `primer:card-success` | `` | Emitted when the form submits successfully | | `primer:ready` | `` | Provides the `PrimerJS` instance, which exposes `setCardholderName()` for pre-filling | *** ## CSS Properties This component uses the shared [Input Styling Tokens](/docs/sdk/primer-checkout-web/styling-variables#input-styling-tokens). ### Typography | Property | Description | Default | | - | - | - | | `--primer-typography-body-large-size` | Input text size | `16px` | | `--primer-typography-body-large-weight` | Input text weight | `400` | | `--primer-typography-body-small-size` | Label text size | `12px` | ### Colors | Property | Description | | - | - | | `--primer-color-text-primary` | Input text color | | `--primer-color-text-placeholder` | Placeholder text color | | `--primer-color-text-disabled` | Disabled text color | | `--primer-color-text-negative` | Error message color | ### Border & Background | Property | Description | | - | - | | `--primer-radius-small` | Input border radius | | `--primer-color-border-outlined-default` | Default border | | `--primer-color-border-outlined-focus` | Focus border | | `--primer-color-border-outlined-error` | Error border | | `--primer-color-background-outlined-default` | Default background | ### Spacing | Property | Description | Default | | - | - | - | | `--primer-space-xsmall` | Gap between label and input | `4px` | | `--primer-space-medium` | Input padding | `12px` | ### Animation | Property | Description | Default | | - | - | - | | `--primer-animation-duration` | Transition duration | `200ms` | | `--primer-animation-easing` | Transition easing | `cubic-bezier(0.44, 0, 0.4, 1)` | *** ## States | State | Description | Visual Change | | - | - | - | | **Default** | Initial state | Standard border and background | | **Hover** | Mouse over input | Border darkens slightly | | **Focus** | Input is focused | Blue border, increased width | | **Filled** | Name entered | Standard appearance | | **Error** | Required but empty on submit | Red border, error message below | | **Disabled** | Form or input disabled | Muted colors, no interaction | | **Hidden** | `visible: false` in options | Not rendered | *** ## Usage Guidelines ### Do * Place inside `` * Configure via SDK options * Use `defaultValue` to pre-fill from user profile ### Don't * Don't place outside card form context *** ## Content Guidelines ### Label | Do | Don't | | - | - | | "Name on card" | "Cardholder name" (too formal) | | "Full name" (when context is clear) | "First and last name" (not all naming conventions use this split) | ### Placeholder | Do | Don't | | - | - | | Empty placeholder (cleanest) | "John Doe" (culturally specific) | | "As shown on card" (helpful hint) | "Enter your name" (redundant with label) | ### Error messages | Do | Don't | | - | - | | "Enter the name on your card" | "Required" | | "Name is required" | "Invalid name" (ambiguous) | *** ## See also > [card] [primer-card-form](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form) > > Parent container > [card] [SDK options](/docs/sdk/primer-checkout-web/sdk-options-reference) > > Configuration options # Card Number Input Source: https://primer.io/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-number Secure input for card numbers with automatic network detection. ## \ Secure, PCI-compliant input for card numbers. Automatically detects and displays card network (Visa, Mastercard, etc.) as user types. ## Quick Reference | | | | - | - | | **Parent** | `` | | **Properties** | `label`, `placeholder`, `aria-label`, `network-selector-position` | | **Features** | Network detection, auto-formatting | *** ## Examples ### Default ```html theme={"dark"} ``` ### Custom Labels ```html theme={"dark"} ``` ### No Placeholder ```html theme={"dark"} ``` ### In Custom Layout ```html theme={"dark"}
``` *** ## Properties | Property | Attribute | Type | Default | Description | | - | - | - | - | - | | `label` | `label` | `string` | `"Card Number"` | Label text | | `placeholder` | `placeholder` | `string` | `"4111 1111 1111 1111"` | Placeholder text | | `ariaLabel` | `aria-label` | `string` | Value of `label` | Screen reader label | | `networkSelectorPosition` | `network-selector-position` | `'left' \| 'right'` | `card.networkSelectorPosition` option, else `'right'` | Side of the input the network selector sits on | Setting to empty string `""`: * `label`: Reverts to default * `placeholder`: Shows no placeholder * `aria-label`: Uses `label` value *** ## Card Network Detection Automatically detects: | Network | Example Prefix | | - | - | | Visa | 4xxx | | Mastercard | 5xxx | | Amex | 34xx, 37xx | | Discover | 6011 | Displays network logo and adjusts formatting (e.g., Amex uses different spacing). The network logo, or the picker for a co-badged card, sits on the right of the input by default. Move it with the `network-selector-position` attribute, or for every card number input at once with the [`card.networkSelectorPosition`](/docs/sdk/primer-checkout-web/sdk-options-reference#cardnetworkselectorposition) option: ```html theme={"dark"} ``` *** ## Validation Validates: * Number length matches detected network (e.g., 16 for Visa, 15 for Amex) * At least one digit entered Errors display automatically on submit or blur. *** ## Methods | Method | Description | | - | - | | `focus()` | Moves keyboard focus into the input | ```javascript theme={"dark"} document.querySelector('primer-input-card-number').focus(); ``` *** ## Events `` does not emit its own events. Validation and submission are managed by the parent ``. ### Relevant Parent Events | Event | Emitted by | How it affects this input | | - | - | - | | `primer:card-submit` | `` or external dispatch | Triggers validation — if this input is invalid, an error message displays below it | | `primer:card-error` | `` | Emitted when any card input fails validation — payload includes all validation errors | | `primer:card-success` | `` | Emitted when the form submits successfully | ### Reacting to card validation errors ```javascript theme={"dark"} const cardForm = document.querySelector('primer-card-form'); cardForm.addEventListener('primer:card-error', (event) => { const { errors } = event.detail; errors.forEach(err => console.log(err.field, err.message)); }); ``` *** ## CSS Properties This component uses the shared [Input Styling Tokens](/docs/sdk/primer-checkout-web/styling-variables#input-styling-tokens). ### Layout | Property | Description | Default | | - | - | - | | `--primer-space-small` | Gap between input and network icon | `8px` | ### Typography | Property | Description | Default | | - | - | - | | `--primer-typography-body-large-size` | Input text size | `16px` | | `--primer-typography-body-large-weight` | Input text weight | `400` | | `--primer-typography-body-small-size` | Label text size | `12px` | ### Colors | Property | Description | | - | - | | `--primer-color-text-primary` | Input text color | | `--primer-color-text-placeholder` | Placeholder text color | | `--primer-color-text-disabled` | Disabled text color | | `--primer-color-text-negative` | Error message color | ### Border & Background | Property | Description | | - | - | | `--primer-radius-small` | Input border radius | | `--primer-color-border-outlined-default` | Default border | | `--primer-color-border-outlined-focus` | Focus border | | `--primer-color-border-outlined-error` | Error border | | `--primer-color-background-outlined-default` | Default background | ### Animation | Property | Description | Default | | - | - | - | | `--primer-animation-duration` | Transition duration | `200ms` | | `--primer-animation-easing` | Transition easing | `cubic-bezier(0.44, 0, 0.4, 1)` | *** ## States | State | Description | Visual Change | | - | - | - | | **Default** | Initial state | Standard border and background | | **Hover** | Mouse over input | Border darkens slightly | | **Focus** | Input is focused | Blue border, increased width | | **Filled** | Valid card number entered | Network icon displayed | | **Error** | Invalid input or validation failed | Red border, error message below | | **Disabled** | Form or input disabled | Muted colors, no interaction | *** ## Usage Guidelines ### Do * Place inside `` * Use for card number collection only ### Don't * Don't use `` separately (internal component) * Don't place outside card form context *** ## Content Guidelines ### Label | Do | Don't | | - | - | | "Card number" | "Credit card number" (not all cards are credit) | | Use sentence case | "CARD NUMBER" | ### Placeholder | Do | Don't | | - | - | | `1234 1234 1234 1234` (formatted example) | "Enter your card number" (redundant with label) | | Empty placeholder (clean look) | A partial number like `4111` | ### Error messages | Do | Don't | | - | - | | "Enter a valid card number" | "Invalid" | | "Card number is incomplete" | "Error in field" | *** ## See also > [card] [primer-card-form](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form) > > Parent container > [card] [primer-input-card-expiry](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-expiry) > > Expiry input > [card] [primer-input-cvv](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-cvv) > > CVV input # CVV Input Source: https://primer.io/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-cvv Secure input for card security codes. ## \ Secure, PCI-compliant input for card security codes (CVV/CVC). Uses iframe for maximum security. ## Quick Reference | | | | - | - | | **Parent** | `` | | **Properties** | `label`, `placeholder`, `aria-label` | | **Features** | Secure iframe, validation | *** ## Examples ### Default ```html theme={"dark"} ``` ### Custom Labels ```html theme={"dark"} ``` ### Inline with Expiry ```html theme={"dark"}
``` *** ## Properties | Property | Attribute | Type | Default | Description | | - | - | - | - | - | | `label` | `label` | `string` | `"CVV"` | Label text | | `placeholder` | `placeholder` | `string` | `"123"` | Placeholder text | | `ariaLabel` | `aria-label` | `string` | Value of `label` | Screen reader label | *** ## Validation Validates: * Required digits entered (3 for most networks, 4 for Amex) * Only numeric characters Errors display automatically on submit or blur. *** ## Dynamic Length (Amex) The CVV field automatically adapts based on the card network detected by ``: | Network | CVV length | Default placeholder | | - | - | - | | Visa, Mastercard, Discover | 3 digits | `123` | | Amex | 4 digits | `1234` | No configuration needed — length adjusts when the card number identifies the network. *** ## Methods | Method | Description | | - | - | | `focus()` | Moves keyboard focus into the input | ```javascript theme={"dark"} document.querySelector('primer-input-cvv').focus(); ``` *** ## Events `` does not emit its own events. Validation and submission are managed by the parent ``. ### Relevant Parent Events | Event | Emitted by | How it affects this input | | - | - | - | | `primer:card-submit` | `` or external dispatch | Triggers validation — if this input is invalid, an error message displays below it | | `primer:card-error` | `` | Emitted when any card input fails validation — payload includes all validation errors | | `primer:card-success` | `` | Emitted when the form submits successfully | ### Reacting to card validation errors ```javascript theme={"dark"} const cardForm = document.querySelector('primer-card-form'); cardForm.addEventListener('primer:card-error', (event) => { const { errors } = event.detail; errors.forEach(err => console.log(err.field, err.message)); }); ``` *** ## CSS Properties This component uses the shared [Input Styling Tokens](/docs/sdk/primer-checkout-web/styling-variables#input-styling-tokens). ### Typography | Property | Description | Default | | - | - | - | | `--primer-typography-body-large-size` | Input text size | `16px` | | `--primer-typography-body-large-weight` | Input text weight | `400` | | `--primer-typography-body-small-size` | Label text size | `12px` | ### Colors | Property | Description | | - | - | | `--primer-color-text-primary` | Input text color | | `--primer-color-text-placeholder` | Placeholder text color | | `--primer-color-text-disabled` | Disabled text color | | `--primer-color-text-negative` | Error message color | ### Border & Background | Property | Description | | - | - | | `--primer-radius-small` | Input border radius | | `--primer-color-border-outlined-default` | Default border | | `--primer-color-border-outlined-focus` | Focus border | | `--primer-color-border-outlined-error` | Error border | | `--primer-color-background-outlined-default` | Default background | ### Spacing | Property | Description | Default | | - | - | - | | `--primer-space-xsmall` | Gap between label and input | `4px` | | `--primer-space-medium` | Input padding | `12px` | ### Animation | Property | Description | Default | | - | - | - | | `--primer-animation-duration` | Transition duration | `200ms` | | `--primer-animation-easing` | Transition easing | `cubic-bezier(0.44, 0, 0.4, 1)` | *** ## States | State | Description | Visual Change | | - | - | - | | **Default** | Initial state | Standard border and background | | **Hover** | Mouse over input | Border darkens slightly | | **Focus** | Input is focused | Blue border, increased width | | **Filled** | Valid CVV entered | Standard appearance | | **Error** | Invalid CVV length | Red border, error message below | | **Disabled** | Form or input disabled | Muted colors, no interaction | *** ## Usage Guidelines ### Do * Place inside `` * Pair with `` in a flex row ### Don't * Don't place outside card form context *** ## Content Guidelines ### Label | Do | Don't | | - | - | | "CVV" (universally recognized) | "Card Verification Value" (too technical) | | "Security code" (accessible alternative) | "CVC" without also accepting "CVV" as an alias | ### Placeholder | Do | Don't | | - | - | | `123` (shows expected length) | "Enter CVV" (redundant with label) | | `1234` when Amex is detected (4 digits) | Always showing 3-digit placeholder regardless of card network | ### Error messages | Do | Don't | | - | - | | "Enter your card's security code" | "Invalid" | | "CVV is incomplete" | "Wrong CVV" (you can't know if it's wrong client-side) | *** ## See also > [card] [primer-card-form](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-card-form) > > Parent container > [card] [primer-input-card-expiry](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-expiry) > > Expiry input > [card] [primer-input-card-number](/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-card-number) > > Card number input # Input Label Source: https://primer.io/docs/sdk/primer-checkout-web/components/primer-card-form/primer-input-label Label component with consistent typography for input fields. ## \ Provides consistent label styling for input fields. Used internally by card inputs and available for custom fields. ## Quick Reference | | | | - | - | | **Parent** | `` | | **Properties** | `disabled` | | **Slot** | `label` (in wrapper) | *** ## Examples ### With Input Wrapper ```html theme={"dark"} Discount Code
``` ### Disabled ```html theme={"dark"} Discount Code ``` *** ## Properties | Property | Attribute | Type | Default | Description | | - | - | - | - | - | | `disabled` | `disabled` | `boolean` | `false` | Applies disabled styling | *** ## CSS Properties | Property | Description | | - | - | | `--primer-typography-body-small-font` | Font family | | `--primer-typography-body-small-size` | Font size | | `--primer-typography-body-small-weight` | Font weight | | `--primer-color-text-primary` | Default color | | `--primer-color-text-disabled` | Disabled color | *** ## States | State | Description | Visual Change | | - | - | - | | **Default** | Normal state | Primary text color | | **Disabled** | `disabled` attribute set | Muted text color | *** ## Usage Guidelines ### Do * Use inside `` in the `label` slot for consistent styling * Match the `disabled` state to the corresponding input * Use a `