# 設定で支払い方法を管理する

支払い方法設定シートを使用して、顧客がアプリの設定ページで支払い方法を管理できるようにします。

Payment Method Settings Sheet は、顧客が保存済みの決済手段を管理できるようにする事前構築された UI コンポーネントです。決済フローの外部でも Payment Method Settings Sheet の UI を使用でき、アプリの外観や世界観に合わせて外観やスタイルをカスタマイズできます。顧客は決済手段の追加や削除ができます。決済手段は `Customer` オブジェクトに保存され、顧客はデバイスにローカル保存されるデフォルトの決済手段を設定できます。アプリ内決済と Payment Method Settings Sheet の両方を使用することで、保存済みの決済手段に関する一貫したエンドツーエンドのソリューションを顧客に提供できます。コード上では、このコンポーネントは歴史的な経緯から `CustomerSheet` として参照されます。ドキュメント全体を通して、コード例で `CustomerSheet` と記載されている場合は、Payment Method Settings Sheet を指しています。

アプリの設定ページでは Payment Method Settings Sheet を使用します。決済や支払いには、[アプリ内決済](https://docs.stripe.com/payments/mobile.md)を使用します。これには決済手段の保存や表示機能が組み込まれており、Payment Method Settings Sheet よりも多くの決済手段に対応しています。

> #### Accounts v2 API サポート
> 
> Payment Method Settings Sheet は*顧客設定のアカウント* (Account configurations represent role-based functionality that you can enable for accounts, such as merchant, customer, or recipient)をサポートしていません。`Customer`オブジェクトのみをサポートしています。
![iOS アプリに保存された複数の支払い方法を提示する支払い方法設定シートのスクリーンショット。](https://b.stripecdn.com/docs-statics-srv/assets/ios-landing.6c4969968fd6efe3d39fe673628f8284.png)

## Stripe をセットアップする

まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。

[React Native SDK](https://github.com/stripe/stripe-react-native) はオープンソースであり、詳細なドキュメントが提供されています。内部では、[ネイティブの iOS](https://github.com/stripe/stripe-ios) および [Android](https://github.com/stripe/stripe-android) の SDK を使用します。Stripe の React Native SDK をインストールするには、プロジェクトのディレクトリーで (使用するパッケージマネージャーによって異なる) 次のいずれかのコマンドを実行します。

#### yarn

```bash
yarn add @stripe/stripe-react-native
```

#### npm

```bash
npm install @stripe/stripe-react-native
```

次に、その他の必要な依存関係をインストールします。

- iOS の場合は、**ios** ディレクトリに移動し、`pod install` を実行して、必要なネイティブ依存関係もインストールしてください。
- Android の場合は、依存関係をインストールする必要はありません。

> [公式の TypeScript ガイド](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project)に従って TypeScript のサポートを追加することをお勧めします。

### Stripe の初期化

React Native アプリで Stripe を初期化するには、決済画面を `StripeProvider` コンポーネントでラップするか、`initStripe` 初期化メソッドを使用します。`publishableKey` の API [公開可能キー](https://docs.stripe.com/keys.md#obtain-api-keys)のみが必要です。次の例は、`StripeProvider` コンポーネントを使用して Stripe を初期化する方法を示しています。

```jsx
import { useState, useEffect } from 'react';
import { StripeProvider } from '@stripe/stripe-react-native';

function App() {
  const [publishableKey, setPublishableKey] = useState('');

  const fetchPublishableKey = async () => {
    const key = await fetchKey(); // fetch key from your server here
    setPublishableKey(key);
  };

  useEffect(() => {
    fetchPublishableKey();
  }, []);

  return (
    <StripeProvider
      publishableKey={publishableKey}
      merchantIdentifier="merchant.identifier" // required for Apple Pay
      urlScheme="your-app" // required for 3D Secure and bank redirects
    >
      {/* Your app code here */}
    </StripeProvider>
  );
}
```

> テストおよび開発時には API の[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。

## 決済手段を有効にする

[支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)を表示して、サポートする支払い方法を有効にします。*SetupIntent* (The Setup Intents API lets you build dynamic flows for collecting payment method details for future payments. It tracks the lifecycle of a payment setup flow and can trigger additional authentication steps if required by law or by the payment method) を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。

多くの顧客から決済を受け付けられるよう、Stripe では、カードやその他一般的な決済手段がデフォルトで有効になっていますが、ビジネスや顧客に適した追加の決済手段を有効にすることをお勧めします。プロダクトと決済手段のサポートについては[決済手段のサポート](https://docs.stripe.com/payments/payment-methods/payment-method-support.md)を、手数料については[料金体系ページ](https://stripe.com/pricing/local-payment-methods)をご覧ください。

> CustomerSheet はカードとアメリカの銀行口座にのみ対応しています。

## 顧客エンドポイントを追加 [サーバー側]

サーバー側で、CustomerSession の client secret を取得するエンドポイントと、新しい決済手段を [Customer](https://docs.stripe.com/api/customers.md) に保存する [SetupIntent](https://docs.stripe.com/api/setup_intents.md) を作成するエンドポイントの 2 つのエンドポイントを作成します。

1. [Customer](https://docs.stripe.com/api/customers.md) ID と [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) の client secret を返すエンドポイントを作成します。

#### curl

```bash
# Create a Customer (skip this and get the existing Customer ID if this is a returning customer)
curl https://api.stripe.com/v1/customers \
  -u <<YOUR_SECRET_KEY>>: \
  -X "POST"

curl https://api.stripe.com/v1/customer_sessions \
  -u <<YOUR_SECRET_KEY>>: \
  -X "POST" \
  -d "customer"="{{CUSTOMER_ID}}" \
  -d "components[customer_sheet][enabled]"=true \
  -d "components[customer_sheet][features][payment_method_remove]"=enabled
```

> レガシーの顧客の一時キーを使用した実装では、保存された決済手段の `allow_redisplay` 値が `unspecified` になります。Customer Sessions の使用時に保存した決済手段に加えて、これらの決済手段を表示するには、`payment_method_allow_redisplay_filters` を `["unspecified", "always"]` に設定します。詳細については、[CustomerSessions](https://docs.stripe.com/api/customer_sessions.md) をご覧ください。

1. [Customer](https://docs.stripe.com/api/customers.md) ID を指定して設定された [SetupIntent](https://docs.stripe.com/api/setup_intents.md) を返すエンドポイントを作成します。

#### curl

```bash
# Create a Customer (skip this and get the existing Customer ID if this is a returning customer)
curl https://api.stripe.com/v1/customers \
  -u <<YOUR_SECRET_KEY>>: \
  -X "POST"

curl https://api.stripe.com/v1/setup_intents \
  -u <<YOUR_SECRET_KEY>>: \
  -d "customer"="{{CUSTOMER_ID}}" \
```

今後の支払いで、顧客が決済フローでオンセッション時にのみ決済手段を使用する場合、[usage](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-usage) パラメーターを *on\_session* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method) に設定して、オーソリ率を改善します。

## 画面を初期化する

2 つのメソッドを実装する `ClientSecretProvider` オブジェクトを作成します。`CustomerSheet は`、`CustomerSession` オブジェクトと前に作成されたエンドポイントを使用して Stripe と通信するために、ClientSecretProvider を必要とします。

```jsx
import {ClientSecretProvider, CustomerSessionClientSecret} from '@stripe/stripe-react-native';

const clientSecretProvider: ClientSecretProvider = {
  // Must return an object with customerId and clientSecret
  async provideCustomerSessionClientSecret(): Promise<CustomerSessionClientSecret> {
    const result = await MyBackend.createCustomerSession();
    return {
      customerId: result.customer,
      clientSecret: result.customerSessionClientSecret,
    };
  },

  // Must return a string
  async provideSetupIntentClientSecret(): Promise<string> {
    const result = await MyBackend.createSetupIntent();
    return result.setupIntent;
  }
};
```

次に、Payment Method Settings Sheet を設定します。これは `CustomerSheet` クラスを使用して、`CustomerSheet.initialize` に希望の設定を提供することで設定できます。

```jsx
import {CustomerSheet} from '@stripe/stripe-react-native';

const {error} = await CustomerSheet.initialize({
  // You must provide intentConfiguration and clientSecretProvider
  intentConfiguration: {
    paymentMethodTypes: ['card'],
  },
  clientSecretProvider: clientSecretProvider,
  headerTextForSelectionScreen: 'Manage your payment method',
  returnURL: 'my-return-url://',
});
```

## 支払い画面を表示する

#### 機能性

`CustomerSheet` を使用して Payment Method Settings Sheet を提示します。顧客がシートを破棄すると、プロミスは `CustomerSheetResult` で解決します。

#### 関数を直接使用する

```jsx
import {CustomerSheet, CustomerSheetError} from '@stripe/stripe-react-native';

const {error, paymentOption, paymentMethod} = await CustomerSheet.present();
if (error) {
  if (error.code === CustomerSheetError.Canceled) {
    // Customer dismissed the sheet without changing their payment option
  } else {
    // Show the error in your UI
  }
} else {
  if (paymentOption && paymentMethod) {
    // Configure your UI based on the payment option
    MyBackend.setDefaultPaymentMethod(paymentMethod.id);
  }
  if (paymentMethod) {
    console.log(JSON.stringify(paymentMethod, null, 2));
  }
}
```

- 顧客が決済手段を選択した場合、結果には `paymentOption` が含まれます。その値は選択された [PaymentOption](https://stripe.dev/stripe-react-native/api-reference/interfaces/PaymentSheet.PaymentOption.html) で、顧客が以前に選択した決済手段を削除した場合は `undefined` になります。決済手段の詳細は `paymentMethod` プロパティで確認できます。
- 顧客がシートをキャンセルした場合、その結果には `error.code === CustomerSheetError.Canceled` の `error` が含まれます。選択された決済手段は変更されません。
- エラーが発生した場合、詳細は `error` に含まれます。

Apple Pay を有効にする方法は[こちら](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-apple-pay)をご覧ください。

#### コンポーネント

支払い方法設定シート (`CustomerSheet`) の表示を制御する状態変数を作成します。

```jsx
import {CustomerSheet, ClientSecretProvider, CustomerSessionClientSecret} from '@stripe/stripe-react-native';

export default function MyScreen() {
  const [customerSheetVisible, setCustomerSheetVisible] = React.useState(false);

  const clientSecretProvider: ClientSecretProvider = {
    async provideCustomerSessionClientSecret(): Promise<CustomerSessionClientSecret> {
      const result = await MyBackend.createCustomerSession();
      return {
        customerId: result.customer,
        clientSecret: result.customerSessionClientSecret,
      };
    },
    async provideSetupIntentClientSecret(): Promise<string> {
      const result = await MyBackend.createSetupIntent();
      return result.setupIntent;
    }
  };

  return (
    <YourPaymentScreen>
      <Button
        title="Manage payment methods"
        onPress={() => {
          setCustomerSheetVisible(true);
        }}
      />
    </YourPaymentScreen>
  );
}
```

`CustomerSheet` コンポーネントをビューの階層に追加します。

```jsx
import { CustomerSheet } from '@stripe/stripe-react-native';

export default function MyScreen() {
  const [customerSheetVisible, setCustomerSheetVisible] = React.useState(false);

  const clientSecretProvider = /* defined above */;

  return (
    <YourPaymentScreen>
      <Button
        title="Manage payment methods"
        onPress={() => {
          setCustomerSheetVisible(true);
        }}
      />
      <CustomerSheet.Component
        visible={customerSheetVisible}
        intentConfiguration={{
          paymentMethodTypes: ['card'],
        }}
        clientSecretProvider={clientSecretProvider}
        headerTextForSelectionScreen={'Manage your payment method'}
        returnURL={'my-return-url://'}
        onResult={() => {/* SEE BELOW */}}
      />
    </YourPaymentScreen>
  )
}
```

`onResult` コールバックを使用して、選択された支払い方法を UI に表示します。

```jsx
import {CustomerSheet, CustomerSheetError} from '@stripe/stripe-react-native';

export default function MyScreen() {
  const [customerSheetVisible, setCustomerSheetVisible] = React.useState(false);

  const clientSecretProvider = /* defined above */;

  return (
    <YourPaymentScreen>
      <Button
        title="Manage payment methods"
        onPress={() => {
          setCustomerSheetVisible(true);
        }}
      />
      <CustomerSheet.Component
        visible={customerSheetVisible}
        intentConfiguration={{
          paymentMethodTypes: ['card'],
        }}
        clientSecretProvider={clientSecretProvider}
        headerTextForSelectionScreen={'Manage your payment method'}
        returnURL={'my-return-url://'}
        onResult={({error, paymentOption, paymentMethod}) => {
          setCustomerSheetVisible(false);
          if (error) {
            if (error.code === CustomerSheetError.Canceled) {
              // Customer dismissed the sheet without changing their payment option
            } else {
              // Show the error in your UI
            }
            return;
          }

          if (paymentOption && paymentMethod) {
            // Configure your UI based on the payment option
            MyBackend.setDefaultPaymentMethod(paymentMethod.id);
          }
          if (paymentMethod) {
            console.log(JSON.stringify(paymentMethod, null, 2));
          }
        }}
      />
    </YourPaymentScreen>
  );
}
```

- 顧客が決済手段を選択した場合、結果には `paymentOption` が含まれます。その値は選択された [PaymentOption](https://stripe.dev/stripe-react-native/api-reference/interfaces/PaymentSheet.PaymentOption.html) で、顧客が以前に選択した決済手段を削除した場合は `undefined` になります。決済手段の詳細は `paymentMethod` プロパティで確認できます。
- 顧客がシートをキャンセルした場合、その結果には `error.code === CustomerSheetError.Canceled` の `error` が含まれます。選択された決済手段は変更されません。
- エラーが発生した場合、詳細は `error` に含まれます。

Apple Pay を有効にする方法は[こちら](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-apple-pay)をご覧ください。

## Optional: ACH 決済を有効にする

ACH デビット決済を有効にするには、[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)の設定セクションで決済方法として `US Bank Account` を有効にします。

## Optional: 選択した支払い方法を取得する

Payment Method Settings Sheet を表示せずに初期設定の決済方法を取得するには、シートを初期化した後 `CustomerSheet.retrievePaymentOptionSelection()` を呼び出します。

```jsx
// Call CustomerSheet.initialize()
...
const {
  error,
  paymentOption,
  paymentMethod,
} = await CustomerSheet.retrievePaymentOptionSelection();
```

## Optional: 画面をカスタマイズする

### デザイン

[Appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=react-native) を使用して、アプリのデザインに合わせて色、フォント、その他の外観の属性をカスタマイズします。

### デフォルトの請求詳細

支払い方法設定シートで収集する請求書の詳細のデフォルト値を設定するには、`defaultBillingDetails` プロパティを設定します。支払い方法設定シートでは、フィールドにあらかじめ指定した値が入力されます。

```jsx
await CustomerSheet.initialize({
  // ...
  defaultBillingDetails: {
    email: 'foo@bar.com',
    address: {
      country: 'US',
    },
  },
});
```

### 請求詳細を収集する

`billingDetailsCollectionConfiguration` を使用して、支払い方法設定シートで請求書の詳細を収集する方法を指定します。

顧客の名前、メールアドレス、電話番号、住所を収集できます。

支払い方法に必要な値を収集しない場合は、以下を実行する必要があります。

1. 支払い方法設定シートで収集しない値を、`defaultBillingDetails` プロパティにアタッチします。
2. `billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を `true` に設定します。

```jsx
await CustomerSheet.initialize({
  // ...
  defaultBillingDetails: {
    email: 'foo@bar.com',
  },
  billingDetailsCollectionConfiguration: {
    name: PaymentSheet.CollectionMode.ALWAYS,
    email: PaymentSheet.CollectionMode.NEVER,
    address: PaymentSheet.AddressCollectionMode.FULL,
    attachDefaultsToPaymentMethod: true
  },
});
```

> 情報の収集に適用される法律については、弁護士に相談してください。電話番号は、取引に必要な場合にのみ収集してください。
