The Rise of Online Payments: Why PaymentSheet is the Way to Go
The Case for PaymentSheet
In today’s digital age, online payments have become the norm. With the pandemic accelerating the shift towards contactless transactions, mobile apps have had to adapt quickly to meet the demand. Many developers are turning to Stripe to integrate online payments into their React Native Android and iOS projects.
When it comes to integrating online payments, Stripe offers two options: PaymentSheet and Elements. While both options have their advantages, PaymentSheet stands out for its ease of use and streamlined integration. Here are just a few reasons why:
- Less Configuration: With PaymentSheet, Stripe has already taken care of most of the configuration for you. This means you don’t have to worry about managing different card configurations for various countries.
- Error Handling: PaymentSheet takes care of error handling, alerting users to any issues with their payment method. This reduces the burden on developers and ensures a smoother user experience.
- Data Privacy: PaymentSheet ensures that you don’t need to store any sensitive data on your servers, protecting you from accidentally breaching data privacy laws.
Building a Donation App with Expo and React Native
Now that we’ve made the case for PaymentSheet, let’s put it into practice. We’ll build a donation app using Expo and React Native, with PaymentSheet handling the payment processing.
Setting Up the Project
To get started, you’ll need:
- Node installed on your machine
- A code editor (such as Visual Studio Code)
- A Stripe account
- The Stripe CLI installed
- A working knowledge of Node and React Native
Creating a Node.js Server
First, we’ll create a Node server to handle Stripe operations. We’ll use Express to create a REST API and the cors package to enable communication between our server and client.
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: true }));
// Initialize Stripe
const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY');
Initializing an Express Server and Handling Stripe Operations
We’ll create a basic server boilerplate and initialize an Express app. We’ll then create a POST route to handle donations and create a PaymentIntent.
app.post('/donate', async (req, res) => {
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: 1000,
currency: 'usd',
});
res.json({ clientSecret: paymentIntent.client_secret });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to create payment intent' });
}
});
Creating a Webhook
To test Stripe webhooks locally, we’ll use the Stripe extension in Visual Studio Code. We’ll create a route to handle Stripe webhook requests and verify the signature to ensure the request is from Stripe.
app.post('/webhook', async (req, res) => {
const sig = req.headers['stripe-signature'];
const event = stripe.webhooks.constructEvent(req.rawBody, sig, 'YOUR_STRIPE_WEBHOOK_SECRET');
// Handle the event
res.json({ received: true });
});
Creating the App with Expo and React Native
Now that our server is set up, we can move on to our Expo and React Native app. We’ll create a new folder for our app and install the Stripe package for Expo.
npx expo init my-donation-app
cd my-donation-app
npm install expo-stripe
Configuring Stripe in React Native
We’ll create a new component called Checkout.js and import the StripeProvider.
import { StripeProvider } from 'expo-stripe';
const Checkout = () => {
// Create a basic layout and map the states with the text boxes
return (
<StripeProvider>
<View>
<TextInput value={cardNumber} onChangeText={(text) => setCardNumber(text)} />
<TextInput value={expMonth} onChangeText={(text) => setExpMonth(text)} />
<TextInput value={expYear} onChangeText={(text) => setExpYear(text)} />
</View>
</StripeProvider>
);
};
Handling the Donate Function
Finally, we’ll handle the donate function by converting the values to integers, checking for errors, and initializing the PaymentSheet using the initPaymentSheet() function.
const handleDonate = async () => {
try {
const cardNumberInt = parseInt(cardNumber, 10);
const expMonthInt = parseInt(expMonth, 10);
const expYearInt = parseInt(expYear, 10);
// Initialize PaymentSheet
const paymentSheet = await initPaymentSheet({
paymentIntentClientSecret: 'YOUR_PAYMENT_INTENT_CLIENT_SECRET',
style: 'alwaysDark',
});
// Present the PaymentSheet
paymentSheet.present();
} catch (err) {
console.error(err);
alert('Failed to initialize PaymentSheet');
}
};
Congratulations! You’ve successfully integrated PaymentSheet into your Expo app. Now it’s time to play around and explore the possibilities. Try using Apple Pay and Google Pay alongside PaymentSheet, or experiment with different payment scenarios.