@checkout.com/checkout-react-native-components

中文文档
1.0.0-beta12发布于 2026/11/03MITTypeScriptCommonJS近 30 天下载 2.9万

[BETA — not for production use] React Native wrapper for native iOS & Android Checkout components

原始使用文档
文档目录24 节
  1. 🚀 Quick Start
  2. Installation
  3. Platform Setup
  4. 🧩 Components Overview
  5. ⚙️ Core Configuration
  6. CheckoutProvider Setup
  7. 📝 Configuration Options
  8. Insight observability (OS and React Native metadata)
  9. 📖 Component Reference
  10. Flow Component
  11. Card Component
  12. Apple Pay Component
  13. Google Pay Component
  14. 🔧 Advanced Features
  15. Imperative API
  16. 🎨 Customization
  17. 🎨 Complete Color Token Reference
  18. 📏 Border Radius
  19. 🔤 Custom Fonts
  20. 🌍 Supported Locales & Custom Translations
  21. 📡 Event Handling
  22. 📋 Complete Event Reference
  23. 📦 Other exports
  24. 📄 License

Checkout.com Checkout.com

Flow for Mobile React Native SDK

Status: Beta License: MIT

🚀 Quick Start

Installation

Install the package using one of the following, depending on your package manager:

npm install @checkout.com/checkout-react-native-components
yarn add @checkout.com/checkout-react-native-components

Platform Setup

This package supports both React Native architectures (New Architecture/Fabric and Old Architecture/Paper) out of the box.

📱 iOS Setup

cd ios
pod install

Depending on which version of checkout-react-native-components you use, you may need to pin FingerprintPro to either 2.12.0 or above. You can do this by manually modifying your Podfile with the following:

  pod 'FingerprintPro', '2.12.0'

For expo, use the expo-build-properties plugin:

  [
    "expo-build-properties",
    {
      "ios": {
        "extraPods": [
          {
            "name": "FingerprintPro",
            "version": "2.12.0"
          }
        ]
      }
    }
  ]

🤖 Android Setup

Add the following repositories to your app's settings.gradle:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://jitpack.io") }
        maven { url = uri("https://maven.fpregistry.io/releases") }
    }
}

Or add the allProjects block to the project build.gradle:

allprojects {
  repositories {
    google()
    mavenCentral()
    maven { url 'https://maven.fpregistry.io/releases' }
    maven { url 'https://www.jitpack.io' }
  }
}

To enable Google Pay payments the following metadata tag must be added to your AndroidManifest.xml:

<meta-data
    android:name="com.google.android.gms.wallet.api.enabled"
    android:value="true" />

While not mandatory, we recommend setting android:allowBackup to false in your AndroidManifest.xml. Failing to set it to false or to override our default value with your own will result in a manifest merge error.

Requirements:

  • New Arch: Android Studio Otter 3 Feature Drop 2025.2.3
  • Old Arch: Android Studio Narwhal

💡 Tip: Use JetBrains Toolbox for easy Android Studio version management.

Expo Setup

Our package cannot run in Expo Go. Instead, you need to run:

npx expo prebuild

This command compiles your app with our package included.

For Android, the repositories step above is a hard requirement to resolve dependencies. Our package provides a general-purpose plugin that appends the repositories defined in the Android Setup block above. The plugin can also append the Google Pay tag to the AndroidManifest.xml if required.

If your app already uses custom plugins that modify build.gradle or AndroidManifest.xml, we recommend extending your existing plugin or creating an additional plugin to customize adding the repositories block to fit your use case. You can find documentation on writing Expo plugins here.

The android:allowBackup tag and plugins can be set in app.json like so:

"android": {
  "allowBackup": false
},
"plugins": [
  [
    "@checkout.com/checkout-react-native-components",
    {
      "enableGooglePay": true
    }
  ]
]

🧩 Components Overview

ComponentDescriptionPlatformKey Features
FlowComplete payment flow with multiple payment methodsiOS/Android3DS support, dynamic payment methods, built-in validation
CardSecure card input formiOS/AndroidCard validation, tokenization, custom styling
Apple PayNative Apple Pay integrationiOS onlySeamless iOS payment experience
Google PayNative Google Pay integrationAndroid onlySeamless Android payment experience
TabbyTabby buy now, pay later (redirect-based APM)iOS/AndroidStandalone component or inside Flow via paymentMethods; see APMs in Flow

⚙️ Core Configuration

CheckoutProvider Setup

Wrap your payment screen with CheckoutProvider to enable payment functionality.

📝 Note: React and React Native imports (useState, useEffect, useRef, Button, etc.) are omitted from the examples below for brevity — import them from react / react-native as usual.

import {
  CheckoutProvider,
  CheckoutConfiguration,
  Locale
} from '@checkout.com/checkout-react-native-components';

