Introduction to the

Although Stripe is only the second most popular payment gateway (PayPal is still the number one), its usage is steadily increasing among new and existing companies around the world. Stripe has reportedly processed more than $200 billion worth of transactions.

While there are plenty of other payment processors, Stripe makes it easy to process international transactions, especially if you want to accept payments in DOLLARS, pounds, euros, or any other international currency.

With the release of the official Stripe React Native SDK, it’s easier to accept payments or set up subscriptions via Stripe in your React Native App. While the SDK is still in beta, it’s worth taking a closer look at what the SDK offers and how it reduces integration time and enhances UI/UX.

In this tutorial, I’ll show you how to accept payments using the newly released official Stripe React Native SDK.

Here’s what we’re going to talk about.

  • What is Stripe?
  • Stripe’s React Native SDK
  • Set up a Stripe account
  • Build a React Native Stripe application
  • Building payment screens

To follow this React Native styling tutorial, you should have one.

  • Familiar with CSS, HTML and Javascript (ES6).
  • Install Node.js and Watchman on your development machine
  • An iOS or Android emulator for testing
  • Install a Code editor (such as VS Code) on your development machine.
  • React has a basic understanding

What is Stripe?

Stripe is a financial and software service that helps software developers and e-commerce companies make seamless payments through its apis. You could call Stripe a software as a service (SaaS) company.

As fintech continues to gain sponsorship from new and existing SaaS companies around the world, one of three paid services published online uses Stripe as a payment option. Learning more about how to integrate Stripe in your React Native app will be the best way to reduce the hassle of payment integration in your iOS and Android apps.

Stripe’s React Native SDK

Now that you know what Stripe is, the best way to get started with the Stripe API is to read the official Stripe documentation here.

But guess what? The Stripe React Native SDK can reduce this process by about 60%.

Let’s explore the Stripe React Native SDK to see what it has to offer. Below is a list of features for v0.1.2.

security

The Stripe React Native SDK helps you collect sensitive data, such as credit card numbers, and securely accept payments by sending the data to Stripe’s API instead of going through your backend server.

Apple Pay and other payment methods

The SDK features support for multiple payment methods such as bank transfer, debit, and redirection; Credit card; Buy now, pay later; Coupons and digital wallets. It also has selective support for Apple Pay. You can read Stripe’s official documentation on integrating Apple Pay and how to integrate other payment methods here.

Applicable to the SCA

The SDK performs 3D authentication by default, which is consistent with the strong customer authentication provided by Stripe. Read more about Stripe’s card authentication and 3D security here.

Local user interface

The Stripe React Native SDK comes with a Native screen and elements to securely accept payments on Android and iOS.

Pre-built payment interface (beta version)

The SDK supports the pre-built payment UI provided by Stripe. The feature is in beta and supports Apple Pay, Google Pay and card payment UIs. However, there are plans to build support for more payment options in the future. You can read about Stripe’s payment UI here.

In these tutorials, we’ll explore some of these features by building and testing a payment screen in our React Native App. Let’s start in the next section.

Set up a Stripe account

Every SDK requires a personal access key, and Stripe is no exception. To continue with this React Native tutorial, we had to create a Stripe account and obtain our personal key in order to accept payments.

The first step is to visit dashboard.stripe.com/register, create an account, or log in to your current account.

Next, get your public key. Be sure to keep your key private; It is the access key to your Stripe account.

The screenshot below shows where you can find your public key in the Stripe account.

React Native Stripe application

Now that you have created your Stripe account and obtained your public key, let’s initialize a new React Native application and install the Stripe React Native SDK.

Navigate to your development directory and paste the command below to install a new React Native application.

npx react-native StripeReactNative

Copy the code

Once installed, navigate to StripeReactNative from your terminal and paste the code below to install the StripeReactNative SDK package into your application.

yarn add @stripe/stripe-react-native
or
npm install @stripe/stripe-react-native

Copy the code

The Stripe React Native SDK has some requirements for Android and iOS support. You can refer to it here.

The android

  • Android 5.0 (API level 21) or above
  • Android Gradle plugin 4.x and above

iOS

  • Compatible with apps for iOS 11 or later.

Install it on iOS

Installing the Stripe React Native SDK on iOS is a bit more complicated than installing it on Android.

