Wednesday

18-06-2025 Vol 19

🍏 Integrating Apple Pay with Stripe in a React Native CLI Project (iOS)

Integrating Apple Pay with Stripe in a React Native CLI Project (iOS)

Accepting payments in your React Native application is crucial for many business models. Apple Pay provides a seamless and secure payment experience for iOS users. This comprehensive guide will walk you through integrating Apple Pay with Stripe in a React Native CLI project (specifically targeting iOS). We will cover setup, configuration, coding, and testing, ensuring you have a robust and functional payment system.

Table of Contents

  1. Introduction to Apple Pay and Stripe
  2. Prerequisites
  3. Setting up your Stripe Account and Apple Developer Account
  4. Creating a New React Native CLI Project
  5. Installing Required Dependencies
  6. Configuring Your iOS Project
    1. Adding the Apple Pay Capability
    2. Configuring the Merchant Identifier
  7. Implementing the Apple Pay Integration
    1. Creating the Payment Request
    2. Presenting the Apple Pay Sheet
    3. Handling Payment Authorization
    4. Completing the Payment
  8. Implementing Backend for Payment Processing
    1. Setting up a Backend Server (Node.js Example)
    2. Creating the Payment Intent Endpoint
    3. Verifying the Payment
  9. Testing Your Apple Pay Integration
  10. Handling Errors and Edge Cases
  11. Best Practices for Security and User Experience
  12. Troubleshooting Common Issues
  13. Conclusion

1. Introduction to Apple Pay and Stripe

Apple Pay is a mobile payment and digital wallet service by Apple, allowing users to make payments in person, in iOS apps, and on the web using Safari. It offers a secure and convenient payment method by using tokenization and biometric authentication.

Stripe is a powerful and versatile payment gateway that provides the infrastructure needed to accept payments online. It offers a wide range of APIs and tools that make integrating payment processing into your application straightforward.

By combining Apple Pay with Stripe, you can provide your users with a secure, frictionless, and trusted payment experience within your React Native iOS application.

2. Prerequisites

Before you begin, ensure you have the following prerequisites:

  • Node.js and npm (or Yarn) installed: These are required for React Native development.
  • React Native CLI installed: You should have the React Native command-line interface installed globally. npm install -g react-native-cli
  • Xcode installed: Xcode is required for iOS development. Ensure you have the latest version installed from the Mac App Store.
  • CocoaPods installed: CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. sudo gem install cocoapods
  • A Stripe account: You need a Stripe account to process payments. Sign up for a Stripe account if you don’t have one already.
  • An Apple Developer account: You need an Apple Developer account to configure Apple Pay and generate the necessary certificates and identifiers.
  • A physical iOS device: While you can simulate some aspects of Apple Pay, testing on a physical device is crucial for verifying the full functionality. Ensure your device supports Apple Pay.

3. Setting up your Stripe Account and Apple Developer Account

Stripe Account Setup:

  1. Sign up for a Stripe account: Go to Stripe’s website and create an account.
  2. Activate your account: Complete the necessary steps to activate your Stripe account, including providing business information and linking a bank account.
  3. Obtain your API keys: Navigate to the Stripe dashboard and retrieve your publishable key and secret key. Keep your secret key secure! Do not expose it in your client-side code.
  4. Configure your Apple Pay settings in Stripe: In the Stripe dashboard, go to Settings -> Payment Methods -> Apple Pay and follow the instructions to register your domain.

Apple Developer Account Setup:

  1. Log in to your Apple Developer account: Go to the Apple Developer website and log in.
  2. Create a Merchant Identifier:
    • Navigate to Certificates, Identifiers & Profiles.
    • Under Identifiers, select “Merchant IDs”.
    • Click the “+” button to create a new Merchant ID.
    • Enter a description and a unique identifier (e.g., merchant.com.yourcompany.appname). This identifier will be used in your application and Stripe configuration.
    • Register the Merchant ID.
  3. Create an App ID:
    • Navigate to Certificates, Identifiers & Profiles.
    • Under Identifiers, select “App IDs”.
    • Click the “+” button to create a new App ID.
    • Enter a description for your app.
    • Select “Explicit App ID” and enter your bundle identifier (e.g., com.yourcompany.appname).
    • Under Capabilities, enable the “Apple Pay” capability and configure it to use the Merchant ID you created.
    • Register the App ID.
  4. Create a Development Provisioning Profile:
    • Navigate to Certificates, Identifiers & Profiles.
    • Under Provisioning Profiles, select “Development”.
    • Click the “+” button to create a new provisioning profile.
    • Select your App ID and the devices you want to use for development.
    • Download the provisioning profile.

