# 支払いを行わずに顧客の決済手段を保存する

決済手段を保存して後で請求を行う方法をご紹介します。

# Checkout Sessions API

> This is a Checkout Sessions API for when payment-ui is embedded-components. View the full page at https://docs.stripe.com/payments/save-and-reuse?payment-ui=embedded-components.

[Checkout Sessions API in `setup` mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-mode) を使用すると、初回の決済なしで顧客の決済の詳細を保存することができます。これは、今すぐ顧客をユーザー登録して決済を設定し、将来顧客がオフラインのときに Payment Intents API を使用して請求する場合に役立ちます。

この導入を使用して、継続課金を設定したり、最終金額が後で (顧客がサービスを受け取った後などに) 決定される 1 回限りの決済を作成します。

> #### カード提示取引
> 
> カード提示取引 (Stripe Terminal による [カード詳細の収集](https://docs.stripe.com/terminal/features/saving-payment-details/save-directly.md) など) では、決済手段の保存に別のプロセスが使用されます。

## 法令遵守

顧客の決済の詳細を保存する際、適用されるすべての法律、規制、ネットワークの規則に準拠する責任があります。これらの要件は通常、以降の購入時の決済フローでの顧客の決済手段を提示する、顧客がウェブサイトやアプリを使用していないときに請求するなど、将来に備えて顧客の決済手段を保存する場合に適用されます。決済手段の保存をどのように計画しているかを示す規約をウェブサイトやアプリに追加し、顧客がオプトインできるようにします。

決済手段を保存する場合、規約に記載された特定の用途にのみ使用できます。顧客がオフラインであるときに決済手段に請求して、以降の購入に備えたオプションとして保存する場合は、この特定の用途について顧客から明示的に同意を収集する必要があります。たとえば、同意を収集するために「今後の使用に備えて決済手段を保存する」チェックボックスを使用します。

顧客がオフラインのときに請求を行うには、規約に以下の内容を含める必要があります。

- 指定された取引で顧客の代理として単独の決済または一連の決済を開始することを許可するという、顧客の同意。
- 予期される決済時期と決済頻度 (たとえば、請求が予定されている分割払いなのか、サブスクリプションの決済なのか、あるいは予定されていないトップアップなのか)。
- 決済金額の決定方法。
- 決済手段をサブスクリプションサービスに使用する場合は、キャンセルに関するポリシー。

これらの規約に関する顧客の書面による同意の記録を必ず保管してください。

> 手動でのサーバー側の確定を使用する必要がある場合、または導入で決済手段を別途提示する必要がある場合は、[代替方法のガイド](https://docs.stripe.com/payments/save-and-reuse-cards-only.md) を参照してください。

## Stripe を設定する [サーバ側]

まず、[Stripe アカウントを作成する](https://dashboard.stripe.com/register)か[サインイン](https://dashboard.stripe.com/login)します。

アプリケーションから Stripe API にアクセスするには、Stripe の公式ライブラリを使用します。

#### Ruby

```bash
# Available as a gem
sudo gem install stripe
```

```ruby
# If you use bundler, you can add this line to your Gemfile
gem 'stripe'
```

## 顧客を作成する [サーバ側]

将来の決済に備えて決済手段を設定するには、顧客を表すオブジェクトに関連付ける必要があります。顧客がアカウントを作成したとき、または初めて取引したときに、Accounts v2 API を使用して顧客設定の [Account](https://docs.stripe.com/api/v2/core/accounts/create.md) オブジェクト、または Customers API を使用して [Customer](https://docs.stripe.com/api/customers/create.md) オブジェクトを作成します。

> #### Accounts v2 API を使用した顧客の表現
> 
> Accounts v2 API では、Connect ユーザーには一般提供され、その他の Stripe ユーザーには公開プレビューで提供されます。Accounts v2 プレビューの一部である場合は、コードで[プレビューバージョン](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning)を指定する必要があります。
> 
> Accounts v2 プレビューへのアクセスをリクエストするには、
> 
> ほとんどのユースケースでは、[Customer](https://docs.stripe.com/api/customers.md) オブジェクトを使用するのではなく、[顧客を顧客設定の Account オブジェクトとしてモデル化する](https://docs.stripe.com/connect/use-accounts-as-customers.md)ことをお勧めします。

#### Accounts v2

```curl
curl -X POST https://api.stripe.com/v2/core/accounts \
  -H "Authorization: Bearer <<YOUR_SECRET_KEY>>" \
  -H "Stripe-Version: 2026-03-25.preview"
```

#### Customers v1

```curl
curl -X POST https://api.stripe.com/v1/customers \
  -u "<<YOUR_SECRET_KEY>>:"
```

## セットアップモードを使用 [サーバ側]

[mode=setup](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-mode) を指定して Checkout Session を作成します。

```curl
curl https://api.stripe.com/v1/checkout/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d mode=setup \
  -d ui_mode=elements \
  -d currency=usd
```

## 顧客に支払い方法を関連付ける [サーバ側]

既存の顧客と Checkout Session を作成していない場合は、*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) の ID を使用して顧客に決済手段を [関連付け](https://docs.stripe.com/api/payment_methods/attach.md) ます。

それ以外の場合は、Checkout Session の作成時に指定した顧客に決済手段が自動的に関連付けられます。

#### Accounts v2

```curl
curl https://api.stripe.com/v1/payment_methods/{{PAYMENTMETHOD_ID}}/attach \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}"
```

#### Customers v1

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

## 決済手段を取得する [サーバ側]

顧客が Checkout Session を正常に完了したら、[checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) webhook を処理します。webhook で Session オブジェクトを取得し、以下を実行します。

- Checkout Session 中に作成された SetupIntent ID である [setup_intent](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-setup_intent) キーの値を取得します。
- SetupIntent ID を使用して、SetupIntent オブジェクトを [取得](https://docs.stripe.com/api/setup_intents/retrieve.md) します。返されるオブジェクトには [payment_method](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-payment_method) ID が含まれ、これを次のステップで顧客に関連付けることができます。

[Webhook の設定](https://docs.stripe.com/webhooks.md) についてもっと知る。

## 後で決済手段に請求する [サーバ側]

PaymentMethod を顧客に関連付けると、[PaymentIntent](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method) を使用して *off-session* (A payment is described as off-session if it occurs without the direct involvement of the customer, using previously-collected payment information) の決済を実行できます。

- [customer_account](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer_account) を `Account` ID に設定するか、[customer](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer) を `Customer` ID に設定し、[payment_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method) を `PaymentMethod` ID に設定します。
- 決済試行時に顧客が決済フローにいないと、カード発行会社、銀行、その他の決済機関などのパートナーによる認証リクエストを実行できないことを [off_session](https://docs.stripe.com/api/payment_intents/confirm.md#confirm_payment_intent-off_session) を `true` に設定して示します。決済フロー中にパートナーが認証をリクエストした場合、Stripe は前回の *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) 取引の顧客情報を使用して免除をリクエストします。免除の条件が満たされていない場合、PaymentIntent はエラーを返すことがあります。
- PaymentIntent の [confirm](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-confirm) プロパティの値を `true` に設定します。これにより、PaymentIntent の作成時にすぐに確定が行われます。

#### Accounts v2

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d "payment_method={{PAYMENTMETHOD_ID}}" \
  -d off_session=true \
  -d confirm=true
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d "customer={{CUSTOMER_ID}}" \
  -d "payment_method={{PAYMENTMETHOD_ID}}" \
  -d off_session=true \
  -d confirm=true
```

決済が失敗すると、リクエストも 402 HTTP ステータスコードで失敗し、PaymentIntent のステータスが *requires\_payment\_method* (This status appears as "requires_source" in API versions before 2019-02-11) になります。アプリケーションに戻って (メールやアプリ内通知などで) 新しい Checkout Session に移動して別の決済手段を選択するよう顧客に通知する必要があります。

#### Accounts v2

```curl
curl https://api.stripe.com/v1/checkout/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d "line_items[0][price_data][currency]=usd" \
  -d "line_items[0][price_data][product_data][name]=T-shirt" \
  -d "line_items[0][price_data][unit_amount]=1099" \
  -d "line_items[0][quantity]=1" \
  -d mode=payment \
  -d ui_mode=elements \
  --data-urlencode "return_url=https://example.com/return"
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/checkout/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer={{CUSTOMER_ID}}" \
  -d "line_items[0][price_data][currency]=usd" \
  -d "line_items[0][price_data][product_data][name]=T-shirt" \
  -d "line_items[0][price_data][unit_amount]=1099" \
  -d "line_items[0][quantity]=1" \
  -d mode=payment \
  -d ui_mode=elements \
  --data-urlencode "return_url=https://example.com/return"
```


# Setup Intents API

> This is a Setup Intents API for when payment-ui is elements. View the full page at https://docs.stripe.com/payments/save-and-reuse?payment-ui=elements.

[Setup Intents API](https://docs.stripe.com/api/setup_intents.md) を使用すると、初回の支払いなしで顧客の支払いの詳細を保存することができます。これは、今すぐ顧客をアカウント登録して支払いを設定し、将来顧客がオフラインのときに請求する場合に役立ちます。

この組み込みを使用して、継続支払いを設定したり、または顧客がサービスを受け取った後など、最終金額が後で決定される 1 回限りの支払いを作成したりします。

> #### カード提示取引
> 
> Stripe Terminal を介したカード詳細の収集などのカード提示取引では、別のプロセスを使用して決済手段を保存します。詳細については、[Terminal のドキュメント](https://docs.stripe.com/terminal/features/saving-payment-details/save-directly.md)をご覧ください。

## 法令遵守

顧客の支払いの詳細を保存する際、適用されるすべての法律、規制、ネットワークの規則に準拠する責任はお客様にあります。これらの要件は通常、以降の購入時の決済フローでの顧客の支払い方法を提示する、顧客がお客様のウェブサイトやアプリを使用していないときに請求するなど、将来に備えて顧客の支払い方法を保存する場合に適用されます。支払い方法の保存をどのように計画しているかを示す規約をウェブサイトやアプリに追加し、顧客が許可できるようにします。

決済手段を保存する場合、規約に記載された特定の用途にのみ使用できます。顧客がオフラインであるときに決済手段に請求して、以降の購入に備えたオプションとして保存する場合は、この特定の用途について顧客から明示的に同意を収集する必要があります。たとえば、同意を収集するために「今後の使用に備えて決済手段を保存する」チェックボックスを使用します。

顧客がオフラインのときに請求するには、規約に以下の内容を含める必要があります。

- 指定された取引で顧客の代理として単独の支払いまたは一連の支払いを開始することをお客様に許可するという、顧客からお客様への同意
- 予期される支払い時期と支払い頻度 (たとえば、請求が予定されている分割払いなのか、サブスクリプションの決済なのか、あるいは予定されていないトップアップなのか)。
- 支払い金額の決定方法
- 支払い方法をサブスクリプションサービスに使用する場合は、キャンセルに関するポリシー

これらの規約に関する顧客の書面による同意の記録を必ず保管してください。

> 手動でのサーバー側の確定を使用する必要がある場合、または実装で支払い方法を別途提示する必要がある場合は、[代替方法のガイド](https://docs.stripe.com/payments/save-and-reuse-cards-only.md)をご覧ください。

## Stripe を設定する [サーバ側]

まず、[Stripe アカウントを作成する](https://dashboard.stripe.com/register)か[サインイン](https://dashboard.stripe.com/login)します。

アプリケーションから Stripe API にアクセスするには、Stripe の公式ライブラリを使用します。

#### Ruby

```bash
# Available as a gem
sudo gem install stripe
```

```ruby
# If you use bundler, you can add this line to your Gemfile
gem 'stripe'
```

## 支払い方法を有効にする

[支払い方法の設定](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)をご覧ください。

## Customer を作成する [サーバ側]

将来の決済に備えて決済手段を設定するには、顧客を表すオブジェクトに関連付ける必要があります。顧客がアカウントを作成したとき、または初めて取引したときに、Accounts v2 API を使用して顧客設定の [Account](https://docs.stripe.com/api/v2/core/accounts/create.md) オブジェクト、または Customers API を使用して [Customer](https://docs.stripe.com/api/customers/create.md) オブジェクトを作成します。

> #### Accounts v2 API を使用した顧客の表現
> 
> Accounts v2 API では、Connect ユーザーには一般提供され、その他の Stripe ユーザーには公開プレビューで提供されます。Accounts v2 プレビューの一部である場合は、コードで[プレビューバージョン](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning)を指定する必要があります。
> 
> Accounts v2 プレビューへのアクセスをリクエストするには、
> 
> ほとんどのユースケースでは、[Customer](https://docs.stripe.com/api/customers.md) オブジェクトを使用するのではなく、[顧客を顧客設定の Account オブジェクトとしてモデル化する](https://docs.stripe.com/connect/use-accounts-as-customers.md)ことをお勧めします。

```curl
curl -X POST https://api.stripe.com/v1/customers \
  -u "<<YOUR_SECRET_KEY>>:"
```

## SetupIntent を作成する [サーバ側]

> 最初に SetupIntent を作成せずに Payment Element をレンダリングする場合は、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=setup)をご覧ください。

[SetupIntent](https://docs.stripe.com/api/setup_intents.md) は、将来の支払いのために顧客の支払い方法を設定する意図を表すオブジェクトです。チェックアウトプロセス中に顧客に表示される決済手段も `SetupIntent` に記載されます。Stripe でダッシュボードの設定から支払い方法を自動的に取得することも、手動でリストすることもできます。

決済手段の提供にコードベースのオプションを必要とする場合を除き、自動のオプションをお勧めします。これは、Stripe で通貨、決済手段の制約、その他のパラメーターを評価し、対応可能な決済手段のリストが決定されるためです。この場合、コンバージョン率上昇につながり、使用通貨と顧客の所在地に最も適した決済手段が優先的に表示されます。優先度の低い決済手段は、オーバーフローメニューの下に隠れた状態となります。

#### ダッシュボードで支払い方法を管理する

一部の決済手段は将来の決済のために保存できないため、将来の決済を設定する際にオプションとして表示されません。決済手段の管理について詳しくは、[決済手段の組み込みオプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)をご覧ください。

必要に応じて、`automatic_payment_methods` を有効にした SetupIntent を作成できます。その SetupIntent は、ダッシュボードで設定した支払い方法を使用して作成されます。最新バージョンの API では機能がデフォルトで有効になっているため、`automatic_payment_methods` パラメーターの指定は任意になりました。

支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。

#### Accounts v2

```curl
curl https://api.stripe.com/v1/setup_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d "automatic_payment_methods[enabled]=true"
```

#### Customers v1

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

#### 支払い方法を手動で列挙する

サポートする[支払い方法](https://docs.stripe.com/payments/payment-methods/integration-options.md)のリストを指定して、サーバー上で SetupIntent を作成します。

#### Accounts v2

```curl
curl https://api.stripe.com/v1/setup_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d "payment_method_types[]=bancontact" \
  -d "payment_method_types[]=card" \
  -d "payment_method_types[]=ideal"
```

#### Customers v1

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

### client secret を取得する

SetupIntent には、*client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) が含まれています。これは、支払いプロセスを安全に完了するためにクライアント側で使用されます。client secret をクライアント側に渡す際は、いくつかの方法を使用できます。

#### 1 ページのアプリケーション

ブラウザーの `fetch` 関数を使用して、サーバーのエンドポイントから client secret を取得します。この方法は、クライアント側が 1 ページのアプリケーションで、特に React などの最新のフロントエンドフレームワークで構築されている場合に最適です。client secret を処理するサーバーのエンドポイントを作成します。

#### Ruby

```ruby
get '/secret' do
  intent = # ... Create or retrieve the SetupIntent
  {client_secret: intent.client_secret}.to_json
end
```

その後、クライアント側で JavaScript を使用して client secret を取得します。

```javascript
(async () => {
  const response = await fetch('/secret');
  const {client_secret: clientSecret} = await response.json();
  // Render the form using the clientSecret
})();
```

#### サーバ側のレンダリング

サーバーからクライアントに client secret を渡します。この方法は、アプリケーションがブラウザーへの送信前に静的なコンテンツをサーバーで生成する場合に最適です。

決済フォームに [client_secret](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-client_secret) を追加します。サーバー側のコードで、SetupIntent から client secret を取得します。

#### Ruby

```erb
<form id="payment-form" data-secret="<%= @intent.client_secret %>">
  <div id="payment-element">
    <!-- placeholder for Elements -->
  </div>
  <button id="submit">Submit</button>
</form>
```

```ruby
get '/checkout' do
  @intent = # ... Fetch or create the SetupIntent
  erb :checkout
end
```

> #### Radar を使用する
> 
> 初回の支払いなしで顧客の支払い方法を保存する場合、[Radar](https://docs.stripe.com/radar.md) のデフォルトでは SetupIntent に対して動作しません。デフォルトで有効にするには、[Radar の設定](https://dashboard.stripe.com/settings/radar)に移動して、**今後のために保存された支払い方法で Radar を使用する**を有効にします。

## 支払いの詳細を収集する [クライアント側]

[Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用してクライアント側で支払い詳細を収集する準備ができました。Payment Element は事前構築された UI コンポーネントであり、多様な支払い方法の詳細の収集を容易にします。

Payment Element には、HTTPS 接続を介して決済情報を Stripe に安全に送信する iframe が含まれています。実装内容を機能させるには、決済ページのアドレスの先頭を `http://` ではなく `https://` にする必要があります。これを行わなくても実装内容のテストはできますが、本番環境で決済を受け付ける準備が整ったら、必ず HTTPS を[有効化](https://docs.stripe.com/security/guide.md#tls)してください。

#### HTML + JS

### Stripe.js を設定する

Payment Element は Stripe.js の機能として自動的に使用できるようになります。決済ページに Stripe.js スクリプトを含めるには、HTML ファイルの `head` にスクリプトを追加します。常に js.stripe.com から Stripe.js を直接読み込むことにより、PCI 準拠が維持されます。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。

```html
<head>
  <title>Checkout</title>
  <script src="https://js.stripe.com/dahlia/stripe.js"></script>
</head>
```

購入ページで次の JavaScript を使用して、Stripe のインスタンスを作成します。

```javascript
// Set your publishable key: remember to change this to your live publishable key in production
// See your keys here: https://dashboard.stripe.com/apikeys
const stripe = Stripe('<<YOUR_PUBLISHABLE_KEY>>');
```

### Payment Element を支払い設定ページに追加する

Payment Element を支払い設定ページに配置する場所が必要です。決済フォームで、一意の ID を持つ空の DOM ノード (コンテナー) を作成します。

```html
<form id="payment-form">
  <div id="payment-element">
    <!-- Elements will create form elements here -->
  </div>
  <button id="submit">Submit</button>
  <div id="error-message">
    <!-- Display error message to your customers here -->
  </div>
</form>
```

前のフォームが読み込まれたら、Payment Element のインスタンスを作成して、それをコンテナーの DOM ノードにマウントします。[Elements](https://docs.stripe.com/js/elements_object/create) インスタンスを作成する際に、前のステップからの [client secret](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-client_secret) を `options` に渡します。

```javascript
const options = {
  clientSecret: '{{CLIENT_SECRET}}',
  // Fully customizable with appearance API.
  appearance: {/*...*/},
};

// Set up Stripe.js and Elements using the SetupIntent's client secretconst elements = stripe.elements(options);

// Create and mount the Payment Element
const paymentElementOptions = { layout: 'accordion'};
const paymentElement = elements.create('payment', paymentElementOptions);
paymentElement.mount('#payment-element');

```

Payment Element によって動的なフォームが表示され、顧客はここで支払い方法を選択できます。支払い方法ごとに、フォームでは、必要な支払いの詳細のすべてを入力するように顧客に自動的に求めます。

### デザインをカスタマイズする

`elements` インスタンスの作成時に `options` に [appearance object](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-appearance) を渡して、サイトのデザインに合わせて Payment Element をカスタマイズします。Stripe Elements は、ドロップイン UI コンポーネントのコレクションです。フォームをさらにカスタマイズする場合や、さまざまな顧客情報を収集するには、[Elements ドキュメント](https://docs.stripe.com/payments/elements.md)を参照してください。

### Apple Pay マーチャントトークンをリクエストする

Apple Pay による決済を受け付ける場合は、`applePay` [オプション](https://docs.stripe.com/js/elements_object/create_payment_element#payment_element_create-options-applePay) を設定して、Apple Pay インターフェイスに表示される内容を変更することをお勧めします。これにより、Apple Pay の [merchant tokens](https://docs.stripe.com/apple-pay/merchant-tokens.md?pay-element=web-pe) が使用されます。次の例は、2030 年 1 月 5 日に開始する決済の設定を示しています。この情報は Apple Pay インターフェイスに反映されます。

```javascript
const paymentElement = elements.create('payment', {
  applePay: {
    deferredPaymentRequest: {
      paymentDescription: 'My deferred payment',
      managementURL: 'https://example.com/billing',
      deferredBilling: {
        amount: 2500,
        label: 'Deferred Fee',
        deferredPaymentDate: new Date('2030-01-05')
      },
    }
  },
  // Other options
});
```

#### React

### Stripe.js を設定する

次の npm パブリックレジストリから [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) と [Stripe.js ローダー](https://www.npmjs.com/package/@stripe/stripe-js)をインストールします。

```bash
npm install --save @stripe/react-stripe-js @stripe/stripe-js
```

### Elements プロバイダーを支払い設定ページに追加して設定する

Payment Element コンポーネントを使用するには、[Elements プロバイダー](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider)で支払い設定ページコンポーネントをラップします。公開可能キーを使用して `loadStripe` を呼び出し、返された `Promise` を `Elements` プロバイダーに渡します。さらに、前のステップの [client secret](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-client_secret) も `options` として `Elements` プロバイダーに渡します。

```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {Elements} from '@stripe/react-stripe-js';
import {loadStripe} from '@stripe/stripe-js';
import SetupForm from './SetupForm';

// Make sure to call `loadStripe` outside of a component's render to avoid
// recreating the `Stripe` object on every render.
const stripePromise = loadStripe('<<YOUR_PUBLISHABLE_KEY>>');

function App() {
  const options = {
    // passing the SetupIntent's client secret
    clientSecret: '{{CLIENT_SECRET}}',
    // Fully customizable with appearance API.
    appearance: {/*...*/},
  };

  return (
    <Elements stripe={stripePromise} options={options}>
      <SetupForm />
    </Elements>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));
```

### Payment Element コンポーネントを追加する

`PaymentElement` コンポーネントを使用して、フォームを構築します。

```jsx
import React from 'react';
import {PaymentElement} from '@stripe/react-stripe-js';

const SetupForm = () => {
  return (
    <form><PaymentElement />
      <button>Submit</button>
    </form>
  );
};

export default SetupForm;
```

Stripe Elements は、ドロップイン UI コンポーネントのコレクションです。フォームをさらにカスタマイズしたり、その他の顧客情報を収集したりする場合は、[Elements のドキュメント](https://docs.stripe.com/payments/elements.md)をご覧ください。

Payment Element によって動的なフォームが表示され、顧客はここで支払い方法を選択できます。支払い方法ごとに、フォームでは、必要な支払いの詳細のすべてを入力するように顧客に自動的に求めます。

### デザインをカスタマイズする

`Elements` プロバイダーを作成する際に、[Appearance (デザイン) オブジェクト](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-appearance)を `options` に渡すことで、サイトのデザインに合わせて Payment Element をカスタマイズできます。

### Apple Pay マーチャントトークンをリクエストする

Apple Pay による決済を受け付ける場合は、`applePay` [オプション](https://docs.stripe.com/js/elements_object/create_payment_element#payment_element_create-options-applePay) を設定して、Apple Pay インターフェイスに表示される内容を変更することをお勧めします。これにより、Apple Pay の [merchant tokens](https://docs.stripe.com/apple-pay/merchant-tokens.md?pay-element=web-pe) が使用されます。次の例は、2030 年 1 月 5 日に開始する決済の設定を示しています。この情報は Apple Pay インターフェイスに反映されます。

```jsx
import React from 'react';
import {PaymentElement} from '@stripe/react-stripe-js';

const SetupForm = () => {
  const options = {
    applePay: {
      deferredPaymentRequest: {
        paymentDescription: 'My deferred payment',
        managementURL: 'https://example.com/billing',
        deferredBilling: {
          amount: 2500,
          label: 'Deferred Fee',
          deferredPaymentDate: new Date('2030-01-05')
        },
      }
    },
    // Other options
  };

  return (
    <form><PaymentElement options={options} />
      <button>Submit</button>
    </form>
  );
};

export default SetupForm;
```

### 通貨を設定する

[automatic_payment_methods](https://docs.stripe.com/api/setup_intents/create.md#create_setup_intent-automatic_payment_methods) で SetupIntents を使用する場合、[Payment Element の作成](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-currency)時に通貨を指定できます。Payment Element は、指定された通貨をサポートする有効な支払い方法をレンダリングします。詳細については、[Payment Element のドキュメント](https://docs.stripe.com/payments/payment-methods/integration-options.md)を参照してください。

### 住所を収集

デフォルトでは、Payment Element は必要な請求住所の詳細のみを収集します。[税金の計算](https://docs.stripe.com/api/tax/calculations/create.md)、配送先情報を入力するなどの一部の動作では、顧客の完全な住所が必要です。次のように対応できます。

- [Address Element](https://docs.stripe.com/elements/address-element.md) を使用して、オートコンプリートとローカリゼーションの機能を利用して、顧客の完全な住所を収集します。これにより、最も正確な税金計算が可能になります。
- 独自のカスタムフォームを使用して住所の詳細を収集する。

## Optional: 決済ページでの Link [クライアント側]

顧客が [Payment Element](https://docs.stripe.com/payments/payment-element.md) で [Link](https://docs.stripe.com/payments/link.md) を使用してスピーディーに購入できるようにします。Link をすでに使用しているログイン中の顧客の情報は、顧客が最初に別のビジネスで Link に情報を保存したかどうかに関係なく、自動入力できます。デフォルトの Payment Element の実装では、カードフォームに Link プロンプトが表示されます。Payment Element で Link を管理するには、 [決済手段の設定](https://dashboard.stripe.com/settings/payment_methods)に移動します。
![購入時に Payment Element で直接 Link を認証または登録する](https://b.stripecdn.com/docs-statics-srv/assets/link-in-pe.2efb5138a4708b781b8a913ebddd9aba.png)

Link の認証または登録のために顧客のメールアドレスを回収する

### 導入オプション

Payment Element を使用して Link を導入する方法は 2 つあります。中でも、Stripe は、利用可能な場合、Payment Element に顧客のメールアドレスを渡す方法を推奨しています。これらのオプションから決定する際は、必ず貴社の決済フローの仕組みを考慮してください。

| 導入オプション                                        | 決済フロー                                                                            | 説明                                                                                                                |
| ---------------------------------------------- | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Payment Element に顧客のメールアドレスを渡します (Recommended) | - 顧客は、購入ページを開く前に (以前のアカウント作成ステップなどで) メールアドレスを入力します。
  - 自社のメールアドレス入力フィールドを使用したい。 | 顧客のメールアドレスを Payment Element にプログラムで渡します。このシナリオでは、顧客は別の UI コンポーネントではなく、決済フォームで直接 Link の認証を行います。                    |
| Payment Element で顧客のメールアドレスを収集する               | - 顧客は、決済時に Payment Element で直接、メールアドレスを入力して認証するか、Link に登録できます。
  - コード変更が不要です。   | 顧客が Link に登録しておらず、Payment Element で対応している決済手段を選択すると、Link を使用して詳細を保存するように求められます。すでに登録している場合は、Link が決済情報を自動的に入力します。 |

[defaultValues](https://docs.stripe.com/js/elements_object/create_payment_element#payment_element_create-options-defaultValues) を使用して、顧客のメールアドレスを Payment Element に渡します。

```javascript
const paymentElement = elements.create('payment', {
  defaultValues: {
    billingDetails: {
      email: 'foo@bar.com',
    }
  },
  // Other options
});
```

詳細については、Link を含むカスタム決済画面を[構築する方法をご覧ください](https://docs.stripe.com/payments/link/add-link-elements-integration.md)。

## Optional: 顧客の支払い方法を保存および取得する

将来の利用に備えて顧客の決済手段を保存するように Payment Element を設定できます。このセクションでは、[決済手段の保存機能](https://docs.stripe.com/payments/save-customer-payment-methods.md)を導入する方法を説明しています。Payment Element で以下を実行できます。

- 買い手に支払い方法を保存することの同意を求める
- 買い手が同意した場合に支払い方法を保存する
- 将来の購入時に保存した支払い方法を買い手に表示する
- 買い手が紛失したカードまたは期限切れのカードを交換するときに[それらのカードを自動的に更新する](https://docs.stripe.com/payments/cards/overview.md#automatic-card-updates)
![Payment Element と保存した決済手段のチェックボックス](https://b.stripecdn.com/docs-statics-srv/assets/spm-save.fe0b24afd0f0a06e0cf4eecb0ce2403a.png)

決済手段を保存します。
![保存された支払い方法が選択された Payment Element](https://b.stripecdn.com/docs-statics-srv/assets/spm-saved.5dba5a8a190a9a0e9f1a99271bed3f4b.png)

以前に保存した支払い方法を再利用します。

### Payment Element で支払い方法の保存機能を有効にする

顧客の ID を指定し (`customer` は `Customer` オブジェクト用、`customer_account` は顧客設定の `Account` オブジェクト用)、セッションで [payment_element](https://docs.stripe.com/api/customer_sessions/object.md#customer_session_object-components-payment_element) コンポーネントを有効にして、サーバー上に [CustomerSession](https://docs.stripe.com/api/customer_sessions/.md) を作成します。有効にする保存済み決済手段の [features](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components-payment_element-features) を設定します。たとえば、[payment_method_save](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components-payment_element-features-payment_method_save) を有効にすると、顧客が決済情報を保存して今後利用できるようにするチェックボックスが表示されます。

PaymentIntent または Checkout Session で `setup_future_usage` を指定すると、決済手段の保存に関するデフォルトの動作を上書きできます。これにより、顧客が明示的に保存を選択しなくても、今後の利用に備えて決済手段が自動的に保存されます。`setup_future_usage` を指定する場合は、同じ決済取引で `payment_method_save_usage` を設定しないでください。設定すると導入エラーが発生します。

> #### Accounts v2 API を使用した顧客の表現
> 
> Accounts v2 API では、Connect ユーザーには一般提供され、その他の Stripe ユーザーには公開プレビューで提供されます。Accounts v2 プレビューの一部である場合は、コードで[プレビューバージョン](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning)を指定する必要があります。
> 
> Accounts v2 プレビューへのアクセスをリクエストするには、
> 
> ほとんどのユースケースでは、[Customer](https://docs.stripe.com/api/customers.md) オブジェクトを使用するのではなく、[顧客を顧客設定の Account オブジェクトとしてモデル化する](https://docs.stripe.com/connect/use-accounts-as-customers.md)ことをお勧めします。

#### Accounts v2

#### Ruby

```ruby

# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

post '/create-intent-and-customer-session' do
  intent = client.v1.setup_intents.create({
    automatic_payment_methods: {enabled: true},
    customer_account: {{CUSTOMER_ACCOUNT_ID}},
  })
  customer_session = client.v1.customer_sessions.create({
    customer_account: {{CUSTOMER_ACCOUNT_ID}},
    components: {
      payment_element: {
          enabled: true,
          features: {
            payment_method_redisplay: 'enabled',
            payment_method_save: 'enabled',
            payment_method_save_usage: 'off_session',
            payment_method_remove: 'enabled',
          },
        },
    },
  })
  {
    client_secret: intent.client_secret,
    customer_session_client_secret: customer_session.client_secret
  }.to_json
end
```

#### Customers v1

#### Ruby

```ruby

# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

post '/create-intent-and-customer-session' do
  intent = client.v1.setup_intents.create({
    # In the latest version of the API, specifying the `automatic_payment_methods` parameter
    # is optional because Stripe enables its functionality by default.
    automatic_payment_methods: {enabled: true},
    customer: {{CUSTOMER_ID}},
  })
  customer_session = client.v1.customer_sessions.create({
    customer: {{CUSTOMER_ID}},
    components: {
      payment_element: {
          enabled: true,
          features: {
            payment_method_redisplay: 'enabled',
            payment_method_save: 'enabled',
            payment_method_save_usage: 'off_session',
            payment_method_remove: 'enabled',
          },
        },
    },
  })
  {
    client_secret: intent.client_secret,
    customer_session_client_secret: customer_session.client_secret
  }.to_json
end
```

Elements インスタンスはその CustomerSession の *client secret* (A client secret is used with your publishable key to authenticate a request for a single object. Each client secret is unique to the object it's associated with) を使用して、顧客が保存した支払い方法にアクセスします。CustomerSession の作成時に適切に[エラーを処理](https://docs.stripe.com/error-handling.md)します。エラーが発生した場合、CustomerSession の client secret はオプションなので、Elements インスタンスに指定する必要はありません。

SetupIntent と CustomerSession の両方の client secret を使用して、Elements インスタンスを作成します。次に、この Elements インスタンスを使用して Payment Element を作成します。

```javascript
// Create the CustomerSession and obtain its clientSecret
const res = await fetch("/create-intent-and-customer-session", {
  method: "POST"
});

const {
  customer_session_client_secret: customerSessionClientSecret
} = await res.json();

const elementsOptions = {
  clientSecret: '{{CLIENT_SECRET}}',customerSessionClientSecret,
  // Fully customizable with appearance API.
  appearance: {/*...*/},
};

// Set up Stripe.js and Elements to use in checkout form, passing the client secret
// and CustomerSession's client secret obtained in a previous step
const elements = stripe.elements(elementsOptions);

// Create and mount the Payment Element
const paymentElementOptions = { layout: 'accordion'};
const paymentElement = elements.create('payment', paymentElementOptions);
paymentElement.mount('#payment-element');
```

SetupIntent の確定時に、顧客が支払いの詳細を保存するためのボックスにチェックマークを付けたかどうかに応じて、Stripe.js が PaymentMethod の [allow_redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) の設定をコントロールします。

### 保存した支払い方法の選択内容を検出する

保存した支払い方法を選択したときにコンテンツを動的に制御するには、Payment Element の `change` イベントをリッスンします。このイベントには、選択した支払い方法の情報が入力されています。

```javascript
paymentElement.on('change', function(event) {
  if (event.value.payment_method) {
    // Control dynamic content if a saved payment method is selected
  }
})
```

## Stripe に支払いの詳細を送信する [クライアント側]

[stripe.confirmSetup](https://docs.stripe.com/js/setup_intents/confirm_setup) を使用して、Payment Element によって収集された詳細で設定を完了します。この関数に [return_url](https://docs.stripe.com/api/setup_intents/create.md#create_setup_intent-return_url) を指定して、設定完了後のユーザーのリダイレクト先を指定します。まず、ユーザーを銀行のオーソリページなどの中間サイトにリダイレクトしてから、`return_url` にリダイレクトできます。

顧客がカード詳細を保存する場合、設定が正常に完了するとすぐに `return_url` にリダイレクトされます。カード支払いでリダイレクトを行わない場合は、[redirect](https://docs.stripe.com/js/setup_intents/confirm_setup#confirm_setup_intent-options-redirect) に `if_required` を設定できます。これにより、リダイレクトベースの支払い方法で購入する顧客のみがリダイレクトされます。

#### HTML + JS

```javascript
const form = document.getElementById('payment-form');

form.addEventListener('submit', async (event) => {
  event.preventDefault();
const {error} = await stripe.confirmSetup({
    //`Elements` instance that was used to create the Payment Element
    elements,
    confirmParams: {
      return_url: 'https://example.com/account/payments/setup-complete',
    }
  });

  if (error) {
    // This point will only be reached if there is an immediate error when
    // confirming the payment. Show error to your customer (for example, payment
    // details incomplete)
    const messageContainer = document.querySelector('#error-message');
    messageContainer.textContent = error.message;
  } else {
    // Your customer will be redirected to your `return_url`. For some payment
    // methods like iDEAL, your customer will be redirected to an intermediate
    // site first to authorize the payment, then redirected to the `return_url`.
  }
});
```

#### React

支払いフォームコンポーネントから [stripe.confirmSetup](https://docs.stripe.com/js/setup_intents/confirm_setup) を呼び出すには、[useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) フックと [useElements](https://docs.stripe.com/sdks/stripejs-react.md#useelements-hook) フックを使用します。

フックではなく従来のクラスコンポーネントを使用する場合は、代わりに [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) を使用します。

```jsx
import React, {useState} from 'react';
import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js';

const SetupForm = () => {
  const stripe = useStripe();
  const elements = useElements();

  const [errorMessage, setErrorMessage] = useState(null);

  const handleSubmit = async (event) => {
    // We don't want to let default form submission happen here,
    // which would refresh the page.
    event.preventDefault();

    if (!stripe || !elements) {
      // Stripe.js hasn't yet loaded.
      // Make sure to disable form submission until Stripe.js has loaded.
      return null;
    }
const {error} = await stripe.confirmSetup({
      //`Elements` instance that was used to create the Payment Element
      elements,
      confirmParams: {
        return_url: 'https://example.com/account/payments/setup-complete',
      },
    });

    if (error) {
      // This point will only be reached if there is an immediate error when
      // confirming the payment. Show error to your customer (for example, payment
      // details incomplete)
      setErrorMessage(error.message);
    } else {
      // Your customer will be redirected to your `return_url`. For some payment
      // methods like iDEAL, your customer will be redirected to an intermediate
      // site first to authorize the payment, then redirected to the `return_url`.
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <PaymentElement />
      <button disabled={!stripe}>Submit</button>
      {/* Show error message to your customers */}
      {errorMessage && <div>{errorMessage}</div>}
    </form>
  )
};

export default SetupForm;
```

`return_url` は、`SetupIntent` の [ステータスを表示](https://docs.stripe.com/payments/payment-intents/verifying-status.md) するウェブサイト上のページと一致している必要があります。Stripe が顧客を `return_url` にリダイレクトするときに、以下の URL クエリパラメーターが渡され、ステータスが確認されます。`return_url` を指定する際に、独自のクエリパラメーターを追加することもできます。このパラメーターはリダイレクトプロセス全体を通じて持続します。

| パラメーター                       | 説明                                                                                                                            |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `setup_intent`               | `SetupIntent` の一意の識別子。                                                                                                        |
| `setup_intent_client_secret` | `SetupIntent` オブジェクトの [client secret](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-client_secret)。 |

[stripe.retrieveSetupIntent](https://docs.stripe.com/js/setup_intents/retrieve_setup_intent) を使用すると、`setup_intent_client_secret` クエリパラメーターを使って `SetupIntent` を取得できます。`SetupIntent` の確認が正常に完了すると、生成された `PaymentMethod` ID は `result.setupIntent.payment_method` に保存され、指定した顧客設定の `Account` または `Customer` に関連付けられます。

#### HTML + JS

```javascript

// Initialize Stripe.js using your publishable key
const stripe = Stripe('{PUBLISHABLE_KEY}');

// Retrieve the "setup_intent_client_secret" query parameter appended to
// your return_url by Stripe.js
const clientSecret = new URLSearchParams(window.location.search).get(
  'setup_intent_client_secret'
);

// Retrieve the SetupIntent
stripe.retrieveSetupIntent(clientSecret).then(({setupIntent}) => {
  const message = document.querySelector('#message')

  // Inspect the SetupIntent `status` to indicate the status of the payment
  // to your customer.
  //
  // Some payment methods will [immediately succeed or fail][0] upon
  // confirmation, while others will first enter a `processing` state.
  //
  // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification
  switch (setupIntent.status) {
    case 'succeeded': {
      message.innerText = 'Success! Your payment method has been saved.';
      break;
    }

    case 'processing': {
      message.innerText = "Processing payment details. We'll update you when processing is complete.";
      break;
    }

    case 'requires_payment_method': {
      message.innerText = 'Failed to process payment details. Please try another payment method.';

      // Redirect your user back to your payment page to attempt collecting
      // payment again

      break;
    }
  }
});
```

#### React

```jsx

// PaymentStatus.jsx

import React, {useState, useEffect} from 'react';
import {useStripe} from '@stripe/react-stripe-js';

const PaymentStatus = () => {
  const stripe = useStripe();
  const [message, setMessage] = useState(null);

  useEffect(() => {
    if (!stripe) {
      return;
    }

    // Retrieve the "setup_intent_client_secret" query parameter appended to
    // your return_url by Stripe.js
    const clientSecret = new URLSearchParams(window.location.search).get(
      'setup_intent_client_secret'
    );

    // Retrieve the SetupIntent
    stripe
      .retrieveSetupIntent(clientSecret)
      .then(({setupIntent}) => {
        // Inspect the SetupIntent `status` to indicate the status of the payment
        // to your customer.
        //
        // Some payment methods will [immediately succeed or fail][0] upon
        // confirmation, while others will first enter a `processing` state.
        //
        // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification
        switch (setupIntent.status) {
          case 'succeeded':
            setMessage('Success! Your payment method has been saved.');
            break;

          case 'processing':
            setMessage("Processing payment details. We'll update you when processing is complete.");
            break;

          case 'requires_payment_method':
            // Redirect your user back to your payment page to attempt collecting
            // payment again
            setMessage('Failed to process payment details. Please try another payment method.');
            break;
        }
      });
  }, [stripe]);


  return message
};

export default PaymentStatus;
```

> 顧客のブラウザーセッションを追跡するツールを利用している場合、リファラー除外リストに `stripe.com` ドメインの追加が必要になる場合があります。リダイレクトを行うと、一部のツールでは新しいセッションが作成され、セッション全体の追跡ができなくなります。

## 保存された支払い方法に後で請求する [サーバ側]

> #### 法令遵守
> 
> 顧客の支払いの詳細を保存する際、お客様は適用されるすべての法律、規制、ネットワークの規則に準拠する責任があります。将来の購入に備えて顧客に過去の決済手段を提供する際は、必ず、特定の将来の使用に備えて決済手段の詳細を保存することについての同意を顧客から収集した決済手段をリストアップします。顧客に関連付けられた決済手段のうち、将来の購入用の保存済みの決済手段として顧客に提示できるものと提示できないものを区別するには、[allow_redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) パラメーターを使用します。

請求する決済手段を見つけるには、顧客に関連付けられている決済手段を一覧表示します。この例ではカードを一覧表示していますが、サポートされている任意の [type](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-type) を一覧表示できます。

> #### Accounts v2 API を使用した顧客の表現
> 
> Accounts v2 API では、Connect ユーザーには一般提供され、その他の Stripe ユーザーには公開プレビューで提供されます。Accounts v2 プレビューの一部である場合は、コードで[プレビューバージョン](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning)を指定する必要があります。
> 
> Accounts v2 プレビューへのアクセスをリクエストするには、
> 
> ほとんどのユースケースでは、[Customer](https://docs.stripe.com/api/customers.md) オブジェクトを使用するのではなく、[顧客を顧客設定の Account オブジェクトとしてモデル化する](https://docs.stripe.com/connect/use-accounts-as-customers.md)ことをお勧めします。

#### Accounts v2

```curl
curl -G https://api.stripe.com/v1/payment_methods \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d type=card
```

#### Customers v1

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

顧客に*オフセッション* (A payment is described as off-session if it occurs without the direct involvement of the customer, using previously-collected payment information)で請求する準備ができたら、顧客の ID と `PaymentMethod` ID を使用して、決済の金額と通貨を指定した `PaymentIntent` を作成します。オフセッション決済を行うには、追加のパラメーターもいくつか設定する必要があります。

- 決済の試行時に顧客が決済フローにおらず、カード発行会社、銀行、その他の決済機関などのパートナーからの認証リクエストに対応できないことを示すには、[off_session](https://docs.stripe.com/api/payment_intents/confirm.md#confirm_payment_intent-off_session) を `true` に設定します。決済フロー中にパートナーが認証をリクエストした場合、Stripe は以前の*オンセッション* (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)取引の顧客情報を使用して適用除外をリクエストします。適用除外の条件が満たされない場合、`PaymentIntent` でエラーが返されることがあります。
- `PaymentIntent` の [confirm](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-confirm) プロパティの値を true に設定すると、`PaymentIntent` の作成時にただちに確認が行われます。
- [payment_method](https://docs.stripe.com/api.md#create_payment_intent-payment_method) を `PaymentMethod` の ID に設定します。
- 導入で顧客をどのように表すかに応じて、[customer_account](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer_account) を顧客設定の `Account` の ID に設定するか、[customer](https://docs.stripe.com/api.md#create_payment_intent-customer) を `Customer` の ID に設定します。

#### Accounts v2

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d "automatic_payment_methods[enabled]=true" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d payment_method={{PAYMENT_METHOD_ID}} \
  --data-urlencode "return_url=https://example.com/order/123/complete" \
  -d off_session=true \
  -d confirm=true
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd \
  -d "automatic_payment_methods[enabled]=true" \
  -d "customer={{CUSTOMER_ID}}" \
  -d payment_method={{PAYMENT_METHOD_ID}} \
  --data-urlencode "return_url=https://example.com/order/123/complete" \
  -d off_session=true \
  -d confirm=true
```

支払いが失敗すると、リクエストも 402 HTTP ステータスコードで失敗し、PaymentIntent のステータスが *requires\_payment\_method* (This status appears as "requires_source" in API versions before 2019-02-11) になります。アプリケーションに戻って支払いを完了するよう (メールやアプリ内通知を送信するなどして) 顧客に通知する必要があります。

Stripe API ライブラリから発生した[エラー](https://docs.stripe.com/api/errors/handling.md)のコードを確認します。支払いが [authentication_required](https://docs.stripe.com/declines/codes.md) 拒否コードで失敗した場合には、拒否された PaymentIntent の client secret を confirmPayment とともに使用し、顧客が支払いを認証できるようにします。

```javascript
const form = document.getElementById('payment-form');

form.addEventListener('submit', async (event) => {
  event.preventDefault();

  const {error} = await stripe.confirmPayment({
    // The client secret of the PaymentIntent
    clientSecret,
    confirmParams: {
      return_url: 'https://example.com/order/123/complete',
    },
  });

  if (error) {
    // This point will only be reached if there is an immediate error when
    // confirming the payment. Show error to your customer (for example, payment
    // details incomplete)
    const messageContainer = document.querySelector('#error-message');
    messageContainer.textContent = error.message;
  } else {
    // Your customer will be redirected to your `return_url`. For some payment
    // methods like iDEAL, your customer will be redirected to an intermediate
    // site first to authorize the payment, then redirected to the `return_url`.
  }
});
```

> `stripe.confirmPayment` の完了には数秒かかる場合があります。この間、フォームが再送信されないように無効化し、スピナーのような待機中のインジケーターを表示します。エラーが発生した場合は、それを顧客に表示し、フォームを再度有効化し、待機中のインジケーターを非表示にします。支払いの完了のために顧客による認証などの追加の手順が必要な場合は、Stripe.js がそのプロセスをステップごとに顧客に提示します。

利用可能額不足など、他の理由で支払いが失敗した場合、新しい支払い方法を入力する支払いページを顧客に送信します。既存の PaymentIntent を再利用し、新しい支払いの詳細を利用して支払いを再試行できます。

## 組み込みをテストする

テスト用の支払いの詳細とテスト用リダイレクトページを使用して、組み込みを確認できます。以下のタブをクリックすると、各支払い方法の詳細を表示できます。

#### カード

| 決済手段     | シナリオ                                                                                                                                                                                                                                                                       | テスト方法                                                                              |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| クレジットカード | カードの設定は成功し、*認証* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase)は必要ありません。 | クレジットカード番号 `4242 4242 4242 4242` と、任意の有効期限、セキュリティーコード、郵便番号を使用してクレジットカードフォームに入力します。 |
| クレジットカード | このカードは初期設定時に認証が必要であり、それ以降は支払いに成功します。                                                                                                                                                                                                                                       | クレジットカード番号 `4000 0025 0000 3155` と、任意の有効期限、セキュリティーコード、郵便番号を使用してクレジットカードフォームに入力します。 |
| クレジットカード | このカードは、初期設定時も、以降の支払いでも認証が必要です。                                                                                                                                                                                                                                             | クレジットカード番号 `4000 0027 6000 3184` と、任意の有効期限、セキュリティーコード、郵便番号を使用してクレジットカードフォームに入力します。 |
| クレジットカード | 設定中にカードは拒否されます。                                                                                                                                                                                                                                                            | クレジットカード番号 `4000 0000 0000 9995` と、任意の有効期限、セキュリティーコード、郵便番号を使用してクレジットカードフォームに入力します。 |

#### 銀行へのリダイレクト

| 決済手段           | シナリオ                                                                                                         | テスト方法                                                                                                             |
| -------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| Bancontact     | 顧客は、Bancontact を使用して、今後の使用に備えた SEPA ダイレクトデビットによる支払い方法の設定を完了しました。                                             | Bancontact フォームで任意の氏名を使用して、リダイレクトページで **Authorize test setup (テスト設定承認)** をクリックします。                                |
| Bancontact     | 顧客は Bancontact リダイレクトページで認証に失敗します。                                                                           | Bancontact フォームで任意の氏名を使用して、リダイレクトページで **Fail test setup (テスト設定失敗)** をクリックします。                                     |
| BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。                                                                             | 口座番号 `900123456` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 |
| BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。                                                                       | 口座番号 `111111113` を使用して、フォームに入力します。                                                                                |
| iDEAL          | 顧客は iDEAL を使用して、今後の使用に備えて [SEPA ダイレクトデビット](https://docs.stripe.com/payments/sepa-debit.md)による決済手段の設定を完了しました。 | iDEAL フォームで任意の氏名と銀行を使用し、リダイレクトページで **Authorize test setup (テスト設定承認)** をクリックします。                                   |
| iDEAL          | 顧客は iDEAL リダイレクトページで認証に失敗します。                                                                                | iDEAL フォームで任意の銀行を選択し、任意の氏名を指定して、リダイレクトページで **Fail test setup (テスト設定失敗)** をクリックします。                                |

#### 口座引き落とし

| 決済手段           | シナリオ                                                                         | テスト方法                                                                                                                   |
| -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。                                             | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 |
| SEPA ダイレクトデビット | 顧客の Payment Intent のステータスは、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。                                                                           |

### 保存された SEPA デビット PaymentMethod への請求をテストする

iDEAL、Bancontact または Sofort を使用して  SetupIntent  が確定されると、[SEPA ダイレクトデビット](https://docs.stripe.com/payments/sepa-debit.md) の *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) が生成されます。SEPA ダイレクトデビットは、[通知遅延型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の決済手段であり、中間の `processing` 状態に移行してから、数日後に `succeeded` または `requires_payment_method` の状態に移行します。

#### メール

`payment_method.billing_details.email` を以下のいずれかの値に設定して、`PaymentIntent` のステータス遷移をテストしてください。任意のテキストとアンダースコアをメールアドレスの前に追加することもできます。例えば、`test_1_generatedSepaDebitIntentsFail@example.com` を使用すると、`PaymentIntent` で使用した際に必ず失敗する SEPA ダイレクトデビットの PaymentMethodになります。

| メールアドレス                                                            | 説明                                                                                                         |
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `generatedSepaDebitIntentsSucceed@example.com`                     | `PaymentIntent` のステータスが `processing` から `succeeded` に遷移します。                                                |
| `generatedSepaDebitIntentsSucceedDelayed@example.com`              | `PaymentIntent` のステータスが 3 分後に `processing` から `succeeded` に遷移します。                                          |
| `generatedSepaDebitIntentsFail@example.com`                        | `PaymentIntent` のステータスが `processing` から `requires_payment_method` に遷移します。                                  |
| `generatedSepaDebitIntentsFailDelayed@example.com`                 | `PaymentIntent` のステータスが 3 分後に `processing` から `requires_payment_method` に遷移します。                            |
| `generatedSepaDebitIntentsSucceedDisputed@example.com`             | `PaymentIntent` のステータスが `processing` から `succeeded` に遷移しますが、不審請求の申し立てがすぐに作成されます。                           |
| `generatedSepaDebitIntentsFailsDueToInsufficientFunds@example.com` | `PaymentIntent` のステータスが `processing` から `requires_payment_method` に遷移し、`insufficient_funds` のエラーコードが返されます。 |

#### PaymentMethod

これらの PaymentMethods を使用して `PaymentIntent` のステータスの遷移をテストしてください。これらのトークンは、自動化されたテストで PaymentMethod がサーバー上の SetupIntent にすぐに関連付けられる際に役に立ちます。

| 決済手段                                                                 | 説明                                                                                                         |
| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `pm_bancontact_generatedSepaDebitIntentsSucceed`                     | `PaymentIntent` のステータスが `processing` から `succeeded` に遷移します。                                                |
| `pm_bancontact_generatedSepaDebitIntentsSucceedDelayed`              | `PaymentIntent` のステータスが 3 分後に `processing` から `succeeded` に遷移します。                                          |
| `pm_bancontact_generatedSepaDebitIntentsFail`                        | `PaymentIntent` のステータスが `processing` から `requires_payment_method` に遷移します。                                  |
| `pm_bancontact_generatedSepaDebitIntentsFailDelayed`                 | `PaymentIntent` のステータスが 3 分後に `processing` から `requires_payment_method` に遷移します。                            |
| `pm_bancontact_generatedSepaDebitIntentsSucceedDisputed`             | `PaymentIntent` のステータスが `processing` から `succeeded` に遷移しますが、不審請求の申し立てがすぐに作成されます。                           |
| `pm_bancontact_generatedSepaDebitIntentsFailsDueToInsufficientFunds` | `PaymentIntent` のステータスが `processing` から `requires_payment_method` に遷移し、`insufficient_funds` のエラーコードが返されます。 |

## Optional: レイアウトをカスタマイズする [クライアント側]

決済フローインターフェイスに合わせて Payment Element のレイアウト (アコーディオンまたはタブ) をカスタマイズできます。各プロパティについて、詳細は [elements.create](https://docs.stripe.com/js/elements_object/create_payment_element#payment_element_create-options) をご覧ください。

#### アコーディオン

Payment Element の作成時にレイアウトの `type` と他のオプションプロパティーを渡すと、レイアウト機能の使用を開始できます。

```javascript
const paymentElement = elements.create('payment', {
  layout: {
    type: 'accordion',
    defaultCollapsed: false,
    radios: 'always',
    spacedAccordionItems: false
  }
});
```

#### タブ

### レイアウトを指定する

レイアウトの値を `tabs` に設定します。以下の例のようなその他のプロパティーを指定するオプションもあります。

```javascript
const paymentElement = elements.create('payment', {
  layout: {
    type: 'tabs',
    defaultCollapsed: false,
  }
});
```

以下の画像は、異なるレイアウト設定を適用した同一 Payment Element の表示を示しています。
![3 つの決済フォーム体験](https://b.stripecdn.com/docs-statics-srv/assets/pe_layout_example.525f78bcb99b95e49be92e5dd34df439.png)

Payment Element のレイアウト

## Optional: Apple Pay および Google Pay [クライアント側]

[カード決済を有効にする場合](https://docs.stripe.com/payments/save-and-reuse.md?platform=web&ui=elements#create-intent)、[ウォレットの表示条件](https://docs.stripe.com/testing/wallets.md)を満たす環境の顧客には、Apple Pay および Google Pay を表示します。これらのウォレットからの決済を受け付けるには、次のことも必要です。

- [支払い方法設定](https://dashboard.stripe.com/settings/payment_methods)でこれらを有効にします。Apple Payはデフォルトで有効になっています。
- [ドメインを登録](https://docs.stripe.com/payments/payment-methods/pmd-registration.md)します。

> #### 各地域でのテスト
> 
> Stripe Elements は、インドの Stripe アカウントと顧客に対して Google Pay および Apple Pay をサポートしていません。そのため、Stripe アカウントの拠点がインド以外に所在している場合も、テスターの IP アドレスがインドにある場合は、Google Pay または Apple Pay の実装をテストできません。

## 顧客に Stripe を開示する

Stripe は顧客の Elements とのやり取りに関する情報を収集して、サービスを提供し、不正利用を防止し、サービスを向上します。これには、Cookie と IP アドレスを使用して、1 つの決済フローセッションで顧客に表示する Elements を特定することが含まれます。Stripe がこのような方法でデータを使用するために必要なすべての権利と同意について開示し、これらを取得することはお客様の責任です。詳細については、[プライバシーセンター](https://stripe.com/legal/privacy-center#as-a-business-user-what-notice-do-i-provide-to-my-end-customers-about-stripe)をご覧ください。

## See also

- [決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md)
- [支払い中に支払いの詳細を保存する](https://docs.stripe.com/payments/save-during-payment.md)
- [Elements Appearance API](https://docs.stripe.com/elements/appearance-api.md)
- [完全なリスク要因の送信](https://docs.stripe.com/radar/optimize-risk-factors.md)