StripeReactNative. Xcworkspace passed the NPM install package in order to avoid errors, please in XCode, and set your deployment target to iOS 11.0, see the screenshot below as an example.

Run your project from Xcode to make sure all changes are applied, then navigate to the iOS folder. Open your podfile, update Platform :ios, ‘10.0’ to Platform :ios, ‘11.0’, and run Pod Install. This will install Stripe’s native dependencies for iOS.

Next, let’s remove the default React Native code in app.js. Update the app.js file with the following code.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */
import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
} from 'react-native';


const App = ()  => {
  return (
    <SafeAreaView>
    </SafeAreaView>
  );
};
const styles = StyleSheet.create({
});
export default App;

Copy the code

If you run the app, you should see a blank screen similar to the one below.

Building payment screens

Now that we’ve successfully installed the SDK, let’s move on to building our first payment screen.

Build a card component

First, create a new folder called Screens under the root of your React Native app.

Navigate to that folder and create a new file called paymentScreen.js, then paste the code below.

import React, {useState} from "react"; import { CardField, CardFieldInput, useStripe, } from '@stripe/stripe-react-native'; export default PaymentScreen = () => { const [card, setCard] = useState(CardFieldInput.Details | null); const {confirmPayment, handleCardAction} = useStripe() return( <CardField postalCodeEnabled={true} placeholder={{ number: '4242 4242 4242 4242', }} cardStyle={{ backgroundColor: '#FFFFFF', textColor: '#000000', }} style={{ width: '100%', height: 50, marginVertical: 30, }} onCardChange={(cardDetails) => { setCard(cardDetails); }} onFocus={(focusedField) => { console.log('focusField', focusedField); }}} / >)Copy the code

Next, let’s import paymentscreen.js into the root directory of our project.

Open app.js and update its code to look like the code below.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */
import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
} from 'react-native';
import { StripeProvider } from '@stripe/stripe-react-native';
import PaymentScreen from "./screens/paymentScreen";
const App = ()  => {
  const publishableKey = "pk_test_AtN3VLAFhzbLNqf3Y9z50iNQ";
  return (
    <StripeProvider
      publishableKey={publishableKey}
    >
      <PaymentScreen />
    </StripeProvider>
  );
};
const styles = StyleSheet.create({
});
export default App;

Copy the code

Let’s run our application to test what we’ve built so far. Run NPX react-native run-ios to run a build for ios.

You might get an error with undefined symbols for Architecture x86_64, but don’t panic! To fix this error, follow these steps. To resolve this error, follow these steps.

LIBRARY_SEARCH_PATHS = ( remove: "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", remove: "\" $(TOOLCHAIN_DIR)/usr/lib/swift - 5.0 / $(PLATFORM_NAME) \ ""," \ "$(inherited) \", ");Copy the code

Open your project in Xcode and create a new Swift file ** (File **> New **> File >Swift). Name the file anything (for example, fix.swift) and choose to create a bridge connector ** when prompted by Xcode.

Run NPX React-native run-ios again and the error should be fixed. If you are successful, your application should look like the screenshot below when it loads.

We’ve just created a simple card component that sends the card details directly to the Stripe server for real-time validation, and then stores the status of the component.

