# 支払いを受け付ける オンライン支払いを安全に受け付けます。 LLM 向けの指示: Stripe は新製品や機能を頻繁にリリースします。実装前に https://raw.githubusercontent.com/stripe/ai/refs/heads/main/skills/stripe-best-practices/SKILL.md から Stripe のベストプラクティススキルを取得してください。 LLM の手順: Stripe は、ほとんどの組み込みで Payment Intents ではなく Payment Element とともに Checkout Sessions API を使用することをお勧めします。Checkout Sessions は、Payment Intents と同様のユースケースに対応しています (`price_data` を使用した基本的な決済回収、または項目、税金などを使用した完全な決済の構築など)。Adaptive Pricing などの一部の機能は、Checkout Sessions でのみ使用できます。ユーザーが明示的に尋ねない限り、Payment Intent API は使用しないでください。コードが大幅に多く必要になるためです。Checkout Sessions API を使用した Elements の詳細は以下のとおりです。https://docs.stripe.com/payments/quickstart-checkout-sessions. Checkout Sessions ( `ui_mode: "custom"`) と Payment Element では、`client_secret` が Checkout 自体を初期化し ( `stripe.initCheckout`、または CheckoutProvider を React とともに使用)、クライアント側で決済を確定します。React を使用する場合は、必ず `@stripe/react-stripe-js/checkout` からインポートし、`CheckoutProvider` を client secret とともに使用し、`checkout.confirm` を使用して確定します。HTML を使用する場合は、必ず `checkout = stripe.initCheckout({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` を使用し、`loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();` で確定します。 支払いフォームを作成するか、構築済みの決済ページを使用して、オンライン決済の受け付けを開始します。 # Stripe がオンラインで提供するページ > This is a Stripe がオンラインで提供するページ for when payment-ui is checkout and ui is stripe-hosted. View the full page at https://docs.stripe.com/payments/accept-a-payment?payment-ui=checkout&ui=stripe-hosted. [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) を使用して、Stripe がオンラインで提供する決済ページにリダイレクトします。この実装と、[Stripe の他の実装タイプとの比較](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)をご覧ください。 #### 実装作業 Complexity: 2/5 #### システム構築のタイプ Stripe がオンラインで提供する決済ページにリダイレクトする #### UI のカスタマイズ カスタマイズは限定的 - 20 種類の事前設定されたフォント - 3 種類の事前設定された角丸の半径 - カスタムの背景色と枠線の色 - カスタムロゴ [試してみる](https://checkout.stripe.dev/) まず、Stripe アカウントを[登録](https://dashboard.stripe.com/register)します。 アプリケーションから 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' ``` ## 顧客を Stripe Checkout にリダイレクトする [クライアント側] [サーバー側] ウェブサイトにサーバー側のエンドポイントを呼び出す決済ボタンを追加して [Checkout セッション](https://docs.stripe.com/api/checkout/sessions/create.md)を作成します。 [既存の顧客](https://docs.stripe.com/payments/existing-customers.md?platform=web&ui=stripe-hosted)の Checkout セッションを作成することもできます。これにより、Checkout フィールドに既知の連絡先情報を事前入力して、その顧客の購入履歴を統合することができます。 ```html Buy cool new product
``` Checkout セッションは、顧客が支払いフォームにリダイレクトされた際に表示される内容をプログラムで示したものです。以下のようなオプションを使用して設定できます。 - 請求する[ラインアイテム](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items) - 使用する通貨 `success_url`。お客様のウェブサイト上にあり、決済完了後に顧客が戻されるページの URL 値です。 > デフォルトでは、Checkout セッションは作成後 24 時間で期限切れとなります。 Checkout セッションを作成したら、レスポンスで返された [URL](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-url) に顧客をリダイレクトします。 #### Ruby ```ruby # This example sets up an endpoint using the Sinatra framework. require 'json' require 'sinatra' require 'stripe' # Don't put any keys in code. Use a secrets vault or environment # variable to supply keys to your integration. This example # shows how to set a secret key for illustration purposes only. # # See https://docs.stripe.com/keys-best-practices and find your # keys at https://dashboard.stripe.com/apikeys. Stripe.api_key = '<>' post '/create-checkout-session' dosession = Stripe::Checkout::Session.create({ line_items: [{ price_data: { currency: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 2000, }, quantity: 1, }], mode: 'payment', # These placeholder URLs will be replaced in a following step. success_url: 'https://example.com/success', }) redirect session.url, 303 end ``` ### 決済手段 デフォルトでは、カードとその他の一般的な決済手段が有効になっています。[Stripe ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で個々の決済手段をオンまたはオフにできます。Checkout では、Stripe は通貨と制限事項を評価して、対応している決済手段を顧客に動的に提示します。 決済手段が顧客にどのように表示されるか確認するには、ダッシュボードで取引 ID を入力するか、または注文金額と通貨を設定します。 [決済手段の設定](https://dashboard.stripe.com/settings/payment_methods)では Apple Pay と Google Pay を有効にすることができます。デフォルトでは、Apple Pay は有効で、Google Pay は無効になっています。ただし、有効になっていても Stripe が除外する場合があります。配送先住所を収集せずに[税金の自動計算を有効にした](https://docs.stripe.com/tax/checkout.md)場合、Google Pay は除外されます。 Checkout の Stripe 上のオンラインページでは、Apple Pay や Google Pay を有効にするために実装内容を変更する必要はありません。Stripe は、これらの決済を他のカード決済と同じように処理します。 ### エンドポイントを確認する ウェブサーバー (`localhost:4242` など) を起動し、次のコマンドを実行して、エンドポイントがアクセス可能であることを確認します。 ```bash curl -X POST -is "http://localhost:4242/create-checkout-session" -d "" ``` 端末に次のようなレスポンスが表示されます。 ```bash HTTP/1.1 303 See Other Location: https://checkout.stripe.com/c/pay/cs_test_... ... ``` ### テスト これで、顧客を Stripe Checkout にリダイレクトする決済ボタンが使用できるようになりました。 1. 決済ボタンをクリックします。 1. Stripe Checkout 支払いフォームにリダイレクトされます。 構築したシステムが機能しない場合: 1. ブラウザの開発者ツールでネットワークタブを開きます。 1. 決済ボタンをクリックし、サーバー側エンドポイント (`POST /create-checkout-session`) に XHR リクエストが送信されたことを確認します。 1. リクエストが 200 ステータスを返すことを確認します。 1. ボタンクリックリスナー内で `console.log(session)` を使用し、正しいデータが返されたことを確認します。 ## 成功ページを表示する [クライアント側] [サーバー側] 顧客が決済フォームを無事に送信したら、成功ページを表示することが重要です。この成功ページはお客様のサイトでホストします。 以下のように、最小限の成功ページを作成します。 ```html Thanks for your order!

Thanks for your order!

We appreciate your business! If you have any questions, please email orders@example.com.