const config: CheckoutConfiguration = {
  publicKey: 'pk_test_your_public_key',
  environment: 'sandbox', // or 'production'
  locale: Locale.en_GB,
  merchantIdentifier: 'merchant.com.your-app.name', // Required for Apple Pay
  translations: {
    [Locale.en_GB]: {
      cardNumber: 'Card Number',
      payButtonPay: 'Pay Now'
    }
  },
  style: {
    colorTokens: {
      primary: '#186AFF',
      background: '#FFFFFF',
      border: '#E3E8F2',
      error: '#E01E5A'
    },
    borderButtonRadius: 12,
    borderFormRadius: 8
  }
};

export default function PaymentScreen() {
  const [paymentSession, setPaymentSession] = useState({
    id: '',
    payment_session_secret: ''
  });

  useEffect(() => {
    fetchPaymentSession().then((data) => {
      setPaymentSession(data);
    });
  }, []);

  return (
    <CheckoutProvider 
      config={config}
      onSuccess={(paymentMethod, paymentID) => {
        console.log('Payment successful:', { paymentMethod, paymentID });
      }}
      onError={(error) => {
        console.error('Payment error:', error);
      }}
      paymentSession={paymentSession}
    >
      {/* Your app components */}
    </CheckoutProvider>
  );
}

📝 Configuration Options

PropertyTypeRequiredDescription
publicKeystring✅Your Checkout.com public API key
environment'sandbox' | 'production'✅Environment for API calls
localeLocale❌Locale for UI text (defaults to English)
merchantIdentifierstring❌Apple Pay merchant identifier
translationsRecord<string, Translations>❌Custom text translations
styleStyle❌UI customization options

Insight observability (OS and React Native metadata)

Native Checkout mobile SDKs attach device and OS data to Insight log events on both platforms:

  • Android (checkout-android-components): device_data.os_version is populated from Build.VERSION.SDK_INT (API level as a string) in LoggerManager / DeviceData. device_data.platform is the Android platform constant used by the Insight module.
  • iOS (checkout-ios-components): device_data.os_version comes from UIDevice.current.systemVersion via Constants.systemVersion in DeviceData.

React Native builds add an optional properties.react_native object on log events when metadata is supplied:

FieldMeaning
versionReact Native version (e.g. from the react-native package)
archOptional (new / old)
engineOptional (hermes / jsc)

By default, CheckoutProvider initialisation merges getDefaultReactNativeMetadata() into initialize: the resolved react-native package version, arch (new when nativeFabricUIManager is present, otherwise old), and engine (hermes when HermesInternal is present, otherwise jsc).

Logs emitted through the native logger (including cross-platform RN bridge logging on iOS) use the same mobile_session_id as the rest of the native session, so RN-originated entries stay correlated with surrounding Insight events.

product_version on React Native SDK builds: CI typically publishes a composite string such as react-native-{rnSdkVersion}:{nativeSdkVersion} (example: react-native-1.0.0-beta7:1.0.1) into native device_data.product_version / log version fields—see your pipeline or native SDK release notes for the exact format.

📖 Component Reference

Flow Component

The Flow component provides a complete payment experience with support for multiple payment methods, 3D Secure, and dynamic payment method display.

Basic Usage

import { Flow } from '@checkout.com/checkout-react-native-components';

const PaymentScreen = () => {
  return (
    <CheckoutProvider config={config} paymentSession={paymentSession}>
      <Flow style={{ marginVertical: 20 }} />
    </CheckoutProvider>
  );
};

Imperative API Usage

const PaymentScreen = () => {
  const flowRef = useRef<FlowRef>(null);

  const handleSubmit = () => {
    flowRef.current?.submit(); // Process payment
  };

  const handleTokenize = () => {
    flowRef.current?.tokenize(); // Tokenize card
  };

  return (
    <CheckoutProvider config={config} paymentSession={paymentSession}>
      <Flow
        ref={flowRef}
        config={{
          showPayButton: false, // Hide built-in pay button
          cardConfigurations: {
            displayCardHolderName: 'top',
            acceptedCardSchemes: ['visa', 'mastercard', 'americanExpress'],
            acceptedCardTypes: ['credit', 'debit'],
            hideSecurityCode: false,
            cardholderNameMaxLength: 64,
          },
        }}
      />
      <Button title="Pay" onPress={handleSubmit} />
      <Button title="Tokenize Card" onPress={handleTokenize} />
    </CheckoutProvider>
  );
};

Flow Props

PropertyTypeRequiredDescription
configFlowConfig❌Flow-specific configuration
styleViewStyle | ViewStyle[]❌React Native styling
refFlowRef❌Imperative API reference

FlowConfig Options