4. Creating a New React Native CLI Project

If you don’t have an existing React Native project, create a new one using the following command:

npx react-native init ApplePayStripeExample

Replace ApplePayStripeExample with the desired name for your project.

Once the project is created, navigate to the project directory:

cd ApplePayStripeExample

5. Installing Required Dependencies

You’ll need to install the following dependencies:

  • @stripe/stripe-react-native: This library provides the necessary components and functions for integrating Stripe with your React Native application.

Install the dependencies using npm or Yarn:

npm install @stripe/stripe-react-native

or

yarn add @stripe/stripe-react-native

After installing the dependencies, you need to link the native modules. For React Native 0.60+, this is usually done automatically with autolinking. However, it is often useful to perform the linking manually to ensure everything works correctly. Navigate to your `ios` directory and run:

cd ios
pod install

If you encounter any issues, you may need to clean your build and rebuild the project.

6. Configuring Your iOS Project

Now, you need to configure your iOS project to support Apple Pay.

6.1 Adding the Apple Pay Capability

  1. Open your project in Xcode: Open the ios/ApplePayStripeExample.xcworkspace file (or your project’s equivalent) in Xcode.
  2. Select your project in the Project Navigator: Click on the project name in the left sidebar.
  3. Select your target: Choose your app’s target from the “TARGETS” list.
  4. Go to the “Signing & Capabilities” tab: Click on this tab.
  5. Add the “Apple Pay” capability: Click the “+ Capability” button and search for “Apple Pay”. Add the capability.
  6. Configure the Merchant Identifiers: In the Apple Pay capability settings, add the Merchant ID you created in the Apple Developer account. Click the “+” button and enter your Merchant ID.

6.2 Configuring the Merchant Identifier

Ensure that the Merchant Identifier you added in Xcode matches the one you created in your Apple Developer account and configured in your Stripe account.

Also, verify that your Bundle Identifier in Xcode matches the App ID you created in your Apple Developer account.

7. Implementing the Apple Pay Integration

Now, let’s implement the Apple Pay integration in your React Native application.

7.1 Creating the Payment Request

First, you need to create a payment request that specifies the details of the transaction, such as the amount, currency, and supported payment networks.

Here’s an example of how to create a payment request in your React Native component:

import React, { useState, useEffect } from 'react';
import { View, Button, Alert } from 'react-native';
import { useStripe } from '@stripe/stripe-react-native';

