# Bacs ダイレクトデビット支払い イギリスの銀行口座を持つ顧客からの Bacs ダイレクトデビット決済を受け付けてください。 # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/bacs-debit/accept-a-payment?payment-ui=checkout. > Stripe は、通貨、支払い方法の制限、その他のパラメーターを評価することで、適切な支払い方法を顧客に自動的に提示できます。 > > - [決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=stripe-hosted)ガイドに従って、[動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用するチェックアウトの統合機能を構築します。 - 動的な決済手段を使用しない場合は、チェックアウトの導入で、決済方法を手動で設定するために以下のステップに従ってください。 イギリスの Stripe ユーザーは、支払いモードで [Checkout](https://docs.stripe.com/payments/checkout.md) を使用して、Bacs ダイレクトデビットによる支払いを受け付けることができます。 [Checkout セッション](https://docs.stripe.com/api/checkout/sessions.md)は、顧客の購入意向の詳細を表します。顧客が支払いを希望する場合は、Checkout セッションを作成します。顧客が Checkout セッションにリダイレクトされると、、顧客が購入を完了できる支払いフォームが Stripe に表示されます。顧客が購入を完了すると、サイトにリダイレクトされます。 ## Stripe を設定する [サーバ側] まず、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 を使用するには、まず*商品* (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)を作成する必要があります。物品やサービスレベルごとに商品を作成します。各商品の料金体系は 1 つ以上の価格で示されます。 たとえば、20 GBP と 25 EUR の、通貨が異なる 2 つの「価格」が設定された T シャツ「商品」を作成できます。これにより、対象商品の詳細を変更せずに価格を変更したり追加したりできるようになります。商品と価格は、[API を通じて](https://docs.stripe.com/api/prices.md)、または[ダッシュボード](https://dashboard.stripe.com/products)を使用して作成できます。 決済時に価格を決定する場合 (たとえば、顧客が寄付金額を設定する場合など)、または事前に価格を作成したくない場合は、既存の商品を使用して Checkout セッションの作成時に[単発の価格](https://docs.stripe.com/payments/accept-a-payment.md?platform=web#redirect-customers)を作成することもできます。 > Prices を使用しない既存の Checkout 組み込みがある場合には、Prices の導入以降に Checkout API が変更されています。この[移行ガイド](https://docs.stripe.com/payments/checkout/migrating-prices.md)を使用してアップグレードするか、[既存の組み込みを維持する](https://support.stripe.com/questions/prices-api-and-existing-checkout-integrations) ことができます。 #### ダッシュボード > サンドボックスで作成された商品は本番環境にコピーできるため、再度作成する必要はありません。ダッシュボードの商品詳細表示で、右上隅にある **本番環境にコピー** をクリックします。この操作はサンドボックスで作成された各商品に対して 1 回のみ実行できます。テスト環境の商品に対する以降の更新は、本番環境の商品には反映されません。 サンドボックスで作業していることを確認します。次に、販売するアイテムを定義します。新しい商品と価格を作成するには、以下を実行します。 - ダッシュボードで [商品](https://dashboard.stripe.com/test/products) セクションに移動します - **商品を追加**をクリックします - 価格を設定する際に**一括**を選択します 指定した商品の名前、説明、画像が Checkout で顧客に表示されます。 #### 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) を作成して商品の価格を定義します。これには商品のコストと使用通貨が含まれます。Bacs ダイレクトデビット支払いは GBP で行う必要があります。 ```curl curl https://api.stripe.com/v1/prices \ -u "<>:" \ -d "product={{PRODUCT_ID}}" \ -d unit_amount=2000 \ -d currency=gbp ``` ## Checkout セッションを作成する [クライアント側] [サーバ側] ウェブサイトに決済ボタンを追加し、サーバー側のエンドポイントを呼び出して Checkout セッションを作成します。 ```html Checkout
``` [line_items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items) を使って Checkout セッションを作成します。項目は、顧客が購入している項目のリストを表します。 顧客は決済を正常に完了すると、`success_url` にリダイレクトされます。これはウェブサイト上のページであり、決済情報の収集に成功し、決済が処理されていることを顧客に知らせます。 顧客が支払いを完了せずに Checkout Session でお客様のロゴをクリックすると、Checkout が顧客を誘導してウェブサイトにリダイレクトします。これは顧客が Checkout にリダイレクトされる前に表示していたウェブサイトのページです。 Checkout は決済を受け付け、将来の使用のために支払い方法を保存できます。この方法で保存された支払い方法は、[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method) による将来の支払いに使用できます。Checkout セッションを作成したら、レスポンスで返された [URL](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-url) に顧客をリダイレクトします。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"="bacs_debit" \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \ -d "mode"="payment" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "payment_intent_data[setup_future_usage]"="off_session" \ -d "success_url"="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` > Bacs ダイレクトデビットのルールでは、支払いの詳細が最初に収集されたときと、口座から引き落とされたときに、顧客は[引き落とし通知メール](https://docs.stripe.com/payments/payment-methods/bacs-debit.md#debit-notifications)を受信する必要があります。Stripe は、デフォルトでこれらのメールを送信します。 Checkout セッションを作成すると、[セッション ID](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-id) が返されます。上の例で示されるように、`success_url` に `{CHECKOUT_SESSION_ID}` テンプレート変数を含めることによって、成功時のページでセッション ID を使用できるようにします。 > 決済開始の検出にあたっては、`success_url` へのリダイレクトのみに依存しないでください。その理由は次のとおりです。 > > - 悪意を持つユーザが、支払いをせずに `success_url` に直接アクセスし、商品やサービスにアクセスできるようになる可能性があります。 - 決済が成功した後で、顧客が `success_url` にリダイレクトされる前にブラウザタブを閉じる可能性あります。 ## 支払い後のイベントを処理する [サーバ側] 顧客は支払いを完了すると、`success_url` パラメータで指定された URL にリダイレクトされます。通常、これはお客様の Web サイト上にある、支払いが成功したことを顧客に知らせるページです。 ただし、Bacs ダイレクトデビットは通知遅延型の決済手段であるため、売上はすぐには利用可能になりません。Bacs ダイレクトデビット決済は通常、売上が利用可能になるまでに 3 営業日かかります。このため、売上が利用可能になるまで注文の *フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected) を保留する必要があります。決済が成功すると、基になる *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) のステータスが `processing` から `succeeded` に変わります。 支払いのステータスに変化があると、以下の Checkout イベントが送信されます。 | イベント名 | 説明 | 次のステップ | | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | ------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout フォームを送信して、デビット支払いのオーソリを正常に実行しています。 | 支払いの成功または失敗の結果を待ちます。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | 顧客の支払いが成功しました。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | 何らかの理由により顧客の支払いが拒否されたか、失敗しました。 | 顧客にメールで連絡して、新たに注文を行うようリクエストします。 | *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) コードでこれら 3 つの Checkout イベントのすべてを処理する必要があります。 各 Checkout Webhook のペイロードには [Checkout Session (セッション) オブジェクト](https://docs.stripe.com/api/checkout/sessions.md) が含まれ、これには、*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)と *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) に関する情報が含まれます。 顧客がリダイレクトされる前に、`checkout.session.completed` Webhook がお客様のサーバーに送信されます。Webhook の確認応答 (任意の `2xx` ステータスコード) によって、`success_url` への顧客のリダイレクトが開始されます。支払いに成功してから 10 秒以内に Stripe が成功確認応答を受け取らなかった場合、顧客は自動的に `success_url` ページにリダイレクトされます。 `success_url` ページで、顧客に成功のメッセ―ジを表示しますが、その際に決済手段 Bacs ダイレクトデビットは即時ではないため、注文のフルフィルメントに数日かかることを知らせます。 遅延通知型の決済の他に即時の決済 (クレジットカードなど) を受け付ける際には、`checkout.session.completed` イベントの受信時に両方の種類の決済を処理できるように、Webhook エンドポイントを更新します。 #### Ruby ```ruby # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. # Find your keys at https://dashboard.stripe.com/apikeys. Stripe.api_key = '<>' # You can find your endpoint's secret in your webhook settings endpoint_secret = 'whsec_...' # Using Sinatra post '/webhook' do payload = request.body.read event = nil # Verify webhook signature and extract the event # See https://stripe.com/docs/webhooks#verify-events for more information. sig_header = request.env['HTTP_STRIPE_SIGNATURE'] begin event = Stripe::Webhook.construct_event( payload, sig_header, endpoint_secret ) rescue JSON::ParserError => e # Invalid payload status 400 return rescue Stripe::SignatureVerificationError => e # Invalid signature status 400 return end case event['type'] when 'checkout.session.completed' session = event['data']['object'] # Check if the order is paid (for example, from a card payment) payment_intent = Stripe::PaymentIntent.retrieve(session.payment_intent) # A delayed notification payment will have the status 'processing' order_paid = payment_intent.status == "succeeded" # Save an order in your database, marked as 'awaiting payment' create_order(session) if order_paid fulfill_order(session) end when 'checkout.session.async_payment_succeeded' session = event['data']['object'] # Fulfill the purchase... fulfill_order(session) when 'checkout.session.async_payment_failed' session = event['data']['object'] # Send an email to the customer asking them to retry their order email_customer_about_failed_payment(session) end status 200 end ``` 顧客や支払いに関する情報を取得するには、Webhook のペイロードの `customer` や `payment_intent` のプロパティで参照される Customer または PaymentIntent オブジェクトを取得します。 ### Webhook をローカルでテストする Webhook をローカルでテストするには、[Stripe CLI](https://docs.stripe.com/stripe-cli.md) を使用できます。Stripe CLI をインストールすると、イベントをサーバーに転送できます。 ```bash stripe listen --forward-to localhost:4242/webhook Ready! Your webhook signing secret is '{{WEBHOOK_SIGNING_SECRET}}' (^C to quit) ``` [Webhook の設定](https://docs.stripe.com/webhooks.md)についてもっと知る。 ## 組み込みをテストする この時点で、銀行口座の詳細を収集して支払いを受け入れる Bacs ダイレクトデビットの基本的な組み込みが完了しています。 この実装の準備ができていることを確認するために、*サンドボックス* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)で使用できる[テスト用銀行口座番号](https://docs.stripe.com/keys.md#test-live-modes)が複数用意されています。 | 銀行コード | 口座番号 | 説明 | | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 108800 | 00012345 | 支払いが成功し、PaymentIntent が `processing` から `succeeded` に変化します。 | | 108800 | 90012345 | 支払いが 3 分後に成功し、PaymentIntent が `processing` から `succeeded` に変化します。 | | 108800 | 33333335 | 支払いが承認されますが、すぐに `debit_not_authorized` エラーコードによって失敗し、PaymentIntent が `processing` から `requires_payment_method` に変わります。同意書は `inactive` になり、この PaymentMethod を再び使用することはできません。 | | 108800 | 93333335 | 支払いが `debit_not_authorized` エラーコードによって 3 分後に失敗し、PaymentIntent が `processing` から `requires_payment_method` に変化します。同意書は `inactive` になり、この PaymentMethod を再び使用することはできません。 | | 108800 | 22222227 | 支払いが `insufficient_funds` エラーコードによって失敗し、PaymentIntent が `processing` から `requires_payment_method` に変化します。同意書は `active` のままで、この PaymentMethod は再使用が可能です。 | | 108800 | 92222227 | 支払いが `insufficient_funds` エラーコードによって 3 分後に失敗し、PaymentIntent が `processing` から `requires_payment_method` に変化します。同意書は `active` のままで、この PaymentMethod は再使用が可能です。 | | 108800 | 55555559 | 支払いが 3 分後に成功し、PaymentIntent が `processing` から `succeeded` に変わりますが、不審請求の申請が直ちに作成されます。 | | 108800 | 00033333 | 支払い方法の作成は成功しますが、同意書が顧客の銀行によって拒否され、即座に inactive に変化します。 | | 108800 | 00044444 | Bacs ダイレクトデビットの設定を求めるリクエストが、口座番号が無効なため即座に失敗し、顧客は送信前に情報を更新するように求められます。支払いの詳細は回収されません。 | | 108800 | 34343434 | 支払い額がアカウントの週次支払い額の上限を超えているため、支払いは `charge_exceeds_source_limit` エラーコードで失敗します。 | | 108800 | 12121212 | 支払い額がアカウントの取引金額の上限を超えているため、支払いは `charge_exceeds_weekly_limit` エラーコードで失敗します。 | テストの実行には前述の任意の口座番号を使用できます。ただし、Bacs ダイレクトデビットによる支払いは処理に数日かかるため、3 分の遅延で動作するテスト用口座番号を使用して、本番環境の支払いの動作のシミュレーションをしやすくします。 > デフォルトでは、Stripe は決済情報が初めて収集されたときと、顧客の口座から引き落としが行われるたびに、顧客に[メール](https://docs.stripe.com/payments/payment-methods/bacs-debit.md#debit-notifications)を送信します。これらの通知は、サンドボックスでは送信されません。 ## 支払いの失敗 支払いはさまざまな理由で失敗する可能性があります。失敗の理由は、[charge.failure_code](https://docs.stripe.com/api/charges/object.md#charge_object-failure_code) から入手できます。特定の失敗コードの支払いのみを再試行できます。支払いを再試行できない場合は、顧客に連絡して、別の銀行口座または別の支払い方法を使用して再度支払うように依頼することをお勧めします。 以下は、現時点で送信される Bacs ダイレクトデビット用の失敗コードの一覧です。コードは随時追加される可能性があるため、コードを開発、保守する際には、これらのタイプがすべてではないことに注意してください。 | 失敗コード | 説明 | 再試行の可否 | | --------------------------- | --------------------------------------------------------------------------------------------------- | ------ | | `account_closed` | 銀行口座が解約されています。 | 不可 | | `bank_ownership_changed` | アカウントが新しい決済代行業者 (PSP) に移管されました。新しい PSP の詳細が通知されているかどうかを確認してください。通知されていない場合は、顧客から新しい同意書を収集する必要があります。 | 不可 | | `debit_not_authorized` | 顧客が銀行に対して、この支払いが無許可であったか、支払い銀行の同意書がないことを通知しました。 | 不可 | | `generic_could_not_process` | この決済は処理できませんでした。 | 可 | | `insufficient_funds` | 顧客の口座には、この支払いに充当できるだけの資金がありません。 | 可 | | `invalid_account_number` | 口座番号が無効です。これは、GBP アカウントの口座ではないか、アカウントが口座振替の決済を処理できないことを示している場合があります。 | 不可 | 支払いを再試行するには、同じ *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) を使用して、再度 [PaymentIntent を確定](https://docs.stripe.com/api/payment_intents/confirm.md)します。 確実に成功させるために、支払いを再試行する前に支払人に連絡することをお勧めします。 ## Optional: 顧客の引き落とし日を設定する Stripe が顧客の銀行口座から引き落としを行う日付は、[ターゲット日](https://docs.stripe.com/API/Checkout/Sessions/object.md#Checkout_session_object-%E6%94%AF%E6%89%95%E3%81%84_method_options-bacs_debit-target_date) を使用して制御できます。ターゲット日は、現在の日付から 3 日以上、15 日以内である必要があります。 目標日は、顧客のアカウントから離脱するための資金をスケジュールします。 次のいずれかの基準を満たす目標日は、引き落としを翌営業日まで延期します。 - 週末、祝日、またはその他の非営業日に当たる予定期日。 - 3 営業日以内に到来する予定期日。 このパラメーターは、ベストエフォート方式で機能します。顧客の銀行は、祝日の関係やその他の理由により、異なる日付に引き落としを処理する場合があります。 # Elements > This is a Elements for when payment-ui is elements. View the full page at https://docs.stripe.com/payments/bacs-debit/accept-a-payment?payment-ui=elements. Web サイトでの Bacs ダイレクトデビットによる決済の受け付けプロセスは、支払いを追跡するオブジェクトの作成、支払い方法に関する情報と同意書承認の収集、Stripe への支払いの送信 (処理のため)、および顧客の銀行口座の確認で構成されます。 Stripe では、[PaymentIntent](https://docs.stripe.com/payments/payment-intents.md) と呼ばれる決済オブジェクトを使用して、支払いが完了するまでの状態のすべてを追跡および処理します。 ## Stripe を設定する [サーバ側] まず、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' ``` ## 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` オブジェクトの ID を、顧客を表す社内の内部表記と関連付けることで、保存されている支払い方法の詳細を後で取得して使用することができます。 新しい `Customer` を作成するか、または既存の `Customer` を取得して、この決済に紐付けます。サーバーに以下のコードを含め、新しい `Customer` を作成します。 ```curl curl -X POST https://api.stripe.com/v1/customers \ -u "<>:" ``` ## 支払い方法の詳細を収集する > Bacs ダイレクトデビットのスキームルールでは、顧客は Stripe が顧客の口座から引き落とすことへの同意書に同意するよう定められています。[Payment Element](https://docs.stripe.com/payments/payment-element.md) は、顧客の支払い詳細を受け付けるときにこの同意書を収集します。そのため、お客様はこの要件に従うために特別な対策を取る必要はありません。 Payment Element を使用してクライアントで支払い詳細を収集する準備ができました。Payment Element は事前構築された UI コンポーネントであり、多様な支払い方法の支払い詳細の収集を容易にします。 Payment Element には、HTTPS 接続を介して支払い情報を Stripe に安全に送信する iframe が含まれています。決済手段によっては、支払い確認のために別のページにリダイレクトする必要があるため、Payment Element を別の iframe 内に配置しないでください。 実装を機能させるには、決済ページのアドレスの先頭を `http://` ではなく `https://` にする必要があります。HTTPS を使用せずに実装をテストすることはできますが、本番環境で支払いを受け付ける準備が整ったら、忘れずに[有効にしてください](https://docs.stripe.com/security/guide.md#tls)。 #### HTML + JS ### Stripe.js を設定する Payment Element は Stripe.js の機能として自動的に使用できるようになります。決済ページに Stripe.js スクリプトを含めるには、HTML ファイルの `head` にスクリプトを追加します。常に js.stripe.com から Stripe.js を直接読み込むことにより、PCI 準拠が維持されます。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 ```html 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
``` #### ダッシュボードから決済手段を管理する 上記のフォームが読み込まれたら、`mode`、`amount`、`currency` を指定して Elements インスタンスを作成します。これらの値によって、顧客に表示される決済手段が決まります。フォームで新しい決済手段を指定するには、必ず[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で有効にしてください。 ```javascript const options = {mode:'payment', amount:1099, currency: 'gbp', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout formconst elements = stripe.elements(options); // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element'); ``` #### 支払い方法を手動で一覧表示する 使用可能にしたい決済方法を手動でリストするには、それぞれを `paymentMethodTypes` に追加してください。 次に、Payment Element のインスタンスを作成し、コンテナーの DOM ノードにマウントします。 ```javascript const options = {mode:'payment', amount:1099, currency: 'gbp', paymentMethodTypes: ['bacs_debit'], // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout formconst 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` プロバイダーに渡します。 #### ダッシュボードから決済手段を管理する `Elements` プロバイダーは、`mode`、`amount`、`currency` も受け入れます。これらの値によって、顧客に表示される決済手段が決まります。フォームで新しい決済手段を指定するには、[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で有効にしてください。 ```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 = {mode:'payment', amount:1099, currency: 'gbp', // Fully customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` #### 支払い方法を手動で一覧表示する ```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 = {mode:'payment', amount:1099, currency: 'gbp', paymentMethodTypes: ['bacs_debit'], // 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; ``` `Elements` プロバイダーを作成する際に [Appearance (デザイン) オブジェクト](https://docs.stripe.com/elements/appearance-api.md) を `options` に渡すことで、サイトのデザインに合わせて Payment Element をカスタマイズできます。 ### 住所を収集 デフォルトでは、Payment Element は必要な請求住所の詳細のみを収集します。[税金の計算](https://docs.stripe.com/api/tax/calculations/create.md)、配送先情報を入力するなどの一部の動作では、顧客の完全な住所が必要です。次のように対応できます。 - [Address Element](https://docs.stripe.com/elements/address-element.md) を使用して、オートコンプリートとローカリゼーションの機能を利用して、顧客の完全な住所を収集します。これにより、最も正確な税金計算が可能になります。 - 独自のカスタムフォームを使用して住所の詳細を収集する。 ## PaymentIntent を作成する [サーバ側] > #### 支払い確定の直前にカスタムのビジネスロジックを実行する > > 支払いの確定ガイドの[ステップ 5](https://docs.stripe.com/payments/finalize-payments-on-the-server.md?platform=web&type=payment#submit-payment) に移動して、支払い確定の直前にカスタムのビジネスロジックを実行します。または、以下のステップに従って既存のシステムをシンプルにします。ここでは、クライアント側で `stripe.confirmPayment` を使用して、支払いの確定と次のアクションの処理の両方を行います。 #### ダッシュボードから決済手段を管理する 顧客が支払いフォームを送信したら、*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) を使用して確認と支払いのプロセスを適切に管理します。`amount` と `currency` を指定してサーバー側で PaymentIntent を作成します。悪意のある顧客が独自の価格を選択できないように、請求金額はクライアント側ではなく、常にサーバー側 (信頼できる環境) で決定してください。 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)) が含まれています。 この値をクライアントに返し、Stripe.js がこれを使用して支払いプロセスを安全に完了できるようにします。 #### Ruby ```ruby require 'stripe' Stripe.api_key = '<>' post '/create-intent' do intent = Stripe::PaymentIntent.create({ # To allow saving and retrieving payment methods, provide the Customer ID. customer: customer.id, amount: 1099, currency: 'gbp', }) {client_secret: intent.client_secret}.to_json end ``` #### 支払い方法を手動で一覧表示する 顧客が決済フォームを送信したら、*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) を使用して確認と決済のプロセスがスムーズに進むようにします。`amount`、`currency`、および `payment_method_types` で 1 つ以上の決済手段を指定して、サーバーで PaymentIntent を作成します。悪意のある顧客が価格を操作できないように、請求金額はクライアント側ではなく、常にサーバー側 (信頼できる環境) で決定してください。 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)) が含まれています。 この値をクライアントに返し、Stripe.js がこれを使用して支払いプロセスを安全に完了できるようにします。 #### Ruby ```ruby require 'stripe' Stripe.api_key = '<>' post '/create-intent' do intent = Stripe::PaymentIntent.create({ # To allow saving and retrieving payment methods, provide the Customer ID. customer: customer.id, amount: 1099, currency: 'gbp', payment_method_types: ['bacs_debit'], }) {client_secret: intent.client_secret}.to_json end ``` ## Stripe に支払いをする [クライアント側] [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を使用して、Payment Element の詳細を使って支払いを完了します。 この関数に [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) を指定して、支払い完了後に Stripe がユーザーをリダイレクトする場所を示します。ユーザーは、最初に銀行の認証ページなどの中間サイトにリダイレクトされてから、`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'); const submitBtn = document.getElementById('submit'); const handleError = (error) => { const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; submitBtn.disabled = false; } form.addEventListener('submit', async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); // Prevent multiple form submissions if (submitBtn.disabled) { return; } // Disable form submission while loading submitBtn.disabled = true; // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { handleError(submitError); return; } // Create the PaymentIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", }); const {client_secret: clientSecret} = await res.json(); // Confirm the PaymentIntent using the details collected by the Payment Element const {error} = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) handleError(error); } 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'; export default function CheckoutForm() { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(); const [loading, setLoading] = useState(false); const handleError = (error) => { setLoading(false); setErrorMessage(error.message); } const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } setLoading(true); // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { handleError(submitError); return; } // Create the PaymentIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", }); const {client_secret: clientSecret} = await res.json(); // Confirm the PaymentIntent using the details collected by the Payment Element const {error} = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) handleError(error); } 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`. } }; return (
{errorMessage &&
{errorMessage}
} ); } ``` ## 支払い後のイベントを処理する Bacs ダイレクトデビットは*遅延通知型の支払い方法* (A payment method that can't immediately return payment status when a customer attempts a transaction (for example, ACH debits). Businesses commonly hold an order in a pending state until payment is successful with these payment methods)であるため、資金は即座には利用できません。 ### タイムライン Bacs Direct Debit では、売上が Stripe 残高で利用可能になるまでに数営業日かかる場合があります。売上が利用可能になるまでの日数を売上処理タイミングと呼びます。支払いは通常、作成日と同じ日に送信され、営業日以外に作成された場合、またはカットオフ時間以降に作成された場合は翌営業日に処理されます。 Bacs Direct Debit の `expected_debit_date`には、[Charges](https://docs.stripe.com/api/charges/object.md) の[payment_method_details](https://docs.stripe.com/api/charges/object.md#charge_object-payment_method_details) からアクセスできます。これは資金が引き落とされる推定日です。この推定日は保証されたものではなく、実際の引き落とし日とは異なる場合があります。この情報は引き落とし日が確定した時点で、API レスポンスおよび[charge.updated](https://docs.stripe.com/api/events/types.md#event_types-charge.updated)、[charge.succeeded](https://docs.stripe.com/api/events/types.md#event_types-charge.succeeded)、[charge.failed](https://docs.stripe.com/api/events/types.md#event_types-charge.failed) のWebhookイベントを通じて参照できるようになります。 同意書がすでに設定されている場合は、Bacs ダイレクトデビットによる決済の成功または失敗を確認するのに 4 営業日かかります。新しい同意書を収集する必要がある場合は、7 営業日かかります。 場合によっては、お客様の Stripe アカウントで支払い成功としてマークされた後に、銀行が支払いの失敗を通知してくることがあります。この場合には、その支払いの失敗は、適切な理由コードを持つ不審請求の申請として識別されます。 次の表は、Stripe が提供する Bacs Direct Debit の支払いの売上処理タイミングを示しています。`T+x` は、提出後 `x` 営業日を指し、支払いの作成日とは異なる可能性があります。 | 売上処理のタイプ | 支払い完了 | 利用可能な資金 | カットオフ時間 | | -------- | ---------------- | ---------------- | ------------------- | | 標準の売上処理 | T+3 at 21:00 UTC | T+4 at 00:00 UTC | 20:00 Europe/London | ### Webhook を設定する 支払いプロセス中と支払い完了後に、Stripe は複数のイベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか、[Webhook のガイド](https://docs.stripe.com/webhooks/quickstart.md)に従って、これらのイベントを受信し、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行してください。 Bacs ダイレクトデビットの場合、[payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを処理して、支払いが成功したことを確認する必要があります。また、[payment_intent.processing](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.processing) イベントと [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) イベントも処理することをお勧めします。 Webhook をローカルでテストするには、[Stripe CLI](https://docs.stripe.com/stripe-cli.md) を使用します。Stripe CLI をインストールすると、イベントをサーバーに転送できます。 ```bash stripe listen --forward-to localhost:4242/webhook Ready! Your webhook signing secret is '{{WEBHOOK_SIGNING_SECRET}}' (^C to quit) ``` [Webhook の設定](https://docs.stripe.com/webhooks.md)についてもっと知る。 ## 組み込みをテストする この実装の準備ができていることを確認するために、*サンドボックス* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)で使用できる[テスト用銀行口座番号](https://docs.stripe.com/keys.md#test-live-modes)が複数用意されています。 | 銀行コード | 口座番号 | 説明 | | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 108800 | 00012345 | 支払いが成功し、PaymentIntent が `processing` から `succeeded` に変化します。 | | 108800 | 90012345 | 支払いが 3 分後に成功し、PaymentIntent が `processing` から `succeeded` に変化します。 | | 108800 | 33333335 | 支払いが承認されますが、すぐに `debit_not_authorized` エラーコードによって失敗し、PaymentIntent が `processing` から `requires_payment_method` に変わります。同意書は `inactive` になり、この PaymentMethod を再び使用することはできません。 | | 108800 | 93333335 | 支払いが `debit_not_authorized` エラーコードによって 3 分後に失敗し、PaymentIntent が `processing` から `requires_payment_method` に変化します。同意書は `inactive` になり、この PaymentMethod を再び使用することはできません。 | | 108800 | 22222227 | 支払いが `insufficient_funds` エラーコードによって失敗し、PaymentIntent が `processing` から `requires_payment_method` に変化します。同意書は `active` のままで、この PaymentMethod は再使用が可能です。 | | 108800 | 92222227 | 支払いが `insufficient_funds` エラーコードによって 3 分後に失敗し、PaymentIntent が `processing` から `requires_payment_method` に変化します。同意書は `active` のままで、この PaymentMethod は再使用が可能です。 | | 108800 | 55555559 | 支払いが 3 分後に成功し、PaymentIntent が `processing` から `succeeded` に変わりますが、不審請求の申請が直ちに作成されます。 | | 108800 | 00033333 | 支払い方法の作成は成功しますが、同意書が顧客の銀行によって拒否され、即座に inactive に変化します。 | | 108800 | 00044444 | Bacs ダイレクトデビットの設定を求めるリクエストが、口座番号が無効なため即座に失敗し、顧客は送信前に情報を更新するように求められます。支払いの詳細は回収されません。 | | 108800 | 34343434 | 支払い額がアカウントの週次支払い額の上限を超えているため、支払いは `charge_exceeds_source_limit` エラーコードで失敗します。 | | 108800 | 12121212 | 支払い額がアカウントの取引金額の上限を超えているため、支払いは `charge_exceeds_weekly_limit` エラーコードで失敗します。 | テストの実行には前述の任意の口座番号を使用できます。ただし、Bacs ダイレクトデビットによる支払いは処理に数日かかるため、3 分の遅延で動作するテスト用口座番号を使用して、本番環境の支払いの動作のシミュレーションをしやすくします。 > デフォルトでは、Stripe は決済情報が初めて収集されたときと、顧客の口座から引き落としが行われるたびに、顧客に[メール](https://docs.stripe.com/payments/payment-methods/bacs-debit.md#debit-notifications)を送信します。これらの通知は、サンドボックスでは送信されません。 ## 支払いの失敗 決済はさまざまな原因で失敗する可能性があります。失敗の理由は、[charge.failure_code](https://docs.stripe.com/api/charges/object.md#charge_object-failure_code) から確認できます。特定の失敗コードの支払いのみを再試行できます。支払いを再試行できない場合は、顧客に連絡して、別の銀行口座または別の決済手段を使用して再度支払うように依頼することをお勧めします。 以下は、現時点で送信される Bacs ダイレクトデビット用の失敗コードの一覧です。コードは随時追加される可能性があるため、コードを開発、保守する際には、これらのタイプがすべてではないことに注意してください。 | 失敗コード | 説明 | 再試行の可否 | | --------------------------- | --------------------------------------------------------------------------------------------------- | ------ | | `account_closed` | 銀行口座が解約されています。 | いいえ | | `bank_ownership_changed` | アカウントが新しい決済代行業者 (PSP) に移管されました。新しい PSP の詳細が通知されているかどうかを確認してください。通知されていない場合は、顧客から新しい同意書を収集する必要があります。 | いいえ | | `debit_not_authorized` | 顧客が銀行に対して、この支払いが未承認であったか、支払い銀行の同意書がないことを通知しました。 | いいえ | | `generic_could_not_process` | この決済は処理できませんでした。 | はい | | `insufficient_funds` | 顧客の口座には、この支払いに充当できるだけの資金がありません。 | はい | | `invalid_account_number` | 口座番号が無効です。これは、GBP アカウントの口座ではないか、アカウントが口座振替の決済を処理できないことを示している場合があります。 | いいえ | 支払いを再試行するには、同じ *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) を使用して、再度 [PaymentIntent を確定](https://docs.stripe.com/api/payment_intents/confirm.md)します。 確実に成功させるために、支払いを再試行する前に支払人に連絡することをお勧めします。 ## Optional: 顧客の引き落とし日を設定する [予定期日](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-payment_method_options-bacs_debit-target_date)を指定して、Stripe が顧客の銀行口座から引き落としを行う日付を制御できます。予定期日は、現在の日付から 3~15 日以内の日付に指定しなければなりません。 目標期日は、売上が顧客の口座を離れる日を期日指定します。設定日の 3 営業日前までの目標期日を設定された [PaymentIntent をキャンセル](https://docs.stripe.com/api/payment_intents/cancel.md)できます。 次のいずれかの条件を満たす予定期日は、翌営業日まで引き落としが延期されます。 - 週末、祝日、またはその他の非営業日に当たる予定期日。 - 3 営業日以内に到来する予定期日。 このパラメーターは、ベストエフォート方式で機能します。顧客の銀行は、祝日の関係やその他の理由により、異なる日付に引き落としを処理する場合があります。 ## Optional: プレフィックスを使用して同意書参照番号をカスタマイズする Bacs ダイレクトデビットの同意書参照番号をカスタマイズすると、同意書の識別をシンプルに行えます。これを行うには、オプションの `payment_method_options.bacs_debit.mandate_options.reference_prefix` 値を指定します。一意のシーケンスの先頭に `reference_prefix` を追加して、参照全体が一意のままになるようにします。 `reference_prefix` は以下の要件を満たしている必要があります。 - 最大長: 12 文字 - 数字または大文字で始める必要があります - 使用できる文字: - 大文字 - 番号 - スペース - 特殊文字: `.`、`/`、`&`、`-`、`_` - 先頭に `DDIC` または `STRIPE` を付けることはできません。 プレフィックスには任意の区切り文字を含めます。デフォルトでは区切り文字は追加されません。末尾のスペースは、最大 1 スペースまでトリミングされます。有効な接頭辞を使用すると、結果の参照は常に 18 文字の長さになります。 #### 支払いインテント ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d currency=gbp \ -d amount=100 \ -d "payment_method_types[]=bacs_debit" \ -d "payment_method_options[bacs_debit][mandate_options][reference_prefix]=EX4MPL3-" ``` #### Setup Intent ```curl curl https://api.stripe.com/v1/setup_intents \ -u "<>:" \ -d "payment_method_types[]=bacs_debit" \ -d "payment_method_options[bacs_debit][mandate_options][reference_prefix]=EX4MPL3-" ``` #### 支払いモードの Checkout セッション ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d currency=gbp \ -d "line_items[0][price_data][currency]=gbp" \ -d "line_items[0][price_data][product_data][name]=Llama" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d "payment_method_types[0]=bacs_debit" \ -d "payment_method_options[bacs_debit][mandate_options][reference_prefix]=EX4MPL3-" ``` #### 設定モードの Checkout セッション ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=setup \ -d "payment_method_types[]=bacs_debit" \ -d "payment_method_options[bacs_debit][mandate_options][reference_prefix]=EX4MPL3-" ``` 生成される参照は `EX4MPL3-19CNCI920C` のようになります。 | エラーコード | メッセージ | | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `invalid_bacs_mandate_reference_prefix_format` | `reference_prefix` は最大 12 文字で、使用できるのは大文字、数字、スペース、および特殊文字 `/`、`_`、`-`、`&`、`.` のみです。先頭に `DDIC` または `STRIPE` を付けることはできません。 | ## See also - [PaymentIntent webhook](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks) - [口座振替の同意を管理](https://docs.stripe.com/payments/payment-methods/bacs-debit.md#mandates)