> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# React Native

> 在您的 React Native 应用程序中集成 Dodo Payments SDK 的完整指南，以实现安全的支付处理

# React Native SDK 集成

Dodo Payments React Native SDK 使您能够在本机 Android 和 iOS 应用中构建安全的支付体验。我们的 SDK 提供可自定义的 UI 组件和收集支付详细信息的屏幕。

* 📦 从 [NPM](https://www.npmjs.com/package/dodopayments-react-native-sdk) 安装我们的 SDK
* 📚 查看我们的 [演示仓库](https://github.com/dodopayments/dodopayments-react-native-demo) 以获取完整的实现示例
* 🎥 观看我们的 [演示视频](https://youtu.be/eicctkqK04Y) 以查看 Dodo Payments SDK 的实际应用

<Frame>
  <iframe className="w-full aspect-video rounded-md" src="https://www.youtube.com/embed/eicctkqK04Y" title="React Native SDK Demo | Dodo Payments" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen />
</Frame>

## 特性

<CardGroup cols={1}>
  <Card title="Simplified Security" icon="shield-check">
    在保持符合 PCI 要求的同时安全地收集敏感支付数据
  </Card>

  <Card title="Multiple Payment Methods" icon="credit-card">
    接受各种[支付方式](/features/payment-methods)以拓展全球覆盖范围
  </Card>

  <Card title="Native UI" icon="mobile">
    为 Android 和 iOS 提供原生界面与元素
  </Card>
</CardGroup>

<Note>
  目前，React Native SDK 还不支持 Apple Pay、Google Pay、Cash App 和 UPI。我们正在积极努力，在未来版本中添加对这些支付方式的支持。
</Note>

## 安装

<Steps>
  <Step title="Install the SDK">
    使用您首选的包管理器安装 Dodo Payments SDK：

    <Tabs>
      <Tab title="npm">
        ```bash theme={null}
        npm install dodopayments-react-native-sdk
        ```
      </Tab>

      <Tab title="yarn">
        ```bash theme={null}
        yarn add dodopayments-react-native-sdk
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Platform-specific setup">
    <Tabs>
      <Tab title="iOS">
        在 iOS 目录中运行 pod install：

        ```bash theme={null}
        cd ios && pod install && npm run ios
        ```
      </Tab>

      <Tab title="Android">
        运行以下命令：

        ```bash theme={null}
        npm run android
        ```
      </Tab>
    </Tabs>
  </Step>
</Steps>

## 客户端设置

<Steps>
  <Step title="Get Publishable Key">
    从 Dodo Payments 控制面板获取您的可发布密钥。（测试模式和直播模式各自独立）
    [https://app.dodopayments.com/developer/others](https://app.dodopayments.com/developer/others)
  </Step>

  <Step title="Setup Payment Provider">
    使用 `DodoPaymentProvider` 包裹您的应用：

    ```tsx App.tsx theme={null}
    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;
    ```

    <Note>
      您需要从 Dodo Payments 控制面板生成 API 密钥。有关详细说明，请参阅我们的[API 密钥生成指南](/api-reference/introduction#api-key-generation)。
    </Note>
  </Step>

  <Step title="Create payment utility function">
    创建一个实用函数，从您的后端 API 获取支付参数：

    ```tsx utils/fetchPaymentParams.ts theme={null}
    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;
    ```

    <Note>
      该函数假定您已有一个后端 API 端点用于创建支付意图并返回客户端密钥。请确保您的后端已正确配置以处理支付创建。有关后端设置示例，请参见我们的[API 集成教程](/developer-resources/integration-guide)。
    </Note>
  </Step>

  <Step title="Implement the payment screen">
    使用 `useCheckout` 钩子创建您的支付界面。以下是完整实现：

    ```tsx PaymentScreen.tsx theme={null}
    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;
    ```

    <Note>
      有关样式、错误处理和自定义选项的完整示例，请查看我们的演示仓库：

      * [基本集成演示](https://github.com/dodopayments/dodopayments-react-native-demo)
    </Note>
  </Step>
</Steps>

## 配置选项

### 会话参数

<ParamField path="clientSecret" type="string" required>
  从一次性支付或订阅 API 获取的支付意图客户端密钥。
</ParamField>

<ParamField path="mode" type="string" required>
  支付会话的模式（测试或直播）。
</ParamField>

<ParamField path="configuration.appearance" type="object">
  支付界面外观的自定义选项
</ParamField>

<ParamField path="configuration.appearance.themes" type="string">
  主题模式：`'light'` 或 `'dark'`
</ParamField>

### 外观自定义

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

#### 颜色自定义

每个颜色分类决定了 UI 中一个或多个组件的颜色。例如，`primary` 定义了支付按钮的颜色。

| 颜色分类                  | 用途                  |
| --------------------- | ------------------- |
| `primary`             | 用于支付按钮和选中项的主色       |
| `background`          | 支付页面的背景色            |
| `componentBackground` | 输入框、选项卡和其他组件的背景色    |
| `componentBorder`     | 输入框、选项卡和其他组件的外部边框颜色 |
| `componentDivider`    | 组件的内部边框颜色（共享边框）     |
| `primaryText`         | 头部文本颜色              |
| `secondaryText`       | 输入字段标签文本颜色          |
| `componentText`       | 输入文本颜色（例如卡号、邮编）     |
| `placeholderText`     | 输入字段占位符文本颜色         |
| `icon`                | 图标颜色（例如关闭按钮）        |
| `error`               | 错误消息和破坏性操作的颜色       |

示例配置，支持浅色和深色模式：

```tsx theme={null}
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',
    },
  },
};
```

#### 形状自定义

您可以自定义支付界面中使用的边框半径、边框宽度和阴影：

```tsx theme={null}
const appearance = {
  shapes: {
    borderRadius: 10, // Border radius for input fields, tabs, and components
    borderWidth: 1,   // Border width for components
  },
};
```

#### 组件特定自定义

您可以自定义特定的 UI 组件，如主按钮（支付按钮）。这些设置优先于全局外观设置：

```tsx theme={null}
const appearance = {
  primaryButton: {
    colors: {
      background: '#000000',
      text: '#ffffff',
      border: '#ff00ff',
    },
    shapes: {
      borderRadius: 10,
      borderWidth: 1.5,
    },
  },
};
```

要应用这些自定义设置，请将它们包含在您的支付会话配置中：

```tsx theme={null}
const params: sessionParams = {
  ...paymentSheetParams,
  configuration: {
    appearance: {
      themes: isDarkMode ? 'dark' : 'light',
      ...appearance, // Include your custom appearance settings
    },
  },
};
```

## 错误处理

在您的结账函数中处理不同的支付状态：

```tsx theme={null}
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);
  }
};
```

<AccordionGroup>
  <Accordion title="Common Error Scenarios">
    * **网络连接问题**：确保网络连接稳定
    * **客户端密钥无效**：验证后端是否生成了有效的支付意图
    * **缺少对等依赖**：安装所有必需依赖项
    * **平台特定配置**：完成 iOS 和 Android 的配置步骤
    * **API 错误**：查阅我们的[错误代码参考](/api-reference/error-codes)以获取详细的错误处理信息
  </Accordion>

  <Accordion title="Debugging Tips">
    * 在开发中启用调试日志
    * 检查到后端的网络请求
    * 验证 API 密钥配置正确
    * 在 iOS 和 Android 平台上测试
    * 查看我们的[技术常见问题](/miscellaneous/faq)以获取常见问题的解答
    * 适当地使用[测试模式与实时模式](/miscellaneous/test-mode-vs-live-mode)
  </Accordion>
</AccordionGroup>

### 测试支付方式

<Tip>
  在开发过程中使用测试卡号，以便在不处理真实支付的情况下验证集成。了解我们的[测试流程](/miscellaneous/testing-process)和可用的测试环境。
</Tip>
