dodopayments-react-native-sdk
v0.3.6
Published
Dodo Payments SDK for React Native
Readme
Dodo Payments React Native SDK
A powerful and secure payment processing SDK for React Native applications, enabling seamless integration of payment functionality in your native Android and iOS apps.
- 📦 Install from NPM
- 📚 Read our Integration Guide
- 🎥 Watch our Demo Video.
Features
- 🔒 Secure Payments: PCI-compliant payment processing
- 💳 Multiple Payment Methods: Support for various payment methods to expand global reach
- 📱 Native UI: Native screens and elements for Android and iOS
- 🎨 Customizable Interface: Extensive theming and appearance options
- 🌓 Theme Support: Built-in light and dark mode support
Prerequisites
- Node.js (v14 or higher)
- React Native development environment setup
- iOS: Xcode and CocoaPods
- Android: Android Studio and Android SDK
- Dodo Payments account and API keys
Installation
1. Install the SDK
Install the Dodo Payments SDK using your preferred package manager:
# Using npm
npm install dodopayments-react-native-sdk
# Using yarn
yarn add dodopayments-react-native-sdk2. Platform-specific setup
iOS
Run pod install in your iOS folder:
cd ios && pod install && npm run iosAndroid
Run the following command:
npm run androidQuick Start
1. Get Publishable Key
Get your publishable key from the Dodo Payments Dashboard. (Distinct for both test and live modes)
2. Setup Payment Provider
Wrap your app with the DodoPaymentProvider:
import React from 'react';
import { DodoPaymentProvider } from 'dodopayments-sdk-react-native';
import PaymentScreen from './PaymentScreen';
function App() {
return (
<DodoPaymentProvider publishableKey="YOUR_PUBLISHABLE_KEY">
<PaymentScreen />
</DodoPaymentProvider>
);
}
export default App;3. Create payment utility function
Create a utility function to fetch payment parameters from your backend API:
const API_URL = 'YOUR_BACKEND_URL'; // Replace with your server URL
const fetchPaymentParams = async () => {
const response = await fetch(`${API_URL}/create-payment`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Failed to fetch payment parameters');
}
return await response.json();
};
export default fetchPaymentParams;4. Implement the payment screen
Create your payment screen using the useCheckout hook:
import React from 'react';
import { View, Text } from 'react-native';
import { useCheckout } from 'dodopayments-react-native-sdk';
import fetchPaymentParams from './utils/fetchPaymentParams';
const PaymentScreen = () => {
const { initPaymentSession, presentPaymentSheet } = useCheckout();
const [error, setError] = React.useState('');
const [loading, setLoading] = React.useState(false);
const handlePayment = async () => {
setLoading(true);
try {
// 1. Get payment parameters from your backend
const { clientSecret } = await fetchPaymentParams();
// 2. Initialize payment session
const params = await initPaymentSession({ clientSecret });
// 3. Present payment sheet
const result = await presentPaymentSheet(params);
if (result?.status === 'succeeded') {
// Handle successful payment
console.log('Payment successful');
} else {
setError(result?.message || 'Payment failed');
}
} catch (err) {
setError('Payment failed');
} finally {
setLoading(false);
}
};
return (
<View>
<Button
onPress={handlePayment}
disabled={loading}
title={loading ? 'Processing...' : 'Pay Now'}
/>
{error && <Text style={{ color: 'red' }}>{error}</Text>}
</View>
);
};
export default PaymentScreen;Configuration
Session Parameters
clientSecret(string, required): The client secret from your payment intent, obtained from One time payment or subscription API.mode(string, required): The mode of the payment session (test or live).configuration.appearance(object): Customization options for the payment sheet appearanceconfiguration.appearance.themes(string): Theme mode:'light'or'dark'
Appearance Customization
You can customize the React Native Unified Checkout to match your app's design by modifying colors, fonts, and more through the appearance parameter when calling initPaymentSession().
Color Customization
Each color category determines the color of one or more components in the UI. For example, primary defines the color of the Pay button.
| Color Category | Usage |
|----------------|-------|
| primary | Primary color for the Pay button and selected items |
| background | Background color of the payment page |
| componentBackground | Background color for inputs, tabs, and other components |
| componentBorder | External border color for inputs, tabs, and other components |
| componentDivider | Internal border color (shared borders) for components |
| primaryText | Header text color |
| secondaryText | Label text color for input fields |
| componentText | Input text color (e.g., card number, zip code) |
| placeholderText | Placeholder text color for input fields |
| icon | Color for icons (e.g., close button) |
| error | Color for error messages and destructive actions |
Example configuration with light and dark mode support:
const appearance = {
colors: {
light: {
primary: '#F8F8F2',
background: '#ffffff',
componentBackground: '#E6DB74',
componentBorder: '#FD971F',
componentDivider: '#FD971F',
primaryText: '#F8F8F2',
secondaryText: '#75715E',
componentText: '#AE81FF',
placeholderText: '#E69F66',
icon: '#F92672',
error: '#FF0000',
},
dark: {
primary: '#00ff0099',
background: '#ff0000',
componentBackground: '#ff0080',
componentBorder: '#62ff08',
componentDivider: '#d6de00',
primaryText: '#5181fc',
secondaryText: '#ff7b00',
componentText: '#00ffff',
placeholderText: '#00ffff',
icon: '#f0f0f0',
error: '#0f0f0f',
},
},
};Shape Customization
You can customize the border radius, border width, and shadow used throughout the payment interface:
const appearance = {
shapes: {
borderRadius: 10, // Border radius for input fields, tabs, and components
borderWidth: 1, // Border width for components
},
};Component-Specific Customization
You can customize specific UI components like the primary button (Pay button). These settings take precedence over the global appearance settings:
const appearance = {
primaryButton: {
colors: {
background: '#000000',
text: '#ffffff',
border: '#ff00ff',
},
shapes: {
borderRadius: 10,
borderWidth: 1.5,
},
},
};Testing
Use test card numbers in development to verify your integration without processing real payments:
- Test Card Number: 4242 4242 4242 4242
- Expiry: Any future date
- CVC: Any 3 digits
Error Handling
Handle different payment states in your checkout function:
const handlePaymentResult = (paymentSheetResponse) => {
switch (paymentSheetResponse?.status) {
case 'cancelled':
// User cancelled the payment
console.log('Payment cancelled by user');
break;
case 'succeeded':
// Payment completed successfully
console.log('Payment succeeded');
// Navigate to success screen or update UI
break;
case 'failed':
// Payment failed
console.log('Payment failed:', paymentSheetResponse?.message);
// Show error message to user
break;
default:
console.log('Unknown payment status:', paymentSheetResponse?.status);
}
};Common Error Scenarios
- Network connectivity issues: Ensure stable internet connection
- Invalid client secret: Verify backend is generating valid payment intents
- Missing peer dependencies: Install all required dependencies
- Platform-specific setup: Complete iOS and Android configuration steps
- API errors: Check our Error Codes Reference for detailed error handling
Debugging Tips
- Enable debug logging in development
- Check network requests to your backend
- Verify API keys are correctly configured
- Test on both iOS and Android platforms
- Review our Technical FAQs for common issues
- Use Test vs Live Mode appropriately
Support
For support, email [email protected] or visit our documentation.
