Stripe React Native SDK

repository·master·Indexed 23 days ago

https://github.com/stripe/stripe-react-native

SDK for building native payment experiences in Android and iOS apps using React Native. Provides pre-built UI components like PaymentSheet and Stripe Connect embedded components (Account Onboarding, Payouts, and Payments), with support for Apple Pay, Google Pay, and 3D Secure. Compatible with Expo and standard React Native projects.

Tokens
29.2K
Snippets
71
Records
147
Agent score
81%

What's inside @stripe/stripe-react-native

  1. Overview of Stripe Connect Embedded Components

    master

    The example app showcases three primary Stripe Connect embedded components provided by the @stripe/stripe-react-native SDK:

    • Account Onboarding: A localized onboarding form with data validation and configurable collection options.
    • Payouts: A component to view and perform payouts.
    • Payments: A component to view payment details, manage disputes, and filter payments by amount, date, status, and payment method.
  2. Understand the Stripe Connect Example App architecture

    master

    The application is built with the following stack and patterns:

    • Framework: Expo (React Native) using Expo Router for file-based routing.
    • SDK: @stripe/stripe-react-native.
    • State Management:
      • SettingsContext: React Context for global app state (merchant selection, appearance, component settings).
      • React Query: Manages server state (fetching merchant lists and publishable keys).
      • AsyncStorage: Provides persistent storage for user preferences.
    • Backend Integration: Communicates with a remote server (default: https://stripe-connect-mobile-example-v1.stripedemos.com/) via endpoints:
      • GET /app_info: Returns publishable key and available merchants.
      • POST /account_session: Creates an account session for embedded components.
    • Core Providers:
      • StripeProvider: Initializes the Stripe SDK with the publishable key.
      • ConnectComponentsProvider: A wrapper for each Connect component that handles client secret fetching, appearance application, and lifecycle management.
  3. Understand PaymentMethodMessagingElementState

    master

    The PaymentMethodMessagingElementState represents the current lifecycle state of the PaymentMethodMessagingElement component:

    • status: 'loading': The component is fetching or processing data.
    • status: 'loaded': The component has successfully loaded the messaging content.
    • status: 'no_content': The component loaded successfully but has no messaging to display.
    • status: 'failed': An error occurred during loading. This state includes an error object of type Error.
  4. Filter accepted Card Brands

    master

    You can control which card brands are accepted in your UI using CardBrandAcceptance. This is useful for limiting payment options to specific networks like Visa or Mastercard.

    Filter Modes:

    • All: Accepts all card brands.
    • Allowed: Only accepts the specific brands provided in the brands array.
    • Disallowed: Rejects the specific brands provided in the brands array.

    Card Brand Categories:

    • amex
    • discover
    • mastercard
    • visa
    export type CardBrandAcceptance = {
        filter: CardBrandAcceptanceFilter.All;
    } | {
        filter: CardBrandAcceptanceFilter.Allowed;
        brands: CardBrandCategory[];
    } | {
        filter: CardBrandAcceptanceFilter.Disallowed;
        brands: CardBrandCategory[];
    };
  5. Access Stripe methods in Class and Functional components

    master

    Stripe functions can be imported directly for use in both class and functional components. For functional components, you can also use dedicated hooks like useConfirmPayment (which provides a loading state) or the primary useStripe hook.

    // 1. Using useConfirmPayment hook (provides loading state)
    import { useConfirmPayment } from '@stripe/stripe-react-native';
    const { confirmPayment, loading } = useConfirmPayment();
    
    // 2. Using useStripe hook (provides all stripe methods)
    import { useStripe } from '@stripe/stripe-react-native';
    const { confirmPayment } = useStripe();
    
    // 3. Direct import (works in class or functional components)
    import { confirmPayment } from '@stripe/stripe-react-native';
  6. Configure Link appearance and display

    master

    The LinkDisplay enum controls whether Stripe Link is shown. Use LinkDisplay.AUTOMATIC (default) or LinkDisplay.NEVER.

    Appearance can be customized using LinkAppearance, which allows you to define lightColors, darkColors, a style ('AUTOMATIC' | 'ALWAYS_LIGHT' | 'ALWAYS_DARK'), and primaryButton settings (cornerRadius and height).

  7. Configure Stripe Connect component appearance

    master

    The app supports 9 theme presets to customize the visual appearance of embedded components. Each preset can modify colors, button styles, border radius, typography, and spacing:

    • Default: Uses Stripe SDK defaults
    • Dark mode: Comprehensive dark theme
    • Dynamic colors: GitHub-inspired palette
    • Forest: Nature-inspired green theme
    • Hot Dog Stand: Bold red/yellow theme
    • Link: Teal/green theme with custom spacing
    • Ocean Breeze: Light blue theme
    • Ogre: Lime/brown experimental theme
    • Retro: 90s-inspired monochrome
  8. Create a new Android Play Store release

    master

    To create a new release, you must increment the versionCode in app.json before building. The versionCode must be an integer higher than any previous upload. The version field is the human-readable string shown to users.

    Full Release Workflow:

    1. Bump version: Increment android.versionCode in app.json.
    2. Regenerate project: Run yarn prebuild to apply the new version and restore signing configuration.
    3. Build AAB: Run ./gradlew :app:bundleRelease in the android folder.
    4. Locate AAB: The signed bundle will be at android/app/build/outputs/bundle/release/app-release.aab.
    {
      "expo": {
        "version": "1.0.0",
        "android": {
          "versionCode": 3
        }
      }
    }
    # 1. Bump version in app.json
    # 2. Regenerate Android project
    yarn prebuild
    
    # 3. Build the release AAB
    cd android
    ./gradlew :app:bundleRelease
    
    # 4. Upload to Play Store
    # The AAB is at: android/app/build/outputs/bundle/release/app-release.aab
  9. Migrate Google Pay from tipsi-stripe to stripe-react-native

    master

    In stripe-react-native, Google Pay functionality is split into two distinct steps: initialization and presentation, replacing the single paymentRequestWithNativePay method used in tipsi-stripe.

    1. Initialize Google Pay: Use initGooglePay to configure the merchant name, country code, billing address requirements, and other settings.
    2. Present Google Pay: Use presentGooglePay to trigger the payment sheet, passing the clientSecret and currency configuration.
    // 1. Initialize
    const { error } = await initGooglePay({
        merchantName: 'Widget Store',
        countryCode: 'US',
        billingAddressConfig: {
          format: 'FULL',
          isPhoneNumberRequired: true,
          isRequired: false,
        },
        existingPaymentMethodRequired: false,
        isEmailRequired: true,
    });
    
    if (error) {
        // handle error
        return;
    }
    
    // 2. Present
    const { error: presentError } = await presentGooglePay({
        clientSecret,
        forSetupIntent: true,
        currencyCode: 'USD',
    });
  10. Android requirements and CardForm configuration

    master

    Android Requirements

    • Android 6.0 (API level 23) or higher.
    • compileSdkVersion must be 36 or higher.
    • Android gradle plugin 4.x or higher.
    • Kotlin 2.x or higher.

    Configure CardForm

    To use the CardForm component, you must configure a Material Components theme in your Android app:

    1. Add the Material dependency to app/build.gradle:
    implementation 'com.google.android.material:material:<version>'
    1. Set a Material Components parent style in styles.xml:
    <style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight">
        <!-- ... -->
    </style>
  11. Install and configure for Expo

    master

    Each Expo SDK version requires a specific version of stripe-react-native. Use expo install to ensure compatibility. After installation, you must configure the @stripe/stripe-react-native plugin in your app.json to enable features like Apple Pay (via merchantIdentifier) and Google Pay.

    expo install @stripe/stripe-react-native
    {
      "expo": {
        "plugins": [
          [
            "@stripe/stripe-react-native",
            {
              "merchantIdentifier": "string | string []",
              "enableGooglePay": "boolean"
            }
          ]
        ]
      }
    }