const App = () => {
  const { initPaymentSheet, presentPaymentSheet } = useStripe();
  const [loading, setLoading] = useState(false);

  const initializePaymentSheet = async () => {
    setLoading(true);

    // 1. Fetch the PaymentIntent client secret from your backend
    const response = await fetch('YOUR_BACKEND_ENDPOINT/create-payment-intent', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        amount: 1000, // Amount in cents
        currency: 'usd',
      }),
    });
    const { clientSecret } = await response.json();

    // 2. Initialize the Payment Sheet with the client secret
    const { error } = await initPaymentSheet({
      paymentIntentClientSecret: clientSecret,
      merchantDisplayName: 'Your Company Name', // Replace with your company name
      allowsDelayedPaymentMethods: true, // allows use of delayed payment methods like 'ACH'
    });

    if (error) {
      Alert.alert('Error initializing payment sheet', error.message);
    }

    setLoading(false);
  };

  const handlePayment = async () => {
    setLoading(true);

    // 3. Present the Payment Sheet
    const { error } = await presentPaymentSheet();

    if (error) {
      Alert.alert('Error presenting payment sheet', error.message);
    } else {
      Alert.alert('Success', 'Your payment was successful!');
    }

    setLoading(false);
  };

  useEffect(() => {
    initializePaymentSheet();
  }, []);

  return (
    
      

Important Notes:

  • Replace YOUR_BACKEND_ENDPOINT/create-payment-intent with the actual URL of your backend endpoint for creating Payment Intents (more on that later).
  • Replace Your Company Name with the actual name of your company.
  • The amount should be in the smallest currency unit (e.g., cents for USD).

7.2 Presenting the Apple Pay Sheet

The presentPaymentSheet function from @stripe/stripe-react-native library will display the Apple Pay sheet to the user. The user can then select their preferred payment method (including Apple Pay if configured) and authorize the payment.

The allowsDelayedPaymentMethods: true parameter can be added during the initPaymentSheet initialization to support payments that can take several days to complete (e.g. ACH). This parameter has to be set before calling the presentPaymentSheet() method.

7.3 Handling Payment Authorization

After the user authorizes the payment, Stripe will handle the payment processing. You need to verify the payment status on your backend to ensure that the payment was successful.

7.4 Completing the Payment

On your backend, you’ll use the Stripe API to confirm the Payment Intent. This finalizes the payment and captures the funds.

8. Implementing Backend for Payment Processing

Handling payment processing directly in your React Native application is not secure. You need to implement a backend to handle sensitive operations like creating Payment Intents and confirming payments. This example uses Node.js, but the principles apply to other backend technologies.

8.1 Setting up a Backend Server (Node.js Example)

Create a new Node.js project and install the Stripe library:

mkdir stripe-backend
cd stripe-backend
npm init -y
npm install stripe express cors

Create an index.js file with the following code:

const express = require('express');
const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY'); // Replace with your secret key
const cors = require('cors');

const app = express();
const port = 3000;

app.use(express.json());
app.use(cors());

app.post('/create-payment-intent', async (req, res) => {
  try {
    const { amount, currency } = req.body;

    // Create a PaymentIntent with the order amount and currency
    const paymentIntent = await stripe.paymentIntents.create({
      amount: amount,
      currency: currency,
      automatic_payment_methods: {
        enabled: true,
      },
    });

    res.send({
      clientSecret: paymentIntent.client_secret,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: error.message });
  }
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

Important Notes:

  • Replace YOUR_STRIPE_SECRET_KEY with your actual Stripe secret key.
  • Ensure you are using the secret key and not the publishable key.
  • Install CORS package for enabling cross-origin requests

8.2 Creating the Payment Intent Endpoint

The /create-payment-intent endpoint is responsible for creating a Payment Intent on the Stripe server. The Payment Intent represents the intent to collect funds from a customer and tracks the lifecycle of the payment process.

This endpoint receives the amount and currency from the client-side application and creates a Payment Intent with those parameters. The automatic_payment_methods parameter is set to enabled: true to allow Stripe to automatically determine the best payment methods to offer the customer.

8.3 Verifying the Payment

After the client-side application receives confirmation that the payment was successful, you should verify the payment status on your backend. You can do this by retrieving the Payment Intent from Stripe and checking its status.

Add the following endpoint to your index.js file:

app.post('/verify-payment', async (req, res) => {
  try {
    const { paymentIntentId } = req.body;

    const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);

    if (paymentIntent.status === 'succeeded') {
      res.send({ status: 'succeeded' });
    } else {
      res.send({ status: 'failed', error: paymentIntent.last_payment_error?.message });
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: error.message });
  }
});

This endpoint receives the Payment Intent ID from the client and retrieves the Payment Intent from Stripe. It then checks the status of the Payment Intent. If the status is succeeded, it sends a success response to the client. Otherwise, it sends a failure response with the error message.

Important Notes:

  • Always verify the payment status on your backend to prevent fraud and ensure that payments are processed correctly.

9. Testing Your Apple Pay Integration

Testing your Apple Pay integration is crucial to ensure it functions correctly and provides a seamless user experience.

  1. Test on a physical device: While you can simulate Apple Pay in the simulator, testing on a physical device is essential to ensure that the payment sheet is displayed correctly and that the payment flow works as expected.
  2. Use a test Stripe account: Use your Stripe test API keys to simulate payments without actually charging real money.
  3. Test different payment methods: Try different payment methods, such as Apple Pay with different credit cards, to ensure that the integration works correctly for all supported payment methods.
  4. Test different amounts: Try different payment amounts, including very small and very large amounts, to ensure that the integration handles different payment amounts correctly.
  5. Test error scenarios: Simulate error scenarios, such as payment failures and network errors, to ensure that the integration handles errors gracefully and provides informative error messages to the user.

10. Handling Errors and Edge Cases

Handling errors and edge cases is essential to ensure that your Apple Pay integration is robust and reliable.

  • Network errors: Handle network errors gracefully by displaying informative error messages to the user and providing them with options to retry the payment.
  • Payment failures: Handle payment failures by displaying informative error messages to the user and providing them with options to try a different payment method or contact customer support.
  • Invalid payment information: Validate payment information on the client-side and server-side to prevent invalid payment information from being submitted.
  • Duplicate payments: Implement measures to prevent duplicate payments, such as by using unique order IDs and checking for existing payments before processing new payments.
  • Expired payment methods: Handle expired payment methods by displaying informative error messages to the user and prompting them to update their payment information.

11. Best Practices for Security and User Experience

Following best practices for security and user experience is essential to ensure that your Apple Pay integration is secure and provides a positive experience for your users.

  • Use HTTPS: Always use HTTPS to encrypt communication between your client-side application and your backend server.
  • Protect your API keys: Never expose your Stripe secret key in your client-side code. Store it securely on your backend server.
  • Validate payment information: Validate payment information on the client-side and server-side to prevent invalid payment information from being submitted.
  • Implement fraud prevention measures: Implement fraud prevention measures, such as Address Verification System (AVS) and Card Verification Value (CVV) checks, to protect against fraudulent transactions.
  • Provide clear and informative error messages: Display clear and informative error messages to the user when errors occur.
  • Offer multiple payment options: Offer multiple payment options, including Apple Pay and other payment methods, to provide users with flexibility and choice.
  • Optimize the payment flow: Optimize the payment flow to make it as seamless and frictionless as possible.
  • Test your integration thoroughly: Test your integration thoroughly to ensure that it functions correctly and provides a positive user experience.

12. Troubleshooting Common Issues

Here are some common issues you might encounter during the Apple Pay integration process and how to troubleshoot them:

  • “Apple Pay is not available” error:
    • Ensure that Apple Pay is enabled on your device.
    • Ensure that your device supports Apple Pay.
    • Ensure that you have a valid payment card added to your Apple Wallet.
    • Ensure that your Merchant ID is configured correctly in Xcode and your Apple Developer account.
  • “Payment sheet not displayed” error:
    • Ensure that you have initialized the Payment Sheet correctly.
    • Ensure that you have a valid Payment Intent client secret.
    • Ensure that your Merchant ID is configured correctly in Xcode and your Apple Developer account.
  • “Payment failed” error:
    • Check the error message returned by Stripe for more information about the cause of the failure.
    • Ensure that the payment card has sufficient funds.
    • Ensure that the payment card is not expired or blocked.
    • Contact Stripe support for assistance.
  • CocoaPods errors during installation:
    • Ensure that you have the latest version of CocoaPods installed.
    • Try running pod install again.
    • Try cleaning your build and rebuilding the project.
    • Check your Podfile for any errors or inconsistencies.

13. Conclusion

Integrating Apple Pay with Stripe in your React Native iOS application can significantly improve the user experience and increase conversion rates. By following this comprehensive guide, you can implement a secure and reliable payment system that provides your users with a seamless and convenient payment experience.

Remember to prioritize security, handle errors gracefully, and test your integration thoroughly to ensure that it functions correctly and provides a positive experience for your users. Good luck!

“`

omcoding

Leave a Reply

Your email address will not be published. Required fields are marked *