A unified React Native payment module supporting Apple Pay (iOS) and Google Pay (Android) with a consistent, type-safe API.
Built with Nitro Modules for high-performance native integration.
Features • Installation • Quick Start • Documentation • API Reference
Full documentation is available at gmi-software.github.io/react-native-pay. The Docusaurus source lives in docs/; run bun run docs:start to view it locally, or bun run docs:build to build static files.
This package presents native payment sheets and returns tokens. Your backend and gateway integration still perform the actual charge.
What you can sell: use Apple Pay and Google Pay only for physical goods and for services used outside the app. Digital content, subscriptions to digital content and in-app features must use In-App Purchase on iOS (App Review Guideline 3.1.1, 3.1.3(e); real-time person-to-person services are an exception under 3.1.3(d)) and Google Play Billing on Android (Payments policy; apps in one of Google's regional alternative billing programs, such as in the US or the EEA, may offer another billing system there, but not Google Pay). Apple Pay apps must also show all material purchase information before the sale and, for recurring payments, disclose the renewal term, what is provided, the charges and how to cancel (Guideline 4.9). See What you can sell.
- ✅ Unified API - Shared payment request/result model across Apple Pay and Google Pay
- ✅ One Hook for Checkout State -
usePaymentCheckout()handles availability checks, cart state, and payment-sheet start - ✅ Native UI Components - Platform-specific payment buttons with full customization
- ✅ Type-Safe - Comprehensive TypeScript definitions with full IntelliSense support
- ✅ Configurable - Dynamic environment and gateway configuration for both platforms
- ✅ Built-in Cart - Shopping cart functionality with batch operations
- ✅ Modern Architecture - Built with Nitro Modules for optimal performance
- ✅ Expo Compatible - Config plugins for seamless Expo integration
- ✅ Production Focused - Built for real-world apps with backend gateway processing
This package requires react-native-nitro-modules to work. Install it first:
npm install react-native-nitro-modules
# or
yarn add react-native-nitro-modules
# or
bun add react-native-nitro-modulesnpm install @gmisoftware/react-native-pay
# or
yarn add @gmisoftware/react-native-pay
# or
bun add @gmisoftware/react-native-pay- React Native 0.70+
- React Native Nitro Modules 0.36.0+ (required)
- Android
minSdkVersion26+ (required for Nitro Modules prefab) - Expo 53–57 (optional; only if you use Expo. SDK 57 requires Node.js 22.13+)
Add the Apple Pay plugin to your app.json or app.config.js:
{
"expo": {
"plugins": [
[
"@gmisoftware/react-native-pay",
{
"merchantIdentifier": "merchant.com.yourcompany.app"
}
]
]
}
}-
Create a Merchant ID in Apple Developer Portal:
- Go to Certificates, Identifiers & Profiles
- Create a new Merchant ID (e.g.,
merchant.com.yourcompany.app) - Add it to your app's capabilities
-
Enable Apple Pay in your App ID:
- Go to your App ID settings
- Enable "Apple Pay Payment Processing"
- Associate your Merchant ID
-
Create Payment Processing Certificate:
- Create a Payment Processing Certificate for your Merchant ID
- Download and install it in your payment processor (Stripe, etc.)
npx expo prebuild --cleanMinimum SDK: set minSdkVersion to 26 or higher (e.g. via expo-build-properties). Nitro Modules 0.36 prefab requires API 26+.
Add the Google Pay plugin to your app.json or app.config.js:
{
"expo": {
"plugins": [
[
"@gmisoftware/react-native-pay",
{
"enableGooglePay": true
}
]
]
}
}-
Enable Google Pay API:
- Go to Google Cloud Console
- Enable the Google Pay API for your project
-
Register Your App (Production Only):
- Submit your app for Google Pay approval
- Provide screenshots and business information
- Get your production gateway merchant ID from your payment processor
npx expo prebuild --cleanFor apps supporting both platforms:
{
"expo": {
"plugins": [
[
"@gmisoftware/react-native-pay",
{
"merchantIdentifier": "merchant.com.yourcompany.app",
"enableGooglePay": true
}
]
]
}
}The easiest way to integrate payments - one hook handles everything:
import React, { useEffect } from 'react'
import {
usePaymentCheckout,
ApplePayButton,
GooglePayButton,
formatAmount,
} from '@gmisoftware/react-native-pay'
import { Platform, View, Text, ActivityIndicator } from 'react-native'
// An order your server created and priced, for example when the user opened
// checkout. Use your own type. Render the screen with `key={order.id}`, so a
// new order starts with an empty cart instead of the previous order's lines.
type Order = {
id: string
lines: { label: string; amount: string }[]
}
function CheckoutScreen({ order }: { order: Order }) {
const {
// Payment availability
isSupported,
isCheckingStatus,
// Cart
items,
total,
addItems,
clearItems,
// Payment processing
startPayment,
isProcessing,
error,
} = usePaymentCheckout({
merchantName: 'Your Store',
currencyCode: 'USD',
countryCode: 'US',
// Charge on your server. It charges the order's stored amount, not one
// the app sends, and allows one charge per order, so a retry after a
// timeout can't charge twice.
onAuthorize: async (token) => {
const response = await fetch('https://api.yourserver.com/process-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
// `total` is what the sheet showed: the server rejects the charge
// if the order no longer matches it.
body: JSON.stringify({ token, orderId: order.id, total: formatAmount(total, 'USD') }),
})
return response.ok
? { status: 'success' }
: { status: 'failure', error: 'Payment failed' }
},
})
// The sheet shows the lines your server priced. startPayment() fails
// for an empty cart, so fill it before the user taps pay.
useEffect(() => {
addItems(order.lines)
return clearItems
}, [order, addItems, clearItems])
const handlePay = async () => {
const result = await startPayment()
if (result.status === 'success') {
// Your server charged the payment: show your confirmation here.
}
// 'failed': `error` is set, including when your server declined or
// could not be reached.
// 'cancelled': the user closed the sheet, and `error` stays null.
}
if (isCheckingStatus) {
return <View><ActivityIndicator /></View>
}
if (!isSupported) {
return <View><Text>Apple Pay / Google Pay is not available</Text></View>
}
return (
<View style={{ padding: 20 }}>
{items.map((item, index) => (
<Text key={index}>{item.label}: ${formatAmount(item.amount)}</Text>
))}
<Text style={{ fontSize: 20, marginVertical: 10 }}>Total: ${total.toFixed(2)}</Text>
{error && <Text style={{ color: 'red' }}>Error: {error.message}</Text>}
{isProcessing ? (
<ActivityIndicator size="large" />
) : (
Platform.OS === 'ios' ? (
<ApplePayButton buttonType="buy" buttonStyle="black" onPress={handlePay} style={{ width: '100%', height: 48 }} />
) : (
<GooglePayButton buttonType="buy" theme="dark" radius={4} onPress={handlePay} style={{ width: '100%', height: 48 }} />
)
)}
</View>
)
}
export default CheckoutScreenresult.status is 'success' only when your server charged the order. onAuthorize keeps the Apple Pay or Google Pay sheet open until your server answers, so the sheet shows the real outcome. If Google Pay returns the payment without asking first, onAuthorize runs after its sheet has closed, so the sheet can't show the outcome. Without onAuthorize, Apple Pay shows its success checkmark as soon as the user authorizes, before your server has charged anything: don't tell the user the payment succeeded until your server answers. See Charging Before the Sheet Closes and the server-side processing guide.
The docs/ directory contains the full technical documentation (Docusaurus, English): introduction, quick start, installation & setup, API reference, guides, troubleshooting, and compatibility. Run bun run docs:start to serve it locally.
1. Check availability → usePaymentCheckout() or HybridPaymentHandler.payServiceStatus()
2. Build cart → addItem() / addItems()
3. Display payment button → ApplePayButton / GooglePayButton
4. Process payment → startPayment()
5. Handle result → Send token to server
6. Complete transaction → Server processes with payment gateway
For Google Pay, you need to configure your payment gateway:
import { usePaymentCheckout } from "@gmisoftware/react-native-pay";
const checkout = usePaymentCheckout({
merchantName: "Your Store", // shown on the Google Pay sheet
currencyCode: "USD",
countryCode: "US",
// Google Pay specific
googlePayMerchantId: "your_google_pay_merchant_id",
googlePayEnvironment: "TEST", // or 'PRODUCTION'
googlePayGateway: "stripe",
googlePayGatewayMerchantId: "your_stripe_merchant_id",
});Without googlePayEnvironment, Google Pay runs in TEST, in release builds too, and a release build logs a warning once per app run when a payment starts (not on the availability check). Set 'PRODUCTION' for live payments.
Without merchantName, the Google Pay sheet shows your app's label. If any cart item is pending, the total is sent as an estimate (ESTIMATED on Google Pay, .pending on Apple Pay).
- Stripe -
googlePayGateway: 'stripe' - Braintree -
googlePayGateway: 'braintree' - Square -
googlePayGateway: 'square' - Adyen -
googlePayGateway: 'adyen' - Authorize.net -
googlePayGateway: 'authorizenet' - Checkout.com -
googlePayGateway: 'checkoutltd'
For the complete list, see Google Pay Gateway Tokens.
The all-in-one hook for handling payments. Manages availability checking, cart state, and payment processing.
interface UsePaymentCheckoutConfig {
merchantName?: string; // "Pay <merchantName>" on Apple Pay; defaults to the app name
totalLabel?: string; // Google Pay total label. Default: 'Total'. Android only
countryCode?: string; // Default: 'US'
currencyCode?: string; // Default: 'USD'
supportedNetworks?: string[]; // PaymentNetwork names. Default: ['visa', 'mastercard', 'amex', 'discover']
merchantCapabilities?: MerchantCapability[]; // Default: ['3DS']. Android: only Debit without Credit
applePayMerchantIdentifier?: string; // Optional iOS override
// Google Pay specific (Android)
googlePayMerchantId?: string;
googlePayEnvironment?: "TEST" | "PRODUCTION";
googlePayGateway?: string;
googlePayGatewayMerchantId?: string;
googlePayAllowedAuthMethods?: GooglePayAuthMethod[]; // Default: ['PAN_ONLY', 'CRYPTOGRAM_3DS']
googlePayAllowPrepaidCards?: boolean; // false leaves prepaid cards out. Default: true
googlePayCheckoutOption?: GooglePayCheckoutOption; // Sheet button label. Default: Google Pay picks
// Contact details, returned in the result (see "Shipping and contact details")
billingContactRequired?: boolean;
shippingContactRequired?: boolean;
emailRequired?: boolean;
phoneNumberRequired?: boolean;
couponCode?: string; // iOS: a code already applied, needs onCouponCodeChange
// Charge the token while the sheet waits (see "Charging before the sheet closes")
onAuthorize?: (
token: PaymentToken,
details: PaymentDetails
) => Promise<PaymentAuthorizationResult>;
// Update the cart while the sheet is open; coupons are iOS only (see "Updating the cart in the sheet")
onShippingAddressChange?: StartPaymentOptions["onShippingAddressChange"];
onShippingMethodChange?: StartPaymentOptions["onShippingMethodChange"];
onPaymentMethodChange?: StartPaymentOptions["onPaymentMethodChange"];
onCouponCodeChange?: StartPaymentOptions["onCouponCodeChange"];
}interface UsePaymentCheckoutReturn {
// Payment availability
isSupported: boolean; // Device supports Apple Pay / Google Pay
hasActiveCard: boolean; // A card on supportedNetworks is ready
isCheckingStatus: boolean; // true until the availability check settles
refreshStatus: () => void; // Check again, e.g. after the user added a card
// Cart management
items: PaymentItem[]; // Current cart items
total: number; // Exact decimal total (NaN if an amount is invalid)
addItem: (label: string, amount: number | string, type?: "final" | "pending") => void;
addItems: (items: Array<{ label; amount; type? }>) => void;
removeItem: (index: number) => void;
updateItem: (index: number, updates: Partial<PaymentItem>) => void;
clearItems: () => void;
// Payment processing
startPayment: () => Promise<PaymentResult>; // Never rejects; check status
isProcessing: boolean; // Payment in progress?
result: PaymentResult | null; // Last payment result; check result.status
error: Error | null; // Last error, a PaymentError with a `code`; null after a cancel
// Utilities
reset: () => void; // Reset payment state
paymentRequest: PaymentRequest; // Full request object
}import { usePaymentCheckout } from "@gmisoftware/react-native-pay";
const checkout = usePaymentCheckout({
merchantName: "Your Store",
currencyCode: "USD",
countryCode: "US",
googlePayMerchantId: "your_google_pay_merchant_id",
googlePayEnvironment: "TEST",
googlePayGateway: "stripe",
googlePayGatewayMerchantId: "your_stripe_merchant_id",
});
// Add single item
checkout.addItem("Product", 29.99);
// Add multiple items at once
checkout.addItems([
{ label: "Product", amount: 29.99 },
{ label: "Shipping", amount: 5.0 },
{ label: "Tax", amount: 2.8, type: "final" },
]);
// Process payment
const result = await checkout.startPayment();Low-level payment handler for direct control.
The native handler is created the first time you use HybridPaymentHandler, not when you import the package, so helpers such as formatAmount and createPaymentRequest import on web and in Jest. Where the native module is missing (web, Expo Go, a build made before installing the package, or Jest without a mock), HybridPaymentHandler and getPaymentHandler() fail with an Error that says how to fix it (the Promise methods reject, the others throw), and usePaymentCheckout reports isSupported: false.
Check payment service availability without blocking the JS thread. Pass the supportedNetworks, merchantCapabilities, googlePayAllowedAuthMethods, googlePayAllowPrepaidCards and googlePayEnvironment your payment request uses. The Promise rejects with the payment's configuration error for a value the payment would refuse.
import { HybridPaymentHandler } from "@gmisoftware/react-native-pay";
const status = await HybridPaymentHandler.payServiceStatus({
supportedNetworks: ["visa", "mastercard"],
googlePayEnvironment: "PRODUCTION",
});
console.log("Wallet supported:", status.isSupported);
console.log("Card ready:", status.hasActiveCard);Returns:
interface PayServiceStatus {
isSupported: boolean; // iOS: canMakePayments(); Android: isReadyToPay
hasActiveCard: boolean; // iOS: canMakePayments(usingNetworks:capabilities:); Android: isReadyToPay with existingPaymentMethodRequired
}Android asks the TEST environment unless you pass googlePayEnvironment, and in TEST hasActiveCard is true whether or not the user has a card. See Check availability for which button to show.
Start a payment request. The request is validated with normalizePaymentRequest first: an invalid amount or code resolves with code: 'CONFIGURATION' before the sheet opens.
import { HybridPaymentHandler } from "@gmisoftware/react-native-pay";
const result = await HybridPaymentHandler.startPayment({
merchantName: "Your Store",
countryCode: "US",
currencyCode: "USD",
merchantCapabilities: ["3DS"],
supportedNetworks: ["visa", "mastercard", "amex"],
paymentItems: [{ label: "Coffee Subscription", amount: "29.99", type: "final" }],
googlePayMerchantId: "your_google_pay_merchant_id",
});On iOS, the Apple Pay sheet lists your paymentItems and then a total labelled with merchantName ("Pay Your Store"). The library adds that total for you, so don't add your own "Total" item.
Options:
interface StartPaymentOptions {
// Charge the token while the sheet waits (see "Charging before the sheet closes")
onAuthorize?: (
token: PaymentToken,
details: PaymentDetails
) => Promise<PaymentAuthorizationResult>;
// Update the cart while the sheet is open; coupons are iOS only (see "Updating the cart in the sheet")
onShippingAddressChange?: (
address: PaymentSheetAddress,
selection: PaymentSheetSelection
) => Promise<PaymentSheetUpdate>;
onShippingMethodChange?: (
method: ShippingMethod,
selection: PaymentSheetSelection
) => Promise<PaymentSheetUpdate>;
onPaymentMethodChange?: (
card: PaymentSheetCard,
selection: PaymentSheetSelection
) => Promise<PaymentSheetUpdate>;
onCouponCodeChange?: (
couponCode: string,
selection: PaymentSheetSelection
) => Promise<PaymentSheetUpdate>;
}
interface PaymentAuthorizationResult {
status: "success" | "failure";
error?: string; // Becomes PaymentResult.error, with code "PROVIDER_ERROR", on failure
}Returns a promise that resolves for every outcome, including a cancel and an invalid request:
interface PaymentResult extends PaymentDetails {
status: "success" | "cancelled" | "failed";
code?: PaymentErrorCode; // Why it didn't succeed, see below
success: boolean; // status === "success"
token?: PaymentToken;
error?: string; // Message for logs, also set on a cancel
}
interface PaymentToken {
paymentMethod: PaymentMethod;
transactionIdentifier?: string; // Apple's ID on iOS, missing on Android
paymentData: string; // iOS: base64 of Apple's payment data. Android: Google Pay's token as is
}A cancel has status: "cancelled" and code: "CANCELLED"; it is not an error. Any other outcome that isn't a success has status: "failed" and one of IN_PROGRESS, CONFIGURATION, NOT_AVAILABLE, PROVIDER_ERROR or UNKNOWN. Branch on status and code, not on error. The error codes page says what each code means and which native cases produce it.
Check whether a payment started with startPayment (directly or by usePaymentCheckout) has not settled yet. While it returns true, startPayment resolves with { status: "failed", code: "IN_PROGRESS" } and the message "A payment is already in progress".
import { HybridPaymentHandler } from "@gmisoftware/react-native-pay";
const isBusy = HybridPaymentHandler.isPaymentInProgress();iOS only: opens Wallet so the user can add a card. Call it from an ApplePayButton with buttonType="setUp". It does nothing on Android, where the Google Pay sheet lets the user add a card.
Each button renders nothing on the other platform and, in development, logs a warning. disabled makes the button ignore taps, for example while a payment is in progress. It does not dim the button: Apple's guidelines ask not to make the Apple Pay button appear unavailable, and Google's do not allow changing the Google Pay button's color.
Native Apple Pay button with full customization.
interface ApplePayButtonProps {
buttonType:
| "buy"
| "setUp"
| "book"
| "donate"
| "continue"
| "reload"
| "addMoney"
| "topUp"
| "order"
| "rent"
| "support"
| "contribute"
| "tip";
buttonStyle: "white" | "whiteOutline" | "black";
// iOS 26+: the plain button instead of the payer's default card. Defaults to false.
disableCardArt?: boolean;
cornerRadius?: number; // Corner radius in points; defaults to the system radius
onPress?: () => void;
disabled?: boolean; // ignores taps while true
style?: ViewStyle;
}From iOS 26 the button can show the payer's default card from Wallet instead of the plain label. Pass disableCardArt when your layout needs the plain button. Card art only shows on a real device with a card in Wallet, never on the simulator. Set rounder corners with cornerRadius, not by clipping the button in a View: Apple's guidelines ask apps not to crop it.
import { ApplePayButton } from "@gmisoftware/react-native-pay";
const handlePayment = async () => {
// Call startPayment() from usePaymentCheckout here
};
<ApplePayButton
buttonType="buy"
buttonStyle="black"
cornerRadius={24}
onPress={handlePayment}
style={{ width: '100%', height: 48 }}
/>Native Google Pay button with customization.
interface GooglePayButtonProps {
buttonType:
| "buy"
| "book"
| "checkout"
| "donate"
| "order"
| "pay"
| "subscribe"
| "plain";
theme: "dark" | "light";
radius?: number; // Corner radius in dp
// The cards your payment accepts, so the button never shows another card.
supportedNetworks?: string[]; // as PaymentRequest.supportedNetworks
googlePayAllowedAuthMethods?: string[]; // as PaymentRequest.googlePayAllowedAuthMethods
googlePayAllowPrepaidCards?: boolean; // as PaymentRequest.googlePayAllowPrepaidCards
merchantCapabilities?: string[]; // as PaymentRequest.merchantCapabilities
onPress?: () => void;
disabled?: boolean; // ignores taps while true
style?: ViewStyle;
}import { GooglePayButton } from "@gmisoftware/react-native-pay";
const handlePayment = async () => {
// Call startPayment() from usePaymentCheckout here
};
<GooglePayButton
buttonType="buy"
theme="dark"
radius={8}
onPress={handlePayment}
style={{ width: '100%', height: 48 }}
/>Create a complete payment request from simplified config.
import { createPaymentRequest } from "@gmisoftware/react-native-pay";
const request = createPaymentRequest({
amount: 29.99,
label: "Coffee Subscription",
merchantName: "Your Store",
countryCode: "US",
currencyCode: "USD",
googlePayMerchantId: "your_google_pay_merchant_id",
googlePayEnvironment: "TEST",
googlePayGateway: "stripe",
googlePayGatewayMerchantId: "your_merchant_id",
});
// request.paymentItems[0].amount === "29.99"Throws if the amount is invalid for the currency (see Amounts).
Validate a request you built yourself and convert every amount to an exact decimal string. currencyCode must be an upper-case ISO 4217 code ("USD") and countryCode an upper-case ISO 3166-1 alpha-2 code ("US"). createPaymentRequest, usePaymentCheckout and HybridPaymentHandler.startPayment call it for you; call it yourself to get the error before you start the payment.
import { normalizePaymentRequest } from "@gmisoftware/react-native-pay";
normalizePaymentRequest({ ...request, paymentItems: [{ label: "Book", amount: 19.9, type: "final" }] });
// paymentItems: [{ label: 'Book', amount: '19.90', type: 'final' }]Create a payment item.
import { createPaymentItem } from "@gmisoftware/react-native-pay";
const item = createPaymentItem("Subscription", "29.99", "final");
// { label: 'Subscription', amount: '29.99', type: 'final' }Calculate the exact decimal total of payment items.
import { calculateTotal, type PaymentItem } from "@gmisoftware/react-native-pay";
const items: PaymentItem[] = [
{ label: "Product", amount: 29.99, type: "final" },
{ label: "Tax", amount: 2.4, type: "final" },
];
const total = calculateTotal(items); // 32.39Format card network name for display.
import { formatNetworkName } from "@gmisoftware/react-native-pay";
formatNetworkName("visa"); // "Visa"
formatNetworkName("mastercard"); // "Mastercard"
formatNetworkName("amex"); // "American Express"// Amount in the currency's major unit: "19.99" or 19.99 (see Amounts below)
type PaymentAmount = number | string;
// Payment Item
interface PaymentItem {
label: string;
amount: PaymentAmount;
type: "final" | "pending";
kind?: "subtotal" | "tax" | "discount"; // Google Pay display item type. Android only
}
// Payment Request
interface PaymentRequest {
applePayMerchantIdentifier?: string;
merchantName?: string; // "Pay <merchantName>" on Apple Pay; defaults to the app name
totalLabel?: string; // Google Pay total label. Default: "Total". Android only
countryCode: string;
currencyCode: string;
paymentItems: PaymentItem[];
merchantCapabilities: string[]; // MerchantCapability values
supportedNetworks: string[]; // PaymentNetwork names; unknown names fail
shippingType?: string; // ShippingType value, iOS only
shippingMethods?: ShippingMethod[]; // → PaymentResult.shippingMethod
billingContactRequired?: boolean; // → PaymentResult.billingContact
shippingContactRequired?: boolean; // → PaymentResult.shippingContact
emailRequired?: boolean; // → PaymentResult.emailAddress
phoneNumberRequired?: boolean; // → PaymentResult.phoneNumber
// At most one: charges after today, asking for a merchant token
recurring?: RecurringPaymentRequest; // subscriptions, iOS 16+
deferred?: DeferredPaymentRequest; // one later charge, iOS 16.4+
automaticReload?: AutomaticReloadPaymentRequest; // top-ups, iOS 16+
applePayMultiTokenContexts?: PaymentTokenContext[]; // several merchants, iOS 16+
couponCode?: string; // iOS only, needs onCouponCodeChange
applePayMerchantCategoryCode?: number; // ISO 18245 code, iOS 18+
applePayLaterAvailability?: string; // ApplePayLaterAvailability value, iOS 17+
// Google Pay specific
googlePayMerchantId?: string;
googlePayEnvironment?: "TEST" | "PRODUCTION";
googlePayGateway?: string;
googlePayGatewayMerchantId?: string;
googlePayAllowedAuthMethods?: string[]; // GooglePayAuthMethod values
googlePayAllowPrepaidCards?: boolean; // false leaves prepaid cards out
googlePayCheckoutOption?: GooglePayCheckoutOption; // the sheet's button label
}
// Payment Result
type PaymentStatus = "success" | "cancelled" | "failed";
type PaymentErrorCode =
| "CANCELLED"
| "IN_PROGRESS"
| "CONFIGURATION"
| "NOT_AVAILABLE"
| "PROVIDER_ERROR"
| "UNKNOWN";
interface PaymentResult extends PaymentDetails {
status: PaymentStatus;
code?: PaymentErrorCode; // Set when status isn't "success"
success: boolean; // status === "success"
token?: PaymentToken;
error?: string; // Message for logs, also set on a cancel
}
// Payment Token
interface PaymentToken {
paymentMethod: PaymentMethod;
transactionIdentifier?: string; // Apple's ID on iOS, missing on Android
paymentData: string; // iOS: base64 of Apple's payment data. Android: Google Pay's token as is
}
// Payment Method
interface PaymentMethod {
displayName?: string; // for the payer, e.g. "Visa •••• 1234"; don't parse it
network?: PaymentNetwork; // "unknown" when the library cannot name it
type: PaymentMethodType; // funding source; "store" is iOS only
secureElementPass?: PKSecureElementPass;
billingAddress?: CNContact;
}
// Payment Networks. Google Pay offers visa, mastercard, amex, discover, jcb
// and interac, plus electron, maestro and elo for Brazilian combo cards.
// Apple Pay offers all of them; each platform leaves out the ones it lacks.
type PaymentNetwork =
| "visa"
| "mastercard"
| "amex"
| "discover"
| "jcb"
| "maestro"
| "electron"
| "elo"
| "idcredit"
| "interac"
| "privateLabel"
| "cartesBancaires"
| "chinaUnionPay"
| "dankort"
| "eftpos"
| "girocard"
| "mada"
| "mir"
| "quicPay"
| "suica"
| "vPay"
| "waon"
| "nanaco"
| "bancontact"
| "postFinance"
| "pagoBancomat"
| "tmoney"
| "meeza"
| "napas"
| "bankAxept"
| "himyan"
| "jaywan"
| "myDebit"
| "conecs"
| "elCorteIngles"
| "ruPay"
| "verve"
| "humo"
| "uzCard"
| "payPak"
| "maal"
| "elcard"
| "unknown"; // results only
// Google Pay auth methods (Android). PAN_ONLY payments need a 3-D Secure step-up:
// https://gmi-software.github.io/react-native-pay/docs/setup/android-google-pay#card-authentication-and-3-d-secure
type GooglePayAuthMethod = "PAN_ONLY" | "CRYPTOGRAM_3DS";
// Google Pay sheet button label (Android): "Continue"/"Pay", "Pay now", "Review Order".
// 'completeImmediatePurchase' fails with a 'pending' item.
type GooglePayCheckoutOption =
| "default"
| "completeImmediatePurchase"
| "continueToReview";
// Payment Method Type
type PaymentMethodType = "unknown" | "debit" | "credit" | "prepaid" | "store";
// Apple Pay merchant capabilities
type MerchantCapability = "3DS" | "EMV" | "Credit" | "Debit";Amounts are numbers (19.99) or decimal strings ("19.99") in the currency's major unit. Before a payment starts, the library validates them and sends them to native code as exact decimal strings (NSDecimalNumber on iOS, BigDecimal on Android), never through Double. The payment does not start when:
- an amount is not a finite number or a plain decimal string (
NaN,"abc","1e3"); - an amount has more decimal places than the currency allows (ISO 4217:
1.005in USD,"1200.5"in JPY). This includes unrounded float results such as0.1 + 0.2; round them withformatAmount(value, currencyCode); - the total is negative. Negative line items (discounts) are allowed.
Google Pay accepts at most two decimal places, so three-decimal amounts ("1.234" KWD) fail on Android.
"3DS" and "EMV" are Apple Pay payment protocols, and PassKit needs at least one of them: EMV only covers China UnionPay, so every other card needs 3DS. Android ignores them. "Credit" and "Debit" limit the accepted card types. iOS adds "3DS" when neither protocol is given, so ["Credit"] is sent as 3DS + Credit. Both platforms match the values case-insensitively, and any other value fails the payment with Unknown merchant capability "<value>". Use "3DS", "EMV", "Credit" or "Debit".
Google Pay can leave credit cards out, but not debit cards. On Android, "Debit" without "Credit" sends allowCreditCards: false, which UK gambling merchants must do; prepaid cards stay allowed. ["3DS", "Credit"] accepts every card type on Android, so check the card on your server if you must refuse debit cards. Give GooglePayButton and payServiceStatus the same merchantCapabilities as the payment.
applePayMerchantCategoryCode (an ISO 18245 code from 0 to 9999, iOS 18+) leaves out the cards that don't accept your category. applePayLaterAvailability ("available", "itemIneligible" or "recurringTransaction", iOS 17+) hides Apple Pay Later and tells the payer why. Earlier iOS versions and Android ignore both; an invalid value fails the payment on iOS. See PaymentRequest.
Set billingContactRequired, shippingContactRequired, emailRequired or phoneNumberRequired to ask the payer for a billing address, a shipping address, an email address or a phone number. Each one fills billingContact, shippingContact, emailAddress or phoneNumber in the result and in the second argument of onAuthorize, on both platforms. Google Pay only collects a phone number with an address: without shippingContactRequired, Android asks for it with at least the billing name, country and postal code.
shippingMethods (with HybridPaymentHandler) lets the payer pick a delivery option; the selected method is added to the total and returned as shippingMethod. The first one is selected by default. On Android the payer can pick another only when the payment has a sheet callback, such as onShippingMethodChange, and shippingContactRequired; otherwise Android charges the first method. See the contact details guide.
shippingType ("shipping", "delivery", "storePickup" or "servicePickup") only changes Apple Pay's labels. An unknown value fails the payment on iOS.
The cart can follow the payer's choices while the Apple Pay or Google Pay sheet is open. onShippingAddressChange, onShippingMethodChange, onPaymentMethodChange and onCouponCodeChange (in StartPaymentOptions or the hook's config) get the change and everything chosen so far, and return new paymentItems, new shippingMethods or an error for the payer: tax by region, an address you don't deliver to, a credit card fee, a coupon code. The coupon field appears only with onCouponCodeChange, and the accepted code comes back as couponCode. On Android, Google Pay has no coupon field, and it can't update recurring, deferred or automaticReload payments. See the dynamic cart guide.
recurring, deferred and automaticReload (with HybridPaymentHandler) charge the payer again later: a subscription, a payment on a later date, or a balance top-up. The sheet shows the schedule, and the payment asks for a merchant token your payment provider can charge later. When the card's network has no merchant tokens, Apple Pay returns a device token instead, so check with your provider. paymentItems stay what the payer pays today, which may be nothing. Android sends them to Google Pay as Merchant Initiated Transactions. See the subscriptions guide.
applePayMultiTokenContexts (with HybridPaymentHandler) pays several merchants with one Apple Pay sheet, such as a marketplace order or a trip with a flight and a hotel. Each context names a merchant and its amount; the amounts must add up to exactly the total, so list yourself too for any share you keep. The result still holds one token: your server finds each merchant's cryptogram in its encrypted payment data. iOS 16+; Android ignores it. See the multi-merchant guide.
interface PaymentDetails {
billingContact?: PaymentContact; // billingContactRequired
shippingContact?: PaymentContact; // shippingContactRequired
emailAddress?: string; // emailRequired
phoneNumber?: string; // phoneNumberRequired
shippingMethod?: ShippingMethod; // the selected entry of shippingMethods
}
interface ShippingMethod {
identifier: string; // unique within the request
label: string;
amount: PaymentAmount; // added to the total while selected
detail?: string;
}
interface PaymentContact {
name?: string;
givenName?: string; // iOS only
familyName?: string; // iOS only
postalAddress?: CNPostalAddress; // isoCountryCode is uppercase
}
interface CNContact {
identifier: string;
contactType: "person" | "organization";
namePrefix: string;
givenName: string;
middleName: string;
familyName: string;
previousFamilyName: string;
nameSuffix: string;
nickname: string;
organizationName: string;
departmentName: string;
jobTitle: string;
phoneticGivenName: string;
phoneticMiddleName: string;
phoneticFamilyName: string;
phoneticOrganizationName?: string;
note: string;
imageDataAvailable?: boolean;
phoneNumbers: CNLabeledPhoneNumber[];
emailAddresses: CNLabeledEmailAddress[];
postalAddresses: CNLabeledPostalAddress[];
}
interface CNPostalAddress {
street?: string;
city?: string;
state?: string;
postalCode?: string;
country?: string;
isoCountryCode?: string;
}For advanced use cases where you need more control:
import {
HybridPaymentHandler,
createPaymentRequest,
ApplePayButton,
GooglePayButton,
} from '@gmisoftware/react-native-pay'
import { Platform } from 'react-native'
// 1. Check availability, against the environment you pay in
const { isSupported } = await HybridPaymentHandler.payServiceStatus({
googlePayEnvironment: 'PRODUCTION',
})
// 2. Create payment request
const paymentRequest = createPaymentRequest({
amount: 99.99,
label: 'Espresso Machine',
merchantName: 'Your Store',
countryCode: 'US',
currencyCode: 'USD',
googlePayMerchantId: 'your_google_pay_merchant_id',
googlePayEnvironment: 'PRODUCTION',
googlePayGateway: 'stripe',
googlePayGatewayMerchantId: 'your_merchant_id',
})
// 3. Handle payment
const handlePayment = async () => {
try {
const result = await HybridPaymentHandler.startPayment(paymentRequest)
if (result.status === 'success' && result.token) {
// Send the token to your server
const response = await fetch('https://api.yourserver.com/process-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: result.token }),
})
if (!response.ok) throw new Error('Payment processing failed')
} else if (result.status === 'failed') {
console.error('Payment failed:', result.code, result.error)
}
} catch (error) {
console.error('Payment error:', error)
}
}
// 4. Render the button.
function PaymentButton() {
if (!isSupported) return null
return Platform.OS === 'ios' ? (
<ApplePayButton
buttonType="buy"
buttonStyle="black"
onPress={handlePayment}
/>
) : (
<GooglePayButton
buttonType="buy"
theme="dark"
onPress={handlePayment}
/>
)
}import { formatAmount, usePaymentCheckout } from "@gmisoftware/react-native-pay";
const checkout = usePaymentCheckout({
merchantName: "Your Store",
currencyCode: "USD",
});
// Add items dynamically
const handleAddToCart = (product: { name: string; price: number }) => {
checkout.addItem(product.name, product.price);
};
// Update quantity: compute from the unit price, not the current amount
const handleUpdateQuantity = (
index: number,
product: { name: string; price: number },
quantity: number
) => {
checkout.updateItem(index, {
label: `${product.name} × ${quantity}`,
amount: formatAmount(product.price * quantity),
});
};
// Apply discount
const handleApplyDiscount = (discountPercent: number) => {
const discountAmount = checkout.total * (discountPercent / 100);
checkout.addItem("Discount", formatAmount(-discountAmount), "final");
};
// Clear cart
const handleClearCart = () => {
checkout.clearItems();
};Apple and Google require their own buttons to start a payment: don't draw your own "Apple Pay" or "G Pay" button. Use ApplePayButton and GooglePayButton, and pick the label and look with their buttonType, buttonStyle, cornerRadius, disableCardArt, theme and radius props. See Apple's Apple Pay guidelines and Google's brand guidelines.
Pass onAuthorize to charge the token while the Apple Pay sheet is still up. The sheet then shows your real outcome instead of an unconditional success:
import { useEffect } from "react";
import { usePaymentCheckout } from "@gmisoftware/react-native-pay";
const order = { id: "order_123", label: "Premium plan", total: "49.99" }; // your order
function useOrderPayment() {
const checkout = usePaymentCheckout({
currencyCode: "USD",
onAuthorize: async (token) => {
const response = await fetch("https://api.yourserver.com/process-payment", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token, orderId: order.id }),
});
return response.ok
? { status: "success" }
: { status: "failure", error: "Payment failed" };
},
});
const { addItem, clearItems } = checkout;
// startPayment() fails for an empty cart, so fill it before the tap.
useEffect(() => {
addItem(order.label, order.total);
return clearItems;
}, [addItem, clearItems]);
return async () => {
const result = await checkout.startPayment();
// result.status is "success" only when your server approved
};
}onAuthorizemust settle within 25 seconds. Otherwise the payment fails with "Payment authorization timed out", and its later result is ignored. Your server may still have charged the card.- Retries: after a failure or a timeout the user can retry from the same sheet, and
onAuthorizeruns again with a new token. Allow one successful charge per order ID, not per token; see the server-side processing guide for idempotency keys after a decline or a timeout. - A rejected promise counts as a failure.
- Android: the Google Pay sheet shows your
errorto the payer, or "Payment authorization failed" without one or after a rejection. If Google Pay returns the payment without asking first,onAuthorizeruns after its sheet has closed and only decides thePaymentResult.
After receiving the payment token, process it on your server:
The server looks up the amount from the order, never from the request, and gives each charge attempt its own idempotency key, so a timeout or a lost response can't charge twice and a retry after a decline isn't answered with the old decline. The token format depends on the platform and your gateway, so chargeWithGateway stands for your gateway's API:
// Backend API endpoint
app.post("/process-payment", async (req, res) => {
const { token, orderId } = req.body;
try {
// The order, its amount and currency come from your database.
const order = await orders.findPayable(orderId, req.user.id);
if (!order) {
return res.status(404).json({ error: "Order not found" });
}
const charge = await chargeWithGateway({
amount: order.amountMinor,
currency: order.currency,
// iOS: base64 of Apple's PKPaymentToken JSON.
// Android: Google Pay's tokenizationData.token for your gateway.
paymentData: token.paymentData,
// Reused after a timeout; a new attempt after a decline.
idempotencyKey: `charge-${order.id}-${order.chargeAttempt}`,
});
if (charge.status !== "succeeded") {
if (charge.status === "declined") await orders.startNextChargeAttempt(order.id);
return res.status(402).json({ error: "The payment was not completed" });
}
await orders.markPaid(order.id, charge.id);
res.json({ success: true, chargeId: charge.id });
} catch (error) {
res.status(500).json({ error: error.message });
}
});The app's PaymentResult is not proof of payment: your server is the source of truth for the amount and the charge. For Stripe, follow its Apple Pay and Google Pay guides to turn the token into a payment; see also Server processing.
@gmisoftware/react-native-pay/
├── android/ # Android implementation
│ ├── src/main/java/com/margelo/nitro/pay/
│ │ ├── Constants.kt # Shared constants
│ │ ├── GooglePayButtonFactory.kt # Button factory
│ │ ├── GooglePayRequestBuilder.kt # Request builder
│ │ ├── HybridGooglePayButton.kt # Button component
│ │ ├── HybridPaymentHandler.kt # Payment handler
│ │ └── PaymentMapper.kt # Data transformation
│ ├── build.gradle
│ └── CMakeLists.txt
│
├── ios/ # iOS implementation
│ ├── ApplePayButtonFactory.swift # Button factory
│ ├── HybridApplePayButton.swift # Button component
│ ├── HybridPaymentHandler.swift # Payment handler
│ └── PassKitTypeMapper.swift # Type conversion
│
├── src/ # TypeScript source
│ ├── specs/ # Nitro specifications
│ │ ├── ApplePayButton.nitro.ts
│ │ ├── GooglePayButton.nitro.ts
│ │ └── PaymentHandler.nitro.ts
│ ├── types/ # Type definitions
│ │ ├── Contact.ts # Contact types
│ │ ├── Payment.ts # Payment types
│ │ └── index.ts
│ ├── utils/ # Utilities
│ │ ├── paymentHelpers.ts
│ │ └── index.ts
│ ├── hooks/ # React hooks
│ │ ├── usePaymentCheckout.ts
│ │ └── index.ts
│ ├── plugin/ # Expo config plugins
│ │ ├── withApplePay.ts
│ │ ├── withGooglePay.ts
│ │ └── index.ts
│ └── index.ts # Public API
│
├── nitrogen/ # Generated code
│ └── generated/
│ ├── android/
│ ├── ios/
│ └── shared/
│
└── package.json
- Platform Abstraction - Single API for both iOS and Android
- Type Safety - Full TypeScript coverage; payment amounts are checked at runtime
- Performance - Built with Nitro Modules for native speed
- Developer Experience - Simple hooks API with sensible defaults
- Production Focused - Designed around backend-controlled payment flows
ApplePayButton renders on iOS whatever the Apple Pay setup. If it's missing, your app hid it: check what isSupported and hasActiveCard returned.
- Verify merchant ID is correctly configured in Apple Developer Portal and matches exactly
- "No Apple Pay merchant identifier configured": set
merchantIdentifierin the Expo plugin and runnpx expo prebuild --clean, or add the Info.plist keyReactNativePayApplePayMerchantIdentifiersin a bare app - Add a card to Apple Wallet on your test device
GooglePayButton renders on Android whatever the Google Pay setup. If it's missing, your app hid it: check what isSupported and hasActiveCard returned.
-
Check that
enableGooglePay: trueis set in your plugin config -
Ensure Google Play Services is installed on the device (an emulator needs a Play image)
-
Add a card to Google Pay on your test device
-
For testing, use
googlePayEnvironment: 'TEST' -
Verify your gateway configuration is correct
# Clean and reinstall
rm -rf node_modules
rm -rf ios/Pods ios/build
rm -rf android/build android/app/build
bun install
cd ios && pod install# Regenerate types
cd package
bun run typecheck
bun run specsCheck out the /example directory for a complete working implementation with:
- Full checkout flow
- Cart management
- Error handling
- Platform-specific UI
Run the example:
cd example
bun install
npx expo prebuild
npx expo run:ios
npx expo run:androidWe welcome contributions! Please follow these guidelines:
# Clone the repository
git clone https://github.com/gmi-software/react-native-pay.git
cd react-native-pay
# Install dependencies
bun install
cd package && bun install
# Generate Nitro bindings
bun run specs- Follow existing TypeScript patterns
- Add JSDoc comments for public APIs
- Use Prettier for formatting (runs automatically)
- Ensure types are properly exported
- Test on both iOS and Android
- Test with real devices (Simulator/Emulator support limited)
- Verify in both TEST and PRODUCTION modes
- Create a feature branch from
main - Write descriptive commit messages
- Update documentation for API changes
- Add examples for new features
- Recurring payment support
- Shipping address collection
- Multi-currency support
- Payment request validation
- Detailed transaction logging
- Web support (via Payment Request API)
MIT © GMI Software
- Built with Nitro Modules by Margelo
- Developed by GMI Software
- 📧 Email: info@gmi.software
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
Made with ❤️ by gmi.software