PropertyTypeDefaultDescription
showPayButtonbooleantrueShow/hide the built-in pay button
paymentButtonAction'payment' | 'tokenize''tokenize' when config is supplied; otherwise 'payment'Action when pay button is pressed
paymentMethodsReadonlyArray<FlowPaymentMethod> | ReadonlySet<FlowPaymentMethod>—Payment methods Flow offers: 'card', 'applePay', 'googlePay', 'tabby'.
cardConfigurationsCardConfigurations—Field-level card form settings (accepted schemes, card types, cardholder name display, etc.). See Card Configuration.
apmConfigurationApmConfiguration—Pay-button configuration shared by every APM row inside Flow (Tabby today). iOS only — ignored on Android. See APMs in Flow.
applePayConfigurationApplePayConfiguration—Configuration for the Apple Pay method shown inside Flow (accepted schemes/types, showApplePayButton). iOS only — ignored on Android. If omitted, Apple Pay is shown with all schemes/types accepted. See Apple Pay in Flow.
googlePayConfigurationGooglePayConfiguration—Configuration for the Google Pay method shown inside Flow (accepted schemes/types). Same shape as the standalone GooglePayConfiguration.
rememberMeConfigurationRememberMeConfiguration—Enables the Remember Me checkbox and optionally pre-fills data.email / data.phone for a returning shopper. Also has showPayButton (required), acceptedCardSchemes and acceptedCardTypes.

APMs in Flow

Alternative payment methods (APMs) share one pay-button setting, so a single flag applies to every APM row Flow renders. It is independent of showPayButton: hiding the card form's button does not hide the APM ones.

📝 Note: apmConfiguration is iOS only and is ignored on Android. Which APMs are offered comes from paymentMethods and the payment session, not from this option.

<Flow
  config={{
    showPayButton: false, // card form renders no button
    apmConfiguration: { showPayButton: true }, // APM rows keep theirs
    paymentMethods: ['card', 'tabby'],
    cardConfigurations,
  }}
/>

The standalone APM components take the same shape through their own configuration prop:

<Tabby configuration={{ showPayButton: false }} />

Apple Pay in Flow

When Flow renders the Apple Pay payment method, you can restrict the accepted card schemes/types and toggle the Apple Pay button via FlowConfig.applePayConfiguration. This uses the same ApplePayConfiguration shape as the standalone ApplePay component.

📝 Note: applePayConfiguration is iOS only and is ignored on Android. It only affects the Apple Pay method inside Flow — the card form is still controlled by cardConfigurations.

import { Flow, CheckoutProvider } from '@checkout.com/checkout-react-native-components';
import type { ApplePayConfiguration } from '@checkout.com/checkout-react-native-components';

const applePayConfiguration: ApplePayConfiguration = {
  acceptedCardSchemes: ['visa', 'mastercard'],
  acceptedCardTypes: ['credit', 'debit'],
  showApplePayButton: true,
};

const PaymentScreen = () => {
  return (
    <CheckoutProvider
      config={{ ...config, merchantIdentifier: 'merchant.com.your-app.name' }}
      paymentSession={paymentSession}
    >
      <Flow
        config={{
          cardConfigurations: {
            displayCardHolderName: 'top',
            acceptedCardSchemes: ['visa', 'mastercard'],
            acceptedCardTypes: ['credit', 'debit'],
            hideSecurityCode: false,
            cardholderNameMaxLength: 64,
          },
          applePayConfiguration,
        }}
      />
    </CheckoutProvider>
  );
};

Card Component

The Card component provides a secure card input form ideal for custom checkout implementations.

Basic Usage

import { Card, CardRef } from '@checkout.com/checkout-react-native-components';

const CardPaymentScreen = () => {
  const cardRef = useRef<CardRef>(null);

  const handleSubmit = () => {
    cardRef.current?.submit();
  };

  return (
    <CheckoutProvider config={config} paymentSession={paymentSession}>
      <Card
        ref={cardRef}
        showPayButton={false}
        cardConfiguration={{
          displayCardHolderName: 'top',
          acceptedCardSchemes: ['visa', 'mastercard', 'americanExpress'],
          acceptedCardTypes: ['credit', 'debit'],
          hideSecurityCode: false,
          cardholderNameMaxLength: 64,
        }}
      />
    </CheckoutProvider>
  );
};

Card Props

PropertyTypeRequiredDescription
cardConfigurationCardConfigurations❌Field-level card form settings. When omitted, the native layer applies its own defaults. See Card Configuration.
showPayButtonboolean❌Show/hide the built-in pay button. Defaults to true.
paymentButtonAction'payment' | 'tokenize'❌Action when the built-in pay button is tapped. Defaults to 'tokenize'.
rememberMeConfigurationRememberMeConfiguration❌Enables the Remember Me checkbox. When omitted, the checkbox is hidden on both platforms.
styleViewStyle | ViewStyle[]❌React Native styling
refCardRef❌Imperative API reference

💳 Card Configuration

CardConfigurations controls the field-level behaviour of the card form. It is accepted by the Card component (as the cardConfiguration prop) and by Flow (inside FlowConfig.cardConfigurations).

import type { CardConfigurations } from '@checkout.com/checkout-react-native-components';

