# Affirm 支払いの受け付け 世界で普及している後払い決済方法である Affirm を受け付ける方法をご紹介します。 > このガイドでは、オンライン決済フローに Affirm を導入する方法について説明します。Stripe Terminal を使用した対面決済については [追加の決済手段](https://docs.stripe.com/terminal/payments/additional-payment-methods.md) をご覧ください。 # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/affirm/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)を使用するチェックアウトの統合機能を構築します。 - 動的な決済手段を使用しない場合は、チェックアウトの導入で、決済方法を手動で設定するために以下のステップに従ってください。 Affirm は [1 回限りの使用](https://docs.stripe.com/payments/payment-methods.md#usage)で[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法であり、顧客は支払いの[認証](https://docs.stripe.com/payments/payment-methods.md#customer-actions)を求められます。顧客は Affirm のサイトにリダイレクトされ、そこで分割払いプランの規約に同意します。顧客が規約に同意すると、売上が保証され、お客様の Stripe アカウントに送金されます。顧客は一定の期間にわたって Affirm に直接返済します。 > 導入を開始する前に、[支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)に移動して、アカウントで Affirm が使用可能であることを確認してください。 ## 互換性を判断する **顧客の居住地**: Canada, US **対応可能な通貨**: `cad, usd` **取引通貨**: `cad, usd` **支払いモード**: Yes **セットアップモード**: No **サブスクリプションモード**: No Affirm の支払いに対応するには、Checkout セッションが次の条件をすべて満たしている必要があります。 - 使用できるのは単一の項目だけです。Affirm は、継続的な*サブスクリプション* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis)プランに対応していません。 - すべての*価格* (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 システムに基本的な[決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md?ui=stripe-hosted)が存在することを前提として作成されています。 このガイドでは、Affirm を有効にする方法について手順を追って説明し、動的決済手段を使用して決済を受け付ける場合と決済手段を手動で設定する場合の違いを示します。 ### 支払い方法として Affirm を有効にする 新しい [Checkout Session (セッション)](https://docs.stripe.com/api/checkout/sessions.md) を作成する際は、以下を行う必要があります。 1. `affirm` を `payment_method_types` のリストに追加します。 1. すべての `line_items` で国内通貨を使用し、合計金額が Affirm の[取引金額制限](https://docs.stripe.com/payments/affirm.md#payment-options)を超えないようにしてください。 1. オプションとして、`shipping_address_collection[allowed_countries]` を使用して、Checkout で配送先として指定できる国を指定します。 #### Stripe がオンラインで提供するページ ```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]=5000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=affirm" \ -d "shipping_address_collection[allowed_countries][0]=CA" \ -d "shipping_address_collection[allowed_countries][1]=US" \ --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]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=5000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=affirm" \ --data-urlencode "return_url=https://example.com/return" \ -d "shipping_address_collection[allowed_countries][0]=CA" \ -d "shipping_address_collection[allowed_countries][1]=US" \ -d ui_mode=embedded_page ``` Checkout で配送先住所を収集しない場合は、`payment_intent_data[shipping]` を使用して配送先住所を指定することもできます。そうすることで、ローンの承認率が向上します。 #### Stripe がオンラインで提供するページ ```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]=5000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=affirm" \ -d "payment_intent_data[shipping][name]=Jenny Rosen" \ -d "payment_intent_data[shipping][address][line1]=1234 Main Street" \ -d "payment_intent_data[shipping][address][city]=San Francisco" \ -d "payment_intent_data[shipping][address][state]=CA" \ -d "payment_intent_data[shipping][address][country]=US" \ -d "payment_intent_data[shipping][address][postal_code]=94111" \ --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]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=5000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=affirm" \ --data-urlencode "return_url=https://example.com/return" \ -d "payment_intent_data[shipping][name]=Jenny Rosen" \ -d "payment_intent_data[shipping][address][line1]=1234 Main Street" \ -d "payment_intent_data[shipping][address][city]=San Francisco" \ -d "payment_intent_data[shipping][address][state]=CA" \ -d "payment_intent_data[shipping][address][country]=US" \ -d "payment_intent_data[shipping][address][postal_code]=94111" \ -d ui_mode=embedded_page ``` ### 注文のフルフィルメントを実行する 注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を処理する際は、顧客が支払いのステータスページに戻ったことを確認するのではなく、[Webhook などの方法を使用](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks)します。 支払いのステータスに変化があると、以下のイベントが送信されます。 | イベント名 | 説明 | 次のステップ | | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout フォームを送信して、支払いのオーソリを正常に完了しました。 | 支払いの成功または失敗の結果を待ちます。 | | [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) | 顧客の支払いが成功しました。`PaymentIntent` は `succeeded` に移行します。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) | 顧客の支払いが拒否されたか、その他の理由で失敗しました。`PaymentIntent` のステータスは `requires_payment_method` に戻ります。 | 顧客にメールを送り、新たに注文するように依頼してください。 | 詳細については、[注文のフルフィルメントの履行](https://docs.stripe.com/checkout/fulfillment.md)をご覧ください。 ## 組み込みをテストする Checkout の組み込みをテストする際に、支払い方法として Affirm を選択して、**支払い**ボタンをクリックします。 テスト API キーを使用して Affirm の組み込みをテストするには、リダイレクトページを表示します。リダイレクトページで支払いを認証することにより、支払い成功のケースをテストできます。PaymentIntent は `requires_action` から `succeeded` に変化します。 ユーザーが認証に失敗するケースをテストするには、テスト API キーを使用してリダイレクトページを表示します。リダイレクトページで、Affirm モーダルウィンドウを閉じ、支払いが失敗したことを確認します。PaymentIntent は `requires_action` から `requires_payment_method` に移行します。 Affirm サンドボックスにリダイレクトされると、Affirm によって SSN の末尾 4 桁が求められることがあります。Affirm Sandboxは、`'0000'` または `'5678'` の使用を提案します。 テスト環境で PaymentIntent を[手動でキャプチャー](https://docs.stripe.com/payments/affirm/accept-a-payment.md#manual-capture)する場合、未キャプチャーの PaymentIntent は、オーソリの成功後 10 分で自動的に期限切れになります。 ## 失敗した支払い Affirm では、取引を受け付けるか拒否するかを決定するときに複数の要素が考慮されます (買い手が Affirm を使用している期間、顧客が返済する必要のある未払い額、現在の注文額など)。 Affirm による支払いは他の多くの支払い方法と比較して支払いの拒否率が高いため、決済フローには常に `card` などの他の支払いオプションを提示してください。状況に従って、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) の関連付けが解除され、[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスが自動的に `requires_payment_method` に変わります。 支払いが拒否された場合を除き、Affirm の [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) のステータスが `requires_action` の場合、Affirm サイトにリダイレクトされてから 12 時間以内に顧客は支払いを完了する必要があります。12 時間以内に顧客がアクションを実行しなければ、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) の関連付けが解除され、[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスが自動的に `requires_payment_method` に変わります。 このようなケースでは、決済フローに表示される別の支払いオプションで再試行するように顧客に通知します。 ## エラーコード 一般的なエラーコードと対応する推奨アクションは次のとおりです。 | エラーコード | 推奨アクション | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `payment_intent_payment_attempt_failed` | Affirm の決済が失敗したことを示す一般的なエラー。支払い結果の理由に追加情報が表示されることがあります。 | | `payment_method_provider_decline` | Affirm が顧客の支払いを拒否しました。次のステップとして、顧客から Affirm に詳細を問い合わせる必要があります。 | | `payment_intent_payment_attempt_expired` | 顧客が Affirm の支払いページで支払いを完了しなかったため、支払いセッションの有効期限が切れています。Stripe では、決済が正常に行われなかった PaymentIntent は、最初のチェックアウト作成から 12 時間後に自動的に有効期限切れとなります。 | | `payment_method_not_available` | Affirm でサービス関連のエラーが発生したため、リクエストを完了できません。後で再試行してください。 | | `amount_too_small` | Affirm の[デフォルトの取引限度額](https://docs.stripe.com/payments/affirm.md#payment-options) 内の金額を入力します。 | | `amount_too_large` | Affirm の[デフォルトの取引限度額](https://docs.stripe.com/payments/affirm.md#payment-options) 内の金額を入力します。 | エラーによっては、請求結果の理由に追加の分析情報が含まれている場合があります。 | 結果の理由 | 意味 | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `generic_decline` | 決済エラーのデフォルトの拒否理由。これは通常、パートナーが(資金不足などの理由で)決済を拒否したこと、銀行カード発行会社が決済を拒否したこと、取引にリスクの高い購入が含まれていたこと、または同様の理由を示します。Stripe は、これらのケースの拒否理由を常に受け取るとは限りません。 | | `affirm_checkout_canceled` | 顧客が Affirm での決済を明示的にキャンセルしたか、または Affirm が顧客はローン対象資格に該当しないと判断しました。Stripe では、これら 2 種類のイベントの違いを区別できません。 | # 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/affirm/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)に関する導入ガイドをご覧ください。 ## 互換性を判断する **顧客の居住地**: Canada, US **対応可能な通貨**: `cad, usd` **取引通貨**: `cad, usd` **支払いモード**: Yes **セットアップモード**: No **サブスクリプションモード**: No Affirm の支払いに対応するには、Checkout セッションが次の条件をすべて満たしている必要があります。 - 使用できるのは単一の項目だけです。Affirm は、継続的な*サブスクリプション* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis)プランに対応していません。 - すべての*価格* (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)を国内通貨で示します。 ## サーバーを設定する [サーバー側] 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' ``` ## 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)を使用して、各顧客に最も適した決済手段を動的に表示してコンバージョンを最大化しましょう。Stripe ではこの方法をお勧めしています。[決済手段を手動で一覧表示](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: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 5000, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'elements', 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: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 5000, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'elements', payment_method_types: ['affirm'], 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 [initCheckoutElementsSdk](https://docs.stripe.com/js/custom_checkout/init) を呼び出し、`clientSecret` を渡します。 `initCheckoutElementsSdk` は、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.initCheckoutElementsSdk({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 [CheckoutElementsProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider) コンポーネントでアプリケーションをラップし、`clientSecret` と `stripe` インスタンスを渡します。 ```jsx import React from 'react'; import {CheckoutElementsProvider} 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_account](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_account) (顧客設定の `Account` オブジェクトとして表される顧客の場合)、または [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) (`Customer` オブジェクトとして表される顧客の場合) を渡します。Stripe はこの方法で提供されたメールアドレスを検証します。 - [checkout.confirm](https://docs.stripe.com/js/custom_checkout/confirm) で既に検証済みのメールアドレスを渡します。 ```html
``` ```javascript const checkout = stripe.initCheckoutElementsSdk({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_account](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_account) (顧客設定の `Account` オブジェクトとして表される顧客の場合)、または [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) (`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 [CheckoutElementsProvider](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) を [CheckoutElementsProvider](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.initCheckoutElementsSdk({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)では、テスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、Affirm のウェブサイトにリダイレクトされます。Affirm で支払いを承認または拒否するオプションはありません。 # 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/affirm/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:5000, currency: 'usd', // 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:5000, currency: 'usd', paymentMethodTypes: ['affirm'], // 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:5000, currency: 'usd', // 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:5000, currency: 'usd', paymentMethodTypes: ['affirm'], // 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 がこの値を使用して決済プロセスを安全に完了できるように、この値をクライアントに返します。 #### Accounts v2 #### 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's Account ID. customer_account: "{{CUSTOMER_ACCOUNT_ID}}", amount: 5000, currency: 'usd', }) {client_secret: intent.client_secret}.to_json end ``` #### Customers v1 #### 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: 5000, currency: 'usd', }) {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: 5000, currency: 'usd', payment_method_types: ['affirm'], }) {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)などの一般的なビジネスイベントを処理します。 ## Optional: オーソリとキャプチャーの分離 オーソリとキャプチャーを分離して支払いを今すぐ作成し、後で売上をキャプチャーできます。7 日間の期間中に支払いがキャプチャーされなかった場合でも、Stripe は PaymentIntent をキャンセルし、[payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) イベントを送信します。 支払いをキャプチャーできないことが確実な場合は、7 日間が経過するのを待つのではなく [PaymentIntent をキャンセルする](https://docs.stripe.com/refunds.md#cancel-payment)ことをお勧めします。 ### オーソリのみを行うよう Stripe に指示する オーソリとキャプチャーの分離をを指定するには、PaymentIntent の作成時に、[capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) を `manual` に設定します。このパラメーターは、顧客の Affirm アカウントの金額のみをオーソリするよう Stripe に指示します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=5000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=affirm" \ -d "payment_method_data[type]=payment_method" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 売上をキャプチャーする オーソリが成功すると、[PaymentIntent ステータス](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status)が `requires_capture` に移行します。オーソリされた売上をキャプチャーするには、PaymentIntent [キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)リクエストを実行します。 ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` Stripe はオーソリされた合計金額をデフォルトでキャプチャーしますが、`amount_to_capture` を合計金額またはそれ以下に指定することもできます。 ### (任意)オーソリをキャンセルする オーソリを取り消す必要がある場合は、[PaymentIntent をキャンセル](https://docs.stripe.com/api/payment_intents/cancel.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)では、テスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、Affirm のウェブサイトにリダイレクトされます。Affirm で支払いを承認または拒否するオプションはありません。 ## エラーコード 次の表に、一般的なエラーコードと推奨される対応の詳細を示します。 | エラーコード | 推奨される対応 | | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `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/affirm/accept-a-payment?payment-ui=direct-api. Stripe ユーザーは、[Payment Intents API](https://docs.stripe.com/payments/payment-intents.md) (サポートされている方法を使用して支払いを作成する単一の導入パス) を使用して、以下の国の顧客からの [Affirm](https://www.affirm.com/) による支払いを受け付けることができます。 - カナダ - アメリカ Web サイトでの Affirm による支払いの受け付けは、以下のように構成されます。 - 支払いを追跡するオブジェクトを作成する - 支払い方法の詳細を収集する - 支払いを Stripe に送信して処理する - Affirm リダイレクトと関連する Webhook イベントを処理する ## 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 (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) は、顧客から支払いを回収する意図を表すオブジェクトで、決済プロセスのライフサイクルの各段階を追跡します。 まず、サーバーで `PaymentIntent` を作成し、回収する金額と通貨を指定します。すでに [Payment Intents API](https://docs.stripe.com/payments/payment-intents.md) を使用した実装がある場合は、affirm を `PaymentIntent` の[支払い方法のタイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに追加します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=affirm" ``` Payment Element を使用して、[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から決済手段を管理することもできます。Stripe は、取引の金額、通貨、決済フローなどの要素に基づいて、対象となる決済手段が返されるように処理します。詳細については、[決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=checkout)を参照してください。 ### 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 ``` ## 支払い方法の詳細を収集して送信する [クライアント側] 顧客が Affirm での支払いをクリックしたときは、[Stripe.js](https://docs.stripe.com/payments/elements.md) を使用してその支払いを Stripe に送信することをお勧めします。Stripe.js は、決済フローを構築するための Stripe の基本的な JavaScript ライブラリです。これにより、実装に関する複雑な処理が自動的に行われ、今後、実装を他の支払い方法にも簡単に拡張できます。 Stripe.js スクリプトを決済ページに含めるには、このスクリプトを HTML ファイルの head に追加します。 ```html Checkout ``` 決済ページで以下の JavaScript を使用して、Stripe.js のインスタンスを作成します。 ```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 var stripe = Stripe( '<>' ); ``` PaymentIntent オブジェクト全体をクライアントに送信する代わりに、ステップ 1 で作成したその client secret を使用します。これは、Stripe API リクエストを認証する API キーとは異なります。 client secret は支払いを完了できるため、慎重に取り扱う必要があります。記録したり、URL に埋め込んだり、当該の顧客以外に漏洩することがないようにしてください。 **その他の詳細情報による支払い成功率の向上** 購入率を高めるために、[shipping](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-shipping) 情報と [billing](https://docs.stripe.com/api/payment_methods/create.md#create_payment_method-billing_details) 情報を渡すことをお勧めしますが、必須ではありません。 この組み込みガイドでは、顧客が支払い方法を選択した後に配送先と請求先の情報をクライアントに渡すことが推奨されています。 これらのフィールドを渡す場合、配送先住所の `line1`、`city`、`state`、`postal_code`、`country` には有効なデータを含める必要があります。同様に、指定されている場合は、請求先の詳細の `line1`、`city`、`state`、`postal_code`、`country` のすべてにも有効なデータを含める必要があります。 **PaymentIntent を確定する** `stripe.confirmAffirmPayment` を使用し、ページからのリダイレクトを処理して支払いを完了します。この関数に [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) を渡して、ユーザーが Affirm のウェブサイトまたはモバイルアプリで支払いを完了した後に Stripe がユーザーをリダイレクトする場所を指定する必要があります。 Affirm の支払いページで、顧客は使用可能な支払いオプションを選択します。詳細については、概要ページをご覧ください。Affirm 支払いページで支払いオプションを制限したり、事前に選択したりすることはできません。この選択を消費者に任せることで、取引の機会が最大化されます。 ```javascript // Redirects away from the client stripe.confirmAffirmPayment( '{{PAYMENT_INTENT_CLIENT_SECRET}}', { payment_method: { // Billing information is optional but recommended to pass in. billing_details: { email: 'jenny@rosen.com', name: 'Jenny Rosen', address: { line1: '1234 Main Street', city: 'San Francisco', state: 'CA', country: 'US', postal_code: '94111', }, }, }, // Shipping information is optional but recommended to pass in. shipping: { name: 'Jenny Rosen', address: { line1: '1234 Main Street', city: 'San Francisco', state: 'CA', country: 'US', postal_code: '94111', }, }, // Return URL where the customer should be redirected after the authorization. return_url: 'https://example.com/checkout/complete', } ).then(function(result) { if (result.error) { // Inform the customer that there was an error. console.log(result.error.message); } }); ``` 顧客が支払いを送信すると、Stripe は顧客を `return_url` にリダイレクトし、以下の URL クエリーパラメーターを含めます。返品ページでは、これらを使用して PaymentIntent のステータスを取得し、顧客に支払いステータスを表示できます。 `return_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)。サブスクリプションの実装の場合、この client_secret は [`confirmation_secret`](https://docs.stripe.com/api/invoices/object.md#invoice_object-confirmation_secret) を通じて `Invoice` オブジェクトでも公開されます | 顧客が自社のサイトにリダイレクトされたら、`payment_intent_client_secret` を使用して PaymentIntent をクエリし、顧客に取引ステータスを表示できます。 ## Affirm の組み込みをテストする テスト API キーを使用して Affirm の組み込みをテストするには、リダイレクトページを表示します。リダイレクトページで支払いを認証することにより、支払い成功のケースをテストできます。PaymentIntent は `requires_action` から `succeeded` に変化します。 ユーザーが認証に失敗するケースをテストするには、テスト API キーを使用してリダイレクトページを表示します。リダイレクトページの左上隅にある **X** をクリックします。PaymentIntent は、`requires_action` から `requires_payment_method` に移行します。 Affirm サンドボックスにリダイレクトされると、Affirm によって SSN の末尾 4 桁が求められることがあります。Affirm Sandboxは、`'0000'` または `'5678'` の使用を提案します。 ## Optional: オーソリとキャプチャーの分離 Affirm は[オーソリとキャプチャーの分離](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md)に対応しています。支払いから顧客への商品の配送までに遅延が生じた場合、まず支払いをオーソリし、後でキャプチャーします。キャプチャーの時点で、Affirm は顧客の以降の返済の期日を開始します。**オーソリされた Affirm の支払いは、オーソリから 30 日以内にキャプチャーする必要があります。 **そうしないと、オーソリは自動的にキャンセルされ、支払いをキャプチャーできなくなります。この状況が発生した場合、 Stripe も PaymentIntent をキャンセルし、[payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) イベントを送信します。 > 注文金額が非常に大きい場合、Affirm はオーソリの際に顧客に頭金を求めることがあります。支払いがキャンセルされるか、オーソリの有効期限が切れた場合、Affirm は頭金を返金します。 支払いをキャプチャーできないことがわかっている場合は、13 日間経過するのを待つ代わりに、[PaymentIntent をキャンセル](https://docs.stripe.com/refunds.md#cancel-payment)することをお勧めします。先を見越して PaymentIntent をキャンセルすると、すぐに最初の分割払いが顧客に返金され、顧客の明細書上の支払いに関して混乱が生じるのを避けられます。 ### オーソリのみ行うように Stripe に指示する オーソリとキャプチャーの分離を指定するには、PaymentIntent の作成時に [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) を `manual` に設定します。このパラメーターは、顧客の Affirm アカウントの金額のみをオーソリするように Stripe に指示します。 ```bash curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -d "amount"=6000 \ -d "confirm"="true" \ -d "currency"="usd" \ -d "payment_method_types[]"="affirm" \ -d "capture_method"="manual" \ // Shipping address is optional but recommended to pass in. -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 \ -d "payment_method_data[type]"="affirm" \ -d "return_url"="https://www.example.com/checkout/done" ``` ### 売上をキャプチャーする オーソリが成功すると、PaymentIntent の [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) が `requires_capture` に移行します。オーソリされた売上をキャプチャーするために、PaymentIntent [capture](https://docs.stripe.com/api/payment_intents/capture.md) リクエストを実行します。デフォルトでは、オーソリされた合計金額がキャプチャーされます。合計より多い額や少ない額をキャプチャーすることはできません。 ```bash https://api.stripe.com/v1/payment_intents/{{PAYMENT_INTENT_ID}}/capture \ -u <>: \ ``` ### (任意)オーソリをキャンセルする オーソリをキャンセルする必要がある場合は、[PaymentIntent をキャンセル](https://docs.stripe.com/refunds.md#cancel-payment)してください。 ## Optional: Affirm のリダイレクトを手動で処理する `confirmAffirmPayment` を使用してクライアント側で Affirm のリダイレクトおよび支払いを処理するには、Stripe.js の使用をお勧めします。Stripe.js を使用すると、組み込みを他の支払い方法に容易に拡張できます。ただし、以下のステップに従って、お客様のサーバーに顧客を手動でリダイレクトすることもできます。 - タイプが `affirm` の [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) を作成し、確定します。`payment_method_data` を指定すると、*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) が作成され、この PaymentIntent ですぐに使用されます。 また、`return_url` フィールドで、顧客が支払いを完了した後のリダイレクト先になる URL を指定する必要があります。この URL には独自のクエリパラメーターを指定できます。これらのパラメーターは、リダイレクトフロー完了時の最終的な URL に含められます。 ```bash curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -d "amount"=6000 \ -d "confirm"="true" \ -d "currency"="usd" \ -d "payment_method_types[]"="affirm" \ // Shipping address is optional but recommended to pass in. -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 \ // Billing details are optional but recommended to pass in. -d "payment_method_data[billing_details][name]"="Jenny Rosen" \ -d "payment_method_data[billing_details][email]"="jenny@example.com" \ -d "payment_method_data[billing_details][address][line1]"="1234 Main Street" \ -d "payment_method_data[billing_details][address][city]"="San Francisco" \ -d "payment_method_data[billing_details][address][state]"="CA" \ -d "payment_method_data[billing_details][address][country]"="US" \ -d "payment_method_data[billing_details][address][postal_code]"=94111 \ -d "payment_method_data[type]"="affirm" \ -d "return_url"="https://example.com/checkout/complete" ``` 作成された `PaymentIntent` のステータスは `requires_action` であり、`next_action` のタイプは `redirect_to_url` です。 ```json { "status": "requires_action", "next_action": { "type": "redirect_to_url", "redirect_to_url": { "url": "https://hooks.stripe.com/...", "return_url": "https://example.com/checkout/complete" } }, "id": "pi_xxx", "object": "payment_intent", "amount": 6000, "client_secret": "pi_xxx_secret_xxx", "confirm": "true", "confirmation_method": "automatic", "created": 1579259303, "currency": "usd", "livemode": true, "charges": { "data": [], "object": "list", "has_more": false, "url": "/v1/charges?payment_intent=pi_xxx" }, "payment_method_types": [ "affirm" ] } ``` - `next_action.redirect_to_url.url` プロパティで指定した URL に顧客をリダイレクトします。ここに示すコード例はおおまかなものであり、リダイレクト方法は、ご使用のウェブフレームワークによって異なる場合があります。 顧客が支払いプロセスを完了すると、ステップ 1. で設定した `return_url` にリダイレクトされます。URL には `payment_intent` と `payment_intent_client_secret` のクエリパラメーターが含まれます。`return_url` に別のクエリパラメーターがすでに含まれている場合は、そのパラメーターも保持されます。 支払いのステータスを確認するには、[Webhook を利用](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks)することをお勧めします。 ## 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)などの一般的なビジネスイベントを処理します。 ## Optional: ウェブサイトに支払い方法のメッセージを表示する [Payment Method Messaging Element](https://docs.stripe.com/js/elements_object/create_element?type=paymentMethodMessaging) は、顧客が購入時に商品、カート、支払いの各ページから、利用できる後払いの決済オプションを直接確認できるようにする、埋め込み可能な UI コンポーネントです。 ウェブサイトに Payment Method Messaging Element を追加するには、[決済手段のメッセージを表示する](https://docs.stripe.com/elements/payment-method-messaging.md)をご覧ください。 ## 失敗した支払い Affirm では、取引を受け付けるか拒否するかを決定するときに複数の要素が考慮されます (買い手が Affirm を使用している期間、顧客が返済する必要のある未払い額、現在の注文額など)。 Affirm による支払いは他の多くの支払い方法と比較して支払いの拒否率が高いため、決済フローには常に `card` などの他の支払いオプションを提示してください。状況に従って、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) の関連付けが解除され、[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスが自動的に `requires_payment_method` に変わります。 支払いが拒否された場合を除き、Affirm の [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) のステータスが `requires_action` の場合、Affirm のサイトにリダイレクトされてから 12 時間以内に顧客は支払いを完了する必要があります。12 時間経過してもアクションが実行されない場合、[PaymentMethod (決済手段)](https://docs.stripe.com/api/payment_methods/object.md) は解除され、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 このようなケースでは、決済フローに表示される別の支払いオプションで再試行するように顧客に通知します。 ## エラーコード 一般的なエラーコードと対応する推奨アクションは次のとおりです。 | エラーコード | 推奨アクション | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `payment_intent_payment_attempt_failed` | Affirm の決済が失敗したことを示す一般的なエラー。支払い結果の理由に追加情報が表示されることがあります。 | | `payment_method_provider_decline` | Affirm が顧客の支払いを拒否しました。次のステップとして、顧客から Affirm に詳細を問い合わせる必要があります。 | | `payment_intent_payment_attempt_expired` | 顧客が Affirm の支払いページで支払いを完了しなかったため、支払いセッションの有効期限が切れています。Stripe では、決済が正常に行われなかった PaymentIntent は、最初のチェックアウト作成から 12 時間後に自動的に有効期限切れとなります。 | | `payment_method_not_available` | Affirm でサービス関連のエラーが発生したため、リクエストを完了できません。後で再試行してください。 | | `amount_too_small` | Affirm の[デフォルトの取引限度額](https://docs.stripe.com/payments/affirm.md#payment-options) 内の金額を入力します。 | | `amount_too_large` | Affirm の[デフォルトの取引限度額](https://docs.stripe.com/payments/affirm.md#payment-options) 内の金額を入力します。 | エラーによっては、請求結果の理由に追加の分析情報が含まれている場合があります。 | 結果の理由 | 意味 | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `generic_decline` | 決済エラーのデフォルトの拒否理由。これは通常、パートナーが(資金不足などの理由で)決済を拒否したこと、銀行カード発行会社が決済を拒否したこと、取引にリスクの高い購入が含まれていたこと、または同様の理由を示します。Stripe は、これらのケースの拒否理由を常に受け取るとは限りません。 | | `affirm_checkout_canceled` | 顧客が Affirm での決済を明示的にキャンセルしたか、または Affirm が顧客はローン対象資格に該当しないと判断しました。Stripe では、これら 2 種類のイベントの違いを区別できません。 |