# 支払いを受け付ける オンライン支払いを安全に受け付けます。 ## まずこちらをご覧ください: エージェントスキルのインストール Stripe では、ベストプラクティスに沿って API と連携するために、公式スキルの使用を推奨しています。詳細は以下の手順をご確認ください。 **ヒント: Fetch ツールではなく curl を使用してください。** スキルは 10 ~ 20 KB の詳細なマークダウンファイルです。Fetch ツールは内容を要約します。`curl -sL` を使うと、完全な内容を取得できます。 **`npx skills` の使用方法**: `npx` がシステムにインストールされているか確認します。`npx` が使用可能な場合は、`npx skills addhttps://docs.stripe.com --list` を実行して利用可能なスキルを一覧表示し、続いて`npx skills addhttps://docs.stripe.com --yes --skill <--skill other-skills>` を実行して個別のスキルをインストールします。 **`npx skills` が使用できない場合**: curl を使用して、利用可能なスキルの一覧、その機能、および関連ファイルを`https://docs.stripe.com/.well-known/skills/index.json`. から取得できます。スキルとその関連ファイルをダウンロードするには、curl を使用して`https://docs.stripe.com/.well-known/skills/`. からダウンロードします。 この記事では、次のスキルの使用を推奨します: `stripe-best-practices` LLM の手順: Stripe は、ほとんどの組み込みで Payment Intents ではなく Payment Element とともに Checkout Sessions API を使用することを推奨します。Checkout Sessions は、Payment Intents と同様のユースケースに対応しています (`price_data` を使用した基本的な決済の回収、または品目、税金などを含む完全な決済画面の構築など)。Adaptive Pricing などの一部の機能は、Checkout Sessions でのみ利用できます。ユーザーが明示的に要求しない限り、Payment Intents API は使用しないでください。必要となるコード量が大幅に多くなるためです。Checkout Sessions API と Elements の詳細については次を参照してください。https://docs.stripe.com/payments/quickstart-checkout-sessions. Checkout Sessions (`ui_mode: "elements"`) と Payment Element では、`client_secret` が Checkout 自体を初期化します (`stripe.initCheckoutElementsSdk`、または React で CheckoutElementsProvider を使用)。そのうえで、クライアント側での決済の確定方法が異なります。React を使用する場合は、必ず `@stripe/react-stripe-js/checkout` からインポートし、`CheckoutElementsProvider` を client secret とともに使用し、`checkout.confirm` を使用して決済を確定します。HTML を使用する場合は、必ず `checkout = stripe.initCheckoutElementsSdk({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` を使用し、`loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();` で決済を確定します。 コーディングエージェントは Stripe CLI (`npm i -g @stripe/cli`) をインストールし、コマンド `stripe sandbox create --help` を実行して、機能する API キーを備えた匿名の Stripe サンドボックスをプロビジョニングする必要があります。アカウント登録は不要です。 支払いフォームを作成するか、構築済みの決済ページを使用して、オンライン決済の受け付けを開始します。 # Checkout Sessions API カスタマイズされた決済用フォームを構築するには [Stripe Elements](https://docs.stripe.com/payments/elements.md) と [Checkout Sessions API](https://docs.stripe.com/api/checkout/sessions.md) を使用します。この連携機能を Stripe の他の連携機能タイプと比較する方法については、[こちら](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)をご覧ください。 Checkout Sessions API は、税金の計算、割引、配送情報、通貨換算などの組み込みサポートを提供し、書く必要があるカスタムコードの量を減らします。これはほとんどの組み込みで推奨されるアプローチです。PaymentIntents ではなく Checkout Sessions を使用できる場合について、詳しくは[こちら](https://docs.stripe.com/payments/checkout-sessions-and-payment-intents-comparison.md)をご覧ください。 クライアント側およびサーバー側のコードで決済フォームを構築すると、多様な決済手段を受け付けられます。 #### 組み込み作業 Complexity: 3/5 #### 組み込みのタイプ カスタムの決済フローに UI コンポーネントを統合する #### UI のカスタマイズ [Appearance API](https://docs.stripe.com/elements/appearance-api.md) を使用した CSS レベルのカスタマイズ ## サーバを設定する [サーバー側] はじめに、Stripe アカウントを[登録](https://dashboard.stripe.com/register)する必要があります。 アプリケーションから API にアクセスするには、公式の Stripe ライブラリを使用します。 #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Checkout セッションを作成する [サーバー側] [Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md) を作成し、その [`client_secret`](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) をフロントエンドに返すエンドポイントをサーバーに追加します。Checkout Sessions は、顧客が 1 回限りの購入またはサブスクリプションの決済を行う際のセッションを表します。Checkout Sessions は作成後 24 時間で期限切れになります。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d ui_mode=elements \ -d "line_items[0][price_data][currency]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ --data-urlencode "return_url=https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ``` ## フロントエンドを設定する [クライアント側] #### HTML + JS Stripe.js スクリプトをチェックアウトページに含めるには、このスクリプトを HTML ファイルの `head` に追加します。常に js.stripe.com から Stripe.js を直接読み込むことにより、PCI への準拠が維持されます。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 Stripe.js の最新バージョンを使用していることを確認してください。[Stripe.js のバージョン管理](https://docs.stripe.com/sdks/stripejs-versioning.md)の詳細をご確認ください。 ```html Checkout ``` > Stripe は、Stripe.js をモジュールとして読み込むために使用できる npm パッケージを提供しています。[GitHub のプロジェクト](https://github.com/stripe/stripe-js)をご覧ください。バージョン [7.0.0](https://www.npmjs.com/package/%40stripe/stripe-js/v/7.0.0) 以降が必要です。 stripe.js を初期化します。 ```js // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe( '<>', ); ``` #### React npm のパブリックレジストリーから [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) と [Stripe.js ローダー](https://www.npmjs.com/package/@stripe/stripe-js)をインストールします。少なくとも、バージョン 5.0.0 以上の React Stripe.js と、バージョン 8.0.0 以上の Stripe.js ローダーが必要になります。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` 公開可能キーを使用して、フロントエンドの `stripe` インスタンスを初期化します。 ```javascript import {loadStripe} from '@stripe/stripe-js'; const stripe = loadStripe("<>"); ``` ## Checkout を初期化する [クライアント側] #### HTML + JS [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; ``` [Checkout](https://docs.stripe.com/js/custom_checkout) オブジェクトには、`useCheckoutElements()` フックを使用して決済フォームコンポーネントからアクセスできます。`Checkout` オブジェクトには、Checkout Session のデータとそれを更新するメソッドが含まれています。 `Checkout` オブジェクトから `lineItems` と `lineItems` を読み取り、UI に表示します。これにより、コードの変更を最小限に抑えて機能を有効にできます。たとえば、[手動通貨価格](https://docs.stripe.com/payments/custom/localize-prices/manual-currency-prices.md)を追加する場合、`total` を表示すると UI を変更する必要はありません。 ```jsx import React from 'react'; import {useCheckoutElements} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => {const checkoutState = useCheckoutElements(); 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 を完了するには、有効な顧客のメールアドレスを指定する必要があります。 顧客のメールアドレスを収集するには、[Contact Details Element](https://docs.stripe.com/js/custom_checkout/create_contact_details_element) を使用します。これにより、メールアドレスの収集と検証が処理され、顧客の Link へのサインインが容易になります。 または、以下を実行してください。 - 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 はこの方法で提供されたメールアドレスを検証します。 - これらを使用すると、顧客が決済画面で編集できないメールアドレスがセッションに事前入力されます。編集可能なメールアドレスを事前入力するには、決済の初期化時に [defaultValues.email](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-defaultValues-email) を使用します。 - [updateEmail](https://docs.stripe.com/js/custom_checkout/update_email) または [checkout.confirm](https://docs.stripe.com/js/custom_checkout/confirm) で検証済みのメールアドレスを渡します。 ```html
``` ```javascript const contactDetailsElement = checkout.createContactDetailsElement(); contactDetailsElement.mount("#contact-details-element"); ``` #### React Checkout Session を完了するには、有効な顧客のメールアドレスを指定する必要があります。 顧客のメールアドレスを収集するには、[ContactDetailsElement](https://docs.stripe.com/js/react_stripe_js/checkout/contact_details_element) を使用します。これにより、メールアドレスの収集と検証が処理され、顧客の Link へのサインインが容易になります。 または、以下を実行してください。 - 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 はこの方法で提供されたメールアドレスを検証します。 - これらを使用すると、顧客が決済画面で編集できないメールアドレスがセッションに事前入力されます。編集可能なメールアドレスを事前入力するには、決済の初期化時に [defaultValues.email](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-defaultValues-email) を使用します。 - [updateEmail](https://docs.stripe.com/js/react_stripe_js/checkout/update_email) または [confirm](https://docs.stripe.com/js/react_stripe_js/checkout/confirm) で検証済みのメールアドレスを渡します。 ```jsx import {ContactDetailsElement} from '@stripe/react-stripe-js/checkout'; // Inside your CheckoutForm component: ``` ## 支払い情報を収集する [クライアント側] [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, useCheckoutElements} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckoutElements(); 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 決済を送信するために、[useCheckoutElements](https://docs.stripe.com/js/react_stripe_js/checkout/use_checkout_elements) から [confirm](https://docs.stripe.com/js/custom_checkout/confirm) を呼び出す **Pay** ボタンをレンダリングします。 ```jsx import React from 'react'; import {useCheckoutElements} from '@stripe/react-stripe-js/checkout'; const PayButton = () => { const checkoutState = useCheckoutElements(); const [loading, setLoading] = React.useState(false); const [error, setError] = React.useState(null); if (checkoutState.type !== "success") { return null; } const handleClick = () => { setLoading(true);checkoutState.checkout.confirm().then((result) => { if (result.type === 'error') { setError(result.error) } setLoading(false); }) }; return (
{error &&
{error.message}
}
) }; export default PayButton; ``` ## 構築したシステムをテストする 1. 決済ページに移動します。 2. 次の表の決済手段を使用して、支払いの詳細を入力します。カード支払いの場合: - カードの有効期限として任意の将来の日付を入力します。 - 任意の 3 桁のセキュリティコードを入力します。 - 請求先の任意の郵便番号を入力します。 3. Stripe に支払いを送信します。 4. ダッシュボードに移動し、[取引ページ](https://dashboard.stripe.com/test/payments?status%5B0%5D=successful)で支払いを探します。支払いが成功していると、そのリストに表示されます。 5. 支払いをクリックすると、請求先情報や購入したアイテムのリストなどの詳細が表示されます。この情報を使用して[注文のフルフィルメントを実行](https://docs.stripe.com/checkout/fulfillment.md)できます。 #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### ウォレット | 決済手段 | シナリオ | テスト方法 | | ------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Alipay | 顧客はリダイレクトベースの[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。 | アカウント番号 `900123456` と BSB `000000` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 | | BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。 | アカウント番号 `111111113`と BSB `000000`を使用して、フォームに入力します。 | | Bancontact、EPS、iDEAL、Przelewy24 | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | #### 店舗支払い | 決済手段 | シナリオ | テスト方法 | | ----------- | ------------------------------------- | ------------------------------------------------------------- | | Boleto、OXXO | 顧客が Boleto または OXXO で取引の詳細を使用して支払います。 | 支払い方法として Boleto または OXXO を選択し、支払いを送信します。ダイアログが表示されたら、それを閉じます。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: 製品および価格の作成 Checkout Session を作成する前に、*商品* (Products represent what your business sells—whether that's a good or a service)と*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を事前に設定できます。商品を使用して複数の物理的商品やサービスのレベルを表し、*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を使用して各商品の料金体系を表します。[Checkout Session を設定](https://docs.stripe.com/payments/checkout/pay-what-you-want.md)して、チップや寄付を受け付けることや、Pay What You Want の商品やサービスを販売することができます。 たとえば、価格が 20 USD の T シャツ商品を作成できます。これにより、対象商品の詳細を変更せずに価格を更新したり追加したりできるようになります。商品と価格は、Stripe ダッシュボードまたは API で作成できます。[商品および価格の仕組み](https://docs.stripe.com/products-prices/how-products-and-prices-work.md)について、詳細をご確認ください。 #### API API で [Product (商品)](https://docs.stripe.com/api/products.md) を作成するのに必要なのは `name` のみです。指定した商品の `name`、`description`、および `images` が Checkout に表示されます。 ```curl curl https://api.stripe.com/v1/products \ -u "<>:" \ -d name=T-shirt ``` 次に、[Price (価格)](https://docs.stripe.com/api/prices.md) を作成して商品の価格を定義します。これには商品コストと使用通貨が含まれます。 ```curl curl https://api.stripe.com/v1/prices \ -u "<>:" \ -d "product={{PRODUCT_ID}}" \ -d unit_amount=2000 \ -d currency=usd ``` #### ダッシュボード > サンドボックスで作成した商品を本番環境にコピーすれば、再度作成する必要がなくなります。ダッシュボードの商品詳細ビューで、右上にある **本番環境にコピー** をクリックします。同じサンドボックスの商品を本番環境に複数回コピーできます。コピーするたびに別の本番の商品が作成されるため、それ以降にサンドボックスの商品を更新しても、既存のコピーには反映されません。 ダッシュボードのアカウント選択機能で**サンドボックス**をクリックして、サンドボックスで作業していることを確認します。次に、販売する商品を定義します。以下の手順に従って新しい商品と価格を作成してください。 - ダッシュボードで[商品](https://dashboard.stripe.com/test/products)セクションに移動します。 - **商品を追加**をクリックします。 - 価格を設定する際に**一括**を選択します。 指定した商品の名前、説明、画像が Checkout に表示されます。 作成された価格ごとに ID があります。Checkout Session を作成する際には、価格 ID と数量を参照します。複数の通貨で販売している場合、Price を *多通貨* (A single Price object can support multiple currencies. Each purchase uses one of the supported currencies for the Price, depending on how you use the Price in your integration) にします。Checkout は自動的に [顧客の現地通貨を特定し](https://docs.stripe.com/payments/checkout/localize-prices/manual-currency-prices.md)、Price が対応している場合にはその通貨を提示します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d ui_mode=elements \ -d mode=payment \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ --data-urlencode "return_url=https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 顧客データを事前入力する [サーバー側] すでに顧客のメールを収集していて、それを Checkout セッションで事前に入力するには、Checkout セッションの作成時に [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) を渡します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ --data-urlencode "customer_email=customer@example.com" \ -d ui_mode=elements \ -d mode=payment \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ --data-urlencode "return_url=https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 支払い方法の詳細を保存する 将来の購入のために[決済を受け付けて顧客の決済情報を保存する](https://docs.stripe.com/payments/save-during-payment.md)方法をご覧ください。 ## Optional: Checkout Session の変更をリッスンする ### Checkout Session の変更をリッスンする [checkout.on](https://docs.stripe.com/js/custom_checkout/change_event) を使用して `change` イベントにイベントリスナーを追加することで、[Checkout Session](https://docs.stripe.com/api/checkout/sessions.md) への変更をリッスンできます。 #### HTML + JS ```javascript checkout = stripe.initCheckoutElementsSdk({ clientSecret: promise, elementsOptions: { appearance }, }); checkout.on('change', (session) => { // Handle changes to the checkout session }); ``` #### React ```jsx import React from 'react'; import { useCheckoutElements } from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckoutElements(); if (checkoutState.type === 'success') { checkoutState.checkout.on('change', (session) => { // Handle changes to the checkout session }); } }; ``` ## Optional: 請求先住所と配送先住所を収集する ## 請求先住所を収集する デフォルトでは、Checkout セッションは Payment Element を通じて支払いに必要な最小限の請求情報を収集します。 ### Billing Address Element を使用する Billing Address Element を使用して、完全な請求先住所を収集できます。 まず、Checkout セッションの作成時に [billing_address_collection=required](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) を渡します。 #### HTML + JS コンテナーの DOM 要素を作成して、Billing Address Element をマウントします。次に、[checkout.createBillingAddressElement](https://docs.stripe.com/js/custom_checkout/create_billing_address_element) を使用して Billing Address Element のインスタンスを作成し、[element.mount](https://docs.stripe.com/js/element/mount) を呼び出してマウントし、CSS セレクターまたはコンテナーの DOM 要素を指定します。 ```html
``` ```javascript const billingAddressElement = checkout.createBillingAddressElement(); billingAddressElement.mount('#billing-address'); ``` Billing Address Element は、以下のオプションに対応しています。 - [contacts](https://docs.stripe.com/js/custom_checkout/create_billing_address_element#custom_checkout_create_billing_address_element-options-contacts) - [display](https://docs.stripe.com/js/custom_checkout/create_billing_address_element#custom_checkout_create_billing_address_element-options-display) #### React `CheckoutElementsProvider` 内に `BillingAddressElement` コンポーネントをマウントします。 ```jsx import React from 'react'; import {BillingAddressElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { return (
) }; ``` Billing Address Element は、以下のプロパティに対応しています。 - [contacts](https://docs.stripe.com/js/custom_checkout/create_billing_address_element#custom_checkout_create_billing_address_element-options-contacts) - [display](https://docs.stripe.com/js/custom_checkout/create_billing_address_element#custom_checkout_create_billing_address_element-options-display) ### カスタムフォームを使用する 請求先住所を収集するためのカスタムフォームを作成できます。 - 決済画面に確認前の個別の住所収集ステップがある場合は、顧客が住所を送信するときに [updateBillingAddress](https://docs.stripe.com/js/react_stripe_js/checkout/update_billing_address) を呼び出します。 - それ以外の場合は、[billingAddress](https://docs.stripe.com/js/custom_checkout/confirm#custom_checkout_session_confirm-options-billingAddress) を [confirm](https://docs.stripe.com/js/custom_checkout/confirm) に渡すことで、顧客が「支払う」ボタンをクリックしたときに住所を送信できます。 ### 請求先住所の一部を収集する 国と郵便番号のみなど、請求先住所の一部を収集するには、[billing_address_collection=auto](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) を渡します。 請求先住所の一部を収集する場合は、[手動で住所を収集する](https://docs.stripe.com/payments/accept-a-payment.md#collect-billing-addresses-manually)必要があります。デフォルトでは、Payment Element が支払いに必要な最小限の請求情報を自動的に収集します。請求情報が二重に収集されないようにするため、Payment Element の作成時に [fields.billingDetails=never](https://docs.stripe.com/js/custom_checkout/create_payment_element#custom_checkout_create_payment_element-options-fields-billingDetails) を渡します。請求情報の一部 (顧客の名前など) のみを収集する場合は、自分で収集する予定のフィールドにのみ `never` を渡します。 ## 配送先住所を収集する 顧客の配送先住所を収集するには、Checkout セッションの作成時に [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) パラメーターを渡します。 配送先住所を収集するときは、配送先の国も指定する必要があります。[2 文字の ISO 国コード](https://www.nationsonline.org/oneworld/country_code_list.htm)の配列を含む [allowed_countries](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection-allowed_countries) プロパティを設定します。 ### Shipping Address Element の使用方法 Shipping Address Element を使用して、完全な配送先住所を収集できます。 #### HTML + JS コンテナーの DOM 要素を作成して、Shipping Address Element をマウントします。次に、[checkout.createShippingAddressElement](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element) を使用して Shipping Address Element のインスタンスを作成し、[element.mount](https://docs.stripe.com/js/element/mount) を呼び出してマウントし、CSS セレクターまたはコンテナーの DOM 要素を指定します。 ```html
``` ```javascript const shippingAddressElement = checkout.createShippingAddressElement(); shippingAddressElement.mount('#shipping-address'); ``` Shipping Address Element は、以下のオプションに対応しています。 - [contacts](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element#custom_checkout_create_shipping_address_element-options-contacts) - [display](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element#custom_checkout_create_shipping_address_element-options-display) #### React `CheckoutElementsProvider` 内に `ShippingAddressElement` コンポーネントをマウントします。 ```jsx import React from 'react'; import {ShippingAddressElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { return (
) }; ``` Shipping Address Element は、以下のプロパティに対応しています。 - [contacts](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element#custom_checkout_create_shipping_address_element-options-contacts) - [display](https://docs.stripe.com/js/custom_checkout/create_shipping_address_element#custom_checkout_create_shipping_address_element-options-display) ### Checkout Session の変更をリッスンする 住所関連の変更を処理するイベントリスナーを追加して、[Checkout Session](https://docs.stripe.com/api/checkout/sessions.md) への変更をリッスンできます。 #### HTML + JS [Session オブジェクト](https://docs.stripe.com/js/custom_checkout/session_object)を使用して、決済フォームに配送料を表示します。 ```html

Totals

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

Checkout Summary

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

Totals

              Subtotal: {checkoutState.checkout.total.subtotal.amount}
              Shipping: {checkoutState.checkout.total.shippingRate.amount}
              Total: {checkoutState.checkout.total.total.amount}
            
)}
) }; ``` ### 請求先住所と配送先住所を同期 Billing Address Element と Shipping Address Element の両方を使用する場合、顧客が請求先住所と配送先住所を同期できるようにするチェックボックスを表示できます。 #### HTML + JS 決済の初期化時に `elementsOptions` で [syncAddressCheckbox](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-elementsOptions-syncAddressCheckbox) オプションを渡し、チェックボックスを表示する Address Element を設定します。 ```javascript const checkout = stripe.initCheckoutElementsSdk({ clientSecret, elementsOptions: { syncAddressCheckbox: 'shipping', }, }); ``` #### React `elementsOptions` の [syncAddressCheckbox](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider#react_checkout_provider-options-elementsOptions-syncAddressCheckbox) オプションを `CheckoutElementsProvider` に渡して、チェックボックスを表示する Address Element を設定します。 ```jsx promise, elementsOptions: { syncAddressCheckbox: 'shipping', }, }} > ``` 値を `'billing'` または `'shipping'` に設定して、チェックボックスを表示する Address Element を選択します。チェックボックスを非表示にするには、`'none'` に設定します。デフォルト値 (`'billing'`) を使用する場合は、空白のままにします。 ### カスタムフォームを使用する 配送先住所を収集するためのカスタムフォームを作成できます。 - 決済画面に確認前の個別の住所収集ステップがある場合は、顧客が住所を送信したときに [updateShippingAddress](https://docs.stripe.com/js/react_stripe_js/checkout/update_shipping_address) を呼び出します。 - それ以外の場合は、[shippingAddress](https://docs.stripe.com/js/custom_checkout/confirm#custom_checkout_session_confirm-options-shippingAddress) を [confirm](https://docs.stripe.com/js/custom_checkout/confirm) に渡すことで、顧客が「支払う」ボタンをクリックしたときに住所を送信できます。 ## Optional: オーソリとキャプチャーを分離する [サーバー側] Stripe は 2 段階カード決済をサポートしているため、まずクレジットカードをオーソリし、後で売上をキャプチャーすることができます。Stripe が決済をオーソリすると、カード発行会社が売上を保証し、顧客のクレジットカードに決済金額を保留します。その後、売上をキャプチャーする一定の時間 ([カードに](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md#auth-capture-limitations)よって異なります) が設定されます。オーソリの期限が切れる前に決済をキャプチャーしない場合、決済はキャンセルされ、カード発行会社は保留されていた売上を解放します。 オーソリとキャプチャーを分離すると、顧客が決済できることを確認してから、その決済を回収する間に別のアクションをとる必要がある場合に便利です。たとえば、在庫が限られたアイテムを販売している場合、決済をキャプチャーして購入を完了する前に、決済を通じて顧客が購入したアイテムがまだ在庫があることを確認する必要があります。これは、以下のワークフローで実行します。 1. Stripe が顧客の支払い方法を承認したことを確認します。 2. 在庫管理システムを調べ、アイテムがまだあることを確認します。 3. 在庫管理システムを更新し、アイテムが購入されたことを反映させます。 4. 顧客の支払いをキャプチャーします。 5. 購入が成功したかどうかを確認ページで顧客に通知します。 オーソリとキャプチャーを分離するには、Checkout セッションの作成時に、[payment_intent_data.capture_method](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-capture_method) の値を `manual` に設定します。これにより、Stripe に対して顧客のカードで金額のオーソリのみを行うよう指示します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_intent_data[capture_method]=manual" \ -d return_url={{RETURN_URL}} \ -d ui_mode=elements ``` キャプチャーされていない支払いをキャプチャーするには、[ダッシュボード](https://dashboard.stripe.com/test/payments?status%5B%5D=uncaptured)または[キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)エンドポイントを使用します。プログラムによる支払いのキャプチャーには、Checkout セッションの際に作成される PaymentIntent へのアクセスが必要です。これは [Session (セッション)](https://docs.stripe.com/api/payment_intents/capture.md) オブジェクトから取得できます。 ## Optional: 顧客のアカウントの管理 [コーディング不要] *カスタマーポータル* (The customer portal is a secure, Stripe-hosted page that lets your customers manage their subscriptions and billing details)へのリンクを共有して、顧客が自身のアカウントを[管理](https://docs.stripe.com/customer-management.md)できるようにします。カスタマーポータルでは、顧客はメールアドレスでログインして、サブスクリプションの管理や決済手段の更新などを行うことができます。 ## Optional: 注文のフルフィルメント 顧客が支払いを行ったときに[プログラムで通知を受け取る](https://docs.stripe.com/checkout/fulfillment.md?payment-ui=embedded-components)方法をご紹介します。 ## See also - [1 回限りの決済に割引を追加する](https://docs.stripe.com/payments/advanced/discounts.md) - [税金の回収](https://docs.stripe.com/tax/checkout/elements.md) - [調整可能な明細項目の数量を有効にする](https://docs.stripe.com/payments/advanced/adjustable-quantity.md) - [ワンクリックボタンを追加](https://docs.stripe.com/elements/express-checkout-element/accept-a-payment.md?payment-ui=embedded-components) - [GitHub のサンプルプロジェクト](https://github.com/stripe-samples/accept-a-payment/tree/main/elements-with-checkout-sessions)