Today, you’ll integrate a payment gateway into your e-commerce app to enable users to purchase the items in their cart. We’ll use Stripe as our payment gateway, as it’s widely used and easy to set up in React Native.
What You Will Do Today:
- Set up a Stripe account and API keys.
- Install the Stripe SDK for React Native.
- Create a checkout function and integrate it with the cart.
Step 1: Set Up a Stripe Account and API Keys
- Go to the Stripe Dashboard and create an account if you don’t already have one.
- In the Developers section, find your Publishable Key and Secret Key:
- Use the Publishable Key for the app (client-side).
- Use the Secret Key on your server to create payment intents.
For security, we’ll use a test server to generate a payment intent. This server can be hosted on a platform like Heroku, Firebase Functions, or AWS Lambda.
Step 2: Setting Up a Test Server for Payment Intents
- Create a simple Express server to handle the payment intent with Stripe:
// server.js
const express = require('express');
const stripe = require('stripe')('YOUR_SECRET_KEY');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/create-payment-intent', async (req, res) => {
const { amount } = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency: 'usd',
});
res.send({ clientSecret: paymentIntent.client_secret });
} catch (error) {
res.status(500).send({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
- Replace
'YOUR_SECRET_KEY'
with your Stripe Secret Key. - Deploy this server on Heroku or any cloud provider and note the URL (e.g.,
https://your-server-url.com
).
Step 3: Install Stripe SDK for React Native
- Install Stripe React Native SDK:
npm install @stripe/stripe-react-native
- Import and initialize Stripe in
App.js
:
// App.js
import { StripeProvider } from '@stripe/stripe-react-native';
export default function App() {
return (
<StripeProvider publishableKey="YOUR_PUBLISHABLE_KEY">
<CartProvider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="LoginScreen" component={LoginScreen} options={{ title: 'Login' }} />
<Stack.Screen name="ProductList" component={ProductList} options={{ title: 'Products' }} />
<Stack.Screen name="ProductDetail" component={ProductDetail} options={{ title: 'Product Details' }} />
<Stack.Screen name="CartScreen" component={CartScreen} options={{ title: 'Cart' }} />
<Stack.Screen name="CheckoutScreen" component={CheckoutScreen} options={{ title: 'Checkout' }} />
</Stack.Navigator>
</NavigationContainer>
</CartProvider>
</StripeProvider>
);
}
Replace "YOUR_PUBLISHABLE_KEY"
with your Stripe Publishable Key.
Step 4: Create a Checkout Screen
- Create
CheckoutScreen.js
in thescreens
folder.
// screens/CheckoutScreen.js
import React, { useContext, useEffect, useState } from 'react';
import { View, Text, Button, StyleSheet, Alert } from 'react-native';
import { CartContext } from '../context/CartContext';
import { CardField, useStripe } from '@stripe/stripe-react-native';
function CheckoutScreen() {
const { cart } = useContext(CartContext);
const { confirmPayment } = useStripe();
const [clientSecret, setClientSecret] = useState('');
useEffect(() => {
const fetchPaymentIntent = async () => {
const amount = cart.reduce((sum, item) => sum + item.price * 100, 0); // Stripe expects amount in cents
const response = await fetch('https://your-server-url.com/create-payment-intent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ amount }),
});
const { clientSecret } = await response.json();
setClientSecret(clientSecret);
};
fetchPaymentIntent();
}, [cart]);
const handlePay = async () => {
const { error, paymentIntent } = await confirmPayment(clientSecret, {
type: 'Card',
billingDetails: { email: '[email protected]' },
});
if (error) {
Alert.alert('Payment failed', error.message);
} else if (paymentIntent) {
Alert.alert('Payment succeeded', 'Thank you for your purchase!');
}
};
return (
<View style={styles.container}>
<Text style={styles.title}>Checkout</Text>
<CardField
postalCodeEnabled={true}
placeholder={{ number: '4242 4242 4242 4242' }}
cardStyle={styles.card}
style={styles.cardContainer}
/>
<Button title="Pay Now" onPress={handlePay} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
justifyContent: 'center',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16,
},
card: {
backgroundColor: '#FFFFFF',
},
cardContainer: {
height: 50,
marginVertical: 30,
},
});
export default CheckoutScreen;
Explanation of Code:
- CardField: Stripe’s component for collecting card details.
- confirmPayment: Sends payment details to Stripe and confirms the payment.
Step 5: Navigating to the Checkout Screen
- In
CartScreen.js
, add a button to navigate to the CheckoutScreen:
import React from 'react';
import { Button } from 'react-native';
<Button title="Proceed to Checkout" onPress={() => navigation.navigate('CheckoutScreen')} />
Step 6: Testing the Payment Flow
- Run your app with
npx react-native run-android
ornpx react-native run-ios
. - Add items to the cart and go to the Checkout screen.
- Enter the test card number
4242 4242 4242 4242
and any future expiration date. - Click Pay Now. If successful, an alert should confirm the payment.
Summary
Today, you integrated Stripe as a payment gateway, allowing users to make secure payments. You created a backend server to handle payment intents and implemented a checkout flow in your app.
Tomorrow, you’ll work on user profiles and order histories.