메인 콘텐츠로 건너뛰기

리액트 네이티브 SDK 통합

Dodo Payments 리액트 네이티브 SDK를 사용하면 네이티브 Android 및 iOS 앱에서 안전한 결제 경험을 구축할 수 있습니다. 우리의 SDK는 결제 세부 정보를 수집하기 위한 사용자 정의 가능한 UI 구성 요소와 화면을 제공합니다.

기능

간소화된 보안

PCI 준수를 유지하면서 민감한 결제 데이터를 안전하게 수집합니다.

다양한 결제 방법

글로벌 도달 범위를 확장하기 위해 다양한 결제 방법을 수락합니다.

네이티브 UI

Android 및 iOS용 네이티브 화면 및 요소
현재 리액트 네이티브 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
결제 의도에서 가져온 클라이언트 비밀, 일회성 결제 또는 구독 API에서 얻습니다.
mode
string
required
결제 세션의 모드(테스트 또는 라이브).
configuration.appearance
object
결제 시트 외관에 대한 사용자 정의 옵션
configuration.appearance.themes
string
테마 모드: 'light' 또는 'dark'

외관 사용자 정의

리액트 네이티브 통합 체크아웃의 색상, 글꼴 등을 수정하여 앱 디자인에 맞게 사용자 정의할 수 있습니다. initPaymentSession()를 호출할 때 appearance 매개변수를 사용하세요.

색상 사용자 정의

각 색상 카테고리는 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 플랫폼 모두에서 테스트하세요
  • 일반적인 문제에 대한 기술 FAQ를 검토하세요
  • 테스트 모드와 라이브 모드를 적절히 사용하세요

테스트 결제 방법

개발 중 테스트 카드 번호를 사용하여 실제 결제를 처리하지 않고 통합을 검증하세요. 우리의 테스트 프로세스 및 사용 가능한 테스트 환경에 대해 자세히 알아보세요.