跳转到主要内容

React Native SDK 集成

Dodo Payments React Native SDK 使您能够在本机 Android 和 iOS 应用中构建安全的支付体验。我们的 SDK 提供可自定义的 UI 组件和收集支付详细信息的屏幕。
  • 📦 从 NPM 安装我们的 SDK
  • 📚 查看我们的 演示仓库 以获取完整的实现示例
  • 🎥 观看我们的 演示视频 以查看 Dodo Payments SDK 的实际应用

特性

简化的安全性

在保持 PCI 合规的同时安全地收集敏感支付数据

多种支付方式

接受各种 支付方式 以扩大全球覆盖范围

本机 UI

适用于 Android 和 iOS 的本机屏幕和元素
目前,Apple Pay、Google Pay、Cash App 和 UPI 在 React Native SDK 中不受支持。我们正在积极努力在未来的版本中添加对这些支付方式的支持。

安装

1

安装 SDK

使用您喜欢的包管理器安装 Dodo Payments SDK:
npm install dodopayments-react-native-sdk
2

平台特定设置

在您的 iOS 文件夹中运行 pod install:
cd ios && pod install && npm run ios

客户端设置

1

获取可发布密钥

从 Dodo Payments 仪表板获取您的可发布密钥。(测试和实时模式各自不同) https://app.dodopayments.com/developer/others
2

设置支付提供商

DodoPaymentProvider 包裹您的应用:
App.tsx
import React from 'react';
import { DodoPaymentProvider } from 'dodopayments-react-native-sdk';
import PaymentScreen from './PaymentScreen';

function App() {
  return (
    <DodoPaymentProvider publishableKey="YOUR_PUBLISHABLE_KEY">
      <PaymentScreen />
    </DodoPaymentProvider>
  );
}

export default App;
您需要从 Dodo Payments 仪表板生成 API 密钥。有关详细说明,请参阅我们的 API 密钥生成指南
3

创建支付实用函数

创建一个实用函数以从您的后端 API 获取支付参数:
utils/fetchPaymentParams.ts
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;
此函数假设您有一个后端 API 端点,该端点创建支付意图并返回客户端密钥。确保您的后端已正确配置以处理支付创建。有关后端设置示例,请参阅我们的 API 集成教程
4

实现支付屏幕

使用 useCheckout 钩子创建您的支付屏幕。以下是完整的实现:
PaymentScreen.tsx
import React from 'react';
import { View, Text, useColorScheme } from 'react-native';
import { useCheckout, type sessionParams } from 'dodopayments-react-native-sdk';
import fetchPaymentParams from './utils/fetchPaymentParams';

const PaymentScreen = () => {
  const { initPaymentSession, presentPaymentSheet } = useCheckout();
  const [error, setError] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [showSuccessScreen, setShowSuccessScreen] = React.useState(false);
  const isDarkMode = useColorScheme() === 'dark';

  const processPayment = async () => {
    setLoading(true);
    setMessage('');
    setError('');

    try {
      // 1. Get payment parameters from your backend
      const key = await fetchPaymentParams();
      
      // 2. Initialize payment session
      const paymentSheetParamsResult = await initPaymentSession({
        clientSecret: key.clientSecret,
      });
      
      // 3. Configure and present payment sheet
      const params: sessionParams = {
        ...(paymentSheetParamsResult as sessionParams),
        configuration: {
          appearance: {
            themes: isDarkMode ? 'dark' : 'light',
            primaryButton: {
              colors: {
                light: {
                  background: 'green',
                  componentBorder: 'green',
                  placeholderText: 'yellow',
                },
                dark: {
                  background: 'green',
                  componentBorder: 'green',
                  placeholderText: 'yellow',
                },
              },
              shapes: {
                borderRadius: 30,
                borderWidth: 3,
              },
            },
          },
          mode: 'test', // DEFAULTS TO TEST MODE
        },
      };

      const paymentSheetResponse = await presentPaymentSheet(params);

      // 4. Handle payment result
      switch (paymentSheetResponse?.status) {
        case 'cancelled':
          setError('Payment cancelled by user.');
          break;
        case 'succeeded':
          setMessage('');
          setShowSuccessScreen(true);
          break;
        case 'failed':
          setError('Payment failed : \n' + paymentSheetResponse?.message);
          break;
        default:
          setError(paymentSheetResponse?.message);
          setMessage('');
      }
    } catch (err) {
      setError('Failed to process payment');
    } finally {
      setLoading(false);
    }
  };

  return (
    <View>
      <Button 
        onPress={processPayment}
        disabled={loading}
        title={loading ? 'Processing...' : 'Pay Now'}
      />
      {error && <Text style={{ color: 'red' }}>{error}</Text>}
      {message && <Text style={{ color: 'green' }}>{message}</Text>}
      {showSuccessScreen && (
        <PaymentSuccessScreen
          amount={total}
          onContinue={() => setShowSuccessScreen(false)}
        />
      )}
    </View>
  );
};

export default PaymentScreen;
有关样式、错误处理和自定义选项的完整示例,请查看我们的演示仓库:

配置选项

会话参数

clientSecret
string
required
支付意图的客户端密钥,从一次性支付或订阅 API 获取。
mode
string
required
支付会话的模式(测试或实时)。
configuration.appearance
object
支付表单外观的自定义选项
configuration.appearance.themes
string
主题模式: 'light''dark'

外观自定义

您可以通过在调用 initPaymentSession() 时修改颜色、字体等,来自定义 React Native 统一结账以匹配您的应用设计。

颜色自定义

每个颜色类别决定 UI 中一个或多个组件的颜色。例如, primary 定义支付按钮的颜色。
颜色类别用途
primary支付按钮和选定项目的主颜色
background支付页面的背景颜色
componentBackground输入框、标签和其他组件的背景颜色
componentBorder输入框、标签和其他组件的外部边框颜色
componentDivider组件的内部边框颜色(共享边框)
primaryText标题文本颜色
secondaryText输入字段的标签文本颜色
componentText输入文本颜色(例如,卡号、邮政编码)
placeholderText输入字段的占位符文本颜色
icon图标颜色(例如,关闭按钮)
error错误消息和破坏性操作的颜色
示例配置,支持浅色和深色模式:
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',
    },
  },
};

形状自定义

您可以自定义支付界面中使用的边框半径、边框宽度和阴影:
const appearance = {
  shapes: {
    borderRadius: 10, // Border radius for input fields, tabs, and components
    borderWidth: 1,   // Border width for components
  },
};

组件特定自定义

您可以自定义特定的 UI 组件,如主按钮(支付按钮)。这些设置优先于全局外观设置:
const appearance = {
  primaryButton: {
    colors: {
      background: '#000000',
      text: '#ffffff',
      border: '#ff00ff',
    },
    shapes: {
      borderRadius: 10,
      borderWidth: 1.5,
    },
  },
};
要应用这些自定义设置,请将它们包含在您的支付会话配置中:
const params: sessionParams = {
  ...paymentSheetParams,
  configuration: {
    appearance: {
      themes: isDarkMode ? 'dark' : 'light',
      ...appearance, // Include your custom appearance settings
    },
  },
};

错误处理

在您的结账函数中处理不同的支付状态:
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);
  }
};
  • 网络连接问题:确保网络连接稳定
  • 无效的客户端密钥:验证后端是否生成有效的支付意图
  • 缺少对等依赖项:安装所有必需的依赖项
  • 平台特定设置:完成 iOS 和 Android 配置步骤
  • API 错误:查看我们的 错误代码参考 以获取详细的错误处理信息
  • 在开发中启用调试日志
  • 检查与后端的网络请求
  • 验证 API 密钥是否正确配置
  • 在 iOS 和 Android 平台上进行测试
  • 查看我们的 技术常见问题 以获取常见问题
  • 适当地使用 测试与实时模式

测试支付方式

在开发中使用测试卡号以验证您的集成,而无需处理真实支付。了解更多关于我们的 测试流程 和可用的测试环境。