> ## 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)をご覧ください
* 🎥 Dodo Payments SDKの動作を確認するには、[デモ動画](https://youtu.be/eicctkqK04Y)をご覧ください

<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>
      APIキーはDodo Paymentsダッシュボードで生成する必要があります。詳しい手順は[API key generation guide](/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 Integration Tutorial](/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>
      スタイリング、エラーハンドリング、およびカスタマイズオプションを含む完全な例については、デモリポジトリをご覧ください:

      * [Basic Integration Demo](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>

### 外観のカスタマイズ

アプリのデザインに合わせてReact Native Unified Checkoutをカスタマイズするには、`initPaymentSession()`の呼び出し時にappearanceパラメータを通じて色やフォントなどを調整します。

#### 色のカスタマイズ

各カラーカテゴリはUI内の1つ以上のコンポーネントの色を決定します。たとえば、`primary`はPayボタンの色を定義します。

| カラーカテゴリ               | 使用用途                       |
| --------------------- | -------------------------- |
| `primary`             | Payボタンと選択された項目のプライマリカラー    |
| `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
  },
};
```

#### コンポーネント固有のカスタマイズ

プライマリボタン（Payボタン）などの特定の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">
    * **Network connectivity issues**: 安定したインターネット接続を確保してください
    * **Invalid client secret**: バックエンドが有効な支払いインテントを生成していることを確認してください
    * **Missing peer dependencies**: 必要な依存関係をすべてインストールしてください
    * **Platform-specific setup**: iOSおよびAndroidの構成手順を完了してください
    * **API errors**: 詳しいエラーハンドリングについては[Error Codes Reference](/api-reference/error-codes)を確認してください
  </Accordion>

  <Accordion title="Debugging Tips">
    * 開発環境でデバッグログを有効化
    * バックエンドへのネットワークリクエストを確認
    * APIキーが正しく設定されているか確認
    * iOSとAndroidの両方のプラットフォームでテスト
    * 共通の問題については[技術的FAQ](/miscellaneous/faq)を参照
    * [テストモードとライブモード](/miscellaneous/test-mode-vs-live-mode)を適切に使用
  </Accordion>
</AccordionGroup>

### テスト決済方法

<Tip>
  開発ではテストカード番号を使って実際の決済処理を行わずに統合を確認してください。テストプロセスと利用可能なテスト環境の詳細については[testing process](/miscellaneous/testing-process)をご覧ください。
</Tip>