``` 次に、この新しいページを使用するように Checkout セッション作成エンドポイントを更新します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=2000 \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ --data-urlencode success_url="http://localhost:4242/success.html" ``` > 成功ページのカスタマイズをご希望の場合、[成功ページをカスタマイズする](https://docs.stripe.com/payments/checkout/custom-success-page.md)を参照してください。 ### テストする 1. 決済ボタンをクリックします。 1. テストカード情報を使用して支払い情報を入力します。 - カード番号として `4242 4242 4242 4242` を入力します。 - カードの有効期限として任意の将来の日付を入力します。 - 任意の 3 桁のセキュリティーコードを入力します。 - 請求先の任意の郵便番号を入力します。 1. **支払う** をクリックします。 1. 新しい成功ページにリダイレクトされます。 次に、Stripe ダッシュボードで新しい支払いを探します。成功した支払いは、ダッシュボードの[支払いリスト](https://dashboard.stripe.com/payments)に表示されます。支払いをクリックすると、その支払いの詳細ページに移動します。**Checkout サマリー**セクションには、請求先情報と購入されたアイテムのリストが含まれ、これを使用して手動で注文のフルフィルメントを実行できます。 ## 支払い後のイベントを処理する 顧客が Checkout セッションの支払いを完了すると、Stripe は [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか、[Webhook ガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信して処理します。これにより、次のアクションがトリガーされます。 - 顧客に注文確認メールを送信します。 - 取引をデータベースに記録します。 - 配送ワークフローを開始します。 顧客がリダイレクトされ、ウェブサイトに戻るのを待たずに、これらのイベントはリッスンできます。Checkout のランディングページからのみフルフィルメントをトリガーする場合、確実性に欠けます。非同期型のイベントをリッスンするようシステムを設定すると、1 回の実装で[異なるタイプの決済手段](https://stripe.com/payments/payment-methods-guide)を受け付けられるようになります。 詳しくは、[Checkout のフルフィルメントガイド](https://docs.stripe.com/checkout/fulfillment.md)をご覧ください。 Checkout で支払いを回収する際には、以下のイベントを処理します。 | イベント | 説明 | アクション | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout セッションを正常に完了すると送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | ACH Direct Debt など、遅延型の決済手段による支払いが成功した場合に送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | ACH Direct Debt など、遅延型の決済手段による支払いが失敗した場合に送信されます。 | 顧客に失敗を通知して、顧客をオンセッションに戻し、支払いを再試行できるようにします。 | ## 導入をテストする Stripe がオンラインで提供する決済フォームの導入をテストするには、以下の手順を使用します。 1. Checkout セッションを作成します。 1. 次の表の方法を使用して、支払い詳細を入力します。 - カードの有効期限として任意の将来の日付を入力します。 - 任意の 3 桁のセキュリティコードを入力します。 - 請求先の任意の郵便番号を入力します。 1. **支払う**をクリックします。指定した `success_url` にリダイレクトされます。 1. ダッシュボードに移動し、[取引ページ](https://dashboard.stripe.com/test/payments?status%5B0%5D=successful)で支払いを探します。支払いが成功していると、そのリストに表示されます。 1. 支払いをクリックすると詳細が表示され、請求先情報と購入されたアイテムのリストが含まれた Checkout サマリーなどを確認できます。これを使用して注文のフルフィルメントを実行できます。 詳細は、[実装のテスト](https://docs.stripe.com/testing.md)をご覧ください。 #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (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)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### ウォレット | 決済手段 | シナリオ | テスト方法 | | ------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Alipay | 顧客はリダイレクトベースの[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。 | アカウント番号 `900123456` と BSB `000000` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 | | BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。 | アカウント番号 `111111113`と BSB `000000`を使用して、フォームに入力します。 | | Bancontact、EPS、iDEAL、Przelewy24 | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | #### 店舗支払い | 決済手段 | シナリオ | テスト方法 | | ----------- | ------------------------------------- | ------------------------------------------------------------- | | Boleto、OXXO | 顧客が Boleto または OXXO で取引の詳細を使用して支払います。 | 支払い方法として Boleto または OXXO を選択し、支払いを送信します。ダイアログが表示されたら、それを閉じます。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ### テストカード | 番号 | 説明 | | ------------------- | --------------------------------------- | | 4242 4242 4242 4242 | 支払いが成功し、すぐに処理されます。 | | 4000 0000 0000 3220 | 支払いの成功には 3D セキュア 2 認証が必要です。 | | 4000 0000 0000 9995 | 常に支払い拒否コード `insufficient_funds` で失敗します。 | ## Optional: 商品および価格を作成する Checkout Session を作成する前に、*商品* (Products represent what your business sells—whether that's a good or a service)と*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を事前に設定できます。商品を使用して複数の物理的商品やサービスのレベルを表し、*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を使用して各商品の料金体系を表します。[Checkout Session を設定](https://docs.stripe.com/payments/checkout/pay-what-you-want.md)して、チップや寄付を受け付けることや、Pay What You Want の商品やサービスを販売することができます。 たとえば、価格が 20 USD の T シャツ商品を作成できます。これにより、対象商品の詳細を変更せずに価格を更新したり追加したりできるようになります。商品と価格は、Stripe ダッシュボードまたは API で作成できます。[商品および価格の仕組み](https://docs.stripe.com/products-prices/how-products-and-prices-work.md)について、詳細をご確認ください。 #### API API で [Product (商品)](https://docs.stripe.com/api/products.md) を作成するのに必要なのは `name` のみです。指定した商品の `name`、`description`、および `images` が Checkout に表示されます。 ```curl curl https://api.stripe.com/v1/products \ -u "<>:" \ -d name=T-shirt ``` 次に、[Price (価格)](https://docs.stripe.com/api/prices.md) を作成して商品の価格を定義します。これには商品コストと使用通貨が含まれます。 ```curl curl https://api.stripe.com/v1/prices \ -u "<>:" \ -d product="{{PRODUCT_ID}}" \ -d unit_amount=2000 \ -d currency=usd ``` #### ダッシュボード > サンドボックスで作成した商品を本番環境にコピーすると、再作成する必要がありません。ダッシュボードの商品の詳細表示で、右上隅にある**本番環境にコピー**をクリックします。この操作は、サンドボックスで作成された各商品に対して 1 回のみ実行できます。テスト商品に対する以降の更新は、本番環境の商品には反映されません。 ダッシュボードのアカウント選択機能で**サンドボックス**をクリックして、サンドボックスで作業していることを確認します。次に、販売する商品を定義します。以下の手順に従って新しい商品と価格を作成してください。 - ダッシュボードで[商品](https://dashboard.stripe.com/test/products)セクションに移動します。 - **商品を追加**をクリックします。 - 価格を設定する際に**一括**を選択します。 指定した商品の名前、説明、画像が Checkout に表示されます。 作成された価格ごとに ID があります。Checkout Session を作成する際には、価格 ID と数量を参照します。複数の通貨で販売している場合、Price を *多通貨* (A single Price object can support multiple currencies. Each purchase uses one of the supported currencies for the Price, depending on how you use the Price in your integration) にします。Checkout は自動的に [顧客の現地通貨を特定し](https://docs.stripe.com/payments/checkout/localize-prices/manual-currency-prices.md)、Price が対応している場合にはその通貨を提示します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ --data-urlencode success_url="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 顧客データを事前入力する [サーバー側] すでに顧客のメールを収集していて、それを Checkout セッションで事前に入力するには、Checkout セッションの作成時に [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) を渡します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ --data-urlencode customer_email="customer@example.com" \ -d "line_items[0][price]"="{{PRICE_ID}}" \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ --data-urlencode success_url="https://example.com/success" ``` ## Optional: 支払い方法の詳細を保存する [サーバー側] デフォルトでは、Checkout で 1 回限りの支払いに使用した支払い方法を将来の支払いに使用することはできません。 ### 支払い方法を保存し、オフセッションでその支払い方法に請求する [payment_intent_data.setup_future_usage](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-setup_future_usage) 引数を渡すことで、1 回限りの支払いに使用した支払い方法を保存するように Checkout を設定できます。これは、キャンセル手数料やノーショー手数料などの将来の手数料に使用するために、登録済みの決済手段を取得しなければならない場合に便利です。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d customer_creation=always \ -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]"=2000 \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ --data-urlencode success_url="https://example.com/success.html" \ -d "payment_intent_data[setup_future_usage]"=off_session ``` If you use Checkout in `subscription` mode, Stripe automatically saves the payment method to charge it for subsequent payments. Card payment methods saved to customers using either `setup_future_usage` or `subscription` mode don’t appear for return purchases in Checkout (more on this below). We recommend using [custom text](https://docs.stripe.com/payments/checkout/custom-components.md#customize-text) to link out to any relevant terms regarding the usage of saved payment information. > 世界の個人情報保護法は複雑かつ曖昧です。[setup_future_usage](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-setup_future_usage) の実装は既存の個人情報の規制に関わる可能性があるため、事前に法務チームや個人情報担当チームに問い合わせることをお勧めします。支払いの詳細を保存することについては、[欧州データ保護委員会から発行されたガイダンス](https://edpb.europa.eu/system/files/2021-05/recommendations022021_on_storage_of_credit_card_data_en_1.pdf)をご覧ください。 ### 支払い方法を保存し、Checkout でその支払い方法を事前入力する デフォルトでは、Checkoutは [Link](https://docs.stripe.com/payments/link/checkout-link.md) を使用して、顧客に支払い情報を安全に保存して再利用するオプションを提供します。決済手段を自分で管理したい場合は、[saved_payment_method_options.payment_method_save](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_save) を Checkout Sessions の作成時に使用し、顧客に決済手段を保存していただき、Checkout で次回購入時に使用できるようにします。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d customer_creation=always \ -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]"=2000 \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ --data-urlencode success_url="https://example.com/success.html" \ -d "saved_payment_method_options[payment_method_save]"=enabled ``` このパラメーターを [payment](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-mode) モードまたは [subscription](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-mode) モードで渡すと、今後の購入に備えて顧客が支払い方法を明示的に保存できるようにするためのオプションのチェックボックスが表示されます。顧客がこのチェックボックスをオンにすると、Checkout は [allow_redisplay: always](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) を指定して支払い方法を保存します。Checkout はこのパラメーターを使用して、今後の購入で支払い方法を事前入力できるかどうかを判断します。`saved_payment_method_options.payment_method_save` を使用する場合、支払い方法を保存するために `setup_future_usage` を渡す必要はありません。 Connect プラットフォームが [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、Stripe の [ガイド](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご確認の上、コード内の `Customer` およびイベント参照を同等の Accounts v2 API リファレンスに置き換えてください。 [saved_payment_method_options.payment_method_save](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_save) を使用するには `Customer` が必要です。新しい顧客を保存するには、Checkout セッションの [customer_creation](https://docs.stripe.com/api/checkout/sessions/create.md) を `always` に設定します。それ以外の場合、セッションで顧客や決済手段は保存されません。 `payment_method_save` が渡されていない場合、または顧客が支払い方法の保存に同意しない場合でも、Checkout は、`subscription` モードで作成された支払い方法または `setup_future_usage` を使用して作成された支払い方法を保存します。これらの決済手段の `allow_redisplay` 値は `limited` であるため、購入の返品に備えてこれらの決済手段が事前入力されることがなくなり、カードネットワークの規則およびデータ保護規制に準拠できます。[これらのモードによって有効になるデフォルトの動作を変更する](https://support.stripe.com/questions/prefilling-saved-cards-in-checkout)方法と、`allow_redisplay` の動作を変更または上書きする方法をご紹介します。 > Checkout を使用してカードやその他の決済手段を保存してオフセッションに請求することはできますが、Checkout では保存したカードのみが事前入力されます。[保存したカード情報を事前入力する](https://support.stripe.com/questions/prefilling-saved-cards-in-checkout)方法をご紹介します。初回の支払いなしで決済手段を保存するには、[Checkout の設定モードを使用](https://docs.stripe.com/payments/save-and-reuse.md?platform=checkout)します。 ### 保存した決済手段を顧客が削除できるようにする 今後の支払いで再表示されないように、保存された決済手段を顧客が削除できるようにするには、Checkout セッションの作成時に [saved_payment_method_options.payment_method_remove](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_remove) を使用します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=2000 \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ --data-urlencode success_url="https://example.com/success.html" \ -d "saved_payment_method_options[payment_method_remove]"=enabled ``` 有効なサブスクリプションに関連付けられていて、請求書やサブスクリプションの支払い用にデフォルトの決済手段が保存されていない場合、顧客は決済手段を削除できません。 ## Optional: オーソリとキャプチャーを分離する [サーバー側] Stripe は 2 段階カード決済をサポートしているため、まずクレジットカードをオーソリし、後で売上をキャプチャーすることができます。Stripe が決済をオーソリすると、カード発行会社が売上を保証し、顧客のクレジットカードに決済金額を保留します。その後、売上をキャプチャーする一定の時間 ([カードに](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md#auth-capture-limitations)よって異なります) が設定されます。オーソリの期限が切れる前に決済をキャプチャーしない場合、決済はキャンセルされ、カード発行会社は保留されていた売上を解放します。 Separating authorization and capture is useful if you need to take additional actions between confirming that a customer is able to pay and collecting their payment. For example, if you’re selling stock-limited items, you might need to confirm that an item purchased by your customer using Checkout is still available before capturing their payment and fulfilling the purchase. Accomplish this using the following workflow: 1. Stripe が顧客の支払い方法を承認したことを確認します。 1. 在庫管理システムを調べ、アイテムがまだあることを確認します。 1. 在庫管理システムを更新し、アイテムが購入されたことを反映させます。 1. 顧客の支払いをキャプチャーします。 1. 購入が成功したかどうかを確認ページで顧客に通知します。 オーソリとキャプチャーを分離するには、Checkout セッションの作成時に、[payment_intent_data.capture_method](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-capture_method) の値を `manual` に設定します。これにより、Stripe に対して顧客のカードで金額のオーソリのみを行うよう指示します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ -d "payment_intent_data[capture_method]"=manual \ --data-urlencode success_url="https://example.com/success.html" ``` キャプチャーされていない支払いをキャプチャーするには、[ダッシュボード](https://dashboard.stripe.com/test/payments?status%5B%5D=uncaptured)または[キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)エンドポイントを使用します。プログラムによる支払いのキャプチャーには、Checkout セッションの際に作成される PaymentIntent へのアクセスが必要です。これは [Session (セッション)](https://docs.stripe.com/api/payment_intents/capture.md) オブジェクトから取得できます。 ## Optional: 顧客のアカウントの管理 [コーディング不要] *カスタマーポータル* (The customer portal is a secure, Stripe-hosted page that lets your customers manage their subscriptions and billing details)へのリンクを共有して、顧客が自身のアカウントを[管理](https://docs.stripe.com/customer-management.md)できるようにします。カスタマーポータルでは、顧客はメールアドレスでログインして、サブスクリプションの管理や決済手段の更新などを行うことができます。 ## See also - [割引を追加する](https://docs.stripe.com/payments/checkout/discounts.md) - [税金を徴収する](https://docs.stripe.com/payments/checkout/taxes.md) - [納税者番号を収集する](https://docs.stripe.com/tax/checkout/tax-ids.md) - [配送先住所を追加する](https://docs.stripe.com/payments/collect-addresses.md?payment-ui=checkout) - [ブランディングをカスタマイズする](https://docs.stripe.com/payments/checkout/customization.md) # オンラインフォーム > This is a オンラインフォーム for when payment-ui is checkout and ui is embedded-form. View the full page at https://docs.stripe.com/payments/accept-a-payment?payment-ui=checkout&ui=embedded-form. [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) を使用して、事前構築した決済フォームをサイトに埋め込みます。この実装と、[Stripe の他の実装タイプとの比較](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)をご覧ください。 #### 実装作業 Complexity: 2/5 #### システム構築のタイプ サイトに構築済みの決済フォームを埋め込む #### UI のカスタマイズ カスタマイズは限定的 - 20 種類の事前設定されたフォント - 3 種類の事前設定された角丸の半径 - カスタムの背景色と枠線の色 - カスタムロゴ Stripe ダッシュボードの[ブランディング設定](https://dashboard.stripe.com/settings/branding/checkout)を使用して、Checkout を自社サイトのデザインに合わせることができます。 まず、Stripe アカウントを[登録](https://dashboard.stripe.com/register)します。 アプリケーションから 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' ``` ## Checkout セッションを作成する [サーバー側] From your server, create a *Checkout Session* (A Checkout Session represents your customer's session as they pay for one-time purchases or subscriptions through Checkout. After a successful payment, the Checkout Session contains a reference to the Customer, and either the successful PaymentIntent or an active Subscription) and set the [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) to `embedded`. You can configure the [Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md) with [line items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items) to include and options such as [currency](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-currency). [既存の顧客](https://docs.stripe.com/payments/existing-customers.md?platform=web&ui=stripe-hosted)の Checkout セッションを作成することもできます。これにより、Checkout フィールドに既知の連絡先情報を事前入力して、その顧客の購入履歴を統合することができます。 自社サイトでホストされているカスタムページに顧客を戻すには、そのページの URL を [return_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-return_url) パラメーターに指定します。URL にテンプレート変数 `{CHECKOUT_SESSION_ID}` を含めて、戻り先ページでセッションのステータスを取得します。Checkout では、リダイレクト前にこの変数が Checkout セッション ID に自動的に置き換えられます。 [戻り先ページの設定](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=embedded-form#return-page)と、[リダイレクト動作をカスタマイズ](https://docs.stripe.com/payments/checkout/custom-success-page.md?payment-ui=embedded-form)するためのその他のオプションについて、詳細をご覧ください。 Checkout セッションの作成後、レスポンスで返される `client_secret` を使用して、[Checkout をマウント](https://docs.stripe.com/payments/accept-a-payment.md#mount-checkout)します。 #### Ruby ```ruby # This example sets up an endpoint using the Sinatra framework. require 'json' require 'sinatra' require 'stripe' # Don't put any keys in code. Use a secrets vault or environment # variable to supply keys to your integration. This example # shows how to set a secret key for illustration purposes only. # # See https://docs.stripe.com/keys-best-practices and find your # keys at https://dashboard.stripe.com/apikeys. Stripe.api_key = '<>' post '/create-checkout-session' do session = Stripe::Checkout::Session.create({ line_items: [{ price_data: { currency: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 2000, }, quantity: 1, }], mode: 'payment',ui_mode: 'embedded',return_url: 'https://example.com/checkout/return?session_id={CHECKOUT_SESSION_ID}' }) {clientSecret: session.client_secret}.to_json end ``` ## Checkout をマウントする [クライアント側] #### HTML + JS Checkout は [Stripe.js](https://docs.stripe.com/js.md) の一部として利用できます。HTML ファイルのヘッダーに Stripe.js スクリプトを追加してページに含めます。次に、マウンティングに使用する空の DOM ノード (コンテナー) を作成します。 ```html
``` 公開可能な API キーで Stripe.js を初期化します。 Checkout セッションの作成、および client secret の取得をサーバーにリクエストする、非同期の `fetchClientSecret` 関数を作成します。 Checkout インスタンスを作成する際に、この関数を `options` に渡します。 ```javascript // Initialize Stripe.js const stripe = Stripe('<>'); initialize(); // Fetch Checkout Session and retrieve the client secret async function initialize() { const fetchClientSecret = async () => { const response = await fetch("/create-checkout-session", { method: "POST", }); const { clientSecret } = await response.json(); return clientSecret; }; // Initialize Checkout const checkout = await stripe.initEmbeddedCheckout({ fetchClientSecret, }); // Mount Checkout checkout.mount('#checkout'); } ``` #### React npm から [react-stripe-js](https://docs.stripe.com/sdks/stripejs-react.md) と Stripe.js ローダーをインストールします。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` 埋め込みの Checkout コンポーネントを使用するには、`EmbeddedCheckoutProvider` を作成します。公開可能 API キーを使用して `loadStripe` を呼び出し、返された `Promise` をプロバイダーに渡します。 Checkout セッションの作成、および client secret の取得をサーバーにリクエストする、非同期の `fetchClientSecret` 関数を作成します。この関数をプロバイダーで受け入れられる `options` プロパティに渡します。 ```jsx import * as React from 'react'; import {loadStripe} from '@stripe/stripe-js'; import { EmbeddedCheckoutProvider, EmbeddedCheckout } from '@stripe/react-stripe-js'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('pk_test_123'); const App = () => { const fetchClientSecret = useCallback(() => { // Create a Checkout Session return fetch("/create-checkout-session", { method: "POST", }) .then((res) => res.json()) .then((data) => data.clientSecret); }, []); const options = {fetchClientSecret}; return (
) } ``` Checkout は、HTTPS 接続を介して支払い情報をStripeに安全に送信する iframe でレンダリングされます。 > 一部の支払い方法では、別のページにリダイレクトして支払いを確定する必要があるため、Checkout は別の iframe 内に配置しないでください。 ### デザインをカスタマイズする アカウントの[ブランディング設定](https://dashboard.stripe.com/settings/branding)で、背景色、ボタンの色、枠線の角丸半径、フォントを設定して、サイトのデザインに合わせて Checkout をカスタマイズします。 デフォルトでは、Checkout は外側に余白やマージンが追加されずに表示されます。必要なマージンを適用するには (四方すべてに 16px など)、目的の余白を適用するコンテナー要素 (div など) を使用することをお勧めします。 ## 戻り先ページを表示する 顧客が支払いを試行すると、Stripe はサイトがホストしている戻りページに顧客をリダイレクトします。Checkout セッションを作成したときに、[return_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-return_url) パラメーターで戻りページの URL は指定されています。[リダイレクト動作をカスタマイズする](https://docs.stripe.com/payments/checkout/custom-success-page.md?payment-ui=embedded-form)ためのオプションについては、こちらの記事をご覧ください。 戻り先ページを表示する際は、URL の Checkout セッション ID を使用して Checkout セッションのステータスを取得します。以下のように、セッションのステータスに応じて結果を処理します。 - `complete`: 支払いが成功しました。Checkout セッションの情報を使用して成功ページを表示します。 - `open`: 支払いが失敗またはキャンセルされました。顧客がやり直せるように Checkout を再度マウントします。 #### Ruby ```ruby get '/session-status' do session = Stripe::Checkout::Session.retrieve(params[:session_id]) {status: session.status, customer_email: session.customer_details.email}.to_json end ``` ```javascript const session = await fetch(`/session_status?session_id=${session_id}`) if (session.status == 'open') { // Remount embedded Checkout } else if (session.status == 'complete') { // Show success page // Optionally use session.payment_status or session.customer_email // to customize the success page } ``` #### リダイレクトベースの支払い方法 決済の進行中、支払い方法によっては、発行会社/銀行のオーソリページなどの中間ページに顧客がリダイレクトされる場合があります。そのページでの操作を完了した顧客は、Stripe によって戻り先ページにリダイレクトされます。 [リダイレクトベースの決済手段とリダイレクト動作](https://docs.stripe.com/payments/checkout/custom-success-page.md?payment-ui=embedded-form#redirect-based-payment-methods)についてご紹介します。 ## 支払い後のイベントを処理する 顧客が Checkout セッションの支払いを完了すると、Stripe は [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか、[Webhook ガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信して処理します。これにより、次のアクションがトリガーされます。 - 顧客に注文確認メールを送信します。 - 取引をデータベースに記録します。 - 配送ワークフローを開始します。 顧客がリダイレクトされ、ウェブサイトに戻るのを待たずに、これらのイベントはリッスンできます。Checkout のランディングページからのみフルフィルメントをトリガーする場合、確実性に欠けます。非同期型のイベントをリッスンするようシステムを設定すると、1 回の実装で[異なるタイプの決済手段](https://stripe.com/payments/payment-methods-guide)を受け付けられるようになります。 詳しくは、[Checkout のフルフィルメントガイド](https://docs.stripe.com/checkout/fulfillment.md)をご覧ください。 Checkout で支払いを回収する際には、以下のイベントを処理します。 | イベント | 説明 | アクション | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout セッションを正常に完了すると送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | ACH Direct Debt など、遅延型の決済手段による支払いが成功した場合に送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | ACH Direct Debt など、遅延型の決済手段による支払いが失敗した場合に送信されます。 | 顧客に失敗を通知して、顧客をオンセッションに戻し、支払いを再試行できるようにします。 | ## 導入をテストする 埋め込みの決済フォームの導入をテストする方法は以下のとおりです。 1. 埋め込み型の Checkout セッションを作成し、決済フォームを自社のページに搭載します。 1. 以下の表に記載の方法を使用して、決済の詳細を入力します。 - カードの有効期限として任意の将来の日付を入力します。 - 任意の 3 桁のセキュリティコード (CVC) を入力します。 - 請求先の任意の郵便番号を入力します。 1. **支払う** をクリックします。`return_url` にリダイレクトされます。 1. ダッシュボードに移動して、[取引ページ](https://dashboard.stripe.com/test/payments?status%5B0%5D=successful)で支払いを探します。支払いが成功すると、そのリストに表示されます。 1. 支払いをクリックすると詳細が表示され、請求先情報と購入されたアイテムのリストが含まれた Checkout サマリーなどを確認できます。これを使用して注文の処理を実行できます。 詳しくは[導入のテスト](https://docs.stripe.com/testing.md)をご覧ください。 #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (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)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### ウォレット | 決済手段 | シナリオ | テスト方法 | | ------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Alipay | 顧客はリダイレクトベースの[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。 | アカウント番号 `900123456` と BSB `000000` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 | | BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。 | アカウント番号 `111111113`と BSB `000000`を使用して、フォームに入力します。 | | Bancontact、EPS、iDEAL、Przelewy24 | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | #### 店舗支払い | 決済手段 | シナリオ | テスト方法 | | ----------- | ------------------------------------- | ------------------------------------------------------------- | | Boleto、OXXO | 顧客が Boleto または OXXO で取引の詳細を使用して支払います。 | 支払い方法として Boleto または OXXO を選択し、支払いを送信します。ダイアログが表示されたら、それを閉じます。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: 支払い方法をさらに追加する Checkout は、デフォルトで[多数の支払い方法に対応](https://docs.stripe.com/payments/payment-methods/integration-options.md#choose-how-to-add-payment-methods)しています。Apple Pay、Google Pay、後払いなどの支払い方法を有効にして表示するには、追加のステップを実行する必要があります。 ### Apple Pay および Google Pay Apple Pay および Google Pay から決済を受け付けるには、次を行う必要があります。 - [支払い方法設定](https://dashboard.stripe.com/settings/payment_methods)でこれらを有効にします。Apple Payはデフォルトで有効になっています。 - 開発環境と本番環境で HTTPS を介してアプリケーションを提供します。 - [ドメインを登録](https://docs.stripe.com/payments/payment-methods/pmd-registration.md)します。 - 開発環境と本番環境でアプリケーションを HTTPS 経由で提供します。[ngrok](https://ngrok.com/) などのサービスを利用して、ローカルテスト用のアプリケーションを提供できます。 さらに、Checkout セッションでは、以下の条件が「すべて」満たされている場合にのみ Apple Pay ボタンが表示されます。 - 顧客のデバイスが macOS バージョン 17 以降または iOS バージョン 17 以降を実行している。 - 顧客が Safari ブラウザを使用している。 - 顧客が、Apple Pay に有効なカードを登録している。 Checkout セッションでは、以下の条件が「すべて」満たされている場合のみ Google Pay ボタンが表示されます。 - 顧客のデバイスが Chrome 61 以降を実行している。 - 顧客が、Google Pay に有効なカードを登録している。 > #### 各地域でのテスト > > Stripe Checkout は、インドの Stripe アカウントと顧客に対して Apple Pay と Google Pay をサポートしていません。ご自身の IP アドレスがインドにある場合は、Stripe アカウントがインド国外に所在していても、Apple Pay または Google Pay の実装内容をテストできません。 ## Optional: 商品および価格を作成する Checkout Session を作成する前に、*商品* (Products represent what your business sells—whether that's a good or a service)と*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を事前に設定できます。商品を使用して複数の物理的商品やサービスのレベルを表し、*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を使用して各商品の料金体系を表します。[Checkout Session を設定](https://docs.stripe.com/payments/checkout/pay-what-you-want.md)して、チップや寄付を受け付けることや、Pay What You Want の商品やサービスを販売することができます。 たとえば、価格が 20 USD の T シャツ商品を作成できます。これにより、対象商品の詳細を変更せずに価格を更新したり追加したりできるようになります。商品と価格は、Stripe ダッシュボードまたは API で作成できます。[商品および価格の仕組み](https://docs.stripe.com/products-prices/how-products-and-prices-work.md)について、詳細をご確認ください。 #### API API で [Product (商品)](https://docs.stripe.com/api/products.md) を作成するのに必要なのは `name` のみです。指定した商品の `name`、`description`、および `images` が Checkout に表示されます。 ```curl curl https://api.stripe.com/v1/products \ -u "<>:" \ -d name=T-shirt ``` 次に、[Price (価格)](https://docs.stripe.com/api/prices.md) を作成して商品の価格を定義します。これには商品コストと使用通貨が含まれます。 ```curl curl https://api.stripe.com/v1/prices \ -u "<>:" \ -d product="{{PRODUCT_ID}}" \ -d unit_amount=2000 \ -d currency=usd ``` #### ダッシュボード > サンドボックスで作成した商品を本番環境にコピーすると、再作成する必要がありません。ダッシュボードの商品の詳細表示で、右上隅にある**本番環境にコピー**をクリックします。この操作は、サンドボックスで作成された各商品に対して 1 回のみ実行できます。テスト商品に対する以降の更新は、本番環境の商品には反映されません。 ダッシュボードのアカウント選択機能で**サンドボックス**をクリックして、サンドボックスで作業していることを確認します。次に、販売する商品を定義します。以下の手順に従って新しい商品と価格を作成してください。 - ダッシュボードで[商品](https://dashboard.stripe.com/test/products)セクションに移動します。 - **商品を追加**をクリックします。 - 価格を設定する際に**一括**を選択します。 指定した商品の名前、説明、画像が Checkout に表示されます。 作成された価格ごとに ID があります。Checkout Session を作成する際には、価格 ID と数量を参照します。複数の通貨で販売している場合、Price を *多通貨* (A single Price object can support multiple currencies. Each purchase uses one of the supported currencies for the Price, depending on how you use the Price in your integration) にします。Checkout は自動的に [顧客の現地通貨を特定し](https://docs.stripe.com/payments/checkout/localize-prices/manual-currency-prices.md)、Price が対応している場合にはその通貨を提示します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ -d ui_mode=embedded \ --data-urlencode return_url="https://example.com/return" ``` ## Optional: 顧客データを事前入力する [サーバー側] すでに顧客のメールを収集していて、それを Checkout セッションで事前に入力するには、Checkout セッションの作成時に [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) を渡します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ --data-urlencode customer_email="customer@example.com" \ -d "line_items[0][price]"="{{PRICE_ID}}" \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ -d ui_mode=embedded \ --data-urlencode return_url="https://example.com/return" ``` ## Optional: 支払い方法の詳細を保存する [サーバー側] デフォルトでは、Checkout で 1 回限りの支払いに使用した支払い方法を将来の支払いに使用することはできません。 ### 支払い方法を保存し、オフセッションでその支払い方法に請求する [payment_intent_data.setup_future_usage](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-setup_future_usage) 引数を渡すことで、1 回限りの支払いに使用した支払い方法を保存するように Checkout を設定できます。これは、キャンセル手数料やノーショー手数料などの将来の手数料に使用するために、登録済みの決済手段を取得しなければならない場合に便利です。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d customer_creation=always \ -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]"=2000 \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ -d ui_mode=embedded \ --data-urlencode return_url="https://example.com/return" \ -d "payment_intent_data[setup_future_usage]"=off_session ``` If you use Checkout in `subscription` mode, Stripe automatically saves the payment method to charge it for subsequent payments. Card payment methods saved to customers using either `setup_future_usage` or `subscription` mode don’t appear for return purchases in Checkout (more on this below). We recommend using [custom text](https://docs.stripe.com/payments/checkout/custom-components.md#customize-text) to link out to any relevant terms regarding the usage of saved payment information. > 世界の個人情報保護法は複雑かつ曖昧です。[setup_future_usage](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-setup_future_usage) の実装は既存の個人情報の規制に関わる可能性があるため、事前に法務チームや個人情報担当チームに問い合わせることをお勧めします。支払いの詳細を保存することについては、[欧州データ保護委員会から発行されたガイダンス](https://edpb.europa.eu/system/files/2021-05/recommendations022021_on_storage_of_credit_card_data_en_1.pdf)をご覧ください。 ### 支払い方法を保存し、Checkout でその支払い方法を事前入力する デフォルトでは、Checkoutは [Link](https://docs.stripe.com/payments/link/checkout-link.md) を使用して、顧客に支払い情報を安全に保存して再利用するオプションを提供します。決済手段を自分で管理したい場合は、[saved_payment_method_options.payment_method_save](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_save) を Checkout Sessions の作成時に使用し、顧客に決済手段を保存していただき、Checkout で次回購入時に使用できるようにします。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d customer_creation=always \ -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]"=2000 \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ -d ui_mode=embedded \ --data-urlencode return_url="https://example.com/return" \ -d "saved_payment_method_options[payment_method_save]"=enabled ``` このパラメーターを [payment](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-mode) モードまたは [subscription](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-mode) モードで渡すと、今後の購入に備えて顧客が支払い方法を明示的に保存できるようにするためのオプションのチェックボックスが表示されます。顧客がこのチェックボックスをオンにすると、Checkout は [allow_redisplay: always](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) を指定して支払い方法を保存します。Checkout はこのパラメーターを使用して、今後の購入で支払い方法を事前入力できるかどうかを判断します。`saved_payment_method_options.payment_method_save` を使用する場合、支払い方法を保存するために `setup_future_usage` を渡す必要はありません。 Connect プラットフォームが [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、Stripe の [ガイド](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご確認の上、コード内の `Customer` およびイベント参照を同等の Accounts v2 API リファレンスに置き換えてください。 [saved_payment_method_options.payment_method_save](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_save) を使用するには `Customer` が必要です。新しい顧客を保存するには、Checkout セッションの [customer_creation](https://docs.stripe.com/api/checkout/sessions/create.md) を `always` に設定します。それ以外の場合、セッションで顧客や決済手段は保存されません。 `payment_method_save` が渡されていない場合、または顧客が支払い方法の保存に同意しない場合でも、Checkout は、`subscription` モードで作成された支払い方法または `setup_future_usage` を使用して作成された支払い方法を保存します。これらの決済手段の `allow_redisplay` 値は `limited` であるため、購入の返品に備えてこれらの決済手段が事前入力されることがなくなり、カードネットワークの規則およびデータ保護規制に準拠できます。[これらのモードによって有効になるデフォルトの動作を変更する](https://support.stripe.com/questions/prefilling-saved-cards-in-checkout)方法と、`allow_redisplay` の動作を変更または上書きする方法をご紹介します。 > Checkout を使用してカードやその他の決済手段を保存してオフセッションに請求することはできますが、Checkout では保存したカードのみが事前入力されます。[保存したカード情報を事前入力する](https://support.stripe.com/questions/prefilling-saved-cards-in-checkout)方法をご紹介します。初回の支払いなしで決済手段を保存するには、[Checkout の設定モードを使用](https://docs.stripe.com/payments/save-and-reuse.md?platform=checkout)します。 ### 保存した決済手段を顧客が削除できるようにする 今後の支払いで再表示されないように、保存された決済手段を顧客が削除できるようにするには、Checkout セッションの作成時に [saved_payment_method_options.payment_method_remove](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_remove) を使用します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=2000 \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ -d ui_mode=embedded \ --data-urlencode return_url="https://example.com/return" \ -d "saved_payment_method_options[payment_method_remove]"=enabled ``` 有効なサブスクリプションに関連付けられていて、請求書やサブスクリプションの支払い用にデフォルトの決済手段が保存されていない場合、顧客は決済手段を削除できません。 ## Optional: 顧客のアカウントの管理 [コーディング不要] *カスタマーポータル* (The customer portal is a secure, Stripe-hosted page that lets your customers manage their subscriptions and billing details)へのリンクを共有して、顧客が自身のアカウントを[管理](https://docs.stripe.com/customer-management.md)できるようにします。カスタマーポータルでは、顧客はメールアドレスでログインして、サブスクリプションの管理や決済手段の更新などを行うことができます。 ## Optional: オーソリとキャプチャーを分離する [サーバー側] Stripe は 2 段階カード決済をサポートしているため、まずクレジットカードをオーソリし、後で売上をキャプチャーすることができます。Stripe が決済をオーソリすると、カード発行会社が売上を保証し、顧客のクレジットカードに決済金額を保留します。その後、売上をキャプチャーする一定の時間 ([カードに](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md#auth-capture-limitations)よって異なります) が設定されます。オーソリの期限が切れる前に決済をキャプチャーしない場合、決済はキャンセルされ、カード発行会社は保留されていた売上を解放します。 Separating authorization and capture is useful if you need to take additional actions between confirming that a customer is able to pay and collecting their payment. For example, if you’re selling stock-limited items, you might need to confirm that an item purchased by your customer using Checkout is still available before capturing their payment and fulfilling the purchase. Accomplish this using the following workflow: 1. Stripe が顧客の支払い方法を承認したことを確認します。 1. 在庫管理システムを調べ、アイテムがまだあることを確認します。 1. 在庫管理システムを更新し、アイテムが購入されたことを反映させます。 1. 顧客の支払いをキャプチャーします。 1. 購入が成功したかどうかを確認ページで顧客に通知します。 オーソリとキャプチャーを分離するには、Checkout セッションの作成時に、[payment_intent_data.capture_method](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-capture_method) の値を `manual` に設定します。これにより、Stripe に対して顧客のカードで金額のオーソリのみを行うよう指示します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ -d "payment_intent_data[capture_method]"=manual \ -d ui_mode=embedded \ --data-urlencode return_url="https://example.com/return" ``` キャプチャーされていない支払いをキャプチャーするには、[ダッシュボード](https://dashboard.stripe.com/test/payments?status%5B%5D=uncaptured)または[キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)エンドポイントを使用します。プログラムによる支払いのキャプチャーには、Checkout セッションの際に作成される PaymentIntent へのアクセスが必要です。これは [Session (セッション)](https://docs.stripe.com/api/payment_intents/capture.md) オブジェクトから取得できます。 ## Optional: 注文のフルフィルメント 顧客が支払いを行ったときに[プログラムで通知を受け取る](https://docs.stripe.com/checkout/fulfillment.md)方法をご紹介します。 ## See also - [割引を追加する](https://docs.stripe.com/payments/checkout/discounts.md) - [税金を徴収する](https://docs.stripe.com/payments/checkout/taxes.md) - [納税者番号を収集する](https://docs.stripe.com/tax/checkout/tax-ids.md) - [配送先住所を追加する](https://docs.stripe.com/payments/collect-addresses.md?payment-ui=checkout) - [ブランディングをカスタマイズする](https://docs.stripe.com/payments/checkout/customization.md) # Checkout Sessions API > This is a Checkout Sessions API for when payment-ui is elements and api-integration is checkout. View the full page at https://docs.stripe.com/payments/accept-a-payment?payment-ui=elements&api-integration=checkout. カスタマイズされた決済用フォームを構築するには [Stripe Elements](https://docs.stripe.com/payments/elements.md) と [Checkout Sessions API](https://docs.stripe.com/api/checkout/sessions.md) を使用します。この連携機能を Stripe の他の連携機能タイプと比較する方法については、[こちら](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)をご覧ください。 Checkout Sessions API は、税金の計算、割引、配送情報、通貨換算などの組み込みサポートを提供し、書く必要があるカスタムコードの量を減らします。これはほとんどの組み込みで推奨されるアプローチです。PaymentIntents ではなく Checkout Sessions を使用できる場合について、詳しくは[こちら](https://docs.stripe.com/payments/checkout-sessions-and-payment-intents-comparison.md)をご覧ください。 クライアント側およびサーバー側のコードで決済フォームを構築すると、多様な決済手段を受け付けられます。 #### 組み込み作業 Complexity: 3/5 #### 組み込みのタイプ カスタムの決済フローに UI コンポーネントを統合する #### UI のカスタマイズ [Appearance API](https://docs.stripe.com/elements/appearance-api.md) を使用した CSS レベルのカスタマイズ ## サーバを設定する [サーバー側] はじめに、Stripe アカウントを[登録](https://dashboard.stripe.com/register)する必要があります。 アプリケーションから 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' ``` ## Checkout セッションを作成する [サーバー側] [Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md) を作成し、その [`client_secret`](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) をフロントエンドに返すエンドポイントをサーバーに追加します。Checkout Sessions は、顧客が 1 回限りの購入またはサブスクリプションの決済を行う際のセッションを表します。Checkout Sessions は作成後 24 時間で期限切れになります。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d ui_mode=custom \ -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]"=2000 \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ --data-urlencode return_url="https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ``` ## フロントエンドを設定する [クライアント側] #### HTML + JS Stripe.js スクリプトをチェックアウトページに含めるには、このスクリプトを HTML ファイルの `head` に追加します。常に js.stripe.com から Stripe.js を直接読み込むことにより、PCI への準拠が維持されます。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 Stripe.js の最新バージョンを使用していることを確認してください。[Stripe.js のバージョン管理](https://docs.stripe.com/sdks/stripejs-versioning.md)の詳細をご確認ください。 ```html Checkout ``` > Stripe は、Stripe.js をモジュールとして読み込むために使用できる npm パッケージを提供しています。[GitHub のプロジェクト](https://github.com/stripe/stripe-js)をご覧ください。バージョン [7.0.0](https://www.npmjs.com/package/%40stripe/stripe-js/v/7.0.0) 以降が必要です。 stripe.js を初期化します。 ```js // 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( '<>', ); ``` #### React npm のパブリックレジストリーから [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) と [Stripe.js ローダー](https://www.npmjs.com/package/@stripe/stripe-js)をインストールします。少なくとも、バージョン 5.0.0 以上の React Stripe.js と、バージョン 8.0.0 以上の Stripe.js ローダーが必要になります。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` 公開可能キーを使用して、フロントエンドの `stripe` インスタンスを初期化します。 ```javascript import {loadStripe} from '@stripe/stripe-js'; const stripe = loadStripe("<>"); ``` ## Checkout を初期化する [クライアント側] #### HTML + JS `clientSecret` を渡して [initCheckout](https://docs.stripe.com/js/custom_checkout/init) を呼び出します。 `initCheckout` は、Checkout Session のデータとそれを更新するメソッドを含む [Checkout](https://docs.stripe.com/js/custom_checkout) オブジェクトを返します。 [actions.getSession()](https://docs.stripe.com/js/custom_checkout/session) から `total` と `lineItems` を読み取り、UI に表示します。これにより、コードの変更を最小限に抑えて新機能を有効にできます。たとえば、[手動通貨価格](https://docs.stripe.com/payments/custom/localize-prices/manual-currency-prices.md)を追加する場合、`total` を表示すれば UI を変更する必要はありません。 ```html
``` ```javascript const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret); const checkout = stripe.initCheckout({clientSecret}); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const session = loadActionsResult.actions.getSession(); const checkoutContainer = document.getElementById('checkout-container'); checkoutContainer.append(JSON.stringify(session.lineItems, null, 2)); checkoutContainer.append(document.createElement('br')); checkoutContainer.append(`Total: ${session.total.total.amount}`); } ``` #### React [CheckoutProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider) コンポーネントでアプリケーションをラップし、`clientSecret` と `stripe` インスタンスを渡します。 ```jsx import React from 'react'; import {CheckoutProvider} from '@stripe/react-stripe-js/checkout'; import CheckoutForm from './CheckoutForm'; const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret); const App = () => { return ( ); }; export default App; ``` `useCheckout()` フックを使用して、CheckoutForm コンポーネントの [Checkout](https://docs.stripe.com/js/custom_checkout) オブジェクトにアクセスします。`Checkout` オブジェクトには、決済セッションからのデータと、それを更新するメソッドが含まれます。 `Checkout` オブジェクトから `lineItems` と `lineItems` を読み取り、UI に表示します。これにより、コードの変更を最小限に抑えて機能を有効にできます。たとえば、[手動通貨価格](https://docs.stripe.com/payments/custom/localize-prices/manual-currency-prices.md)を追加する場合、`total` を表示すると UI を変更する必要はありません。 ```jsx import React from 'react'; import {useCheckout} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => {const checkoutState = useCheckout(); if (checkoutState.type === 'loading') { return (
Loading...
); } if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } return (
{JSON.stringify(checkoutState.checkout.lineItems, null, 2)} {/* A formatted total amount */} Total: {checkoutState.checkout.total.total.amount}
); }; ``` ## 顧客のメールアドレスを収集する [クライアント側] #### HTML + JS Checkout Session を完了するには、有効な顧客のメールアドレスを指定する必要があります。 これらの手順では、メールアドレス入力欄を作成し、`Checkout` オブジェクトの [updateEmail](https://docs.stripe.com/js/custom_checkout/update_email) を使用します。 または、以下を実行してください。 - Checkout Session の作成時に [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) または [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) を渡します。Stripe はこの方法で指定されたメールアドレスを検証します。 - [checkout.confirm](https://docs.stripe.com/js/custom_checkout/confirm) で既に検証済みのメールアドレスを渡します。 ```html
``` ```javascript const checkout = stripe.initCheckout({clientSecret}); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const {actions} = loadActionsResult; const emailInput = document.getElementById('email'); const emailErrors = document.getElementById('email-errors'); emailInput.addEventListener('input', () => { // Clear any validation errors emailErrors.textContent = ''; }); emailInput.addEventListener('blur', () => { const newEmail = emailInput.value;actions.updateEmail(newEmail).then((result) => { if (result.error) { emailErrors.textContent = result.error.message; } }); }); } ``` #### React Checkout Session を完了するには、有効な顧客のメールアドレスを指定する必要があります。 これらの手順では、メールアドレス入力欄を作成し、`Checkout` オブジェクトの [updateEmail](https://docs.stripe.com/js/react_stripe_js/checkout/update_email) を使用します。 または、以下を実行してください。 - Checkout Session の作成時に [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) または [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) を渡します。Stripe はこの方法で指定されたメールアドレスを検証します。 - [confirm](https://docs.stripe.com/js/react_stripe_js/checkout/confirm) で既に検証済みのメールアドレスを渡します。 ```jsx import React from 'react'; import {useCheckout} from '@stripe/react-stripe-js/checkout'; const EmailInput = () => { const checkoutState = useCheckout(); const [email, setEmail] = React.useState(''); const [error, setError] = React.useState(null); if (checkoutState.type === 'loading') { return (
Loading...
); } else if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } const handleBlur = () => {checkoutState.checkout.updateEmail(email).then((result) => { if (result.type === 'error') { setError(result.error); } }) }; const handleChange = (e) => { setError(null); setEmail(e.target.value); }; return (
{error &&
{error.message}
}
); }; export default EmailInput; ``` ## 支払い情報を収集する [クライアント側] [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用して、クライアントで支払い情報を収集します。Payment Element は、さまざまな決済手段で支払い情報の収集を簡略化する事前構築済みの UI コンポーネントです。 Payment Element には、HTTPS 接続を介して支払い情報を Stripe に安全に送信する iframe が含まれています。一部の支払い方法では、支払いを確定するために別のページにリダイレクトする必要があるため、Payment Element を別の iframe 内に配置しないでください。 iframe を使用して Apple Pay または Google Pay を受け付けたい場合は、iframe の [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) 属性を `"payment *"` と等しく設定する必要があります。 構築済みのシステムを機能させるには、決済ページのアドレスの先頭を `http://` ではなく `https://` にする必要があります。HTTPS を使用しなくてもシステムをテストできますが、本番環境で決済を受け付ける準備が整ったら、必ず、HTTPS を[有効](https://docs.stripe.com/security/guide.md#tls)にしてください。 #### HTML + JS まず、コンテナーの DOM 要素を作成して、[Payment Element](https://docs.stripe.com/payments/payment-element.md) をマウントします。次に、[checkout.createPaymentElement](https://docs.stripe.com/js/custom_checkout/create_payment_element) を使用して `Payment Element` のインスタンスを作成し、[element.mount](https://docs.stripe.com/js/element/mount) を呼び出してマウントし、CSS セレクターまたはコンテナーの DOM 要素を指定します。 ```html
``` ```javascript const paymentElement = checkout.createPaymentElement(); paymentElement.mount('#payment-element'); ``` 対応しているオプションについては、[Stripe.js のドキュメント](https://docs.stripe.com/js/custom_checkout/create_payment_element#custom_checkout_create_payment_element-options) をご覧ください。 フロントエンドで Checkout を初期化するときに [elementsOptions.appearance](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-elementsOptions-appearance) を渡すことで、すべての Elements の[デザインをカスタマイズ](https://docs.stripe.com/payments/checkout/customization/appearance.md)できるようになります。 #### React [CheckoutProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider) 内に [Payment Element](https://docs.stripe.com/payments/payment-element.md) コンポーネントをマウントします。 ```jsx import React from 'react';import {PaymentElement, useCheckout} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckout(); if (checkoutState.type === 'loading') { return (
Loading...
); } if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } return (
{JSON.stringify(checkoutState.checkout.lineItems, null, 2)} {/* A formatted total amount */} Total: {checkoutState.checkout.total.total.amount} ); }; export default CheckoutForm; ``` 対応しているオプションについては、[Stripe.js のドキュメント](https://docs.stripe.com/js/custom_checkout/create_payment_element#custom_checkout_create_payment_element-options) をご覧ください。 [elementsOptions.appearance](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider#react_checkout_provider-options-elementsOptions-appearance) を [CheckoutProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider) に渡すことで、すべての Elements の[外観をカスタマイズ](https://docs.stripe.com/payments/checkout/customization/appearance.md)できます。 ## 支払いを送信する [クライアント側] #### HTML + JS `Checkout` インスタンスから [確定](https://docs.stripe.com/js/custom_checkout/confirm) を呼び出す**支払う** ボタンをレンダリングして、決済を送信します。 ```html
``` ```js const checkout = stripe.initCheckout({clientSecret}); checkout.on('change', (session) => { document.getElementById('pay-button').disabled = !session.canConfirm; }); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const {actions} = loadActionsResult; const button = document.getElementById('pay-button'); const errors = document.getElementById('confirm-errors'); button.addEventListener('click', () => { // Clear any validation errors errors.textContent = ''; actions.confirm().then((result) => { if (result.type === 'error') { errors.textContent = result.error.message; } }); }); } ``` #### React [useCheckout](https://docs.stripe.com/js/react_stripe_js/checkout/use_checkout) から [confirm](https://docs.stripe.com/js/custom_checkout/confirm) を呼び出して決済を送信する **Pay** ボタンをレンダリングします。 ```jsx import React from 'react'; import {useCheckout} from '@stripe/react-stripe-js/checkout'; const PayButton = () => { const checkoutState = useCheckout(); const [loading, setLoading] = React.useState(false); const [error, setError] = React.useState(null); if (checkoutState.type !== "success") { return null; } const handleClick = () => { setLoading(true);checkoutState.checkout.confirm().then((result) => { if (result.type === 'error') { setError(result.error) } setLoading(false); }) }; return (
{error &&
{error.message}
}
) }; export default PayButton; ``` ## 構築したシステムをテストする 1. 決済ページに移動します。 1. 次の表の決済手段を使用して、支払いの詳細を入力します。カード支払いの場合: - カードの有効期限として任意の将来の日付を入力します。 - 任意の 3 桁のセキュリティコードを入力します。 - 請求先の任意の郵便番号を入力します。 1. Stripe に支払いを送信します。 1. ダッシュボードに移動し、[取引ページ](https://dashboard.stripe.com/test/payments?status%5B0%5D=successful)で支払いを探します。支払いが成功していると、そのリストに表示されます。 1. 支払いをクリックすると、請求先情報や購入したアイテムのリストなどの詳細が表示されます。この情報を使用して[注文のフルフィルメントを実行](https://docs.stripe.com/checkout/fulfillment.md)できます。 #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (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)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### ウォレット | 決済手段 | シナリオ | テスト方法 | | ------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Alipay | 顧客はリダイレクトベースの[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。 | アカウント番号 `900123456` と BSB `000000` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 | | BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。 | アカウント番号 `111111113`と BSB `000000`を使用して、フォームに入力します。 | | Bancontact、EPS、iDEAL、Przelewy24 | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | #### 店舗支払い | 決済手段 | シナリオ | テスト方法 | | ----------- | ------------------------------------- | ------------------------------------------------------------- | | Boleto、OXXO | 顧客が Boleto または OXXO で取引の詳細を使用して支払います。 | 支払い方法として Boleto または OXXO を選択し、支払いを送信します。ダイアログが表示されたら、それを閉じます。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: 製品および価格の作成 Checkout Session を作成する前に、*商品* (Products represent what your business sells—whether that's a good or a service)と*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を事前に設定できます。商品を使用して複数の物理的商品やサービスのレベルを表し、*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を使用して各商品の料金体系を表します。[Checkout Session を設定](https://docs.stripe.com/payments/checkout/pay-what-you-want.md)して、チップや寄付を受け付けることや、Pay What You Want の商品やサービスを販売することができます。 たとえば、価格が 20 USD の T シャツ商品を作成できます。これにより、対象商品の詳細を変更せずに価格を更新したり追加したりできるようになります。商品と価格は、Stripe ダッシュボードまたは API で作成できます。[商品および価格の仕組み](https://docs.stripe.com/products-prices/how-products-and-prices-work.md)について、詳細をご確認ください。 #### API API で [Product (商品)](https://docs.stripe.com/api/products.md) を作成するのに必要なのは `name` のみです。指定した商品の `name`、`description`、および `images` が Checkout に表示されます。 ```curl curl https://api.stripe.com/v1/products \ -u "<>:" \ -d name=T-shirt ``` 次に、[Price (価格)](https://docs.stripe.com/api/prices.md) を作成して商品の価格を定義します。これには商品コストと使用通貨が含まれます。 ```curl curl https://api.stripe.com/v1/prices \ -u "<>:" \ -d product="{{PRODUCT_ID}}" \ -d unit_amount=2000 \ -d currency=usd ``` #### ダッシュボード > サンドボックスで作成した商品を本番環境にコピーすると、再作成する必要がありません。ダッシュボードの商品の詳細表示で、右上隅にある**本番環境にコピー**をクリックします。この操作は、サンドボックスで作成された各商品に対して 1 回のみ実行できます。テスト商品に対する以降の更新は、本番環境の商品には反映されません。 ダッシュボードのアカウント選択機能で**サンドボックス**をクリックして、サンドボックスで作業していることを確認します。次に、販売する商品を定義します。以下の手順に従って新しい商品と価格を作成してください。 - ダッシュボードで[商品](https://dashboard.stripe.com/test/products)セクションに移動します。 - **商品を追加**をクリックします。 - 価格を設定する際に**一括**を選択します。 指定した商品の名前、説明、画像が Checkout に表示されます。 作成された価格ごとに ID があります。Checkout Session を作成する際には、価格 ID と数量を参照します。複数の通貨で販売している場合、Price を *多通貨* (A single Price object can support multiple currencies. Each purchase uses one of the supported currencies for the Price, depending on how you use the Price in your integration) にします。Checkout は自動的に [顧客の現地通貨を特定し](https://docs.stripe.com/payments/checkout/localize-prices/manual-currency-prices.md)、Price が対応している場合にはその通貨を提示します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d ui_mode=custom \ -d mode=payment \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ --data-urlencode return_url="https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 顧客データを事前入力する [サーバー側] すでに顧客のメールを収集していて、それを Checkout セッションで事前に入力するには、Checkout セッションの作成時に [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) を渡します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ --data-urlencode customer_email="customer@example.com" \ -d ui_mode=custom \ -d mode=payment \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ --data-urlencode return_url="https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 支払い方法の詳細を保存する 将来の購入のために[決済を受け付けて顧客の決済情報を保存する](https://docs.stripe.com/payments/save-during-payment.md)方法をご覧ください。 ## Optional: Checkout Session の変更をリッスンする ### Checkout Session の変更をリッスンする [checkout.on](https://docs.stripe.com/js/custom_checkout/change_event) を使用して `change` イベントにイベントリスナーを追加することで、[Checkout Session](https://docs.stripe.com/api/checkout/sessions.md) への変更をリッスンできます。 #### HTML + JS ```javascript checkout = stripe.initCheckout({ clientSecret: promise, elementsOptions: { appearance }, }); checkout.on('change', (session) => { // Handle changes to the checkout session }); ``` #### React ```jsx import React from 'react'; import { useCheckout } from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckout(); if (checkoutState.type === 'success') { checkoutState.checkout.on('change', (session) => { // Handle changes to the checkout session }); } }; ``` ## Optional: 請求先住所と配送先住所を収集する ## 請求先住所を収集する デフォルトでは、Checkout セッションは Payment Element を通じて支払いに必要な最小限の請求情報を収集します。 ### Billing Address Element を使用する Billing Address Element を使用して、完全な請求先住所を収集できます。 まず、Checkout セッションの作成時に [billing_address_collection=required](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) を渡します。 #### HTML + JS コンテナーの DOM 要素を作成して、Billing Address Element をマウントします。次に、[checkout.createBillingAddressElement](https://docs.stripe.com/js/custom_checkout/create_billing_address_element) を使用して Billing Address Element のインスタンスを作成し、[element.mount](https://docs.stripe.com/js/element/mount) を呼び出してマウントし、CSS セレクターまたはコンテナーの DOM 要素を指定します。 ```html
``` ```javascript const billingAddressElement = checkout.createBillingAddressElement(); billingAddressElement.mount('#billing-address'); ``` Billing Address Element は、以下のオプションに対応しています。 - [contacts](https://docs.stripe.com/js/custom_checkout/create_billing_address_element#custom_checkout_create_billing_address_element-options-contacts) - [display](https://docs.stripe.com/js/custom_checkout/create_billing_address_element#custom_checkout_create_billing_address_element-options-display) #### React `CheckoutProvider` 内に `BillingAddressElement` コンポーネントをマウントします。 ```jsx import React from 'react'; import {BillingAddressElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { return (
) }; ``` Billing Address Element は、以下のプロパティに対応しています。 - [contacts](https://docs.stripe.com/js/custom_checkout/create_billing_address_element#custom_checkout_create_billing_address_element-options-contacts) - [display](https://docs.stripe.com/js/custom_checkout/create_billing_address_element#custom_checkout_create_billing_address_element-options-display) ### カスタムフォームを使用する 請求先住所を収集するためのカスタムフォームを作成できます。 - 決済画面に確認前の個別の住所収集ステップがある場合は、顧客が住所を送信するときに [updateBillingAddress](https://docs.stripe.com/js/react_stripe_js/checkout/update_billing_address) を呼び出します。 - それ以外の場合は、[billingAddress](https://docs.stripe.com/js/custom_checkout/confirm#custom_checkout_session_confirm-options-billingAddress) を [confirm](https://docs.stripe.com/js/custom_checkout/confirm) に渡すことで、顧客が「支払う」ボタンをクリックしたときに住所を送信できます。 ### 請求先住所の一部を収集する 国と郵便番号のみなど、請求先住所の一部を収集するには、[billing_address_collection=auto](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) を渡します。 請求先住所の一部を収集する場合は、[手動で住所を収集する](https://docs.stripe.com/payments/accept-a-payment.md#collect-billing-addresses-manually)必要があります。デフォルトでは、Payment Element が支払いに必要な最小限の請求情報を自動的に収集します。請求情報が二重に収集されないようにするため、Payment Element の作成時に [fields.billingDetails=never](https://docs.stripe.com/js/custom_checkout/create_payment_element#custom_checkout_create_payment_element-options-fields-billingDetails) を渡します。請求情報の一部 (顧客の名前など) のみを収集する場合は、自分で収集する予定のフィールドにのみ `never` を渡します。 ## 配送先住所を収集する 顧客の配送先住所を収集するには、Checkout セッションの作成時に [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) パラメーターを渡します。 配送先住所を収集するときは、配送先の国も指定する必要があります。[2 文字の ISO 国コード](https://www.nationsonline.org/oneworld/country_code_list.htm)の配列を含む [allowed_countries](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection-allowed_countries) プロパティを設定します。 ### Shipping Address Element の使用方法 Shipping Address Element を使用して、完全な配送先住所を収集できます。 #### HTML + JS コンテナーの DOM 要素を作成して、Shipping Address Element をマウントします。次に、[checkout.createShippingAddressElement](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element) を使用して Shipping Address Element のインスタンスを作成し、[element.mount](https://docs.stripe.com/js/element/mount) を呼び出してマウントし、CSS セレクターまたはコンテナーの DOM 要素を指定します。 ```html
``` ```javascript const shippingAddressElement = checkout.createShippingAddressElement(); shippingAddressElement.mount('#shipping-address'); ``` Shipping Address Element は、以下のオプションに対応しています。 - [contacts](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element#custom_checkout_create_shipping_address_element-options-contacts) - [display](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element#custom_checkout_create_shipping_address_element-options-display) #### React `CheckoutProvider` 内に `ShippingAddressElement` コンポーネントをマウントします。 ```jsx import React from 'react'; import {ShippingAddressElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { return (
) }; ``` Shipping Address Element は、以下のプロパティに対応しています。 - [contacts](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element#custom_checkout_create_shipping_address_element-options-contacts) - [display](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element#custom_checkout_create_shipping_address_element-options-display) ### Checkout Session の変更をリッスンする 住所関連の変更を処理するイベントリスナーを追加して、[Checkout Session](https://docs.stripe.com/api/checkout/sessions.md) への変更をリッスンできます。 #### HTML + JS [Session オブジェクト](https://docs.stripe.com/js/custom_checkout/session_object)を使用して、決済フォームに配送料を表示します。 ```html

Totals

``` ```javascript const checkout = stripe.initCheckout({clientSecret}); const subtotal = document.getElementById('subtotal'); const shipping = document.getElementById('shipping'); const total = document.getElementById('total'); checkout.on('change', (session) => { subtotal.textContent = `Subtotal: ${session.total.subtotal.amount}`; shipping.textContent = `Shipping: ${session.total.shippingRate.amount}`; total.textContent = `Total: ${session.total.total.amount}`; }); ``` #### React [useCheckout](https://docs.stripe.com/js/react_stripe_js/checkout/use_checkout) を使用して、決済フォームに配送料を表示します。 ```jsx import React from 'react'; import {useCheckout, ShippingAddressElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckout(); if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } return (

Checkout Summary

{checkoutState.type === 'success' && ( <>
              {JSON.stringify(checkoutState.checkout.lineItems, null, 2)}
            

Totals

              Subtotal: {checkoutState.checkout.total.subtotal.amount}
              Shipping: {checkoutState.checkout.total.shippingRate.amount}
              Total: {checkoutState.checkout.total.total.amount}
            
)}
) }; ``` ### 請求先住所と配送先住所を同期 Billing Address Element と Shipping Address Element の両方を使用する場合、顧客が請求先住所と配送先住所を同期できるようにするチェックボックスを表示できます。 #### HTML + JS 決済の初期化時に `elementsOptions` で [syncAddressCheckbox](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-elementsOptions-syncAddressCheckbox) オプションを渡し、チェックボックスを表示する Address Element を設定します。 ```javascript const checkout = stripe.initCheckout({ clientSecret, elementsOptions: { syncAddressCheckbox: 'shipping', }, }); ``` #### React `elementsOptions` の [syncAddressCheckbox](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider#react_checkout_provider-options-elementsOptions-syncAddressCheckbox) オプションを `CheckoutProvider` に渡して、チェックボックスを表示する Address Element を設定します。 ```jsx promise, elementsOptions: { syncAddressCheckbox: 'shipping', }, }} > ``` 値を `'billing'` または `'shipping'` に設定して、チェックボックスを表示する住所 Element を選択します。チェックボックスを非表示にするには、`'none'` に設定します。 ### カスタムフォームを使用する 配送先住所を収集するためのカスタムフォームを作成できます。 - 決済画面に確認前の個別の住所収集ステップがある場合は、顧客が住所を送信したときに [updateShippingAddress](https://docs.stripe.com/js/react_stripe_js/checkout/update_shipping_address) を呼び出します。 - それ以外の場合は、[shippingAddress](https://docs.stripe.com/js/custom_checkout/confirm#custom_checkout_session_confirm-options-shippingAddress) を [confirm](https://docs.stripe.com/js/custom_checkout/confirm) に渡すことで、顧客が「支払う」ボタンをクリックしたときに住所を送信できます。 ## Optional: オーソリとキャプチャーを分離する [サーバー側] Stripe は 2 段階カード決済をサポートしているため、まずクレジットカードをオーソリし、後で売上をキャプチャーすることができます。Stripe が決済をオーソリすると、カード発行会社が売上を保証し、顧客のクレジットカードに決済金額を保留します。その後、売上をキャプチャーする一定の時間 ([カードに](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md#auth-capture-limitations)よって異なります) が設定されます。オーソリの期限が切れる前に決済をキャプチャーしない場合、決済はキャンセルされ、カード発行会社は保留されていた売上を解放します。 Separating authorization and capture is useful if you need to take additional actions between confirming that a customer is able to pay and collecting their payment. For example, if you’re selling stock-limited items, you might need to confirm that an item purchased by your customer using Checkout is still available before capturing their payment and fulfilling the purchase. Accomplish this using the following workflow: 1. Stripe が顧客の支払い方法を承認したことを確認します。 1. 在庫管理システムを調べ、アイテムがまだあることを確認します。 1. 在庫管理システムを更新し、アイテムが購入されたことを反映させます。 1. 顧客の支払いをキャプチャーします。 1. 購入が成功したかどうかを確認ページで顧客に通知します。 オーソリとキャプチャーを分離するには、Checkout セッションの作成時に、[payment_intent_data.capture_method](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-capture_method) の値を `manual` に設定します。これにより、Stripe に対して顧客のカードで金額のオーソリのみを行うよう指示します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ -d "payment_intent_data[capture_method]"=manual \ -d return_url={{RETURN_URL}} \ -d ui_mode=custom ``` キャプチャーされていない支払いをキャプチャーするには、[ダッシュボード](https://dashboard.stripe.com/test/payments?status%5B%5D=uncaptured)または[キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)エンドポイントを使用します。プログラムによる支払いのキャプチャーには、Checkout セッションの際に作成される PaymentIntent へのアクセスが必要です。これは [Session (セッション)](https://docs.stripe.com/api/payment_intents/capture.md) オブジェクトから取得できます。 ## Optional: 顧客のアカウントの管理 [コーディング不要] *カスタマーポータル* (The customer portal is a secure, Stripe-hosted page that lets your customers manage their subscriptions and billing details)へのリンクを共有して、顧客が自身のアカウントを[管理](https://docs.stripe.com/customer-management.md)できるようにします。カスタマーポータルでは、顧客はメールアドレスでログインして、サブスクリプションの管理や決済手段の更新などを行うことができます。 ## Optional: 注文のフルフィルメント 顧客が支払いを行ったときに[プログラムで通知を受け取る](https://docs.stripe.com/checkout/fulfillment.md?payment-ui=embedded-components)方法をご紹介します。 ## See also - [1 回限りの支払いに割引を追加する](https://docs.stripe.com/payments/checkout/discounts.md?payment-ui=embedded-components) - [税金を徴収する](https://docs.stripe.com/payments/checkout/taxes.md?payment-ui=embedded-components) - [項目の数を調整可能にする](https://docs.stripe.com/payments/checkout/adjustable-quantity.md?payment-ui=embedded-components) - [ワンクリックボタンを追加](https://docs.stripe.com/elements/express-checkout-element/accept-a-payment.md?payment-ui=embedded-components) # Payment Intents API > This is a Payment Intents API for when payment-ui is elements and api-integration is paymentintents. View the full page at https://docs.stripe.com/payments/accept-a-payment?payment-ui=elements&api-integration=paymentintents. [Stripe Elements](https://docs.stripe.com/payments/elements.md) と [Payment Intents API](https://docs.stripe.com/api/payment_intents.md) を使用してカスタマイズされた決済フォームを構築します。この連携機能を Stripe の他の統合タイプと比較する方法は[こちら](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)をご覧ください。 Payment Intents API は、独自の決済フローの構築に使用できる下位レベルの API ですが、非常に多くのコードと継続的なメンテナンスが必要です。ほとんどの組み込みには [Payment Element with Checkout Sessions](https://docs.stripe.com/payments/quickstart-checkout-sessions.md) をお勧めします。Payment Intents と同様の決済フローに対応しているためです。PaymentIntents の代わりに [Checkout Sessions を使用するタイミングの詳細をご確認ください](https://docs.stripe.com/payments/checkout-sessions-and-payment-intents-comparison.md)。 クライアント側およびサーバー側のコードでさまざまな支払い方法を受け付ける決済フォームを構築します。 #### 実装作業 Complexity: 4/5 #### システム構築のタイプ カスタムの決済フローに UI コンポーネントを組み合わせる #### UI のカスタマイズ [Appearance API](https://docs.stripe.com/elements/appearance-api.md) による CSS レベルのカスタマイズ > #### Stripe Tax、割引、配送、通貨換算の使用をご希望の場合 > > Stripe には税金、割引、配送料、通貨換算を管理する支払い Element の導入があります。詳細については、[Checkout ページの構築](https://docs.stripe.com/payments/quickstart-checkout-sessions.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' ``` ## PaymentIntent を作成する [サーバー側] > 最初に PaymentIntent を作成せずに Payment Element をレンダリングする場合は、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=payment)をご覧ください。 [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md) オブジェクトは、顧客から支払いを回収する意図を示し、支払いプロセス全体を通して請求の実施と状態の変化を追跡します。 このドキュメントで説明される決済の組み込みの概要。 (See full diagram at https://docs.stripe.com/payments/accept-a-payment) ### PaymentIntent を作成する サーバーで [amount](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-amount) および [currency](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-currency) を指定して PaymentIntent を作成します。最新バージョンの API では `automatic_payment_methods` パラメーターの指定は必須ではありません。この機能はデフォルトで有効になっています。決済手段は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は、取引の金額、通貨、決済フローなどの要素に基づいて、適切な決済手段が返されるように処理します。 Stripe はお客様の[決済手段設定](https://dashboard.stripe.com/settings/payment_methods)を使用して、お客様が有効にした決済手段を表示します。決済手段が顧客に対してどのように表示されるかを確認するには、[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods/review)で取引 ID を入力するか、注文金額と通貨を設定します。決済手段を上書きするには、[payment_method_types](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-payment_method_types) 属性を使用して有効にする決済手段を手動で一覧表示します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true ``` > 支払い額は常に、クライアント側ではなく、信頼性の高い環境であるサーバー側で決定してください。このようにすることで、悪意のある顧客が価格を操作できないようにすることができます。 ### client secret を取得する PaymentIntent には、*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 PaymentIntent {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/payment_intents/object.md#payment_intent_object-client_secret) を追加します。サーバー側のコードで、PaymentIntent から client secret を取得します。 #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## 支払いの詳細を収集する [クライアント側] [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用してクライアント側で支払い詳細を収集します。Payment Element は事前構築された UI コンポーネントであり、さまざまな決済手段の詳細の収集をシンプルにします。 Payment Element には、HTTPS 接続を介して支払い情報を Stripe に安全に送信する iframe が含まれています。一部の支払い方法では、支払いを確定するために別のページにリダイレクトする必要があるため、Payment Element を別の iframe 内に配置しないでください。 iframe を使用して Apple Pay または Google Pay を受け付けたい場合は、iframe の [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) 属性を `"payment *"` と等しく設定する必要があります。 構築済みのシステムを機能させるには、決済ページのアドレスの先頭を `http://` ではなく `https://` にする必要があります。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 Checkout ``` 決済ページで以下の 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('<>'); ``` ### Payment Element を支払いページに追加する Payment Element を決済ページに配置する場所が必要です。決済フォームで、一意の ID を持つ空の DOM ノード (コンテナー) を作成します。 ```html
``` 前のフォームが読み込まれたら、Payment Element のインスタンスを作成して、それをコンテナーの DOM ノードにマウントします。[Elements](https://docs.stripe.com/js/elements_object/create) インスタンスを作成する際に、前のステップからの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を `options` に渡します。 client secret は支払いを完了できるため、慎重に取り扱う必要があります。記録したり、URL に埋め込んだり、当該の顧客以外に漏洩することがないようにしてください。 ```javascript const options = { clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in a previous stepconst elements = stripe.elements(options); // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element'); ``` #### 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/payment_intents/object.md#payment_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 CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); function App() { const options = { // passing the client secret obtained in step 3 clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Payment Element コンポーネントを追加する `PaymentElement` コンポーネントを使用して、フォームを構築します。 ```jsx import React from 'react'; import {PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { return (
); }; export default CheckoutForm; ``` 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 をカスタマイズできます。 ### 住所を収集 デフォルトでは、Payment Element は必要な請求住所の詳細のみを収集します。[税金の計算](https://docs.stripe.com/api/tax/calculations/create.md)、配送先情報を入力するなどの一部の動作では、顧客の完全な住所が必要です。次のように対応できます。 - [Address Element](https://docs.stripe.com/elements/address-element.md) を使用して、オートコンプリートとローカリゼーションの機能を利用して、顧客の完全な住所を収集します。これにより、最も正確な税金計算が可能になります。 - 独自のカスタムフォームを使用して住所の詳細を収集する。 ### Apple Pay マーチャントトークンをリクエストする 連携機能を [Apple Pay 決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=checkout)ように設定している場合は、加盟店が開始する取引 (MIT) を有効にするために、Apple Pay インターフェイスがマーチャントトークンを返すように設定することをお勧めします。Payment Element で[関連するマーチャントトークンのタイプをリクエスト](https://docs.stripe.com/apple-pay/merchant-tokens.md?pay-element=web-pe)してください。 ## 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 で支払い方法の保存機能を有効にする サーバー側で [PaymentIntent](https://docs.stripe.com/api/payment_intents/.md) を作成するときに、[CustomerSession](https://docs.stripe.com/api/customer_sessions/.md) も作成します。その際、[Customer ID](https://docs.stripe.com/api/customers/object.md#customer_object-id) を指定して、セッションの [payment_element](https://docs.stripe.com/api/customer_sessions/object.md#customer_session_object-components-payment_element) コンポーネントを有効にします。有効にする保存済みの決済手段[機能](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 セッションで `setup_future_usage` を指定して、決済手段を保存するためのデフォルトの動作を上書きできます。これにより、顧客が明示的に保存を選択しなくても、将来の使用に備えて決済手段を自動的に保存できます。 > [payment_method_remove](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components-payment_element-features-payment_method_remove) を有効にして、保存済みの決済手段を買い手が削除できるようにすると、その決済手段を利用しているサブスクリプションに影響します。決済手段を削除すると、[PaymentMethod](https://docs.stripe.com/api/payment_methods.md) とその [Customer](https://docs.stripe.com/api/customers.md) の関連付けが解除されます。 #### Ruby ```ruby # Don't put any keys in code. Use a secrets vault or environment # variable to supply keys to your integration. This example # shows how to set a secret key for illustration purposes only. # # See https://docs.stripe.com/keys-best-practices and find your # keys at https://dashboard.stripe.com/apikeys. Stripe.api_key = '<>' post '/create-intent-and-customer-session' do intent = Stripe::PaymentIntent.create({ amount: 1099, currency: 'usd', # 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 = Stripe::CustomerSession.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 インスタンスに指定する必要はありません。 PaymentIntent と 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'); ``` PaymentIntent の確定時に、顧客が支払いの詳細を保存するためのボックスにチェックマークを付けたかどうかに応じて、Stripe.js が PaymentIntent の [setup_future_usage](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-setup_future_usage) および [allow_redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) の設定をコントロールします。 ### セキュリティコードの再収集を実行する オプションとして、[PaymentIntent の作成時](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-card-require_cvc_recollection)に `require_cvc_recollection` を指定して、顧客がカードで支払う場合にセキュリティコードの再収集を実行します。 ### 保存した支払い方法の選択内容を検出する 保存した支払い方法を選択したときにコンテンツを動的に制御するには、Payment Element の `change` イベントをリッスンします。このイベントには、選択した支払い方法の情報が入力されています。 ```javascript paymentElement.on('change', function(event) { if (event.value.payment_method) { // Control dynamic content if a saved payment method is selected } }) ``` ## 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 に登録できます。 - コード変更が不要です。 | 顧客が 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 が表示された後、PaymentIntent の [amount](https://docs.stripe.com/api/payment_intents/update.md#update_payment_intent-amount) などの属性を更新することができます (割引コードや配送料金など)。サーバー側で [PaymentIntent を更新](https://docs.stripe.com/api/payment_intents/update.md)して、[elements.fetchUpdates](https://docs.stripe.com/js/elements_object/fetch_updates) を呼び出すと、Payment Element に反映された新しい金額を確認できます。次の例では、PaymentIntent の amount (金額) を更新するサーバーエンドポイントを作成する方法を示しています。 #### Ruby ```ruby get '/update' do intent = Stripe::PaymentIntent.update( '{{PAYMENT_INTENT_ID}}', {amount: 1499}, ) {status: intent.status}.to_json end ``` この例は、クライアント側でこれらの変更を反映するために UI を更新する方法を示しています。 ```javascript (async () => { const response = await fetch('/update'); if (response.status === 'requires_payment_method') { const {error} = await elements.fetchUpdates(); } })(); ``` ## Stripe に支払いを送信する [クライアント側] Payment Element からの詳細を指定して [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を使用し、支払いを完了します。ユーザーが支払いを完了した後に Stripe がユーザーをリダイレクトする場所を指定するには、この関数に [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) を指定します。ユーザーはまず、銀行のオーソリページなどの中間サイトにリダイレクトされ、その後 `return_url` にリダイレクトされます。カード支払いでは、支払いが正常に完了するとすぐに `return_url` にリダイレクトします。 カード決済で支払いの完了後にリダイレクトを行わない場合は、[redirect](https://docs.stripe.com/js/payment_intents/confirm_payment#confirm_payment_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.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, 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`. } }); ``` #### React 支払いフォームコンポーネントから [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を呼び出すには、[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 CheckoutForm = () => { 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; } const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, 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) 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 (
{/* Show error message to your customers */} {errorMessage &&
{errorMessage}
} ); }; export default CheckoutForm; ``` `return_url` が、Web サイト上の支払いステータスを表示するページと対応していることを確認します。Stripe が顧客を `return_url` にリダイレクトするときは、以下の URL クエリーパラメーターが指定されます。 | パラメーター | 説明 | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent` | `PaymentIntent` の一意の識別子。 | | `payment_intent_client_secret` | `PaymentIntent` オブジェクトの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。 | > 顧客のブラウザーセッションを追跡するツールを利用している場合、リファラー除外リストに `stripe.com` ドメインの追加が必要になる場合があります。リダイレクトを行うと、一部のツールでは新しいセッションが作成され、セッション全体の追跡ができなくなります。 クエリパラメーターのいずれか 1 つを使用して PaymentIntent を取得します。[PaymentIntent のステータス](https://docs.stripe.com/payments/paymentintents/lifecycle.md)を調べて、顧客に表示する内容を決定します。また、`return_url` を指定するときにカスタムのクエリパラメーターを追加することもできます。このパラメーターはリダイレクトプロセスの間維持されます。 #### HTML + JS ```javascript // Initialize Stripe.js using your publishable key const stripe = Stripe('<>'); // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { const message = document.querySelector('#message') // Inspect the PaymentIntent `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 (paymentIntent.status) { case 'succeeded': message.innerText = 'Success! Payment received.'; break; case 'processing': message.innerText = "Payment processing. We'll update you when payment is received."; break; case 'requires_payment_method': message.innerText = 'Payment failed. Please try another payment method.'; // Redirect your user back to your payment page to attempt collecting // payment again break; default: message.innerText = 'Something went wrong.'; break; } }); ``` #### React ```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 "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe .retrievePaymentIntent(clientSecret) .then(({paymentIntent}) => { // Inspect the PaymentIntent `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 (paymentIntent.status) { case 'succeeded': setMessage('Success! Payment received.'); break; case 'processing': setMessage("Payment processing. We'll update you when payment is received."); break; case 'requires_payment_method': // Redirect your user back to your payment page to attempt collecting // payment again setMessage('Payment failed. Please try another payment method.'); break; default: setMessage('Something went wrong.'); break; } }); }, [stripe]); return message; }; export default PaymentStatus; ``` ## 支払い後のイベントを処理する [サーバー側] 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか [Webhook のガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信し、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアントでは、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了する場合、また悪意を持つクライアントがレスポンスを不正操作する場合もあります。非同期型のイベントをリッスンするよう組み込みを設定すると、単一の組み込みで[複数の異なるタイプの支払い方法](https://stripe.com/payments/payment-methods-guide)を受け付けることができます。 Payment Element を使用して支払いを回収する場合は、`payment_intent.succeeded` イベントのほかにこれらのイベントを処理することをお勧めします。 | イベント | 説明 | アクション | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.succeeded) | 顧客が正常に支払いを完了したときに送信されます。 | 顧客に注文の確定を送信し、顧客の注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [payment_intent.processing](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.processing) | 顧客が正常に支払いを開始したが、支払いがまだ完了していない場合に送信されます。このイベントは、多くの場合、顧客が口座引き落としを開始するときに送信されます。その後、`payment_intent.succeeded` イベント、また、失敗の場合は `payment_intent.payment_failed` イベントが送信されます。 | 顧客に注文確認メールを送信し、支払いが保留中であることを示します。デジタル商品では、支払いの完了を待たずに注文のフルフィルメントを行うことが必要になる場合があります。 | | [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed) | 顧客が支払いを試みたが、支払いに失敗する場合に送信されます。 | 支払いが `processing` から `payment_failed` に変わった場合は、顧客に再度支払いを試すように促します。 | ## 導入をテストする カスタムの決済システムをテストするには、以下の手順を実行します。 1. Payment Intent を作成して client secret を取得します。 1. 次の表の方法を使用して、支払い詳細を入力します。 - カードの有効期限として任意の将来の日付を入力します。 - 任意の 3 桁のセキュリティコードを入力します。 - 請求先の任意の郵便番号を入力します。 1. Stripe に支払いを送信します。指定した `return_url` にリダイレクトされます。 1. ダッシュボードに移動し、[取引ページ](https://dashboard.stripe.com/test/payments?status%5B0%5D=successful)で支払いを探します。支払いが成功していると、そのリストに表示されます。 1. 支払いをクリックすると詳細が表示され、請求先情報と購入されたアイテムのリストなどを確認できます。これを使用して注文のフルフィルメントを実行できます。 詳細は、[実装のテスト](https://docs.stripe.com/testing.md)をご覧ください。 #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (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)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### ウォレット | 決済手段 | シナリオ | テスト方法 | | ------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Alipay | 顧客はリダイレクトベースの[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。 | アカウント番号 `900123456` と BSB `000000` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 | | BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。 | アカウント番号 `111111113`と BSB `000000`を使用して、フォームに入力します。 | | Bancontact、EPS、iDEAL、Przelewy24 | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | #### 店舗支払い | 決済手段 | シナリオ | テスト方法 | | ----------- | ------------------------------------- | ------------------------------------------------------------- | | Boleto、OXXO | 顧客が Boleto または OXXO で取引の詳細を使用して支払います。 | 支払い方法として Boleto または OXXO を選択し、支払いを送信します。ダイアログが表示されたら、それを閉じます。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: 支払い方法をさらに追加する Payment Element は、デフォルトで[多数の支払い方法に対応](https://docs.stripe.com/payments/payment-methods/integration-options.md#choose-how-to-add-payment-methods)しています。一部の支払い方法を有効にして表示するには、追加のステップを実行する必要があります。 ### Affirm Affirm の使用を開始するには、[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で有効にする必要があります。支払い方法に Affirm を指定して PaymentIntent を作成する際に、[配送先住所](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-shipping)も含める必要があります。この例では、顧客が[支払い方法を選択](https://docs.stripe.com/payments/accept-a-payment.md#web-create-intent)した後に配送情報をクライアントに渡すことを推奨しています。Stripe での [Affirm](https://docs.stripe.com/payments/affirm.md) の使用方法の詳細をご確認ください。 #### HTML + JS ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://my-site.com/order/123/complete',shipping: { name: 'Jenny Rosen', address: { line1: '1 Street', city: 'Seattle', state: 'WA', postal_code: '95123', country: 'US' } }, } }); if (error) { // This point is reached if there's 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 is redirected to your `return_url`. For some payment // methods like iDEAL, your customer is redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }); ``` #### React ```jsx import React, {useState} from 'react'; import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { 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; } const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://my-site.com/order/123/complete',shipping: { name: 'Jenny Rosen', address: { line1: '1 Street', city: 'Seattle', state: 'WA', postal_code: '95123', country: 'US' } }, } }); 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 (
{/* Show error message to your customers */} {errorMessage &&
{errorMessage}
} ) }; export default CheckoutForm; ``` #### Affirm をテストする 次の表を使用してさまざまなシナリオをテストする方法をご紹介します。 | シナリオ | テスト方法 | | ------------------------------- | -------------------------------------------------------------- | | 顧客は Affirm による支払いに成功します。 | フォームに入力し (必ず配送先住所も含める)、支払いの認証を行います。 | | 顧客は Affirm のリダイレクトページで認証に失敗します。 | フォームに入力し、リダイレクトページで **Fail Test Payment (テスト支払い失敗)** をクリックします。 | ### Afterpay (Clearpay) 支払い方法に Afterpay を指定して PaymentIntent を作成する場合は、[配送先住所](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-shipping)を含める必要があります。Stripe での [Afterpay](https://docs.stripe.com/payments/afterpay-clearpay.md) の使用方法の詳細をご確認ください。 決済手段は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripeは取引額、通貨、決済フローなどの要素に基づいて、適切な決済手段が返されるように処理します。以下の例では、[automatic_payment_methods](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-automatic_payment_methods-enabled) 属性を使用していますが、[決済手段タイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)を使用して `afterpay_clearpay` を一覧表示することができます。最新バージョンのAPIでは `automatic_payment_methods` パラメーターの指定は必須ではありません。この機能はデフォルトで有効になっています。いずれのオプションを選択する場合でも、必ず[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で Afterpay Clearpay を有効にしてください。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true \ -d "shipping[name]"="Jenny Rosen" \ -d "shipping[address][line1]"="1234 Main Street" \ -d "shipping[address][city]"="San Francisco" \ -d "shipping[address][state]"=CA \ -d "shipping[address][country]"=US \ -d "shipping[address][postal_code]"=94111 ``` #### Afterpay (Clearpay) をテストする 次の表を使用してさまざまなシナリオをテストする方法をご紹介します。 | シナリオ | テスト方法 | | ---------------------------------- | -------------------------------------------------------------- | | 顧客が Afterpay での支払いに成功しました。 | フォームに入力し (必ず配送先住所も含める)、支払いの認証を行います。 | | 顧客が Afterpay のリダイレクトページで認証に失敗しました。 | フォームに入力し、リダイレクトページで **Fail Test Payment (テスト支払い失敗)** をクリックします。 | ### Apple Pay および Google Pay [カード決済を有効にする場合](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=paymentintents#create-the-paymentintent)、[ウォレットの表示条件](https://docs.stripe.com/testing/wallets.md)を満たす環境にある顧客に対して Apple Pay および Google Pay を表示します。これらのウォレットからの決済を受け付けるには、次のことも必要です。 - [支払い方法設定](https://dashboard.stripe.com/settings/payment_methods)でこれらを有効にします。Apple Payはデフォルトで有効になっています。 - 開発環境と本番環境で HTTPS を介してアプリケーションを提供します。 - [ドメインを登録](https://docs.stripe.com/payments/payment-methods/pmd-registration.md)します。 - ウォレットの決済モーダルの同期状態を維持するために [PaymentIntent](https://docs.stripe.com/api/payment_intents.md) の金額を更新する場合は、[サーバーからの更新を取得](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=paymentintents#fetch-updates)します。 > #### 各地域でのテスト > > Stripe Elements は、インドの Stripe アカウントと顧客に対して Google Pay および Apple Pay をサポートしていません。そのため、Stripe アカウントの拠点がインド以外に所在している場合も、テスターの IP アドレスがインドにある場合は、Google Pay または Apple Pay の実装をテストできません。 Stripe での [Apple Pay](https://docs.stripe.com/apple-pay.md) および [Google Pay](https://docs.stripe.com/google-pay.md) の使用方法の詳細をご確認ください。 ### ACH ダイレクトデビット ACH ダイレクトデビットによる支払い方法で Payment Element を使用する際には、次のステップに従います。 1. [Customer オブジェクト](https://docs.stripe.com/api/customers.md)を作成します。 ```curl curl -X POST https://api.stripe.com/v1/customers \ -u "<>:" ``` 1. `PaymentIntent` の作成時に顧客 ID を指定します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d setup_future_usage=off_session \ -d customer={{CUSTOMER_ID}} \ -d "payment_method_types[]"=us_bank_account ``` 1. [確認方法](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-payment_method_options-us_bank_account-verification_method)を選択します。 Payment Element で ACH ダイレクトデビットによる支払い方法を使用する場合は、`automatic` または `instant` のみを選択できます。 Stripe での [ACH ダイレクトデビット](https://docs.stripe.com/payments/ach-direct-debit.md)の使用方法の詳細をご確認ください。 #### ACH ダイレクトデビットをテストする | シナリオ | テスト方法 | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 顧客が即時の確認を使用し、アメリカの銀行口座で決済しました。 | **アメリカの銀行口座**を選択し、フォームに入力します。Test Institution (機関をテスト) をクリックします。モーダルに表示される指示に従って銀行口座を関連付け、支払いボタンをクリックします。 | | 顧客が少額入金を使用し、アメリカの銀行口座で決済しました。 | Select **US bank account** and fill out the form. Click **Enter bank details manually instead**. Follow the instructions on the modal to link your bank account. You can use these [test account numbers](https://docs.stripe.com/payments/ach-direct-debit/accept-a-payment.md?platform=web#test-account-numbers). Click your payment button. | | 顧客が銀行口座を関連付けるプロセスを完了できませんでした。 | **アメリカの銀行口座**を選択し、Test Institution (機関をテスト) または**代わりに手動で銀行口座情報を入力**をクリックします。完了せずにモーダルを閉じます | ### BLIK BLIK で Payment Element を使用する場合、ユーザーはバンキングアプリで支払いの承認を求めるモーダルを閉じることができます。この操作では、ユーザーは購入ページに戻らずに `return_url` にリダイレクトされます。Stripe での [BLIK](https://docs.stripe.com/payments/blik.md) の使用方法の詳細をご確認ください。 ユーザーがモーダルを閉じた場合、これに対応するには、`return_url` に対するサーバー側のハンドラで、Payment Intent の `status` が `succeeded` になっているか、まだ `requires_action` (ユーザーが支払わずにモーダルを閉じたことを示す) のままであるかを調べ、それぞれのケースに応じて対応します。 ### QR コードを使用した支払い方法 QR コードベースの支払い方法 (WeChat Pay、PayNow、Pix、PromptPay、Cash App Pay) で Payment Element を使用すると、ユーザーは QR コードのモーダルを閉じることができます。この操作では、ユーザーが決済ページに戻らずに、お客様の `return_url` にリダイレクトされます。 ユーザーが QR コードのモーダルを閉じた操作を処理するには、お客様の `return_url` に対するサーバー側のハンドラーで、Payment Intent の `status` が `succeeded` になっているか、まだ `requires_action` (ユーザーが支払わずにモーダルを閉じたことを示す) のままであるかを調べ、それぞれのケースに応じて処理します。 それ以外に、QR コードのモーダルを閉じたときのリダイレクトを防止する詳細オプションパラメーター [`redirect=if_required`](https://docs.stripe.com/js/payment_intents/confirm_payment#confirm_payment_intent-options-redirect) を渡すことで、`return_url` への自動リダイレクトを防止する方法もあります。 ### Cash App Pay Payment Element は、さまざまな顧客認証方式を使用しているため、デスクトップウェブとモバイルウェブでは動的なフォームをレンダリングする方法が異なります。Stripe での [Cash App Pay](https://docs.stripe.com/payments/cash-app-pay.md) の使用方法の詳細をご確認ください。 #### モバイル版ウェブアプリの要素 Cash App Pay は、モバイルウェブで行われるリダイレクトベースの決済手段です。これにより、顧客は本番環境の Cash App、またはテスト環境のテスト用支払いページにリダイレクトされます。支払いが完了すると、`redirect=if_required` を設定したかどうかに関係なく `return_url` にリダイレクトされます。 #### デスクトップ版ウェブアプリの要素 Cash App Pay は、デスクトップウェブでの QR コードを利用した支払い方法です。この支払い方法では、Payment Element により、QR コードのモーダルがレンダリングされます。顧客は、QR コードスキャンアプリケーションまたは Cash App モバイルアプリケーションを使用して QR コードをスキャンする必要があります。 本番環境では、顧客が Cash App にリダイレクトされると、すぐに `return_url` にリダイレクトされます。テスト環境では、`return_url` にリダイレクトされる前に支払いを承認または拒否することができます。顧客は、支払いの完了前に QR コードモーダルを閉じることもでき、これを行うと `return_url` へのリダイレクトがトリガーされます。 Payment Intent の `status` を調べられるように、`return_url` は必ずウェブサイトのページに対応させる必要があります。Payment Intent の `status` は、`succeeded`、`failed`、`requires_action` (たとえば、顧客が QR コードをスキャンせずにモーダルを閉じた場合) のいずれかです。 それ以外に、詳細オプションパラメーター `redirect=if_required` を渡すことでも `return_url` への自動リダイレクトを防止できます。これにより、QR コードのモーダルを閉じたときのリダイレクトを防止できます。 ### PayPal PayPal を使用するには、[登録済みドメイン](https://docs.stripe.com/payments/payment-methods/pmd-registration.md)を使用していることを確認します。 ## 顧客に 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 - [Stripe Elements](https://docs.stripe.com/payments/elements.md) - [支払いの事前設定](https://docs.stripe.com/payments/save-and-reuse.md) - [支払い中に支払いの詳細を保存する](https://docs.stripe.com/payments/save-during-payment.md) - [支払いフローで消費税、GST、VAT を計算する](https://docs.stripe.com/tax/custom.md) # iOS でのアプリ内実装 > This is a iOS でのアプリ内実装 for when payment-ui is mobile and platform is ios. View the full page at https://docs.stripe.com/payments/accept-a-payment?payment-ui=mobile&platform=ios. ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-overview.9e0d68d009dc005f73a6f5df69e00458.png) [PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) クラスを使用して、Stripe の構築済み決済 UI を iOS アプリの決済フローに組み込みます。[GitHub](https://github.com/stripe/stripe-ios/tree/master/Example/PaymentSheet%20Example) のサンプル実装をご覧ください。 ## Stripe を設定する [サーバー側] [クライアント側] まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。 ### サーバー側 この接続方法では、Stripe API と通信するエンドポイントがサーバー上に必要です。サーバーから 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' ``` ### クライアント側 [Stripe iOS SDK](https://github.com/stripe/stripe-ios) はオープンソースです。[詳細なドキュメントが提供されており](https://stripe.dev/stripe-ios/index.html)、iOS 13 以降をサポートするアプリと互換性があります。 #### Swift Package Manager SDK をインストールするには、以下のステップに従います。 1. Xcode で、**File (ファイル)** > **Add Package Dependencies… (パッケージ依存関係を追加)** を選択し、リポジトリー URL として `https://github.com/stripe/stripe-ios-spm` を入力します。 1. [リリースページ](https://github.com/stripe/stripe-ios/releases)から最新のバージョン番号を選択します。 1. **StripePaymentSheet** 製品を[アプリのターゲット](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)に追加します。 #### CocoaPods 1. まだインストールしていない場合は、[CocoaPods](https://guides.cocoapods.org/using/getting-started.html) の最新バージョンをインストールします。 1. 既存の [Podfile](https://guides.cocoapods.org/syntax/podfile.html) がない場合は、以下のコマンドを実行して作成します。 ```bash pod init ``` 1. この行を `Podfile` に追加します。 ```podfile pod 'StripePaymentSheet' ``` 1. 以下のコマンドを実行します。 ```bash pod install ``` 1. これ以降は、Xcode でプロジェクトを開く際に、`.xcodeproj` ファイルではなく、必ず `.xcworkspace` ファイルを使用するということを忘れないでください。 1. 今後、SDK の最新バージョンに更新するには、以下を実行します。 ```bash pod update StripePaymentSheet ``` #### Carthage 1. まだインストールしていない場合は、[Carthage](https://github.com/Carthage/Carthage#installing-carthage) の最新バージョンをインストールします。 1. この行を `Cartfile` に追加します。 ```cartfile github "stripe/stripe-ios" ``` 1. [Carthage のインストール手順](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos)に従います。必ず、[こちら](https://github.com/stripe/stripe-ios/tree/master/StripePaymentSheet/README.md#manual-linking)にリストされている必要なフレームワークのすべてを埋め込んでください。 1. 今後、SDK の最新バージョンに更新するには、以下のコマンドを実行します。 ```bash carthage update stripe-ios --platform ios ``` #### 手動のフレームワーク 1. Stripe の [GitHub リリースページ](https://github.com/stripe/stripe-ios/releases/latest)に移動して、**Stripe.xcframework.zip** をダウンロードして解凍します。 1. **StripePaymentSheet.xcframework** を、Xcode プロジェクトの **General (一般) ** 設定の **Embedded Binaries (埋め込みバイナリー)** セクションにドラッグします。**Copy items if needed (必要に応じてアイテムをコピーする)** を必ず選択してください。 1. [こちら](https://github.com/stripe/stripe-ios/tree/master/StripePaymentSheet/README.md#manual-linking)にリストされている必要なフレームワークのすべてに対して、ステップ 2 を繰り返します。 1. 今後、Stripe の SDK の最新バージョンに更新するには、ステップ 1 から 3 を繰り返します。 > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases (リリース)](https://github.com/stripe/stripe-ios/releases) ページをご覧ください。リポジトリの[リリースをウォッチ](https://help.github.com/en/articles/watching-and-unwatching-releases-for-a-repository#watching-releases-for-a-repository)して、新しいリリースの公開時に通知を受け取ることも可能です。 ## 支払い方法を有効にする [支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)を表示して、サポートする支払い方法を有効にします。*PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。 多くの顧客から決済を受け付けられるよう、Stripe では、カードやその他一般的な決済手段がデフォルトで有効になっていますが、ビジネスや顧客に適した追加の決済手段を有効にすることをお勧めします。プロダクトと決済手段のサポートについては[決済手段のサポート](https://docs.stripe.com/payments/payment-methods/payment-method-support.md)を、手数料については[料金体系ページ](https://stripe.com/pricing/local-payment-methods)をご覧ください。 ## エンドポイントを追加する [サーバー側] > #### 注 > > PaymentIntent の作成前に PaymentSheet を表示するには、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=payment)をご覧ください。 Connect プラットフォームが [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、Stripe の [ガイド](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご確認の上、コード内の `Customer` およびイベント参照を同等の Accounts v2 API リファレンスに置き換えてください。 この接続方法では、以下の 3 つの Stripe API オブジェクトを使用します。 1. [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md): Stripe はこれを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して支払いの試行と支払い状態の変化を追跡します。 1. (オプション) [Customer (顧客)](https://docs.stripe.com/api/customers.md): 今後の支払いに備えて決済手段を設定するには、決済手段を*Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に関連付ける必要があります。Customer オブジェクトは、顧客がビジネスでアカウントを作成するときに作成します。顧客がゲストとして支払いを行う場合は、支払いの前に Customer オブジェクトを作成し、後でこのオブジェクトを顧客のアカウントを表す内部表現に関連付けることができます。 1. (オプション) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md): Customer オブジェクトの情報は機密情報であるため、アプリから直接取得することはできません。CustomerSession により、SDK に Customer への範囲を設定した一時的なアクセス権が付与され、また追加の設定オプションが提供されます。すべての[設定オプション](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)のリストをご覧ください。 > Customer にカードを保存したことがなく、リピート顧客に保存されたカードの再利用を許可しない場合は、実装で Customer オブジェクトおよび CustomerSession オブジェクトを省略できます。 セキュリティ上の理由により、アプリでこれらのオブジェクトを作成することはできません。代わりに、サーバー側で以下を行うエンドポイントを追加します。 1. Customer を取得するか、新規作成する。 1. 顧客の [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) を作成します。 1. [amount](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-amount)、[currency](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-currency)、[customer](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer) を指定して PaymentIntent を作成します。 1. PaymentIntent の *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))、CustomerSession の `client_secret`、Customer の [id](https://docs.stripe.com/api/customers/object.md#customer_object-id)、および貴社の[公開可能キー](https://dashboard.stripe.com/apikeys)をアプリに返します。 決済プロセス中に顧客に表示される支払い方法は、PaymentIntent にも含まれています。Stripe にダッシュボードの設定から支払い方法を取得するよう指定することも、手動でリストに表示することもできます。選択したオプションにかかわらず、顧客に表示される支払い方法は、PaymentIntent で渡す通貨によって絞り込まれることにご注意ください。たとえば、PaymentIntent で `eur` を渡し、ダッシュボードで OXXO が有効になっている場合、OXXO は `eur` による決済に対応していないため、顧客に表示されません。 構築済みのシステムで、決済手段を提供するためにコードベースのオプションが必要になる場合を除き、自動化されたオプションを使用することをお勧めします。これは、Stripe が通貨、決済手段の制約、その他のパラメーターを評価して、対応可能な決済手段を決定するためです。自動化されたオプションでは、購入完了率の向上につながり、使用通貨と顧客の所在地に最適な決済手段が優先的に表示されます。 #### ダッシュボードで支払い方法を管理する 支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。PaymentIntent は、ダッシュボードで設定された支払い方法を使用して作成されます。ダッシュボードを使用しない場合や、支払い方法を手動で指定する場合は、`payment_method_types` 属性を使用して支払い方法を一覧表示することができます。 #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. -d "automatic_payment_methods[enabled]"=true \ ``` #### 支払い方法を手動で一覧表示する #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ -d "payment_method_types[]"="bancontact" \ -d "payment_method_types[]"="card" \ -d "payment_method_types[]"="ideal" \ -d "payment_method_types[]"="klarna" \ -d "payment_method_types[]"="sepa_debit" \ ``` > 各決済手段は PaymentIntent で渡された通貨に対応している必要があり、ビジネスは、各決済手段を使用できる国のいずれかに所在する必要があります。対応状況について、詳細は[決済手段の導入オプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)ページをご覧ください。 ## 支払いの詳細を収集する [クライアント側] 決済画面に Mobile Payment Element を表示するには、必ず以下を行ってください。 - 顧客が購入している商品を合計金額とともに表示する - [Address Element](https://docs.stripe.com/elements/address-element.md?platform=ios) を使用して、必要な配送先情報を顧客から収集する - Stripe の UI を表示する購入ボタンを追加する #### UIKit アプリの Checkout 画面で、前のステップで作成したエンドポイントから PaymentIntent の client Secret、CustomerSession の client Secret、顧客 ID、公開可能キーを取得します。`STPAPIClient.shared` を使用して公開可能キーを設定し、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) を初期化します。 #### iOS (Swift) ```swift import UIKit@_spi(CustomerSessionBetaAccess) import StripePaymentSheet class CheckoutViewController: UIViewController { @IBOutlet weak var checkoutButton: UIButton! var paymentSheet: PaymentSheet? let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint override func viewDidLoad() { super.viewDidLoad() checkoutButton.addTarget(self, action: #selector(didTapCheckoutButton), for: .touchUpInside) checkoutButton.isEnabled = false // MARK: Fetch the PaymentIntent client secret, CustomerSession client secret, Customer ID, and publishable key var request = URLRequest(url: backendCheckoutUrl) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let customerId = json["customer"] as? String, let customerSessionClientSecret = json["customerSessionClientSecret"] as? String, let paymentIntentClientSecret = json["paymentIntent"] as? String, let publishableKey = json["publishableKey"] as? String, let self = self else { // Handle error return } STPAPIClient.shared.publishableKey = publishableKey// MARK: Create a PaymentSheet instance var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. configuration.allowsDelayedPaymentMethods = true self.paymentSheet = PaymentSheet(paymentIntentClientSecret:paymentIntentClientSecret, configuration: configuration) DispatchQueue.main.async { self.checkoutButton.isEnabled = true } }) task.resume() } } ``` 顧客が**購入**ボタンをタップしたら、`present` を呼び出して PaymentSheet を表示します。顧客が支払いを完了したら、Stripe は PaymentSheet を閉じ、[PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) とともに完了ブロックを呼び出します。 #### iOS (Swift) ```swift @objc func didTapCheckoutButton() { // MARK: Start the checkout process paymentSheet?.present(from: self) { paymentResult in // MARK: Handle the payment result switch paymentResult { case .completed: print("Your order is confirmed") case .canceled: print("Canceled!") case .failed(let error): print("Payment failed: \(error)") } } } ``` #### SwiftUI 決済画面用の `ObservableObject` モデルを作成します。このモデルは、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) と [PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) を公開します。 ```swift import StripePaymentSheet import SwiftUI class CheckoutViewModel: ObservableObject { let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint @Published var paymentSheet: PaymentSheet? @Published var paymentResult: PaymentSheetResult? } ``` 前のステップで作成したエンドポイントから PaymentIntent の client secret、CustomerSession の client secret、顧客 ID、公開可能キーを取得します。`STPAPIClient.shared` を使用して公開可能キーを設定し、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) を初期化します。 ```swift @_spi(CustomerSessionBetaAccess) import StripePaymentSheet import SwiftUI class CheckoutViewModel: ObservableObject { let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint @Published var paymentSheet: PaymentSheet? @Published var paymentResult: PaymentSheetResult? func preparePaymentSheet() { // MARK: Fetch thePaymentIntent and Customer information from the backend var request = URLRequest(url: backendCheckoutUrl) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let customerId = json["customer"] as? String, let customerSessionClientSecret = json["customerSessionClientSecret"] as? String, letpaymentIntentClientSecret = json["paymentIntent"] as? String, let publishableKey = json["publishableKey"] as? String, let self = self else { // Handle error return } STPAPIClient.shared.publishableKey = publishableKey// MARK: Create a PaymentSheet instance var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. configuration.allowsDelayedPaymentMethods = true DispatchQueue.main.async { self.paymentSheet = PaymentSheet(paymentIntentClientSecret:paymentIntentClientSecret, configuration: configuration) } }) task.resume() } } struct CheckoutView: View { @ObservedObject var model = CheckoutViewModel() var body: some View { VStack { if model.paymentSheet != nil { Text("Ready to pay.") } else { Text("Loading…") } }.onAppear { model.preparePaymentSheet() } } } ``` [PaymentSheet.PaymentButton](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/PaymentButton.html) を `View` に追加します。これは、SwiftUI の `Button` と同様に動作し、`View` を追加することでカスタマイズされます。ボタンをタップすると PaymentSheet が表示されます。支払いが完了すると、Stripe は PaymentSheet を閉じ、[PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) オブジェクトとともに `onCompletion` ハンドラが呼び出されます。 ```swift @_spi(CustomerSessionBetaAccess) import StripePaymentSheet import SwiftUI class CheckoutViewModel: ObservableObject { let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint @Published var paymentSheet: PaymentSheet? @Published var paymentResult: PaymentSheetResult? func preparePaymentSheet() { // MARK: Fetch the PaymentIntent and Customer information from the backend var request = URLRequest(url: backendCheckoutUrl) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let customerId = json["customer"] as? String, let customerSessionClientSecret = json["customerSessionClientSecret"] as? String, let paymentIntentClientSecret = json["paymentIntent"] as? String, let publishableKey = json["publishableKey"] as? String, let self = self else { // Handle error return } STPAPIClient.shared.publishableKey = publishableKey // MARK: Create a PaymentSheet instance var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret) // Set `allowsDelayedPaymentMethods` to true if your business can handle payment methods // that complete payment after a delay, like SEPA Debit and Sofort. configuration.allowsDelayedPaymentMethods = true DispatchQueue.main.async { self.paymentSheet = PaymentSheet(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) } }) task.resume() } func onPaymentCompletion(result: PaymentSheetResult) { self.paymentResult = result } } struct CheckoutView: View { @ObservedObject var model = CheckoutViewModel() var body: some View { VStack {if let paymentSheet = model.paymentSheet { PaymentSheet.PaymentButton( paymentSheet: paymentSheet, onCompletion: model.onPaymentCompletion ) { Text("Buy") } } else { Text("Loading…") }if let result = model.paymentResult { switch result { case .completed: Text("Payment complete") case .failed(let error): Text("Payment failed: \(error.localizedDescription)") case .canceled: Text("Payment canceled.") } } }.onAppear { model.preparePaymentSheet() } } } ``` `PaymentSheetResult` が `.completed` の場合は、ユーザーに通知します (注文確認画面を表示するなど)。 `allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。 ## 戻り先 URL を設定する [クライアント側] 顧客はお客様のアプリから離れて、(Safari やバンキングアプリなどで) 認証する場合があります。ユーザーが認証後にアプリに自動的に戻れるようにするには、[カスタム URL スキームを構成](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)し、URL を SDK に転送するようにアプリのデリゲートを設定します。Stripe は[ユニバーサルリンク](https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content)には対応していません。 #### SceneDelegate #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } let stripeHandled = StripeAPI.handleURLCallback(with: url) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } } ``` #### AppDelegate #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } return false } ``` #### SwiftUI #### Swift ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { Text("Hello, world!").onOpenURL { incomingURL in let stripeHandled = StripeAPI.handleURLCallback(with: incomingURL) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } } } } } ``` さらに、[PaymentSheet.Configuration](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) オブジェクトの [returnURL](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:6Stripe12PaymentSheetC13ConfigurationV9returnURLSSSgvp) をアプリの URL に設定します。 ```swift var configuration = PaymentSheet.Configuration() configuration.returnURL = "your-app://stripe-redirect" ``` ## 支払い後のイベントを処理する [サーバー側] 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか [Webhook のガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信し、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアントでは、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了する場合、また悪意を持つクライアントがレスポンスを不正操作する場合もあります。非同期型のイベントをリッスンするよう組み込みを設定すると、単一の組み込みで[複数の異なるタイプの支払い方法](https://stripe.com/payments/payment-methods-guide)を受け付けることができます。 Payment Element を使用して支払いを回収する場合は、`payment_intent.succeeded` イベントのほかにこれらのイベントを処理することをお勧めします。 | イベント | 説明 | アクション | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.succeeded) | 顧客が正常に支払いを完了したときに送信されます。 | 顧客に注文の確定を送信し、顧客の注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [payment_intent.processing](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.processing) | 顧客が正常に支払いを開始したが、支払いがまだ完了していない場合に送信されます。このイベントは、多くの場合、顧客が口座引き落としを開始するときに送信されます。その後、`payment_intent.succeeded` イベント、また、失敗の場合は `payment_intent.payment_failed` イベントが送信されます。 | 顧客に注文確認メールを送信し、支払いが保留中であることを示します。デジタル商品では、支払いの完了を待たずに注文のフルフィルメントを行うことが必要になる場合があります。 | | [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed) | 顧客が支払いを試みたが、支払いに失敗する場合に送信されます。 | 支払いが `processing` から `payment_failed` に変わった場合は、顧客に再度支払いを試すように促します。 | ## 組み込みをテストする #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (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)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ---------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | Bancontact、iDEAL | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: Link を有効にする [支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)で Link を有効にすると、顧客は Link のワンクリックのスピーディーな決済ボタンを使用して、支払い情報を安全に保存し、再利用できるようになります。 ### 顧客のメールアドレスを Mobile Payment Element に渡す Link はメールアドレスを使用して顧客を認証します。Stripe では、決済プロセスを効率化するために、できるだけ多くの情報を事前入力することをお勧めします。 顧客の氏名、メールアドレス、電話番号を事前入力するには、`PaymentSheet.Configuration` を初期化した後に `defaultBillingDetails` に顧客情報を指定します。 ```swift var configuration = PaymentSheet.Configuration() configuration.defaultBillingDetails.name = "Jenny Rosen" configuration.defaultBillingDetails.email = "jenny.rosen@example.com" configuration.defaultBillingDetails.phone = "888-888-8888" ``` ## Optional: Apple Pay を有効化する > 決済画面に専用の **Apple Pay** ボタンがある場合は、[Apple Pay ガイド](https://docs.stripe.com/apple-pay.md#present-payment-sheet)に従い、`ApplePayContext` を使用して Apple Pay ボタンからの支払いを回収します。その他の種類の支払い方法を処理するには、`PaymentSheet` を使用できます。 ### Apple 加盟店 ID を登録する Apple Developer Web サイトで [新規 ID を登録](https://developer.apple.com/account/resources/identifiers/add/merchant) して、Apple 加盟店 ID を取得します。 フォームに説明と ID を入力します。説明はお客様の記録用であり、後で変更できます。アプリの名前を ID として使用することをお勧めします (`merchant.com.{{YOUR_APP_NAME}}` など)。 ### 新しい Apple Pay 証明書を作成する 支払いデータを暗号化するためのアプリの証明書を作成します。 ダッシュボードの [iOS certificate settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、**新規アプリケーションを追加**をクリックし、表示されるガイドに従います。 証明書署名リクエスト (CSR) ファイルをダウンロードして、Apple Pay の利用を可能にする安全な証明書を Apple から取得します。 1 つの CSR ファイルを使用して証明書を 1 つだけ発行する必要があります。Apple 加盟店 ID を切り替えた場合、ダッシュボードの [iOS Certificate Settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、新しい CSR と証明書を取得する必要があります。 ### Xcode を使用して組み込む Apple Pay ケイパビリティをアプリに追加します。Xcode でプロジェクト設定を開き、**Signing & Capabilities (署名およびケイパビリティ)** タブを選択して、**Apple Pay** ケイパビリティを追加します。この段階で開発者アカウントへのログインを要求される場合があります。前の手順で作成した加盟店 ID を選択すると、アプリで Apple Pay を受け付けられるようになります。 ![](https://b.stripecdn.com/docs-statics-srv/assets/xcode.a701d4c1922d19985e9c614a6f105bf1.png) Xcode で Apple Pay ケイパビリティを有効化する ### Apple Pay を追加する #### 1 回限りの支払い Apple Pay を PaymentSheet に追加するには、Apple 加盟店 ID と[お客様のビジネスの国コード](https://dashboard.stripe.com/settings/account)で `PaymentSheet.Configuration` を初期化してから、[applePay](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:6Stripe12PaymentSheetC13ConfigurationV8applePayAC05ApplefD0VSgvp) を設定します。 #### iOS (Swift) ```swift var configuration = PaymentSheet.Configuration() configuration.applePay = .init( merchantId: "merchant.com.your_app_name", merchantCountryCode: "US" ) ``` #### 継続支払い Apple Pay を PaymentSheet に追加するには、Apple 加盟店 ID と[お客様のビジネスの国コード](https://dashboard.stripe.com/settings/account)で `PaymentSheet.Configuration` を初期化してから、[applePay](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:6Stripe12PaymentSheetC13ConfigurationV8applePayAC05ApplefD0VSgvp) を設定します。 継続支払いに関する [Apple のガイドライン](https://developer.apple.com/design/human-interface-guidelines/apple-pay#Supporting-subscriptions)に従い、`PKPaymentRequest` で追加の属性を設定する必要もあります。[ApplePayConfiguration.paymentRequestHandlers](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/applepayconfiguration/handlers/paymentrequesthandler) にハンドラーを追加して、請求する予定の金額 (たとえば月額 9.95 USD) を指定して [PKPaymentRequest.paymentSummaryItems](https://developer.apple.com/documentation/passkit/pkpaymentrequest/1619231-paymentsummaryitems) を設定します。 `PKPaymentRequest` で `recurringPaymentRequest` または `automaticReloadPaymentRequest` プロパティを設定することで、[加盟店トークン](https://developer.apple.com/apple-pay/merchant-tokens/)を導入することもできます。 Apple Pay で継続支払いを使用する方法の詳細については、[Apple の PassKit に関するドキュメント](https://developer.apple.com/documentation/passkit/pkpaymentrequest)をご覧ください。 #### iOS (Swift) ```swift let customHandlers = PaymentSheet.ApplePayConfiguration.Handlers( paymentRequestHandler: { request in // PKRecurringPaymentSummaryItem is available on iOS 15 or later if #available(iOS 15.0, *) { let billing = PKRecurringPaymentSummaryItem(label: "My Subscription", amount: NSDecimalNumber(string: "59.99")) // Payment starts today billing.startDate = Date() // Payment ends in one year billing.endDate = Date().addingTimeInterval(60 * 60 * 24 * 365) // Pay once a month. billing.intervalUnit = .month billing.intervalCount = 1 // recurringPaymentRequest is only available on iOS 16 or later if #available(iOS 16.0, *) { request.recurringPaymentRequest = PKRecurringPaymentRequest(paymentDescription: "Recurring", regularBilling: billing, managementURL: URL(string: "https://my-backend.example.com/customer-portal")!) request.recurringPaymentRequest?.billingAgreement = "You'll be billed $59.99 every month for the next 12 months. To cancel at any time, go to Account and click 'Cancel Membership.'" } request.paymentSummaryItems = [billing] request.currencyCode = "USD" } else { // On older iOS versions, set alternative summary items. request.paymentSummaryItems = [PKPaymentSummaryItem(label: "Monthly plan starting July 1, 2022", amount: NSDecimalNumber(string: "59.99"), type: .final)] } return request } ) var configuration = PaymentSheet.Configuration() configuration.applePay = .init(merchantId: "merchant.com.your_app_name", merchantCountryCode: "US", customHandlers: customHandlers) ``` ### 注文の追跡 iOS 16 以降で[注文の追跡](https://developer.apple.com/design/human-interface-guidelines/technologies/wallet/designing-order-tracking)情報を追加するには、`PaymentSheet.ApplePayConfiguration.Handlers` で [authorizationResultHandler](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/applepayconfiguration/handlers/authorizationresulthandler) を設定します。支払いの完了後、Stripe は iOS が Apple Pay の決済画面を閉じる前に実装を呼び出します。 `authorizationResultHandler` の実装で、完了した注文の注文の詳細をサーバーから取得します。提供された [PKPaymentAuthorizationResult](https://developer.apple.com/documentation/passkit/pkpaymentauthorizationresult) に詳細を追加し、変更された結果を返します。 注文の追跡の詳細については、[Apple のウォレットでの注文に関するドキュメント](https://developer.apple.com/documentation/walletorders)をご覧ください。 #### iOS (Swift) ```swift let customHandlers = PaymentSheet.ApplePayConfiguration.Handlers( authorizationResultHandler: { result in do { // Fetch the order details from your service let myOrderDetails = try await MyAPIClient.shared.fetchOrderDetails(orderID: orderID) result.orderDetails = PKPaymentOrderDetails( orderTypeIdentifier: myOrderDetails.orderTypeIdentifier, // "com.myapp.order" orderIdentifier: myOrderDetails.orderIdentifier, // "ABC123-AAAA-1111" webServiceURL: myOrderDetails.webServiceURL, // "https://my-backend.example.com/apple-order-tracking-backend" authenticationToken: myOrderDetails.authenticationToken) // "abc123" // Return your modified PKPaymentAuthorizationResult return result } catch { return PKPaymentAuthorizationResult(status: .failure, errors: [error]) } } ) var configuration = PaymentSheet.Configuration() configuration.applePay = .init(merchantId: "merchant.com.your_app_name", merchantCountryCode: "US", customHandlers: customHandlers) ``` ## カードのスキャンを有効化する iOS をサポートするカードスキャン機能を有効にするには、アプリケーションの `Info.plist` の `NSCameraUsageDescription` (**プライバシー - カメラ利用の詳細**)を設定し、カメラにアクセスする理由を入力して下さい (例:「カードをスキャンするため」)。 ## Optional: ACH 決済を有効にする ACH デビット支払いを有効にするには、アプリの依存関係として `StripeFinancialConnections`を含めます。 [Stripe iOS SDK](https://github.com/stripe/stripe-ios) はオープンソースです。[詳細なドキュメントが提供されており](https://stripe.dev/stripe-ios/index.html)、iOS 13 以降をサポートするアプリと互換性があります。 #### Swift Package Manager SDK をインストールするには、以下のステップに従います。 1. Xcode で、**File (ファイル)** > **Add Package Dependencies… (パッケージ依存関係を追加)** を選択し、リポジトリー URL として `https://github.com/stripe/stripe-ios-spm` を入力します。 1. [リリースページ](https://github.com/stripe/stripe-ios/releases)から最新のバージョン番号を選択します。 1. **StripeFinancialConnections** 製品を[アプリのターゲット](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)に追加します。 #### CocoaPods 1. まだインストールしていない場合は、[CocoaPods](https://guides.cocoapods.org/using/getting-started.html) の最新バージョンをインストールします。 1. 既存の [Podfile](https://guides.cocoapods.org/syntax/podfile.html) がない場合は、以下のコマンドを実行して作成します。 ```bash pod init ``` 1. この行を `Podfile` に追加します。 ```podfile pod 'StripeFinancialConnections' ``` 1. 以下のコマンドを実行します。 ```bash pod install ``` 1. これ以降は、Xcode でプロジェクトを開く際に、`.xcodeproj` ファイルではなく、必ず `.xcworkspace` ファイルを使用するということを忘れないでください。 1. 今後、SDK の最新バージョンに更新するには、以下を実行します。 ```bash pod update StripeFinancialConnections ``` #### Carthage 1. まだインストールしていない場合は、[Carthage](https://github.com/Carthage/Carthage#installing-carthage) の最新バージョンをインストールします。 1. この行を `Cartfile` に追加します。 ```cartfile github "stripe/stripe-ios" ``` 1. [Carthage のインストール手順](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos)に従います。必ず、[こちら](https://github.com/stripe/stripe-ios/tree/master/StripeFinancialConnections/README.md#manual-linking)にリストされている必要なフレームワークのすべてを埋め込んでください。 1. 今後、SDK の最新バージョンに更新するには、以下のコマンドを実行します。 ```bash carthage update stripe-ios --platform ios ``` #### 手動のフレームワーク 1. Stripe の [GitHub リリースページ](https://github.com/stripe/stripe-ios/releases/latest)に移動して、**Stripe.xcframework.zip** をダウンロードして解凍します。 1. **StripeFinancialConnections.xcframework** を、Xcode プロジェクトの **General (一般) ** 設定の **Embedded Binaries (埋め込みバイナリー)** セクションにドラッグします。**Copy items if needed (必要に応じてアイテムをコピーする)** を必ず選択してください。 1. [こちら](https://github.com/stripe/stripe-ios/tree/master/StripeFinancialConnections/README.md#manual-linking)にリストされている必要なフレームワークのすべてに対して、ステップ 2 を繰り返します。 1. 今後、Stripe の SDK の最新バージョンに更新するには、ステップ 1 から 3 を繰り返します。 > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases (リリース)](https://github.com/stripe/stripe-ios/releases) ページをご覧ください。リポジトリの[リリースをウォッチ](https://help.github.com/en/articles/watching-and-unwatching-releases-for-a-repository#watching-releases-for-a-repository)して、新しいリリースの公開時に通知を受け取ることも可能です。 ## Optional: 画面をカスタマイズする カスタマイズはすべて、[PaymentSheet.Configuration](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) オブジェクトで設定されます。 ### デザイン Customize colors, fonts, and so on to match the look and feel of your app by using the [appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=ios). ### 決済手段のレイアウト [paymentMethodLayout](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/configuration-swift.struct/paymentmethodlayout) を使用して、画面上の決済手段のレイアウトを設定します。横や縦に表示することも、Stripe がレイアウトを自動で最適化するように設定することもできます。 ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-mpe-payment-method-layouts.9d0513e2fcec5660378ba1824d952054.png) #### Swift ```swift var configuration = PaymentSheet.Configuration() configuration.paymentMethodLayout = .automatic ``` ### ユーザーの住所を収集する [Address Element](https://docs.stripe.com/elements/address-element.md?platform=ios) を使用して、顧客から国内および国外の配送先住所や請求先住所を収集します。 ### 加盟店の表示名 [merchantDisplayName](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:18StripePaymentSheet0bC0C13ConfigurationV19merchantDisplayNameSSvp) を設定し、顧客に表示するビジネス名を指定します。デフォルトではアプリ名になります。 #### Swift ```swift var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "My app, Inc." ``` ### ダークモード `PaymentSheet` は、ユーザーのシステム全体の表示設定 (ライト / ダークモード) に合わせて自動的に調整されます。アプリがダークモードに対応していない場合は、[style](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:18StripePaymentSheet0bC0C13ConfigurationV5styleAC18UserInterfaceStyleOvp) を `alwaysLight` または `alwaysDark` モードに設定できます。 ```swift var configuration = PaymentSheet.Configuration() configuration.style = .alwaysLight ``` ### デフォルトの請求詳細 支払い画面で収集される請求詳細のデフォルト値を設定するには、`defaultBillingDetails` プロパティーを設定します。`PaymentSheet` の各フィールドに、指定したそれらの値が事前に読み込まれます。 ```swift var configuration = PaymentSheet.Configuration() configuration.defaultBillingDetails.address.country = "US" configuration.defaultBillingDetails.email = "foo@bar.com" ``` ### 請求の詳細の収集 `billingDetailsCollectionConfiguration` を使用して、決済画面で請求の詳細を収集する方法を指定します。 顧客の名前、メールアドレス、電話番号、住所を収集できます。 支払い方法で必須の請求詳細のみを収集する場合は、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を true に設定します。その場合、`PaymentSheet.Configuration.defaultBillingDetails` が支払い方法の[請求詳細](https://docs.stripe.com/api/payment_methods/object.md?lang=node#payment_method_object-billing_details)として設定されます。 支払い方法で必ずしも必須ではない追加の請求詳細を収集する場合は、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を false に設定します。 その場合、`PaymentSheet` で収集した請求詳細が支払い方法の請求詳細として設定されます。 ```swift var configuration = PaymentSheet.Configuration() configuration.defaultBillingDetails.email = "foo@bar.com" configuration.billingDetailsCollectionConfiguration.name = .always configuration.billingDetailsCollectionConfiguration.email = .never configuration.billingDetailsCollectionConfiguration.address = .full configuration.billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod = true ``` > 情報の収集に適用される法律については、弁護士に相談してください。電話番号は、取引に必要な場合にのみ収集してください。 ## Optional: ユーザーのログアウトを処理する `PaymentSheet` は、ユーザーがアプリ内で Link を使用したかどうかを記憶するために、情報をローカルに保存します。`PaymentSheet` の内部状態をクリアするには、ユーザーがログアウトした際に `PaymentSheet.resetCustomer()` メソッドを呼び出します。 ```swift import UIKit import StripePaymentSheet class MyViewController: UIViewController { @objc func didTapLogoutButton() { PaymentSheet.resetCustomer() // Other logout logic required by your app } } ``` ## Optional: UI で支払いを完了する 支払い方法の詳細を収集するためにのみ支払い画面を表示して、後で `confirm` メソッドを呼び出して、アプリの UI で支払いを完了できます。これは、カスタムの購入ボタンがある場合や、支払いの詳細を収集した後で追加のステップが必要な場合に便利です。 ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-multi-step.cd631ea4f1cd8cf3f39b6b9e1e92b6c5.png) アプリの UI で支払いを完了する #### UIKit 以下のステップでは、アプリの UI で支払いを完了する方法を説明します。[GitHub](https://github.com/stripe/stripe-ios/blob/master/Example/PaymentSheet%20Example/PaymentSheet%20Example/ExampleCustomCheckoutViewController.swift) でサンプルの実装をご覧下さい。 1. 最初に、`PaymentSheet` ではなく、[PaymentSheet.FlowController](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller) を初期化し、その `paymentOption` プロパティで UI を更新します。このプロパティには、顧客が最初に選択したデフォルトの支払い方法を表す画像とラベルが含まれています。 ```swift PaymentSheet.FlowController.create(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) { [weak self] result in switch result { case .failure(let error): print(error) case .success(let paymentSheetFlowController): self?.paymentSheetFlowController = paymentSheetFlowController // Update your UI using paymentSheetFlowController.paymentOption } } ``` 1. 次に、`presentPaymentOptions` を呼び出し、支払いの詳細を収集します。完了したら、`paymentOption` プロパティで再度 UI を更新します。 ```swift paymentSheetFlowController.presentPaymentOptions(from: self) { // Update your UI using paymentSheetFlowController.paymentOption } ``` 1. 最後に、`confirm` を呼び出します。 ```swift paymentSheetFlowController.confirm(from: self) { paymentResult in // MARK: Handle the payment result switch paymentResult { case .completed: print("Payment complete!") case .canceled: print("Canceled!") case .failed(let error): print(error) } } ``` #### SwiftUI 以下のステップでは、アプリの UI で支払いを完了する方法を説明します。[GitHub](https://github.com/stripe/stripe-ios/blob/master/Example/PaymentSheet%20Example/PaymentSheet%20Example/ExampleSwiftUICustomPaymentFlow.swift) でサンプルの実装をご覧下さい。 1. 最初に、`PaymentSheet` ではなく、[PaymentSheet.FlowController](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller) を初期化します。その `paymentOption` プロパティには、顧客が現在選択している支払い方法を表す画像とラベルが含まれており、これを UI で使用することができます。 ```swift PaymentSheet.FlowController.create(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) { [weak self] result in switch result { case .failure(let error): print(error) case .success(let paymentSheetFlowController): self?.paymentSheetFlowController = paymentSheetFlowController // Use the paymentSheetFlowController.paymentOption properties in your UI myPaymentMethodLabel = paymentSheetFlowController.paymentOption?.label ?? "Select a payment method" myPaymentMethodImage = paymentSheetFlowController.paymentOption?.image ?? UIImage(systemName: "square.and.pencil")! } } ``` 1. [PaymentSheet.FlowController.PaymentOptionsButton](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller/paymentoptionsbutton) を使用して、支払いの詳細を収集するための画面を表示するボタンをラップします。`PaymentSheet.FlowController` が `onSheetDismissed` 引数を呼び出すと、`PaymentSheet.FlowController` インスタンスの `paymentOption` に現在選択されている支払い方法が反映されます。 ```swift PaymentSheet.FlowController.PaymentOptionsButton( paymentSheetFlowController: paymentSheetFlowController, onSheetDismissed: { myPaymentMethodLabel = paymentSheetFlowController.paymentOption?.label ?? "Select a payment method" myPaymentMethodImage = paymentSheetFlowController.paymentOption?.image ?? UIImage(systemName: "square.and.pencil")! }, content: { /* An example button */ HStack { Text(myPaymentMethodLabel) Image(uiImage: myPaymentMethodImage) } } ) ``` 1. [PaymentSheet.FlowController.PaymentOptionsButton](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller/paymentoptionsbutton) を使用して、支払いを確定するボタンをラップします。 ```swift PaymentSheet.FlowController.ConfirmButton( paymentSheetFlowController: paymentSheetFlowController, onCompletion: { result in // MARK: Handle the payment result switch result { case .completed: print("Payment complete!") case .canceled: print("Canceled!") case .failed(let error): print(error) } }, content: { /* An example button */ Text("Pay") } ) ``` `allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。 ## Optional: 確定時のセキュリティコードの再収集を有効にする PaymentIntent の確定時に、保存されたカードのセキュリティコードを再収集する次の手順は、実装システムに以下が含まれていることを前提としています。 - 決済の詳細を収集する前の PaymentIntent の作成 ### インテント作成のパラメーターを更新する 支払いの確定時にセキュリティコードを再収集するには、PaymentIntent の作成時に `require_cvc_recollection` を含めます。 #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an Ephemeral Key for the Customer curl https://api.stripe.com/v1/ephemeral_keys \ -u <>: \ -H "Stripe-Version: 2026-02-25.clover" \ -H "Stripe-Account: 2026-02-25.clover" \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \-d "payment_method_options[card][require_cvc_recollection]"=true \ # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. -d "automatic_payment_methods[enabled]"=true \ ``` # Android でのアプリ内実装 > This is a Android でのアプリ内実装 for when payment-ui is mobile and platform is android. View the full page at https://docs.stripe.com/payments/accept-a-payment?payment-ui=mobile&platform=android. ![](https://b.stripecdn.com/docs-statics-srv/assets/android-overview.471eaf89a760f5b6a757fd96b6bb9b60.png) [PaymentSheet](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/index.html) クラスを使用して、Stripe の構築済み決済 UI を Android アプリの決済フローに組み込みます。 ## Stripe を設定する [サーバー側] [クライアント側] まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。 ### サーバー側 この接続方法では、Stripe API と通信するエンドポイントがサーバー上に必要です。サーバーから 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' ``` ### クライアント側 [Stripe Android SDK](https://github.com/stripe/stripe-android) はオープンソースであり、[詳細なドキュメントが提供されています](https://stripe.dev/stripe-android/)。 SDK をインストールするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの `dependencies` ブロックに `stripe-android` を追加します。 #### Kotlin ```kotlin plugins { id("com.android.application") } android { ... } dependencies { // ... // Stripe Android SDK implementation("com.stripe:stripe-android:23.0.2") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.0.2") } ``` > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases](https://github.com/stripe/stripe-android/releases) ページをご覧ください。新しいリリースの公開時に通知を受け取るには、[リポジトリのリリースを確認](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)してください。 ## 支払い方法を有効にする [支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)を表示して、サポートする支払い方法を有効にします。*PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。 多くの顧客から決済を受け付けられるよう、Stripe では、カードやその他一般的な決済手段がデフォルトで有効になっていますが、ビジネスや顧客に適した追加の決済手段を有効にすることをお勧めします。プロダクトと決済手段のサポートについては[決済手段のサポート](https://docs.stripe.com/payments/payment-methods/payment-method-support.md)を、手数料については[料金体系ページ](https://stripe.com/pricing/local-payment-methods)をご覧ください。 ## エンドポイントを追加する [サーバー側] > #### 注 > > PaymentIntent の作成前に PaymentSheet を表示するには、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=payment)をご覧ください。 Connect プラットフォームが [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、Stripe の [ガイド](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご確認の上、コード内の `Customer` およびイベント参照を同等の Accounts v2 API リファレンスに置き換えてください。 この接続方法では、以下の 3 つの Stripe API オブジェクトを使用します。 1. [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md): Stripe はこれを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して支払いの試行と支払い状態の変化を追跡します。 1. (オプション) [Customer (顧客)](https://docs.stripe.com/api/customers.md): 今後の支払いに備えて決済手段を設定するには、決済手段を*Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に関連付ける必要があります。Customer オブジェクトは、顧客がビジネスでアカウントを作成するときに作成します。顧客がゲストとして支払いを行う場合は、支払いの前に Customer オブジェクトを作成し、後でこのオブジェクトを顧客のアカウントを表す内部表現に関連付けることができます。 1. (オプション) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md): Customer オブジェクトの情報は機密情報であるため、アプリから直接取得することはできません。CustomerSession により、SDK に Customer への範囲を設定した一時的なアクセス権が付与され、また追加の設定オプションが提供されます。すべての[設定オプション](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)のリストをご覧ください。 > Customer にカードを保存したことがなく、リピート顧客に保存されたカードの再利用を許可しない場合は、実装で Customer オブジェクトおよび CustomerSession オブジェクトを省略できます。 セキュリティ上の理由により、アプリでこれらのオブジェクトを作成することはできません。代わりに、サーバー側で以下を行うエンドポイントを追加します。 1. Customer を取得するか、新規作成する。 1. 顧客の [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) を作成します。 1. [amount](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-amount)、[currency](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-currency)、[customer](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer) を指定して PaymentIntent を作成します。 1. PaymentIntent の *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))、CustomerSession の `client_secret`、Customer の [id](https://docs.stripe.com/api/customers/object.md#customer_object-id)、および貴社の[公開可能キー](https://dashboard.stripe.com/apikeys)をアプリに返します。 決済プロセス中に顧客に表示される支払い方法は、PaymentIntent にも含まれています。Stripe にダッシュボードの設定から支払い方法を取得するよう指定することも、手動でリストに表示することもできます。選択したオプションにかかわらず、顧客に表示される支払い方法は、PaymentIntent で渡す通貨によって絞り込まれることにご注意ください。たとえば、PaymentIntent で `eur` を渡し、ダッシュボードで OXXO が有効になっている場合、OXXO は `eur` による決済に対応していないため、顧客に表示されません。 構築済みのシステムで、決済手段を提供するためにコードベースのオプションが必要になる場合を除き、自動化されたオプションを使用することをお勧めします。これは、Stripe が通貨、決済手段の制約、その他のパラメーターを評価して、対応可能な決済手段を決定するためです。自動化されたオプションでは、購入完了率の向上につながり、使用通貨と顧客の所在地に最適な決済手段が優先的に表示されます。 #### ダッシュボードで支払い方法を管理する 支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。PaymentIntent は、ダッシュボードで設定された支払い方法を使用して作成されます。ダッシュボードを使用しない場合や、支払い方法を手動で指定する場合は、`payment_method_types` 属性を使用して支払い方法を一覧表示することができます。 #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. -d "automatic_payment_methods[enabled]"=true \ ``` #### 支払い方法を手動で一覧表示する #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ -d "payment_method_types[]"="bancontact" \ -d "payment_method_types[]"="card" \ -d "payment_method_types[]"="ideal" \ -d "payment_method_types[]"="klarna" \ -d "payment_method_types[]"="sepa_debit" \ ``` > 各決済手段は PaymentIntent で渡された通貨に対応している必要があり、ビジネスは、各決済手段を使用できる国のいずれかに所在する必要があります。対応状況について、詳細は[決済手段の導入オプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)ページをご覧ください。 ## 支払いの詳細を収集する [クライアント側] 決済ページでは、Mobile Payment Element を表示する前に以下を実行する必要があります。 - 購入商品と合計金額を表示する - [Address Element](https://docs.stripe.com/elements/address-element.md?platform=android) を使用して必要な配送先情報を収集する - Stripe の UI を表示する決済ボタンを含める #### Jetpack Compose 決済アクティビティーの `onCreate` 内で `PaymentSheet` インスタンスを[初期化](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-builder/index.html)して、結果を処理するメソッドを渡します。 ```kotlin import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult @Composable fun App() { val paymentSheet = remember { PaymentSheet.Builder(::onPaymentSheetResult) }.build() } private fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { // implemented in the next steps } ``` 次に、前のステップで作成したエンドポイントから、PaymentIntent のClient Secret、顧客 SessionのClient Secret、顧客 ID、公開可能キーを取得します。公開可能キーは `PaymentConfiguration` を使用して設定し、その他は保存して、PaymentSheet を表示するときに使用します。 ```kotlin import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberimport androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import com.stripe.android.PaymentConfiguration import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult @Composable fun App() { val paymentSheet = remember { PaymentSheet.Builder(::onPaymentSheetResult) }.build()val context = LocalContext.current var customerConfig by remember { mutableStateOf(null) } varpaymentIntentClientSecret by remember { mutableStateOf(null) } LaunchedEffect(context) { // Make a request to your own server and retrieve payment configurations val networkResult = ... if (networkResult.isSuccess) {paymentIntentClientSecret = networkResult.paymentIntent customerConfig = PaymentSheet.CustomerConfiguration.createWithCustomerSession( id = networkResult.customer, clientSecret = networkResult.customerSessionClientSecret )PaymentConfiguration.init(context, networkResult.publishableKey)} } } private fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { // implemented in the next steps } ``` 顧客が決済ボタンをタップしたら、[presentWithPaymentIntent](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/index.html#1814490530%2FFunctions%2F2002900378) を呼び出して支払い画面を表示します。顧客が決済を完了すると、画面が閉じ、[PaymentSheetResult](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result/index.html) とともに [PaymentSheetResultCallback](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result-callback/index.html) が呼び出されます。 ```kotlin import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import com.stripe.android.PaymentConfiguration import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult @Composable fun App() { val paymentSheet = remember { PaymentSheet.Builder(::onPaymentSheetResult) }.build() val context = LocalContext.current var customerConfig by remember { mutableStateOf(null) } var paymentIntentClientSecret by remember { mutableStateOf(null) } LaunchedEffect(context) { // Make a request to your own server and retrieve payment configurations val networkResult = ... if (networkResult.isSuccess) { paymentIntentClientSecret = networkResult.paymentIntent customerConfig = PaymentSheet.CustomerConfiguration.createWithCustomerSession( id = networkResult.customer, clientSecret = networkResult.customerSessionClientSecret ) PaymentConfiguration.init(context, networkResult.publishableKey) } }Button( onClick = { val currentConfig = customerConfig val currentClientSecret =paymentIntentClientSecret if (currentConfig != null && currentClientSecret != null) { presentPaymentSheet(paymentSheet, currentConfig, currentClientSecret) } } ) { Text("Checkout") } }private fun presentPaymentSheet( paymentSheet: PaymentSheet, customerConfig: PaymentSheet.CustomerConfiguration,paymentIntentClientSecret: String ) { paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, PaymentSheet.Configuration.Builder(merchantDisplayName = "My merchant name") .customer(customerConfig) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. .allowsDelayedPaymentMethods(true) .build() ) } private fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) {when(paymentSheetResult) { is PaymentSheetResult.Canceled -> { print("Canceled") } is PaymentSheetResult.Failed -> { print("Error: ${paymentSheetResult.error}") } is PaymentSheetResult.Completed -> { // Display for example, an order confirmation screen print("Completed") } } } ``` #### ビュー (クラシック) 決済アクティビティーの `onCreate` 内で、結果を処理するメソッドを渡して、`PaymentSheet` インスタンスを[初期化](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/index.html#-394860221%2FConstructors%2F2002900378)します。 #### Kotlin ```kotlin import com.stripe.android.paymentsheet.PaymentSheet class CheckoutActivity : AppCompatActivity() { lateinit var paymentSheet: PaymentSheet override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) paymentSheet = PaymentSheet.Builder(::onPaymentSheetResult).build(this) } fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { // implemented in the next steps } } ``` 次に、前のステップで作成したエンドポイントから、PaymentIntent のClient Secret、顧客 SessionのClient Secret、顧客 ID、公開可能キーを取得します。公開可能キーは `PaymentConfiguration` を使用して設定し、その他は保存して、PaymentSheet を表示するときに使用します。 #### Kotlin ```kotlin import com.stripe.android.paymentsheet.PaymentSheet class CheckoutActivity : AppCompatActivity() { lateinit var paymentSheet: PaymentSheetlateinit var customerConfig: PaymentSheet.CustomerConfiguration lateinit varpaymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) paymentSheet = PaymentSheet.Builder(::onPaymentSheetResult).build(this)lifecycleScope.launch { // Make a request to your own server and retrieve payment configurations val networkResult = MyBackend.getPaymentConfig() if (networkResult.isSuccess) {paymentIntentClientSecret = networkResult.paymentIntent customerConfig = PaymentSheet.CustomerConfiguration.createWithCustomerSession( id = networkResult.customer, clientSecret = networkResult.customerSessionClientSecret )PaymentConfiguration.init(context, networkResult.publishableKey)} } } fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { // implemented in the next steps } } ``` 顧客が決済ボタンをタップしたら、[presentWithPaymentIntent](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/index.html#1814490530%2FFunctions%2F2002900378) を呼び出して支払い画面を表示します。顧客が決済を完了すると、画面が閉じ、[PaymentSheetResult](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result/index.html) とともに [PaymentSheetResultCallback](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result-callback/index.html) が呼び出されます。 #### Kotlin ```kotlin // ... class CheckoutActivity : AppCompatActivity() { lateinit var paymentSheet: PaymentSheet lateinit var customerConfig: PaymentSheet.CustomerConfiguration lateinit var paymentIntentClientSecret: String // ...fun presentPaymentSheet() { paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, PaymentSheet.Configuration.Builder(merchantDisplayName = "My merchant name") .customer(customerConfig) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. .allowsDelayedPaymentMethods(true) .build() ) } fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) {when(paymentSheetResult) { is PaymentSheetResult.Canceled -> { print("Canceled") } is PaymentSheetResult.Failed -> { print("Error: ${paymentSheetResult.error}") } is PaymentSheetResult.Completed -> { // Display for example, an order confirmation screen print("Completed") } } } } ``` `allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。 ## 支払い後のイベントを処理する [サーバー側] 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか [Webhook のガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信し、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアントでは、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了する場合、また悪意を持つクライアントがレスポンスを不正操作する場合もあります。非同期型のイベントをリッスンするよう組み込みを設定すると、単一の組み込みで[複数の異なるタイプの支払い方法](https://stripe.com/payments/payment-methods-guide)を受け付けることができます。 Payment Element を使用して支払いを回収する場合は、`payment_intent.succeeded` イベントのほかにこれらのイベントを処理することをお勧めします。 | イベント | 説明 | アクション | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.succeeded) | 顧客が正常に支払いを完了したときに送信されます。 | 顧客に注文の確定を送信し、顧客の注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [payment_intent.processing](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.processing) | 顧客が正常に支払いを開始したが、支払いがまだ完了していない場合に送信されます。このイベントは、多くの場合、顧客が口座引き落としを開始するときに送信されます。その後、`payment_intent.succeeded` イベント、また、失敗の場合は `payment_intent.payment_failed` イベントが送信されます。 | 顧客に注文確認メールを送信し、支払いが保留中であることを示します。デジタル商品では、支払いの完了を待たずに注文のフルフィルメントを行うことが必要になる場合があります。 | | [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed) | 顧客が支払いを試みたが、支払いに失敗する場合に送信されます。 | 支払いが `processing` から `payment_failed` に変わった場合は、顧客に再度支払いを試すように促します。 | ## 組み込みをテストする #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (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)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ---------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | Bancontact、iDEAL | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: Link を有効にする [支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)で Link を有効にすると、顧客は Link のワンクリックのスピーディーな決済ボタンを使用して、支払い情報を安全に保存し、再利用できるようになります。 ### 顧客のメールアドレスを Mobile Payment Element に渡す Link はメールアドレスを使用して顧客を認証します。Stripe では、決済プロセスを効率化するために、できるだけ多くの情報を事前入力することをお勧めします。 顧客の氏名、メールアドレス、電話番号を事前入力するには、`PaymentSheet.Configuration` を初期化する際に `defaultBillingDetails` に顧客情報を指定します。 #### Kotlin ```kotlin val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Example, Inc.") .defaultBillingDetails( PaymentSheet.BillingDetails( name = "Jenny Rosen", email = "jenny.rosen@example.com", phone = "888-888-8888" ) ) .build() ``` ## Optional: Google Pay を有効化する ### 実装方法を設定する Google Pay を使用するには、まず以下を **AndroidManifest.xml** の `` に追加し、Google Pay API を有効化します。 ```xml ... ``` 詳細は、Google Pay の Android 向け [Google Pay API を設定する](https://developers.google.com/pay/api/android/guides/setup) を参照してください。 ### Google Pay を追加する 組み込みに Google Pay を追加するには、[PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) を初期化する際に、お客様の Google Pay 環境 (本番またはテスト) と[ビジネスの国コード](https://dashboard.stripe.com/settings/account)を指定して [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html) を渡します。 #### Kotlin ```kotlin val googlePayConfiguration = PaymentSheet.GooglePayConfiguration( environment = PaymentSheet.GooglePayConfiguration.Environment.Test, countryCode = "US", currencyCode = "USD" // Required for Setup Intents, optional for Payment Intents ) val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "My merchant name") .googlePay(googlePayConfiguration) .build() ``` ### Google Pay をテストする Google では、[テストクレジットカードスイート](https://developers.google.com/pay/api/android/guides/resources/test-card-suite) を使用してテスト決済を行うことができます。Stripe [テストカード](https://docs.stripe.com/testing.md) をテストスイートと併用できます。 Google Pay がサポートされている国では、シミュレーションされたデバイスではなく、物理的な Android デバイスを使用して Google Pay をテストする必要があります。Google ウォレットに保存した実際のクレジットカードを使用して、テスト用デバイスの Google アカウントにログインします。 ## Optional: カードのスキャンを有効化する カードスキャンサポートを有効にするには、[Google Pay & Wallet Console](https://pay.google.com/business/console?utm_source=devsite&utm_medium=devsite&utm_campaign=devsite) から Google Pay API への[本番アクセスをリクエスト](https://developers.google.com/pay/api/android/guides/test-and-deploy/request-prod-access)します。 - Google Pay を有効にしている場合、対象のデバイスの UI でカードスキャン機能が自動的に利用可能になります。対象のデバイスの詳細については、[Google Pay API の制約](https://developers.google.com/pay/payment-card-recognition/debit-credit-card-recognition)をご覧ください。 - **重要:** カードスキャン機能は、[Google Pay & Wallet Console](https://pay.google.com/business/console) に登録された同じ署名キーで署名されたビルドにのみ表示されます。異なる署名キーを使用したテストまたはデバッグビルド (Firebase App Tester を通じて配布されたビルドなど) では、 **カードをスキャン** オプションは表示されません。プレリリースビルドでカードスキャンをテストするには、以下のいずれかを行う必要があります。 - 本番環境の署名キーを使用してテストビルドに署名する - Google Pay & Wallet Console にテスト署名キーのフィンガープリントを追加する ## Optional: ACH 決済を有効にする ACH デビット決済を有効にするには、アプリの依存関係として Financial Connections を指定します。 [Stripe Android SDK](https://github.com/stripe/stripe-android) はオープンソースであり、[詳細なドキュメントが提供されています](https://stripe.dev/stripe-android/)。 SDK をインストールするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの `dependencies` ブロックに `financial-connections` を追加します。 #### Kotlin ```kotlin plugins { id("com.android.application") } android { ... } dependencies { // ... // Financial Connections Android SDK implementation("com.stripe:financial-connections:23.0.2") } ``` > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases](https://github.com/stripe/stripe-android/releases) ページをご覧ください。新しいリリースの公開時に通知を受け取るには、[リポジトリのリリースを確認](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)してください。 ## Optional: 画面をカスタマイズする すべてのカスタマイズは、[PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html) オブジェクトを使用して設定されます。 ### デザイン Customize colors, fonts, and more to match the look and feel of your app by using the [appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=android). ### 決済手段のレイアウト [paymentMethodLayout](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/-builder/index.html#2123253356%2FFunctions%2F2002900378) を使用して、画面上の決済手段のレイアウトを設定します。横や縦に表示することも、Stripe がレイアウトを自動で最適化するように設定することもできます。 ![](https://b.stripecdn.com/docs-statics-srv/assets/android-mpe-payment-method-layouts.3bcfe828ceaad1a94e0572a22d91733f.png) #### Kotlin ```kotlin PaymentSheet.Configuration.Builder("Example, Inc.") .paymentMethodLayout(PaymentSheet.PaymentMethodLayout.Automatic) .build() ``` ### ユーザーの住所を収集する [Address Element](https://docs.stripe.com/elements/address-element.md?platform=android) を使用して、顧客から国内および国外の配送先住所や請求先住所を収集します。 ### ビジネス表示名 [merchantDisplayName](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html#-191101533%2FProperties%2F2002900378) を設定し、顧客に表示するビジネス名を指定します。デフォルトではアプリ名になります。 #### Kotlin ```kotlin PaymentSheet.Configuration.Builder( merchantDisplayName = "My app, Inc." ).build() ``` ### ダークモード `PaymentSheet` は、ユーザーのシステム全体の表示設定 (ライト/ダークモード) に合わせてデフォルトで自動的に調整されます。これを変更するには、アプリでライトモードまたはダークモードを設定します。 #### Kotlin ```kotlin // force dark AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) // force light AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) ``` ### デフォルトの請求詳細 支払い画面で収集される請求詳細のデフォルト値を設定するには、`defaultBillingDetails` プロパティーを設定します。`PaymentSheet` の各フィールドに、指定したそれらの値が事前に読み込まれます。 #### Kotlin ```kotlin val address = PaymentSheet.Address(country = "US") val billingDetails = PaymentSheet.BillingDetails( address = address, email = "foo@bar.com" ) val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Merchant, Inc.") .defaultBillingDetails(billingDetails) .build() ``` ### 請求先情報の収集を設定する `BillingDetailsCollectionConfiguration` を使用して、PaymentSheet で請求詳細を収集する方法を指定します。 顧客の名前、メールアドレス、電話番号、住所を収集できます。 UI でデフォルトの請求詳細が収集されない場合でも、それらの詳細を PaymentMethod オブジェクトに関連付けるには、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を `true` に設定します。 #### Kotlin ```kotlin val billingDetails = PaymentSheet.BillingDetails( email = "foo@bar.com" ) val billingDetailsCollectionConfiguration = BillingDetailsCollectionConfiguration( attachDefaultsToPaymentMethod = true, name = BillingDetailsCollectionConfiguration.CollectionMode.Always, email = BillingDetailsCollectionConfiguration.CollectionMode.Never, address = BillingDetailsCollectionConfiguration.AddressCollectionMode.Full, ) val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Merchant, Inc.") .defaultBillingDetails(billingDetails) .billingDetailsCollectionConfiguration(billingDetailsCollectionConfiguration) .build() ``` > 情報の収集に適用される法律については、弁護士に相談してください。電話番号は、取引に必要な場合にのみ収集してください。 ## Optional: ユーザーのログアウトを処理する `PaymentSheet` は、ユーザーがアプリ内で Link を使用したかどうかを記憶するために、情報をローカルに保存します。`PaymentSheet` の内部状態をクリアするには、ユーザーがログアウトした際に `PaymentSheet.resetCustomer()` メソッドを呼び出します。 #### Kotlin ```kotlin class MyActivity: Activity { fun onLogoutButtonClicked() { PaymentSheet.resetCustomer(this) // Other logout logic required by your app } } ``` ## Optional: UI で支払いを完了する 支払い画面を表示して支払い方法の詳細のみを収集し、アプリの UI に戻って支払いを完了できます。これは、カスタムの購入ボタンがある場合や、支払いの詳細を収集した後で追加のステップが必要な場合に便利です。 ![](https://b.stripecdn.com/docs-statics-srv/assets/android-multi-step.84d8a0a44b1baa596bda491322b6d9fd.png) > 導入サンプルは[GitHubで入手できます](https://github.com/stripe/stripe-android/blob/master/paymentsheet-example/src/main/java/com/stripe/android/paymentsheet/example/samples/ui/paymentsheet/custom_flow/CustomFlowActivity.kt)。 1. 最初に、[Builder](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/-builder/index.html) メソッドのいずれかを使用して、`PaymentSheet` ではなく [PaymentSheet.FlowController](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/index.html) を初期化します。 #### Android (Kotlin) ```kotlin class CheckoutActivity : AppCompatActivity() { private lateinit var flowController: PaymentSheet.FlowController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val flowController = PaymentSheet.FlowController.Builder( resultCallback = ::onPaymentSheetResult, paymentOptionResultCallback = ::onPaymentOption, ).build(this) } } ``` 1. 次に、バックエンドから取得した Stripe オブジェクトキーで `configureWithPaymentIntent` を呼び出し、[getPaymentOption()](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/index.html#-2091462043%2FFunctions%2F2002900378) を使用してコールバックで UI を更新します。ここには、顧客が現在選択している決済手段を表す画像とラベルが含まれています。 #### Android (Kotlin) ```kotlin flowController.configureWithPaymentIntent( paymentIntentClientSecret = paymentIntentClientSecret, configuration = PaymentSheet.Configuration.Builder("Example, Inc.") .customer(PaymentSheet.CustomerConfiguration( id = customerId, ephemeralKeySecret = ephemeralKeySecret )) .build() ) { isReady, error -> if (isReady) { // Update your UI using `flowController.getPaymentOption()` } else { // handle FlowController configuration failure } } ``` 1. 次に、[presentPaymentOptions](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/index.html#449924733%2FFunctions%2F2002900378) を呼び出して、決済の詳細を収集します。顧客が操作を完了すると、画面は閉じ、すでに `create` で渡されている [paymentOptionCallback](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-option-callback/index.html) が呼び出されます。このメソッドを実装し、返された `paymentOption` で UI を更新します。 #### Android (Kotlin) ```kotlin // ... flowController.presentPaymentOptions() // ... private fun onPaymentOption(paymentOptionResult: PaymentOptionResult) { val paymentOption = paymentOptionResult.paymentOption if (paymentOption != null) { paymentMethodButton.text = paymentOption.label paymentMethodButton.setCompoundDrawablesRelativeWithIntrinsicBounds( paymentOption.drawableResourceId, 0, 0, 0 ) } else { paymentMethodButton.text = "Select" paymentMethodButton.setCompoundDrawablesRelativeWithIntrinsicBounds( null, null, null, null ) } } ``` 1. 最後に、[confirm](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/index.html#-479056656%2FFunctions%2F2002900378) を呼び出して支払いを完了します。顧客が操作を完了すると、画面は閉じ、すでに `create` で渡されている [paymentResultCallback](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result-callback/index.html#237248767%2FFunctions%2F2002900378) が呼び出されます。 #### Android (Kotlin) ```kotlin // ... flowController.confirmPayment() // ... private fun onPaymentSheetResult( paymentSheetResult: PaymentSheetResult ) { when (paymentSheetResult) { is PaymentSheetResult.Canceled -> { // Payment canceled } is PaymentSheetResult.Failed -> { // Payment Failed. See logcat for details or inspect paymentSheetResult.error } is PaymentSheetResult.Completed -> { // Payment Complete } } } ``` `allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。 ## Optional: 確定時のセキュリティコードの再収集を有効にする PaymentIntent の確定時に、保存されたカードのセキュリティコードを再収集する次の手順は、実装システムに以下が含まれていることを前提としています。 - 決済の詳細を収集する前の PaymentIntent の作成 ### インテント作成のパラメーターを更新する 支払いの確定時にセキュリティコードを再収集するには、PaymentIntent の作成時に `require_cvc_recollection` を含めます。 #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an Ephemeral Key for the Customer curl https://api.stripe.com/v1/ephemeral_keys \ -u <>: \ -H "Stripe-Version: 2026-02-25.clover" \ -H "Stripe-Account: 2026-02-25.clover" \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \-d "payment_method_options[card][require_cvc_recollection]"=true \ # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. -d "automatic_payment_methods[enabled]"=true \ ``` # React Native でのアプリ内実装 > This is a React Native でのアプリ内実装 for when payment-ui is mobile and platform is react-native. View the full page at https://docs.stripe.com/payments/accept-a-payment?payment-ui=mobile&platform=react-native. ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-overview.9e0d68d009dc005f73a6f5df69e00458.png) この統合は、決済の詳細収集や決済確認など、決済に必要なすべてのステップを一つのシートにまとめ、アプリ上部に表示されます。 ## Stripe を設定する [サーバー側] [クライアント側] まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。 ### サーバー側 この接続方法では、Stripe API と通信するエンドポイントがサーバー上に必要です。サーバーから 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' ``` ### クライアント側 [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 ( {/* Your app code here */} ); } ``` > テストおよび開発時には 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)を表示して、サポートする支払い方法を有効にします。*PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。 多くの顧客から決済を受け付けられるよう、Stripe では、カードやその他一般的な決済手段がデフォルトで有効になっていますが、ビジネスや顧客に適した追加の決済手段を有効にすることをお勧めします。プロダクトと決済手段のサポートについては[決済手段のサポート](https://docs.stripe.com/payments/payment-methods/payment-method-support.md)を、手数料については[料金体系ページ](https://stripe.com/pricing/local-payment-methods)をご覧ください。 ## エンドポイントを追加する [サーバー側] > #### 注 > > PaymentIntent の作成前に PaymentSheet を表示するには、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=payment)をご覧ください。 Connect プラットフォームが [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、Stripe の [ガイド](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご確認の上、コード内の `Customer` およびイベント参照を同等の Accounts v2 API リファレンスに置き換えてください。 この接続方法では、以下の 3 つの Stripe API オブジェクトを使用します。 1. [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md): Stripe はこれを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して支払いの試行と支払い状態の変化を追跡します。 1. (オプション) [Customer (顧客)](https://docs.stripe.com/api/customers.md): 今後の支払いに備えて決済手段を設定するには、決済手段を*Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に関連付ける必要があります。Customer オブジェクトは、顧客がビジネスでアカウントを作成するときに作成します。顧客がゲストとして支払いを行う場合は、支払いの前に Customer オブジェクトを作成し、後でこのオブジェクトを顧客のアカウントを表す内部表現に関連付けることができます。 1. (オプション) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md): Customer オブジェクトの情報は機密情報であるため、アプリから直接取得することはできません。CustomerSession により、SDK に Customer への範囲を設定した一時的なアクセス権が付与され、また追加の設定オプションが提供されます。すべての[設定オプション](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)のリストをご覧ください。 > Customer にカードを保存したことがなく、リピート顧客に保存されたカードの再利用を許可しない場合は、実装で Customer オブジェクトおよび CustomerSession オブジェクトを省略できます。 セキュリティ上の理由により、アプリでこれらのオブジェクトを作成することはできません。代わりに、サーバー側で以下を行うエンドポイントを追加します。 1. Customer を取得するか、新規作成する。 1. 顧客の [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) を作成します。 1. [amount](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-amount)、[currency](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-currency)、[customer](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer) を指定して PaymentIntent を作成します。 1. PaymentIntent の *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))、CustomerSession の `client_secret`、Customer の [id](https://docs.stripe.com/api/customers/object.md#customer_object-id)、および貴社の[公開可能キー](https://dashboard.stripe.com/apikeys)をアプリに返します。 決済プロセス中に顧客に表示される支払い方法は、PaymentIntent にも含まれています。Stripe にダッシュボードの設定から支払い方法を取得するよう指定することも、手動でリストに表示することもできます。選択したオプションにかかわらず、顧客に表示される支払い方法は、PaymentIntent で渡す通貨によって絞り込まれることにご注意ください。たとえば、PaymentIntent で `eur` を渡し、ダッシュボードで OXXO が有効になっている場合、OXXO は `eur` による決済に対応していないため、顧客に表示されません。 構築済みのシステムで、決済手段を提供するためにコードベースのオプションが必要になる場合を除き、自動化されたオプションを使用することをお勧めします。これは、Stripe が通貨、決済手段の制約、その他のパラメーターを評価して、対応可能な決済手段を決定するためです。自動化されたオプションでは、購入完了率の向上につながり、使用通貨と顧客の所在地に最適な決済手段が優先的に表示されます。 #### ダッシュボードで支払い方法を管理する 支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。PaymentIntent は、ダッシュボードで設定された支払い方法を使用して作成されます。ダッシュボードを使用しない場合や、支払い方法を手動で指定する場合は、`payment_method_types` 属性を使用して支払い方法を一覧表示することができます。 #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. -d "automatic_payment_methods[enabled]"=true \ ``` #### 支払い方法を手動で一覧表示する #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ -d "payment_method_types[]"="bancontact" \ -d "payment_method_types[]"="card" \ -d "payment_method_types[]"="ideal" \ -d "payment_method_types[]"="klarna" \ -d "payment_method_types[]"="sepa_debit" \ ``` > 各決済手段は PaymentIntent で渡された通貨に対応している必要があり、ビジネスは、各決済手段を使用できる国のいずれかに所在する必要があります。対応状況について、詳細は[決済手段の導入オプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)ページをご覧ください。 ## 支払いの詳細を収集する [クライアント側] 決済ページでは、モバイル決済 Element を表示する前に以下を実行する必要があります。 - 購入商品と合計金額を表示する - 必要な配送先情報を収集する - Stripe の UI を表示する決済ボタンを含める アプリの決済フローで、前のステップで作成したバックエンドのエンドポイントにネットワークリクエストを送信し、`useStripe` フックから `initPaymentSheet` を呼び出します。 ```javascript export default function CheckoutScreen() { const { initPaymentSheet, presentPaymentSheet } = useStripe(); const [loading, setLoading] = useState(false); const fetchPaymentSheetParams = async () => { const response = await fetch(`${API_URL}/payment-sheet`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); const { paymentIntent, ephemeralKey, customer } = await response.json(); return { paymentIntent, ephemeralKey, customer, }; }; const initializePaymentSheet = async () => { const { paymentIntent, ephemeralKey, customer, } = await fetchPaymentSheetParams(); const { error } = await initPaymentSheet({ merchantDisplayName: "Example, Inc.", customerId: customer, customerEphemeralKeySecret: ephemeralKey, paymentIntentClientSecret: paymentIntent, // Set `allowsDelayedPaymentMethods` to true if your business can handle payment //methods that complete payment after a delay, like SEPA Debit and Sofort. allowsDelayedPaymentMethods: true, defaultBillingDetails: { name: 'Jane Doe', } }); if (!error) { setLoading(true); } }; const openPaymentSheet = async () => { // see below }; useEffect(() => { initializePaymentSheet(); }, []); return (