メインコンテンツへスキップ

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;
APIキーはDodo Paymentsダッシュボードで生成する必要があります。詳しい手順はAPI key generation guideをご覧ください。
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 Integration Tutorialをご覧ください。
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'

外観のカスタマイズ

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

色のカスタマイズ

各カラーカテゴリはUI内の1つ以上のコンポーネントの色を決定します。たとえば、primaryはPayボタンの色を定義します。
カラーカテゴリ使用用途
primaryPayボタンと選択された項目のプライマリカラー
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
  },
};

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

プライマリボタン(Payボタン)などの特定の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);
  }
};
  • Network connectivity issues: 安定したインターネット接続を確保してください
  • Invalid client secret: バックエンドが有効な支払いインテントを生成していることを確認してください
  • Missing peer dependencies: 必要な依存関係をすべてインストールしてください
  • Platform-specific setup: iOSおよびAndroidの構成手順を完了してください
  • API errors: 詳しいエラーハンドリングについてはError Codes Referenceを確認してください
  • 開発時にデバッグログを有効にしてください
  • バックエンドへのネットワークリクエストを確認してください
  • APIキーが正しく構成されているか検証してください
  • iOSとAndroidの両方でテストしてください
  • よくある問題についてはTechnical FAQsを参照してください
  • Test vs Live Modeを適切に使い分けてください

テスト決済方法

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