> ## 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.

# 리액트 네이티브

> 리액트 네이티브 애플리케이션에서 Dodo Payments SDK를 통합하여 안전한 결제 처리를 위한 완벽한 가이드

# 리액트 네이티브 SDK 통합

Dodo Payments 리액트 네이티브 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">
    글로벌 범위를 확대하려면 다양한 [payment methods](/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 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>
      스타일링, 오류 처리, 사용자화 옵션이 포함된 전체 예제는 다음 데모 리포지토리를 확인하세요:

      * [기본 통합 데모](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>

### 외관 사용자 정의

You can customize the React Native Unified Checkout to match your app's design by modifying colors, fonts, and more through the appearance parameter when calling `initPaymentSession()`.

#### 색상 사용자 정의

각 색상 카테고리는 UI의 하나 이상의 구성 요소 색상을 결정합니다. 예를 들어, `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
  },
};
```

#### 구성 요소별 사용자 정의

기본 버튼(결제 버튼)과 같은 특정 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 플랫폼에서 테스트
    * 일반적인 문제에 대한 [기술 FAQ](/miscellaneous/faq) 검토
    * [테스트 모드와 라이브 모드](/miscellaneous/test-mode-vs-live-mode)를 적절히 사용
  </Accordion>
</AccordionGroup>

### 테스트 결제 방법

<Tip>
  개발 중에는 실제 결제를 처리하지 않도록 테스트 카드 번호를 사용하여 통합을 검증하세요. 우리는 [testing process](/miscellaneous/testing-process) 및 사용 가능한 테스트 환경에 대해 자세히 안내합니다.
</Tip>
