Skip to content

About

Unified Apple and Google Pay for React Native

Resources

Code of conduct

Contributing

Stars

13 stars

Watchers

1 watching

Forks

Repository files navigation

react-native-pay

A unified React Native payment module supporting Apple Pay (iOS) and Google Pay (Android) with a consistent, type-safe API.

npm version License: MIT TypeScript Expo Compatible

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.


Features

  • ✅ 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

Installation

Step 1: Install React Native Nitro Modules

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

Step 2: Install React Native Pay

npm install @gmisoftware/react-native-pay
# or
yarn add @gmisoftware/react-native-pay
# or
bun add @gmisoftware/react-native-pay

Prerequisites

  • React Native 0.70+
  • React Native Nitro Modules 0.36.0+ (required)
  • Android minSdkVersion 26+ (required for Nitro Modules prefab)
  • Expo 53–57 (optional; only if you use Expo. SDK 57 requires Node.js 22.13+)

Platform Setup

iOS Setup (Apple Pay)

1. Configure Expo Config Plugin

Add the Apple Pay plugin to your app.json or app.config.js:

{
  "expo": {
    "plugins": [
      [
        "@gmisoftware/react-native-pay",
        {
          "merchantIdentifier": "merchant.com.yourcompany.app"
        }
      ]
    ]
  }
}

2. Apple Developer Account Setup

  1. Create a Merchant ID in Apple Developer Portal:

  2. Enable Apple Pay in your App ID:

    • Go to your App ID settings
    • Enable "Apple Pay Payment Processing"
    • Associate your Merchant ID
  3. Create Payment Processing Certificate:

    • Create a Payment Processing Certificate for your Merchant ID
    • Download and install it in your payment processor (Stripe, etc.)

3. Run Prebuild (Expo)

npx expo prebuild --clean

Android Setup (Google Pay)

Minimum SDK: set minSdkVersion to 26 or higher (e.g. via expo-build-properties). Nitro Modules 0.36 prefab requires API 26+.

1. Configure Expo Config Plugin

Add the Google Pay plugin to your app.json or app.config.js:

{
  "expo": {
    "plugins": [
      [
        "@gmisoftware/react-native-pay",
        {
          "enableGooglePay": true
        }
      ]
    ]
  }
}

2. Google Cloud Console Setup

  1. Enable Google Pay API:

  2. 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

3. Run Prebuild (Expo)

npx expo prebuild --clean

Combined Setup (Both Platforms)

For apps supporting both platforms:

{
  "expo": {
    "plugins": [
      [
        "@gmisoftware/react-native-pay",
        {
          "merchantIdentifier": "merchant.com.yourcompany.app",
          "enableGooglePay": true
        }
      ]
    ]
  }
}

Quick Start

Basic Example with Hook (Recommended)

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 CheckoutScreen

result.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.


Documentation

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.

Payment Flow Overview

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

Google Pay Configuration

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).

Supported Payment Gateways

  • 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.


API Reference

usePaymentCheckout(config)

The all-in-one hook for handling payments. Manages availability checking, cart state, and payment processing.

Configuration

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"];
}

Returns

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
}

Example

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();

HybridPaymentHandler

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.

Methods

payServiceStatus(options?: PayServiceStatusOptions): Promise<PayServiceStatus>

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.

startPayment(request: PaymentRequest, options?: StartPaymentOptions): Promise<PaymentResult>

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.

isPaymentInProgress(): boolean

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();
openPaymentSetup(): void

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.


Button Components

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.

ApplePayButton (iOS)

Native Apple Pay button with full customization.

Props
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.

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

GooglePayButton (Android)

Native Google Pay button with customization.

Props
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;
}
Example
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 }}
/>

Utility Functions

createPaymentRequest(config)

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).

normalizePaymentRequest(request)

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

createPaymentItem(label, amount, type)

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

calculateTotal(items)

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.39

formatNetworkName(network)

Format card network name for display.

import { formatNetworkName } from "@gmisoftware/react-native-pay";

formatNetworkName("visa"); // "Visa"
formatNetworkName("mastercard"); // "Mastercard"
formatNetworkName("amex"); // "American Express"

TypeScript Types

Core Types

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

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.005 in USD, "1200.5" in JPY). This includes unrounded float results such as 0.1 + 0.2; round them with formatAmount(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.

Merchant capabilities

"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.

Shipping and contact details

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.

Updating the cart in the sheet

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.

Subscriptions and later payments

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.

Several merchants (iOS)

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.

Contact Types

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

Advanced Usage

Manual Payment Flow (Without Hook)

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

Dynamic Cart Management

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();
};

Custom Payment Buttons

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.

Charging Before the Sheet Closes

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
  };
}
  • onAuthorize must 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 onAuthorize runs 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 error to the payer, or "Payment authorization failed" without one or after a rejection. If Google Pay returns the payment without asking first, onAuthorize runs after its sheet has closed and only decides the PaymentResult.

Server-Side Processing

After receiving the payment token, process it on your server:

Node.js example

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.


Architecture

Package Structure

@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

Design Principles

  1. Platform Abstraction - Single API for both iOS and Android
  2. Type Safety - Full TypeScript coverage; payment amounts are checked at runtime
  3. Performance - Built with Nitro Modules for native speed
  4. Developer Experience - Simple hooks API with sensible defaults
  5. Production Focused - Designed around backend-controlled payment flows

Troubleshooting

iOS Issues

Apple Pay button not showing

ApplePayButton renders on iOS whatever the Apple Pay setup. If it's missing, your app hid it: check what isSupported and hasActiveCard returned.

The payment fails with CONFIGURATION

  • Verify merchant ID is correctly configured in Apple Developer Portal and matches exactly
  • "No Apple Pay merchant identifier configured": set merchantIdentifier in the Expo plugin and run npx expo prebuild --clean, or add the Info.plist key ReactNativePayApplePayMerchantIdentifiers in a bare app
  • Add a card to Apple Wallet on your test device

Android Issues

Google Pay button not showing

GooglePayButton renders on Android whatever the Google Pay setup. If it's missing, your app hid it: check what isSupported and hasActiveCard returned.

isSupported or hasActiveCard is false on Android

  • Check that enableGooglePay: true is 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

General Issues

Build errors with Nitro

# 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

Type errors

# Regenerate types
cd package
bun run typecheck
bun run specs

Examples

Check 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:android

Contributing

We welcome contributions! Please follow these guidelines:

Development Setup

# 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

Code Style

  • Follow existing TypeScript patterns
  • Add JSDoc comments for public APIs
  • Use Prettier for formatting (runs automatically)
  • Ensure types are properly exported

Testing

  • Test on both iOS and Android
  • Test with real devices (Simulator/Emulator support limited)
  • Verify in both TEST and PRODUCTION modes

Pull Requests

  • Create a feature branch from main
  • Write descriptive commit messages
  • Update documentation for API changes
  • Add examples for new features

Roadmap

  • Recurring payment support
  • Shipping address collection
  • Multi-currency support
  • Payment request validation
  • Detailed transaction logging
  • Web support (via Payment Request API)

License

MIT © GMI Software


Credits


Support


Made with ❤️ by gmi.software

About

Unified Apple and Google Pay for React Native

Resources

Code of conduct

Contributing

Stars

13 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages