跳转到主要内容

React Native SDK 集成

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

特性

Simplified Security

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

Multiple Payment Methods

接受各种支付方式以拓展全球覆盖范围

Native UI

为 Android 和 iOS 提供原生界面与元素
目前,React Native SDK 还不支持 Apple Pay、Google Pay、Cash App 和 UPI。我们正在积极努力,在未来版本中添加对这些支付方式的支持。

安装

1

Install the SDK

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

Platform-specific setup

在 iOS 目录中运行 pod install:
cd ios && pod install && npm run ios

客户端设置

1

Get Publishable Key

从 Dodo Payments 控制面板获取您的可发布密钥。(测试模式和直播模式各自独立) https://app.dodopayments.com/developer/others
2

Setup Payment Provider

使用 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

Create payment utility function

创建一个实用函数,从您的后端 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

Implement the payment screen

使用 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
必填
从一次性支付或订阅 API 获取的支付意图客户端密钥。
mode
string
必填
支付会话的模式(测试或直播)。
configuration.appearance
object
支付界面外观的自定义选项
configuration.appearance.themes
string
主题模式:'light''dark'

外观自定义

您可以通过在调用 initPaymentSession() 时修改 appearance 参数中的颜色、字体等设置,使 React Native Unified Checkout 与您的应用设计更加一致。

颜色自定义

每个颜色分类决定了 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 平台上进行测试
  • 查阅我们的技术常见问题以解决常见问题
  • 适当使用测试模式与直播模式

测试支付方式

在开发过程中使用测试卡号,以便在不处理真实支付的情况下验证集成。了解我们的测试流程和可用的测试环境。