const cardConfiguration: CardConfigurations = {
  displayCardHolderName: 'top',                              // 'top' | 'bottom' | 'hidden'
  acceptedCardSchemes: ['visa', 'mastercard'],               // Array or Set
  acceptedCardTypes: ['credit', 'debit'],                    // Array or Set
  hideSecurityCode: false,
  cardholderNameMaxLength: 64,                               // clamped to [0, 255]
};
Fields
PropertyTypeDescription
displayCardHolderName'top' | 'bottom' | 'hidden'Position of the cardholder name field, or hide it entirely.
acceptedCardSchemesReadonlySet<CardScheme> | ReadonlyArray<CardScheme>Allowed card schemes. Unknown values are filtered out on validation.
acceptedCardTypesReadonlySet<CardType> | ReadonlyArray<CardType>Allowed card types (credit, debit, etc.). Unknown values are filtered out on validation.
hideSecurityCodebooleanHide the CVV/security-code field.
cardholderNameMaxLengthnumberMax characters for the cardholder name. Values are clamped to the range [0, 255].
Supported values
type CardScheme =
  | 'mada'
  | 'cartesBancaires'
  | 'visa'
  | 'mastercard'
  | 'americanExpress'
  | 'dinersClub'
  | 'discover'
  | 'jcb'
  | 'chinaUnionPay'
  | 'jaywan'
  | 'maestro'
  | 'unknown';

type CardType =
  | 'credit'
  | 'debit'
  | 'prepaid'
  | 'deferreddebit'
  | 'charge';
Array vs Set on collection fields

acceptedCardSchemes and acceptedCardTypes accept both Array and Set inputs by design:

  • Array is accepted for DX — ergonomic literals (['visa', 'mastercard']), JSON-friendly fixtures, easier spreading.
  • Set is the canonical form — gives you uniqueness guarantees and membership methods (has, set algebra) when composing configurations programmatically.

Validation normalises the input to a ReadonlySet internally, so you can pass whichever form fits your call site.

Apple Pay Component

The Apple Pay component provides native Apple Pay integration for iOS devices.

Basic Usage

import { ApplePay, CheckoutProvider } from '@checkout.com/checkout-react-native-components';

const PaymentScreen = () => {
  return (
    <CheckoutProvider
      config={{
        ...config,
        merchantIdentifier: 'merchant.com.your-app.name' // Required!
      }}
      paymentSession={paymentSession}
    >
      <ApplePay style={{ height: 60, marginVertical: 10 }} />
    </CheckoutProvider>
  );
};

Restricting Card Schemes and Types

You can restrict which card schemes and card types are accepted through Apple Pay using the configuration prop:

import { ApplePay, CheckoutProvider } from '@checkout.com/checkout-react-native-components';
import type { ApplePayConfiguration } from '@checkout.com/checkout-react-native-components';

const applePayConfig: ApplePayConfiguration = {
  acceptedCardSchemes: ['visa', 'mastercard'],
  acceptedCardTypes: ['credit', 'debit'],
  showApplePayButton: true, // default; set to false to hide the native button
};

const PaymentScreen = () => {
  return (
    <CheckoutProvider
      config={{
        ...config,
        merchantIdentifier: 'merchant.com.your-app.name'
      }}
      paymentSession={paymentSession}
    >
      <ApplePay
        configuration={applePayConfig}
        style={{ height: 60, marginVertical: 10 }}
      />
    </CheckoutProvider>
  );
};

Apple Pay Props

PropertyTypeRequiredDescription
configurationApplePayConfiguration❌Restrict accepted card schemes/types and toggle the Apple Pay button
styleViewStyle | ViewStyle[]❌React Native styling

ApplePayConfiguration

PropertyTypeDefaultDescription
acceptedCardSchemesCardScheme[] | ReadonlySet<CardScheme>allRestricts which card schemes are accepted. If omitted or empty, all schemes are accepted.
acceptedCardTypes('credit' | 'debit')[] | ReadonlySet<'credit' | 'debit'>allRestricts which card types are accepted. If omitted or empty, all types are accepted.
showApplePayButtonbooleantrueShow/hide the native Apple Pay button. Set to false to render Apple Pay without the built-in button (for custom layouts).

Supported Card Schemes: mada, cartesBancaires, visa, mastercard, americanExpress, dinersClub, discover, jcb, chinaUnionPay, jaywan, maestro

Supported Card Types: credit, debit

Apple Pay Merchant Identifier Setup

If you are using Expo and encounter the following error:

"No payment cards for the accepted card schemes found in Apple Wallet. User needs to add a card"

You will need to add your Apple Pay Merchant ID in the ios entitlements object (com.apple.developer.in-app-payments array) within the app.json file:

{
  "ios": {
    "supportsTablet": true,
    "bundleIdentifier": "com.checkout.components.MyRnDemo",
    "appleTeamId": "7VZD1234WM",
    "entitlements": {
      "com.apple.developer.in-app-payments": [
        "merchant.com.flow.bright.sandbox"
      ]
    }
  }
}

📝 Note: Apple Pay requires a valid merchantIdentifier in your CheckoutConfiguration and is only available on iOS devices.

Google Pay Component

The Google Pay component provides native Google Pay integration for Android devices.

Basic Usage