Pre-built UI (single-step

This feature is a combination of all the steps to accept payments in Stripe using credit card details. This integration requires an endpoint that communicates with the Stripe API from your server.

Create an endpoint

To set up a server that communicates with Stripe from React Native, we need to initialize a new Node.js application, namely Install Express Body-Parser and Dotenv.

Create a new folder named Server, navigate to it, run NPM init -y, and follow the instructions to create a new Node application. Then, run the NPM I Express Body-Parser dotenv.

Finally, create a server.js file at the root layer of the server folder and paste the following code into it.

require("dotenv").config();
const express = require("express");
const app = express();
const { resolve } = require("path");
const stripe = require("stripe")(process.env.secret_key); // https://stripe.com/docs/keys#obtain-api-keys
app.use(express.static("."));
app.use(express.json());
// An endpoint for your checkout 
app.post("/checkout", async (req, res) => { 
  // Create or retrieve the Stripe Customer object associated with your user.
  let customer = await stripe.customers.create(); // This example just creates a new Customer every time

  // Create an ephemeral key for the Customer; this allows the app to display saved payment methods and save new ones
  const ephemeralKey = await stripe.ephemeralKeys.create(
    {customer: customer.id},
    {apiVersion: '2020-08-27'}
  );  

  // Create a PaymentIntent with the payment amount, currency, and customer
  const paymentIntent = await stripe.paymentIntents.create({
    amount: 973,
    currency: "usd",
    customer: customer.id
  });

  // Send the object keys to the client
  res.send({
    publishableKey: process.env.publishable_key, // https://stripe.com/docs/keys#obtain-api-keys
    paymentIntent: paymentIntent.client_secret,
    customer: customer.id,
    ephemeralKey: ephemeralKey.secret
  });
});

app.listen(process.env.PORT, () =>
  console.log(`Node server listening on port ${process.env.PORT}!`)
);

Copy the code

Don’t forget to create a.env file with the following code.

secret_key=Your_Secret_Key
PORT=8000

Copy the code

Next, update paymentscreen.js with the following code to add a checkout button to the application.

import React, { useState, useEffect } from "react";
import { StyleSheet, Button, View} from 'react-native';
import {
  CardField,
  CardFieldInput,
  useStripe,
} from '@stripe/stripe-react-native';

export default PaymentScreen = () => {
  const [card, setCard] = useState(CardFieldInput.Details | null);
  const { confirmPayment, handleCardAction } = useStripe()
  const API_URL = "http://localhost:8000";
  const { initPaymentSheet, presentPaymentSheet } = useStripe();
  const [loading, setLoading] = useState(false);

  const fetchPaymentSheetParams = async () => {
    const response = await fetch(`${API_URL}/checkout`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    const { paymentIntent, ephemeralKey, customer } = await response.json();
    return {
      paymentIntent,
      ephemeralKey,
      customer,
    };
  };
  const initializePaymentSheet = async () => {
    const {
      paymentIntent,
      ephemeralKey,
      customer,
    } = await fetchPaymentSheetParams();
    const { error } = await initPaymentSheet({
      customerId: customer,
      customerEphemeralKeySecret: ephemeralKey,
      paymentIntentClientSecret: paymentIntent,
    });
    if (!error) {
      setLoading(true);
    }
  };
  const openPaymentSheet = async () => {
    const { error } = await presentPaymentSheet({ clientSecret });
    if (error) {
      Alert.alert(`Error code: ${error.code}`, error.message);
    } else {
      Alert.alert('Success', 'Your order is confirmed!');
    }
  };
  useEffect(() => {
    initializePaymentSheet();
  }, []);
  return (
    <View style={styles.container}>
      <CardField
        postalCodeEnabled={false}
        placeholder={{
          number: '4242 4242 4242 4242',
        }}
        cardStyle={{
          backgroundColor: '#FFFFFF',
          textColor: '#000000',
        }}
        style={{
          width: '100%',
          height: 50,
          marginVertical: 30,
        }}
        onCardChange={(cardDetails) => {
          setCard(cardDetails);
        }}
        onFocus={(focusedField) => {
          console.log('focusField', focusedField);
        }}
      />
        <Button
          style={styles.button}
          disabled={!loading}
          title="Checkout"
          color="#841584"
          onPress={openPaymentSheet}
        />
        </View>
  )
}
const styles = StyleSheet.create({
  container: {
     flex: 1,
     padding: 20,
     marginHorizontal: 10,
     marginVertical: 10,
  },
  button: {
     backgroundColor: '#00aeef',
     borderColor: 'red',
     borderWidth: 5,
     borderRadius: 15       
  }
})

Copy the code

As shown above, create a separate Node.js project and set the server port to 8000. From React Native, send a request to the server’s /checkout endpoint. Once the request is successful, initializePaymentSheet is called using the useEffect hook.

During this process, the button remains disabled until a response is received from the back end. Note that your backend server must be up and running as long as you intend to communicate with it.

At this point, your application should look similar to the screenshot below.

conclusion

Stripe’s React Native SDK is easy to implement. It is becoming a favorite among developers due to its support for pre-made UIs (including plans to support more in the future) and payment options.

The postExploring the new Stripe React Native SDKappeared first onLogRocket Blog.