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

React Native SDKの統合

Dodo PaymentsのReact Native SDKを使用すると、ネイティブのAndroidおよびiOSアプリで安全な決済体験を構築できます。私たちのSDKは、決済情報を収集するためのカスタマイズ可能なUIコンポーネントと画面を提供します。
  • 📦 NPMからSDKをインストール
  • 📚 完全な実装例については、デモリポジトリをご覧ください
  • 🎥 Dodo Payments SDKの動作を確認するには、デモ動画をご覧ください

機能

簡素化されたセキュリティ

PCI準拠を維持しながら、機密の決済データを安全に収集します

複数の決済方法

グローバルなリーチを拡大するために、さまざまな決済方法を受け入れます

ネイティブUI

AndroidおよびiOS用のネイティブ画面と要素
現在、React Native SDKではApple Pay、Google Pay、Cash App、およびUPIはサポートされていません。今後のリリースでこれらの決済方法のサポートを追加するために積極的に取り組んでいます。

インストール

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
決済インテントから取得したクライアントシークレット。
mode
string
required
決済セッションのモード(テストまたはライブ)。
configuration.appearance
object
決済シートの外観に関するカスタマイズオプション
configuration.appearance.themes
string
テーマモード: 'light' または 'dark'

外観のカスタマイズ

決済セッションを呼び出す際に、appearanceパラメータを通じて色、フォントなどを変更することで、React Native Unified Checkoutをアプリのデザインに合わせてカスタマイズできます。

色のカスタマイズ

各色カテゴリは、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);
  }
};
  • ネットワーク接続の問題: 安定したインターネット接続を確保してください
  • 無効なクライアントシークレット: バックエンドが有効な決済インテントを生成していることを確認してください
  • 欠落しているピア依存関係: 必要なすべての依存関係をインストールしてください
  • プラットフォーム固有のセットアップ: iOSおよびAndroidの設定手順を完了してください
  • APIエラー: 詳細なエラーハンドリングについては、エラーコードリファレンスをご覧ください
  • 開発中にデバッグログを有効にする
  • バックエンドへのネットワークリクエストを確認する
  • APIキーが正しく設定されていることを確認する
  • iOSおよびAndroidプラットフォームの両方でテストする
  • 一般的な問題については、技術的FAQをご覧ください
  • テストモードとライブモードを適切に使用する

テスト決済方法

開発中にテストカード番号を使用して、実際の決済を処理せずに統合を確認します。私たちのテストプロセスと利用可能なテスト環境について詳しく学んでください。