# Boleto 支払い ブラジルで一般的な支払い方法である Boleto を受け付ける方法をご紹介します。 # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/boleto/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)を使用するチェックアウトの統合機能を構築します。 - 動的な決済手段を使用しない場合は、チェックアウトの導入で、決済方法を手動で設定するために以下のステップに従ってください。 Boleto は [1 回限りの使用](https://docs.stripe.com/payments/payment-methods.md#usage)の決済手段であり、顧客が支払いを完了するには、[追加の手順を実行](https://docs.stripe.com/payments/payment-methods.md#customer-actions)する必要があります。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は、ATM、銀行、オンラインバンクポータル、または公認の代理店のいずれかで、生成された番号が記載された Boleto の支払い票を使用して支払います。 ## 互換性を判断する **サポート対象のビジネスの所在地**: BR **対応可能な通貨**: `brl` **取引通貨**: `brl` **支払いモード**: Yes **セットアップモード**: No **サブスクリプションモード**: Yes Checkout Session が Boleto の決済をサポートするには、以下の条件を満たす必要があります。 - すべてのラインアイテムの*価格* (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 セッションを作成します。 ## 支払いを受け付ける > このガイドを使用する前に、まず Checkout で[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md?integration=checkout)ための実装を構築します。 このガイドでは、Boleto を有効にする方法について手順を追って説明し、動的な支払い方法を使用して決済を受け付ける場合と支払い方法を手動で設定する場合の違いを示します。 ### 支払い方法として Boleto を有効にする 新しい [Checkout セッション](https://docs.stripe.com/api/checkout/sessions.md)を作成する際は、以下を行う必要があります。 1. `boleto` を `payment_method_types` のリストに追加する 1. すべての `line_items` が `brl` 通貨を使用していることを確認します。 #### Stripe ホスト型ページ ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=brl" \ -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 "payment_method_types[0]=card" \ -d "payment_method_types[1]=boleto" \ --data-urlencode "success_url=https://example.com/success" ``` #### 組み込みフォーム ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=brl" \ -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 "payment_method_types[0]=card" \ -d "payment_method_types[1]=boleto" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded ``` ### その他の支払い方法オプション `Session` の [payment method options](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_method_options-boleto-expires_after_days) で、Boleto 店舗支払いの有効期限が切れるまでの日数を設定するオプションの `expires_after_days` パラメーターを指定できます。たとえば、月曜日に Boleto 店舗支払いを作成し、`expires_after_days` を 2 に設定した場合、Boleto 店舗支払いの有効期限は、アメリカ/サンパウロ時間 (UTC-3) の水曜日 23:59 です。0 に設定すると、Boleto 店舗支払いの有効期限はその日の終わりです。 `expires_after_days` パラメーターは、0 日から 60 日の範囲で設定できます。デフォルトは 3 日です。アカウントのデフォルトの有効期限は、 [Payment methods settings](https://dashboard.stripe.com/settings/payment_methods) でカスタマイズできます。 #### Stripe ホスト型ページ ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=brl" \ -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 "payment_method_options[boleto][expires_after_days]=7" \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=boleto" \ --data-urlencode "success_url=https://example.com/success" ``` #### 組み込みフォーム ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=brl" \ -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 "payment_method_options[boleto][expires_after_days]=7" \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=boleto" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded ``` ### Stripe がオンラインで提供する取引の詳細ページにリダイレクトする > カード決済とは異なり、Boleto による決済では顧客は [success_url](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-success_url) にリダイレクトされません。 Checkout フォームの送信に成功すると、顧客は `hosted_voucher_url` にリダイレクトされます。顧客はオンラインの取引詳細ページから Boleto 番号をコピーしたり、支払い票の PDF をダウンロードしたりできます。 Stripe は、Boleto の支払い票が正常に作成されると、[payment_intent.requires_action](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.requires_action) イベントを送信します。顧客に取引の詳細へのリンクをメールで送信する必要がある場合は、[payment_intent.next_action.boleto_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-hosted_voucher_url) の `hosted_voucher_url` に記載されています。詳しくは、[Webhook で PaymentIntent を監視する](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks)方法をご確認ください。 Stripe では、[ブランディング設定](https://dashboard.stripe.com/account/branding) ページで顧客に表示される UI をカスタマイズすることができます。取引の詳細には、以下のブランド設定を適用できます。 - **アイコン**: ブランド画像と公開ビジネス名 - **アクセント**— 番号コピーボタンのカラーとして使用されます - **ブランドカラー**: 背景色として使用されます ### 注文のフルフィルメントを行う Boleto は通知遅延型の決済手段であるため、*Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) などの方法を使用して支払いステータスを監視し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を行う必要があります。詳しくは、[Webhook の設定と注文のフルフィルメントの実行](https://docs.stripe.com/checkout/fulfillment.md)をご覧ください。 支払いのステータスに変化があると、以下のイベントが送信されます。 | イベント名 | 説明 | 次のステップ | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout フォームの送信を完了しました。Stripe が Boleto 支払い向けに取引の詳細を生成しています。 顧客が Boleto の取引の詳細を紛失した場合に備え、顧客に `hosted_voucher_url` をメールで送信することもできます。 | 顧客が Boleto の支払いを行うのを待っています。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | 顧客は Boleto の支払いを完了しました。`PaymentIntent` が `succeeded` に移行します。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | Boleto 支払いの有効期限が切れたか、その他の理由で支払いが失敗しました。`PaymentIntent` のステータスは `requires_payment_method` に戻ります。 | 顧客にメールで連絡して、新たに注文を行うようリクエストします。 | ## 組み込みをテストする Checkout の組み込みをテストする際は、支払い方法として Boleto を選択して、**支払う**ボタンをクリックします。 | メールアドレス | 説明 | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `{any_prefix}@{any_domain}` | 顧客が 3 分後に支払い、約 3 分後に `payment_intent.succeeded` Webhook を受信する Boleto の支払いをシミュレーションします。本番環境では、1 営業日後にこの Webhook が届きます。 例: fulaninho@example.com | | `{any_prefix}succeed_immediately@{any_domain}` | 顧客が即座に支払い、数秒以内に `payment_intent.succeeded` Webhook を受信する Boleto の支払い方法をシミュレーションします。本番環境では、1 営業日後にこの Webhook が届きます。 例: succeed_immediately@example.com | | `{any_prefix}expire_immediately@{any_domain}` | 顧客が支払う前に期限切れになり、数秒以内に `payment_intent.payment_failed` Webhook を受信する Boleto の支払いをシミュレーションします。 [決済手段オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-boleto-expires_after_days)で `expires_after_days` パラメータに設定された値に関係なく、[next_action.boleto_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-expires_at) の `expires_at` フィールドには、現在時刻が設定されます。 例: expire_immediately@example.com | | `{any_prefix}expire_with_delay@{any_domain}` | 顧客が支払う前に期限切れになり、約 3 分後に `payment_intent.payment_failed` Webhook を受信する Boleto の支払いをシミュレーションします。 [決済手段オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-boleto-expires_after_days)で `expires_after_days` パラメータに設定された値に関係なく、[next_action.boleto_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-expires_at) の `expires_at` フィールドが 3 分後に設定されます。 例: expire_with_delay@example.com | | `{any_prefix}fill_never@{any_domain}` | 成功することなく、[決済手段オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-boleto-expires_after_days)で指定されたパラメータに基づき、[next_action.boleto_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-expires_at) の `expires_at` フィールドに従って有効期限が切れ、その後 `payment_intent.payment_failed` Webhook を受け取る Boleto 支払い票をシミュレートします。 例: fill_never@example.com | | 納税者番号 | 説明 | | ------------------------------------------------- | -------------------------------------------- | | CPF `000.000.000-00` CNPJ `00.000.000/0000-00` | サンドボックスで、`tax_id` にこれらの値を設定し、納税者番号の検証を回避します。 | ## 返金を処理する Boleto での支払いは返金できません。一部の加盟店では、直接問い合わせた顧客にクレジットを提供するプロセスを別途作成しています。 ## 不審請求の申請を処理する Boleto での支払いに関して、顧客が不審請求を申請することはできません。 ## Optional: 支払い手順メールを送信する ダッシュボードの[メール設定](https://dashboard.stripe.com/settings/emails)ページで Boleto 決済の手順のメールを有効にできます。有効にすると、Stripe は、PaymentIntent の確定時に支払い手順のメールを送信します。メールには、Boleto 番号と Stripe の店舗支払いページへのリンクが含まれます。 > テスト環境では、手順メールは Stripe アカウントに関連付けられたメールアドレスにのみ送信されます。 ## See also - [Checkout のフルフィルメント](https://docs.stripe.com/checkout/fulfillment.md) - [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/boleto/accept-a-payment?payment-ui=elements&api-integration=checkout. ビジネス ニーズに合った API を判断するには、[比較ガイド](https://docs.stripe.com/payments/checkout-sessions-and-payment-intents-comparison.md) を参照してください。 [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用して、ウェブサイトまたはアプリケーションにカスタムの Stripe 決済フォームを埋め込み、顧客に決済手段を提供します。高度な設定とカスタマイズについては、[決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md)に関する導入ガイドをご覧ください。 ## 互換性の判断 **サポート対象のビジネスの所在地**: BR **対応可能な通貨**: `brl` **取引通貨**: `brl` **支払いモード**: Yes **セットアップモード**: No **サブスクリプションモード**: Yes Boleto 支払いに対応するには、Checkout セッションが次の条件をすべて満たしている必要があります。 - すべてのラインアイテムの価格が、同じ通貨である必要があります。異なる通貨のラインアイテムが存在する場合は、通貨ごとに別の Checkout セッションを作成します。 ## サーバーを設定する [サーバー側] アプリケーションから 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 Session を作成する [サーバー側] [Checkout セッション](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 セッションは、顧客が 1 回限りの購入またはサブスクリプションの支払いを行う際のセッションを表します。Checkout セッションは作成後 24 時間で期限切れとなります。 [動的支払い方法](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md) を使用して、各顧客に最も関連性の高い支払い方法を動的に表示し、コンバージョンを最大化することをお勧めします。[支払い方法を手動でリスト](https://docs.stripe.com/payments/payment-methods/integration-options.md#listing-payment-methods-manually) して、動的支払い方法を無効にすることもできます。 #### ダッシュボードで支払い方法を管理する #### TypeScript ```javascript import express, {Express} from 'express'; const app: Express = express(); app.post('/create-checkout-session', async (req: Express.Request, res: Express.Response) => { const session = await stripe.checkout.sessions.create({ line_items: [ { price_data: { currency: 'brl', product_data: { name: 'T-shirt', }, unit_amount: 2000, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'custom', return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}' }); res.json({checkoutSessionClientSecret: session.client_secret}); }); app.listen(3000, () => { console.log('Running on port 3000'); }); ``` #### 決済手段を手動で一覧表示する #### TypeScript ```javascript import express, {Express} from 'express'; const app: Express = express(); app.post('/create-checkout-session', async (req: Express.Request, res: Express.Response) => { const session = await stripe.checkout.sessions.create({ line_items: [ { price_data: { currency: 'brl', product_data: { name: 'T-shirt', }, unit_amount: 2000, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'custom', payment_method_types: ['boleto'], return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}' }); res.json({checkoutSessionClientSecret: session.client_secret}); }); app.listen(3000, () => { console.log('Running on port 3000'); }); ``` ## フロントエンドを設定する [クライアント側] #### HTML + JS HTML ファイルの `head` に Stripe.js スクリプトを追加し、チェックアウトページに含めます。PCI への準拠を維持するために、常に js.stripe.com から Stripe.js を直接読み込んでください。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 最新の Stripe.js バージョンであることをご確認の上、以下のスクリプトタグ `` を読み込んでください。詳しくは[Stripe.js バージョン管理](https://docs.stripe.com/sdks/stripejs-versioning.md)をご覧ください。 ```html Checkout ``` > Stripe では npm パッケージをご用意しており、これを使用して Stripe.js をモジュールとして読み込むことができます。[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@^5.0.0 @stripe/stripe-js@^8.0.0 ``` 公開可能キーを使用してフロントエンドで `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; ``` ## 実装をテストする 実装内容をテストするには、決済手段を選択して**支払う**をタップします。*サンドボックス* (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)では、テスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、boleto のウェブサイトにリダイレクトされます。boleto で支払いを承認または拒否するオプションはありません。 # 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/boleto/accept-a-payment?payment-ui=elements&api-integration=paymentintents. ビジネス ニーズに合った API を判断するには、[比較ガイド](https://docs.stripe.com/payments/checkout-sessions-and-payment-intents-comparison.md) を参照してください。 [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用して、ウェブサイトまたはアプリケーションにカスタムの Stripe 決済フォームを埋め込み、顧客に決済手段を提供します。高度な設定とカスタマイズについては、[決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md)に関する導入ガイドをご覧ください。 ## Stripe をセットアップする [サーバー側] 開始するには、[Stripe アカウントを作成](https://dashboard.stripe.com/register)を作成します。 アプリケーションから Stripe APIにアクセスするには、公式ライブラリを使用してください。 #### 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' ``` ## 決済詳細を収集する [クライアント側] 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:2000, currency: 'brl', // 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:2000, currency: 'brl', paymentMethodTypes: ['boleto'], // 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:2000, currency: 'brl', // 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:2000, currency: 'brl', paymentMethodTypes: ['boleto'], // 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: 2000, currency: 'brl', }) {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: 2000, currency: 'brl', payment_method_types: ['boleto'], }) {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}
} ); } ``` ## Optional: 支払い後のイベントを処理する 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。ダッシュボード、カスタム *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests)、またはパートナーソリューションを使用してこれらのイベントを受信し、また、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアント側では、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了したりする可能性があります。また、悪意を持つクライアントがレスポンスを不正操作する恐れもあります。非同期型のイベントをリッスンするよう構築済みのシステムを設定することで、これ以降はより多くの決済手段を簡単に受け付けられるようになります。[サポートされているすべての決済手段の違い](https://stripe.com/payments/payment-methods-guide)をご確認ください。 - **ダッシュボードでイベントを手動で処理する** ダッシュボードを使用して、テスト決済を[ダッシュボードで表示](https://dashboard.stripe.com/test/payments)したり、メール領収書を送信したり、入金を処理したり、失敗した決済を再試行したりできます。 - **Custom Webhook を構築する** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **構築済みアプリを導入する** パートナーアプリケーションを統合することで、[自動化](https://stripe.partners/?f_category=automation)や[マーケティング/セールス](https://stripe.partners/?f_category=marketing-and-sales)などの一般的なビジネスイベントを処理します。 ## 実装をテストする 実装内容をテストするには、決済手段を選択して**支払う**をタップします。*サンドボックス* (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)では、テスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、boleto のウェブサイトにリダイレクトされます。boleto で支払いを承認または拒否するオプションはありません。 ## エラーコード 次の表に、一般的なエラーコードと推奨される対応の詳細を示します。 | エラーコード | 推奨される対応 | | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent_invalid_currency` | 対応している通貨を入力してください。 | | `missing_required_parameter` | 必須パラメーターの詳細については、エラーメッセージをご確認ください。 | | `payment_intent_payment_attempt_failed` | このコードは、PaymentIntent の [last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) フィールドに表示されることがあります。エラーメッセージで、エラーの詳細な理由とエラー処理に関する提案を確認してください。 | | `payment_intent_authentication_failure` | このコードは、PaymentIntent の[last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) フィールドに表示されることがあります。エラーメッセージで、詳細な失敗理由とエラー処理に関する推奨事項を確認してください。このエラーは、統合のテスト時に失敗を手動でトリガーした場合に発生します。 | | `payment_intent_redirect_confirmation_without_return_url` | PaymentIntent を確定する際は、`return_url` を指定します。 | # ダイレクト API > This is a ダイレクト API for when payment-ui is direct-api. View the full page at https://docs.stripe.com/payments/boleto/accept-a-payment?payment-ui=direct-api. ブラジルの Stripe ユーザーは、Payment Intents API および Payment Methods API を使用して、ブラジルの顧客から Boleto での支払いを受け付けることができます。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は ATM、銀行、オンラインバンクポータル、または公認の代理店のいずれかで、生成された番号が記載された Boleto の支払い票を使用して支払います。 ## 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' ``` ## PaymentIntent を作成する [サーバ側] Stripe は [PaymentIntent](https://docs.stripe.com/api/payment_intents.md) オブジェクトを使用して、顧客から支払いを回収するお客様の意図を示し、Boleto 支払い票の作成から支払いの完了までの状態の変化を追跡します。 サーバーで金額と`brl`通貨を使用して PaymentIntent を作成します (Boleto は他の通貨をサポートしていません)。すでに[Payment Intents API](https://docs.stripe.com/payments/payment-intents.md)を使用した統合がある場合は、`PaymentIntent`の[決済手段タイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに`boleto`を追加します。 返される 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 をクライアントに送り返します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=brl \ -d "payment_method_types[]=boleto" ``` ### その他の支払い方法オプション `PaymentIntent` の[決済手段オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-boleto-expires_after_days)でオプションの `expires_after_days` パラメータを指定すると、Boleto 支払い票の有効期限が切れるまでの暦日数を設定できます。たとえば、月曜日に Boleto の支払い票を作成し、`expires_after_days` を 2 に設定した場合、Boleto の支払い票は水曜日のアメリカ/サンパウロ時間 (UTC-3) の 23:59 に有効期限が切れます。0 に設定すると、その日の終わりに Boleto の支払い票の有効期限が切れます。`expires_after_days` パラメーターは 0 日から 60 日までの範囲で設定できます。既定値は 3 日です。アカウントのデフォルトの有効期限は、[決済手段の設定](https://dashboard.stripe.com/settings/payment_methods)でカスタマイズできます ## 支払い方法の詳細を収集する [クライアント側] クライアントで支払いフォームを作成し、必要な請求先情報を顧客から収集します。 | フィールド | 値 | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | 顧客の氏名。 | | `email` | 顧客のメールアドレス。 | | `tax_id` | 顧客の CPF (個人の場合) または CNPJ (ビジネスの場合)。CPF は 11 桁で、`000.000.000-00` または `00000000000` の形式にする必要があります。CNPJ は 14 桁で、`00.000.000/0000-00` または `00000000000000` の形式にする必要があります。 | | `address` | 顧客の住所の町名と番地。 | | `city` | 顧客の住所の市区町村。 | | `state` | 顧客住所のブラジルの 2 文字の州 コード ([ISO_3166-2:BR](https://en.wikipedia.org/wiki/ISO_3166-2:BR))。 | | `postal_code` | 顧客住所の郵便番号。郵便番号の形式は、`XXXXX-XXX` または `XXXXXXXX` にする必要があります。 | > `name`、`address`、`city` のフィールドには、[基本ラテン文字 (ASCII) ユニコードブロック](https://en.wikipedia.org/wiki/Basic_Latin_\(Unicode_block\))の英数字を 1 文字以上含める必要があります。 ```html
``` ## Stripe に支払いを送信する [クライアント側] 顧客が Boleto による決済をクリックしたら、Stripe.js を使用してその支払いを Stripe に送信します。[Stripe.js](https://docs.stripe.com/payments/elements.md) は、支払いフローを構築するための Stripe の基本的な JavaScript ライブラリです。 Stripe.js スクリプトを決済ページに含めるには、このスクリプトを HTML ファイルの `head` に追加します。 ```html Checkout ``` 決済ページで以下の JavaScript を使用して、Stripe.js のインスタンスを作成します。 ```javascript // Set your publishable key. Remember to switch to your live publishable key in production! // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` [stripe.confirmBoletoPayment](https://docs.stripe.com/js/payment_intents/confirm_boleto_payment) と、ステップ 2 で作成した `PaymentIntent` オブジェクトの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を使用して、顧客の請求先情報を送信します。 確定されると、Stripe はモーダルを自動的に開き、顧客に Boleto の取引詳細を表示します。 ```javascript var form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const result = await stripe.confirmBoletoPayment( '{{PAYMENT_INTENT_CLIENT_SECRET}}', { payment_method: { boleto: { tax_id: document.getElementById('tax_id').value, }, billing_details: { name: document.getElementById('name').value, email: document.getElementById('email').value, address: { line1: document.getElementById('address').value, city: document.getElementById('city').value, state: document.getElementById('state').value, postal_code: document.getElementById('postal_code').value, country: 'BR', }, }, }, } ); // Stripe.js will open a modal to display the Boleto voucher to your customer // This async function finishes when the customer closes the modal if (result.error) { // Display error to your customer const errorMsg = document.getElementById('error-message'); errorMsg.innerText = result.error.message; } }); ``` > `stripe.confirmBoletoPayment` の完了には数秒かかる場合があります。この間、フォームが再送信されないように無効化し、スピナーのような待機中のインジケータを表示します。エラーが発生した場合は、それを顧客に表示し、フォームを再度有効化し、待機中のインジケータを非表示にします。 Boleto 伝票が正常に作成されると、返された PaymentIntent の `status` プロパティの値は `requires_action` になります。[ダッシュボード](https://dashboard.stripe.com/test/payments)で、またはオブジェクトのステータスプロパティを調べて、PaymentIntent のステータスを確認します。Boleto 伝票が正常に作成されなかった場合は、返された `error` を調べて原因を特定します (たとえば、無効なメール形式など)。 ### オプション: 顧客に取引の詳細へのリンクをメールで送信する Stripe は、Boleto の支払い票が正常に作成されると、[payment_intent.requires_action](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.requires_action) イベントを送信します。顧客に取引の詳細へのリンクをメールで送信する必要がある場合は、[payment_intent.next_action.boleto_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-hosted_voucher_url) の `hosted_voucher_url` に記載されています。 ### オプション: 取引の詳細をカスタマイズする Stripe では、[ブランディング設定](https://dashboard.stripe.com/account/branding)ページで、顧客に表示される UI をカスタマイズできます。 取引の詳細には、以下のブランド設定を適用できます。 - **アイコン**: ブランド画像と公開ビジネス名 - **アクセント**— 番号コピーボタンのカラーとして使用されます - **ブランドカラー**: 背景色として使用されます ## 支払い後のイベントを処理する [サーバ側] Boleto による決済は非同期型であるため、売上はすぐには利用可能になりません。決済後、顧客が直ちに Boleto 伝票の支払いを行わないことがあります。 Stripe は、支払われた Boleto の支払い票ごとに、翌営業日 (ブラジルの祝日を除く月曜日から金曜日) に [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。ダッシュボードまたはカスタム *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) を使用して、これらのイベントを受信し、アクションを実行します (顧客への注文確認メールの送信、データベースへの販売の記録、配送ワークフローの開始、など)。 Boleto 伝票が有効期限日の 23:59 America/Sao_Paulo (UTC-3) までに支払われなかった場合、Stripe は 1 営業日後に [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) イベントを送信します。たとえば、Boleto 伝票の有効期限が木曜日に切れる場合には、このイベントは金曜日に送信され、有効期限が金曜日に切れる場合には、このイベントは次の月曜日に送信されます。 | イベント | 説明 | 次のステップ | | ------------------------------- | ---------------------------------- | ------------------------------------ | | `payment_intent.succeeded` | 顧客が有効期限前に Boleto の支払いを行いました。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | `payment_intent.payment_failed` | 顧客が有効期限までに Boleto 伝票の支払いを行いませんでした。 | 顧客にメールまたはプッシュ通知で連絡し、別の決済手段をリクエストします。 | ## 組み込みをテストする *サンドボックス* (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)で、[stripe.confirmBoletoPayment](https://docs.stripe.com/js/payment_intents/confirm_boleto_payment) を呼び出すときに `payment_method.billing_details.email` に次の値を設定して、さまざまなシナリオをテストします。 | メールアドレス | 説明 | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `{any_prefix}@{any_domain}` | 顧客が 3 分後に支払い、約 3 分後に `payment_intent.succeeded` Webhook を受信する Boleto の支払いをシミュレーションします。本番環境では、1 営業日後にこの Webhook が届きます。 例: fulaninho@example.com | | `{any_prefix}succeed_immediately@{any_domain}` | 顧客が即座に支払い、数秒以内に `payment_intent.succeeded` Webhook を受信する Boleto の支払い方法をシミュレーションします。本番環境では、1 営業日後にこの Webhook が届きます。 例: succeed_immediately@example.com | | `{any_prefix}expire_immediately@{any_domain}` | 顧客が支払う前に期限切れになり、数秒以内に `payment_intent.payment_failed` Webhook を受信する Boleto の支払いをシミュレーションします。 [決済手段オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-boleto-expires_after_days)で `expires_after_days` パラメータに設定された値に関係なく、[next_action.boleto_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-expires_at) の `expires_at` フィールドには、現在時刻が設定されます。 例: expire_immediately@example.com | | `{any_prefix}expire_with_delay@{any_domain}` | 顧客が支払う前に期限切れになり、約 3 分後に `payment_intent.payment_failed` Webhook を受信する Boleto の支払いをシミュレーションします。 [決済手段オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-boleto-expires_after_days)で `expires_after_days` パラメータに設定された値に関係なく、[next_action.boleto_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-expires_at) の `expires_at` フィールドが 3 分後に設定されます。 例: expire_with_delay@example.com | | `{any_prefix}fill_never@{any_domain}` | 成功することなく、[決済手段オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-boleto-expires_after_days)で指定されたパラメータに基づき、[next_action.boleto_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-expires_at) の `expires_at` フィールドに従って有効期限が切れ、その後 `payment_intent.payment_failed` Webhook を受け取る Boleto 支払い票をシミュレートします。 例: fill_never@example.com | | 納税者番号 | 説明 | | ------------------------------------------------- | -------------------------------------------- | | CPF `000.000.000-00` CNPJ `00.000.000/0000-00` | サンドボックスで、`tax_id` にこれらの値を設定し、納税者番号の検証を回避します。 | ## Optional: 独自に取引の詳細ページを構築する [クライアント側] `confirmBoletoPayment` で Boleto の取引詳細の表示を処理するには、Stripe.js を利用することをお勧めします。ただし、取引詳細を手動で顧客に表示することもできます。 ステップ 4 で stripe.confirmBoletoPayment をコールする際に `handleActions: false` を指定して、顧客に Boleto の詳細を表示する次のアクションを処理するように指定できます。 ```javascript var form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const result = await stripe.confirmBoletoPayment( '{{PAYMENT_INTENT_CLIENT_SECRET}}', { payment_method: { boleto: { tax_id: document.getElementById('tax_id').value, }, billing_details: { name: document.getElementById('name').value, email: document.getElementById('email').value, address: { line1: document.getElementById('address').value, city: document.getElementById('city').value, state: document.getElementById('state').value, postal_code: document.getElementById('postal_code').value, country: 'BR', }, }, }, }, {handleActions: false}, ); if (result.error) { // Display error to your customer const errorMsg = document.getElementById('error-message'); errorMsg.innerText = result.error.message; } else { // An Boleto voucher was successfully created const amount = result.paymentIntent.amount; const currency = result.paymentIntent.currency; const details = result.paymentIntent.next_action.boleto_display_details; const number = details.number; const expires_at = details.expires_at; // Handle the next action by displaying the Boleto details to your customer // You can also use the generated hosted voucher const hosted_voucher_url = details.hosted_voucher_url; } }); ``` 少なくとも、以下を含めます。 | 詳細 | 説明 | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 番号 | Boleto の番号は、顧客が簡単にクリップボードにコピーできるようにして表示します。[next_action.boleto_display_details.number](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-number) にある `PaymentIntent` オブジェクトの番号を見つけます。 | | 有効期限 | Boleto 支払い票の有効期限を表示します。[next_action.boleto_display_details.expires_at](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-expires_at) の `PaymentIntent` で Boleto 支払い票が期限切れになる UNIX タイムスタンプを見つけます。 | | PDF をダウンロードする | ダウンロードボタンを表示して、顧客が Boleto の PDF をダウンロードできるようにします。顧客が Boleto の取引詳細の PDF をダウンロードできる場所は、[next_action.boleto_display_details.pdf](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-boleto_display_details-pdf) の `PaymentIntent` にあります。 | ## Optional: サーバ側で Payment Intent を確定する [サーバ側] `confirmBoletoPayment` で Boleto の Payment Intent を*確定* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects)するには、Stripe.js を使用することをお勧めします。Stripe.js を使用することで、組み込みを他の支払い方法に容易に拡張できます。ただし、サーバー側で以下のようにして Payment Intent を確定することもできます。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=brl \ -d confirm=true \ -d "payment_method_types[]=boleto" \ -d "payment_method_data[type]=boleto" \ -d "payment_method_data[billing_details][name]=João da Silva" \ --data-urlencode "payment_method_data[billing_details][email]=joao@exemplo.com" \ -d "payment_method_data[billing_details][address][line1]=1234 Av. Paulista" \ -d "payment_method_data[billing_details][address][city]=São Paulo" \ -d "payment_method_data[billing_details][address][state]=SP" \ -d "payment_method_data[billing_details][address][postal_code]=01310-000" \ -d "payment_method_data[billing_details][address][country]=BR" \ -d "payment_method_data[boleto][tax_id]=000.000.000-00" ``` ## Optional: 支払い手順メールを送信する ダッシュボードの[メール設定](https://dashboard.stripe.com/settings/emails)ページで Boleto 決済の手順のメールを有効にできます。有効にすると、Stripe は、PaymentIntent の確定時に支払い手順のメールを送信します。メールには、Boleto 番号と Stripe の店舗支払いページへのリンクが含まれます。 > テスト環境では、手順メールは Stripe アカウントに関連付けられたメールアドレスにのみ送信されます。 ## 有効期限とキャンセル Boleto バウチャーは `expires_at` UNIX タイムスタンプを過ぎると期限切れになり、顧客は有効期限が切れた Boleto バウチャーの支払いはできません。有効期限前に Boleto バウチャーをキャンセルすることはできません。 Boleto の有効期限が切れると、PaymentIntent のステータスは `requires_payment_method` に変わります。この時点では、別の支払い方法を指定して PaymentIntent を確定するか、キャンセルすることができます。