import { CheckoutProvider, GooglePay } from '@checkout.com/checkout-react-native-components';

const PaymentScreen = () => {
  return (
    <CheckoutProvider config={config} paymentSession={paymentSession}>
      <GooglePay />
    </CheckoutProvider>
  );
};

Configuring Accepted Card Schemes and Types

You can restrict which card schemes and card types are accepted via Google Pay by passing a googlePayConfiguration prop:

import { CheckoutProvider, GooglePay } from '@checkout.com/checkout-react-native-components';
import type { GooglePayConfiguration } from '@checkout.com/checkout-react-native-components';

const googlePayConfiguration: GooglePayConfiguration = {
  acceptedCardSchemes: ['visa', 'mastercard'],
  acceptedCardTypes: ['credit', 'prepaid'],
};

const PaymentScreen = () => {
  return (
    <CheckoutProvider config={config} paymentSession={paymentSession}>
      <GooglePay googlePayConfiguration={googlePayConfiguration} />
    </CheckoutProvider>
  );
};

When googlePayConfiguration is omitted, all schemes and types from the payment session are accepted.

Accepted Card Schemes: mada, cartesBancaires, visa, mastercard, americanExpress, dinersClub, discover, jcb, chinaUnionPay, jaywan, maestro

Accepted Card Types: credit, prepaid

Google Pay Props

PropertyTypeRequiredDescription
googlePayConfigurationGooglePayConfiguration❌Configuration for accepted card schemes and types
styleViewStyle | ViewStyle[]❌React Native styling

GooglePayConfiguration

PropertyTypeRequiredDescription
acceptedCardSchemesCardScheme[] | ReadonlySet<CardScheme>❌Restrict which card schemes are accepted. Omit to accept all from payment session.
acceptedCardTypes('credit' | 'prepaid')[] | ReadonlySet<'credit' | 'prepaid'>❌Restrict which card types are accepted. Omit to accept all from payment session.

📝 Note: Google Pay is only available on Android devices.

🔧 Advanced Features

Imperative API

Both Flow and Card components support imperative APIs (submit and tokenize) for programmatic control:

import { CheckoutProvider, Card, Flow, FlowRef, CardRef } from '@checkout.com/checkout-react-native-components';

const PaymentScreen = () => {
  const flowRef = useRef<FlowRef>(null);
  const cardRef = useRef<CardRef>(null);

  // Trigger payment submission programmatically
  const processPayment = () => {
    flowRef.current?.submit();
  };

  // Tokenize card details without submitting
  const tokenizeCard = () => {
    cardRef.current?.tokenize();
  };

  // Update the payment amount (minor currency unit)
  const updateAmount = (amount: number, currency?: string) => {
    flowRef.current?.update({ amount, currency });
  };

  const cardConfiguration = {
    displayCardHolderName: 'top',
    acceptedCardSchemes: ['visa', 'mastercard', 'americanExpress'],
    acceptedCardTypes: ['credit', 'debit'],
    hideSecurityCode: false,
    cardholderNameMaxLength: 64,
  } as const;

  return (
    <CheckoutProvider config={config} paymentSession={paymentSession}>
      <Flow
        ref={flowRef}
        config={{ showPayButton: false, cardConfigurations: cardConfiguration }}
      />
      <Card
        ref={cardRef}
        showPayButton={false}
        cardConfiguration={cardConfiguration}
      />

      <Button title="Process Payment" onPress={processPayment} />
      <Button title="Save Card" onPress={tokenizeCard} />
      <Button title="Update amount" onPress={() => updateAmount(1000, 'GBP')} />
    </CheckoutProvider>
  );
};

🎨 Customization

🎨 Complete Color Token Reference

const customStyle = {
  colorTokens: {
    // Primary brand color
    primary: '#186AFF',
    
    // Background colors
    background: '#FFFFFF',
    formBackground: '#F7F9FC',
    
    // Border colors
    border: '#E3E8F2',
    formBorder: '#C8D1E0',
    outline: '#91B2EE',
    
    // State colors
    error: '#E01E5A',
    success: '#1AA27B',
    disabled: '#B0B0B0',
    
    // Text colors
    secondary: '#545F7A',
    inverse: '#FFFFFF',
    
    // Action colors
    action: '#186AFF',
    
    // Android specific
    scrolledContainer: '#F0F0F0' // Android only
  }
};

Accepted color formats

Every color token accepts any of these formats, validated and normalised by the SDK before reaching the native layer (identical rendering on iOS and Android):

  • Hex: #RGB, #RGBA, #RRGGBB, #RRGGBBAA (with or without #)
  • rgb(r, g, b) and rgba(r, g, b, a) (alpha 0–1)
  • Named CSS colors, e.g. rebeccapurple

Alpha/transparency is supported via the 4/8-digit hex or rgba() forms (e.g. #186AFF80 or rgba(24, 106, 255, 0.5)). An unparseable color is reported and the SDK falls back to its default rather than rendering an unexpected value.

📏 Border Radius

const customBorders = {
  borderButtonRadius: 12,  // Button border radius (all corners)
  borderFormRadius: 8      // Form field border radius (all corners)
};

Each radius accepts either a single number (applied to all four corners) or a per-corner object. Omitted corners default to 0:

const customBorders = {
  borderFormRadius: {
    topLeft: 8,
    topRight: 16,
    bottomLeft: 0,
    bottomRight: 0,
  },
};

iOS note: iOS applies a single radius to a set of corners rather than an independent radius per corner. When corner radii differ, iOS approximates by applying the largest requested radius to every rounded corner. Android honours each corner exactly. Use a single number, or equal corner radii, for identical rendering across platforms.

🔤 Custom Fonts

const fonts = {
  button: {
    fontFamily: 'brand_sans',
    fontSize: 14,
    letterSpacing: 2,
    lineHeight: 20,
  },
  input: {
    fontFamily: 'brand_sans',
    fontSize: 14,
    letterSpacing: 2,
    lineHeight: 20,
  },
  footnote: {
    fontFamily: 'brand_sans',
    fontSize: 14,
    letterSpacing: 2,
    lineHeight: 20,
  },
  label: {
    fontFamily: 'brand_sans',
    fontSize: 14,
    letterSpacing: 2,
    lineHeight: 20,
  },
  subheading: {
    fontFamily: 'brand_sans',
    fontSize: 14,
    letterSpacing: 2,
    lineHeight: 20,
  },
  heading: {
    fontFamily: 'brand_sans',
    fontSize: 24,
    fontWeight: 700,
    letterSpacing: 0,
    lineHeight: 28,
  },
};

The stylable roles are button, footnote, heading, input, label and subheading.

Font weight

fontWeight accepts a numeric value on the standard 100–1000 scale. Weights from 300 to 800 render identically on iOS and Android. The platforms differ only at the extremes, because the Android SDK exposes six weights (Light–ExtraBold) while iOS exposes nine:

fontWeightiOSAndroid
100 / 200ultraLight / thinLight
300–800light → heavyLight → ExtraBold (identical)
900 / 1000blackExtraBold

For pixel-consistent results across both platforms, stay within the 300–800 range.

Set fontFamily to either a built-in generic family or the name of a custom font you have bundled in your app.

iOS

The SDK supports all iOS default system fonts, as well as any custom font bundled in your app (pass the font's PostScript name as fontFamily).

Android

The following built-in generic font families are supported:

  • SansSerif
  • Serif
  • Monospace
  • Cursive
  • Default

Custom fonts: any other fontFamily value is resolved against your app's res/font resources. Bundle the font file under android/app/src/main/res/font/ (lowercase, e.g. res/font/brand_sans.ttf) and pass the resource name as fontFamily (e.g. "brand_sans"). If no matching resource is found the default family is used, so a misspelled name degrades gracefully rather than crashing.

Font file names in res/font must be lowercase and contain only letters, digits and underscores, per Android resource naming rules.

🌍 Supported Locales & Custom Translations

Supported Locales

const Locale = {
  ar: 'ar',           // Arabic
  da_DK: 'da-DK',     // Danish
  de_DE: 'de-DE',     // German
  el: 'el',           // Greek
  en_GB: 'en-GB',     // English (UK)
  es_ES: 'es-ES',     // Spanish
  fi_FI: 'fi-FI',     // Finnish
  fil_PH: 'fil-PH',   // Filipino
  fr_FR: 'fr-FR',     // French
  hi_IN: 'hi-IN',     // Hindi
  id_ID: 'id-ID',     // Indonesian
  it_IT: 'it-IT',     // Italian
  ja_JP: 'ja-JP',     // Japanese
  ms_MY: 'ms-MY',     // Malay
  nb_NO: 'nb-NO',     // Norwegian
  nl_NL: 'nl-NL',     // Dutch
  pt_PT: 'pt-PT',     // Portuguese
  sv_SE: 'sv-SE',     // Swedish
  th_TH: 'th-TH',     // Thai
  vi_VN: 'vi-VN',     // Vietnamese
  zh_CN: 'zh-CN',     // Chinese (Simplified)
  zh_HK: 'zh-HK',     // Chinese (Hong Kong)
  zh_TW: 'zh-TW'      // Chinese (Traditional)
} as const

Translations Interface

All available translation keys with their descriptions:

export type Translations = {
  addBillingAddress?: string;
  addAddress?: string;
  address?: string;
  addressLine1?: string;
  addressLine2?: string;
  billingAddress?: string;
  card?: string;
  cardExpiryDate?: string;
  cardExpiryDateIncomplete?: string;
  cardExpiryDateInvalid?: string;
  cardExpiryDatePlaceholderMonth?: string;
  cardExpiryDatePlaceholderYear?: string;
  cardHolderName?: string;
  cardNumber?: string;
  cardNumberInvalid?: string;
  cardNumberNotSupported?: string;
  cardSecurityCode?: string;
  cardSecurityCodeInvalid?: string;
  cardSecurityCodePlaceholder?: string;
  city?: string;
  confirm?: string;
  country?: string;
  selectCountry?: string;
  editAddress?: string;
  email?: string;
  emailFormatInvalid?: string;
  firstName?: string;
  formRequired?: string;
  lastName?: string;
  insufficientCharacters?: string;
  noMatchesFound?: string;
  optional?: string;
  payButtonPay?: string;
  payButtonPaymentComplete?: string;
  payButtonPaymentProcessing?: string;
  paymentDeclinedInvalidCustomerData?: string;
  paymentDeclinedInvalidPaymentSessionData?: string;
  paymentDeclinedMerchantMisconfiguration?: string;
  paymentDeclinedNotEnoughFunds?: string;
  paymentDeclinedTryAgain?: string;
  phoneNumber?: string;
  search?: string;
  state?: string;
  trySearchingWithAnotherTerm?: string;
  useShippingAsBilling?: string;
  zip?: string;
  preferredSchemeCta?: string;
  preferredSchemeDescription?: string;
  selectState?: string;
  cardTypeNotSupported?: string;
  cardTypeCredit?: string;
  cardTypeDebit?: string;
  cardTypePrepaid?: string;
  cardTypeCharge?: string;
  deferredDebit?: string;
  fullName?: string;
  mustBeGreaterThan?: string;
  phoneNumberInvalid?: string;
  saveCardDetails?: string;
  done?: string;
  edit?: string;
  useSavedPaymentMethod?: string;
  savedCardsHeader?: string;
  otherPaymentMethodsHeader?: string;
  useNewCard?: string;
  setDefaultPaymentMethod?: string;
  storedCardSavedForRememberMe?: string;
  expired?: string;
  default?: string;
  addCard?: string;
  useDifferentPaymentMethod?: string;
  logout?: string;
  rememberMeUseSavedDetails?: string;
  rememberMeVerifyAndPay?: string;
  rememberMeModalCTA?: string;
  otpCode?: string;
  otpResendCountdown?: string;
  otpResendDescription?: string;
  otpResendCTA?: string;
  otpMaxRetries?: string;
  otpMaxResends?: string;
  otpResendEmail?: string;
  otpResendPhone?: string;
  otpSendPhone?: string;
  otpSendingPhone?: string;
  otpCodeDescriptionEmail?: string;
  otpCodeDescriptionPhone?: string;
  otpCodeDescriptionWhatsApp?: string;
  otpCodeDescription?: string;
  otpCodeError?: string;
  otpCodeExpired?: string;
  otpCodeSend?: string;
  otpCodeEmail?: string;
  otpCodePhone?: string;
  otpCodeWhatsApp?: string;
  otpDifferentMethod?: string;
  addressFormTitle?: string;
  storeForFutureUseCollectConsent?: string;
  rememberMeDescription?: string;
  continueWithoutSavedDetails?: string;
  change?: string;
  apmInfoText?: string;
  tamaraSubtitle?: string;
  customerPhoneNotRegistered?: string;
  paymentDeclinedPaymentExpired?: string;
  paymentContextError?: string;
};

Custom Translations Example

const customTranslations = {
  [Locale.en_GB]: {
    // Address and billing
    addBillingAddress: 'Add Billing Address',
    addAddress: 'Add Address',
    address: 'Address',
    addressLine1: 'Address Line 1',
    addressLine2: 'Address Line 2',
    billingAddress: 'Billing Address',
    
    // Card form labels
    card: 'Card',
    cardNumber: 'Card Number',
    cardExpiryDate: 'MM/YY',
    cardExpiryDatePlaceholderMonth: 'MM',
    cardExpiryDatePlaceholderYear: 'YY',
    cardSecurityCode: 'CVV',
    cardSecurityCodePlaceholder: 'CVV',
    cardHolderName: 'Cardholder Name',
    
    // Personal information
    firstName: 'First Name',
    lastName: 'Last Name',
    email: 'Email Address',
    phoneNumber: 'Phone Number',
    
    // Location fields
    city: 'City',
    state: 'State/Province',
    zip: 'ZIP/Postal Code',
    country: 'Country',
    selectCountry: 'Select Country',
    selectState: 'Select State',
    
    // Actions and buttons
    payButtonPay: 'Pay Now',
    payButtonPaymentProcessing: 'Processing...',
    payButtonPaymentComplete: 'Payment Complete',
    confirm: 'Confirm',
    editAddress: 'Edit Address',
    search: 'Search',
    
    // Validation and error messages
    formRequired: 'This field is required',
    cardNumberInvalid: 'Invalid card number',
    cardNumberNotSupported: 'Card type not supported',
    cardExpiryDateIncomplete: 'Expiry date incomplete',
    cardExpiryDateInvalid: 'Invalid expiry date',
    cardSecurityCodeInvalid: 'Invalid security code',
    emailFormatInvalid: 'Invalid email format',
    insufficientCharacters: 'Insufficient characters',
    
    // Payment errors
    paymentDeclinedTryAgain: 'Payment declined. Please try again.',
    paymentDeclinedNotEnoughFunds: 'Insufficient funds',
    paymentDeclinedInvalidCustomerData: 'Invalid payment details',
    paymentDeclinedInvalidPaymentSessionData: 'Invalid payment session data',
    paymentDeclinedMerchantMisconfiguration: 'Merchant configuration error',
    
    // Search and selection
    noMatchesFound: 'No matches found',
    trySearchingWithAnotherTerm: 'Try searching with another term',
    
    // Miscellaneous
    optional: 'Optional',
    useShippingAsBilling: 'Use shipping address as billing address',
    preferredSchemeCta: 'Select Preferred Scheme',
    preferredSchemeDescription: 'Please select your preferred card scheme'
  }
};

📡 Event Handling

📋 Complete Event Reference

import type {
  CardMetadata,
  Error as CheckoutError,
  TokenizationResult,
} from '@checkout.com/checkout-react-native-components';

const eventHandlers = {
  // Component lifecycle
  onReady: (paymentMethod: string) => {
    console.log('Component ready for:', paymentMethod);
  },
  
  // Form validation
  onChange: (paymentMethod: string, isValid: boolean, isAvailable: boolean) => {
    console.log('Form state changed:', { paymentMethod, isValid, isAvailable });
    // Update UI based on form validity
  },
  
  // Payment submission
  onSubmit: (paymentMethod: string) => {
    console.log('Payment submitted for:', paymentMethod);
    // Show loading state
  },
  
  // Tokenization
  onTokenized: async (tokenizationResult: TokenizationResult) => {
    console.log('Card tokenized:', tokenizationResult);
    
    if (tokenizationResult.data.cardType === 'credit') {
      return {
        continue: false,
        error: 'Credit cards are not accepted.',
      };
    }

    await utilizeToken(tokenizationResult.data.token);

    return { continue: true, error: null };
  },
  
  // Card BIN changes (partial metadata while the shopper types)
  onCardBinChanged: (cardMetadata: Partial<CardMetadata>) => {
    console.log('Card BIN changed:', cardMetadata.scheme, cardMetadata.bin);
  },

  // Payment success
  onSuccess: (paymentMethod: string, paymentID: string) => {
    console.log('Payment successful:', { paymentMethod, paymentID });
    // Navigate to success screen
  },
  
  // Error handling — compare against ErrorCode / ErrorType (both exported)
  onError: (error: CheckoutError) => {
    console.error('Payment error:', error);
    // e.g. error.errorCode === ErrorCode.CardAuthenticationFailed
    // Show error message to user
  },
  
  // Handle submit — return your server-side submission result back to the SDK
  handleSubmit: async (sessionData: string) => {
    // Forward `sessionData` to your server-side integration for payment submission
    const submitResponse = await performPaymentSubmission(sessionData);

    return {
      success: true,
      paymentSessionSubmissionResult: submitResponse,
    };
  },
};

<CheckoutProvider config={config} paymentSession={paymentSession} {...eventHandlers}>
  {/* Components */}
</CheckoutProvider>

📦 Other exports

  • ErrorCode and ErrorType — constants to compare against error.errorCode and error.type in onError.
  • Country — enum of ISO 3166-1 alpha-2 country codes (e.g. Country.Albania === 'AL').

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

版本与发布记录

@checkout.com/checkout-react-native-components 共发布 12 个版本,首次发布于 2025/10/01;过去 12 个月发布了 8 个版本。

版本发布日期距今
1.0.0-beta12latest2026/11/036 天前
1.0.0-beta112026/10/1920 天前
1.0.0-beta7.2beta7-patch22026/09/211 个月前
1.0.0-beta7.1beta7-patch12026/09/101 个月前
1.0.0-beta82026/04/106 个月前
1.0.0-beta72026/03/107 个月前

关于 @checkout.com/checkout-react-native-components 的常见问题

@checkout.com/checkout-react-native-components 是什么?

[BETA — not for production use] React Native wrapper for native iOS & Android Checkout components

如何安装 @checkout.com/checkout-react-native-components?

在项目目录运行 npm install @checkout.com/checkout-react-native-components,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(*)、react-native(*)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@checkout.com/checkout-react-native-components 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@checkout.com/checkout-react-native-components 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@checkout.com/checkout-react-native-components 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.19.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@checkout.com/checkout-react-native-components 可以商用吗?

@checkout.com/checkout-react-native-components 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@checkout.com/checkout-react-native-components 的下载量有多少?

根据 npm 官方下载统计,@checkout.com/checkout-react-native-components 在 2026/10/10 – 2026/11/08 这 30 天内被下载 28,788 次,日均约 960 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@checkout.com/checkout-react-native-components 还在维护吗?

最新版本 1.0.0-beta12 发布于 2026/11/03(6 天前);至今共发布 12 个版本,其中过去 12 个月发布了 8 个;首次发布于 2025/10/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。