コンテンツにスキップ
アカウントを作成
または
サインイン
Stripe ドキュメントのロゴ
/
AI に質問する
アカウントを作成
サインイン
始める
支払い
財務の自動化
プラットフォームおよびマーケットプレイス
資金管理
開発者向けのツール
始める
支払い
財務の自動化
始める
支払い
財務の自動化
プラットフォームおよびマーケットプレイス
資金管理
概要
Stripe Payments について
構築済みのシステムをアップグレード
支払いの分析
オンライン決済
概要ユースケースを見つけるManaged Payments
Payment Links を使用する
決済ページを構築
    概要
    クイックスタート
    デザインをカスタマイズする
    追加情報を収集する
    税金を徴収する
    決済フローを動的に更新
      配送オプションを動的にカスタマイズ
      ラインアイテムを動的に更新する
    商品カタログを管理する
    サブスクリプション
    決済手段を管理
    顧客が現地通貨で支払いできるようにする
    割引、アップセル、オプション品目を追加する
    将来の支払いを設定する
    支払い中に支払い詳細を保存する
    サーバーで支払いを手動で承認する
    支払い後
    Elements with Checkout Sessions API ベータ版の変更ログ
    従来の Checkout からの移行
    Checkout を移行して Prices を使用
高度なシステムを構築
アプリ内実装を構築
決済手段
決済手段を追加
決済手段を管理
Link による購入の迅速化
支払いインターフェイス
Payment Links
Checkout
Web Elements
アプリ内 Elements
決済シナリオ
カスタムの決済フロー
柔軟なアクワイアリング
オーケストレーション
店頭支払い
端末
他の Stripe プロダクト
Financial Connections
仮想通貨
Climate
ホーム支払いBuild a checkout pageDynamically update checkout

注

このページはまだ日本語ではご利用いただけません。より多くの言語で文書が閲覧できるように現在取り組んでいます。準備が整い次第、翻訳版を提供いたしますので、もう少しお待ちください。

配送オプションを動的にカスタマイズする

顧客の配送先住所に基づいて配送オプションを更新します。

ページをコピー

Learn how to dynamically update shipping options based on the address that your customer enters in Checkout.

Use cases

  • Validate an address: Confirm whether you can ship a product to a customer’s address using your own custom validation rules. You can also create a custom UI for customers to confirm their preferred address.
  • Show relevant shipping options: Display only available shipping methods, based on the customer’s address. For example, show overnight shipping only for deliveries in your country.
  • Dynamically calculate shipping rates: Calculate and display shipping fees based on a customer’s delivery address.
  • Update shipping rates based on order total: Offer shipping rates based on the shipping address or order total, such as free shipping for orders over 100 USD. For checkouts allowing quantity changes or cross-sells, see Dynamically updating line items.

Limitations

  • Only supported in payment mode. Shipping rates aren’t available in subscription mode.
  • Doesn’t support updates in response to changes from outside of the checkout page.

Checkout セッションを作成する
サーバー側

サーバーで Checkout セッションを作成します。

  • ui_mode を embedded に設定します。
  • permissions.update_shipping_details を server_only に設定します。
  • shipping_address_collection.allowed_countries に、配送先を提供する国のリストを設定します。
  • shipping_options.shipping_rate_data を設定して、0 USD のダミー配送料を作成します。

デフォルトでは、Stripe Checkout クライアントは、Checkout セッションオブジェクトの shipping_details を、顧客が入力する顧客の名前や住所などの配送情報で自動的に更新します。

警告

permissions.update_shipping_details が server_only の場合、クライアント側の自動更新は無効になり、サーバーのみが Stripe の秘密キーを使用して配送情報を更新できます。

Command Line
cURL
curl https://api.stripe.com/v1/checkout/sessions \ -u "
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:"
\ -d ui_mode=embedded \ -d "permissions[update_shipping_details]"=server_only \ -d "shipping_address_collection[allowed_countries][0]"=US \ -d "shipping_options[0][shipping_rate_data][display_name]"="Dummy shipping" \ -d "shipping_options[0][shipping_rate_data][fixed_amount][amount]"=0 \ -d "shipping_options[0][shipping_rate_data][fixed_amount][currency]"=usd \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ -d mode=payment \ --data-urlencode return_url="https://example.com/return"

配送オプションをカスタマイズする
サーバー側

サーバーで、顧客の配送先住所に基づいて配送オプションを計算する新しいエンドポイントを作成します。

  1. リクエスト本文から取得した checkoutSessionId を使用して、Checkout セッションを取得します。
  2. リクエスト本文にある顧客の配送先情報を検証します。
  3. 顧客の配送先住所と Checkout セッションのラインアイテムに基づいて配送オプションを計算します。
  4. 顧客の shipping_details と shipping_options で Checkout セッションを更新します。
Ruby
require 'sinatra' require 'json' require 'stripe' set :port, 4242 # Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/apikeys Stripe.api_key =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
# Return a boolean indicating whether the shipping details are valid def validate_shipping_details(shipping_details) # TODO: Remove error and implement... raise NotImplementedError.new(<<~MSG) Validate the shipping details the customer has entered. MSG end # Return an array of the updated shipping options or the original options if no update is needed def calculate_shipping_options(shipping_details, session) # TODO: Remove error and implement... raise NotImplementedError.new(<<~MSG) Calculate shipping options based on the customer's shipping details and the Checkout Session's line items. MSG end post '/calculate-shipping-options' do content_type :json request.body.rewind request_data = JSON.parse(request.body.read) checkout_session_id = request_data['checkout_session_id'] shipping_details = request_data['shipping_details'] # 1. Retrieve the Checkout Session session = Stripe::Checkout::Session.retrieve(checkout_session_id) # 2. Validate the shipping details if !validate_shipping_details(shipping_details) return { type: 'error', message: "We can't ship to your address. Please choose a different address." }.to_json end # 3. Calculate the shipping options shipping_options = calculate_shipping_options(shipping_details, session) # 4. Update the Checkout Session with the customer's shipping details and shipping options if shipping_options Stripe::Checkout::Session.update(checkout_session_id, { collected_information: { shipping_details: shipping_details }, shipping_options: shipping_options }) return { type: 'object', value: { succeeded: true } }.to_json else return { type: 'error', message: "We can't find shipping options. Please try again." }.to_json end end

Checkout をマウントする
クライアント側

Checkout は Stripe.js の一部として利用できます。HTML ファイルのヘッダーに Stripe.js スクリプトを追加してページに含めます。次に、マウンティングに使用する空の DOM ノード (コンテナ) を作成します。

index.html
<head> <script src="https://js.stripe.com/v3/"></script> </head> <body> <div id="checkout"> <!-- Checkout will insert the payment form here --> </div> </body>

公開可能な API キーで Stripe.js を初期化します。

index.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(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
);

サーバーに Checkout セッションの作成をリクエストする非同期の fetchClientSecret 関数を作成し、クライアントシークレットを取得します。

顧客の配送先住所に基づいて配送オプションを計算するようにサーバーへリクエストする、非同期の onShippingDetailsChange 関数を作成します。顧客が配送先情報フォームの入力を終えると、Stripe Checkout がこの関数を呼び出します。

index.js
initialize(); async function initialize() { // Fetch Checkout Session and retrieve the client secret const fetchClientSecret = async () => { const response = await fetch("/create-checkout-session", { method: "POST", }); const { clientSecret } = await response.json(); return clientSecret; }; // Call your backend to set shipping options const onShippingDetailsChange = async (shippingDetailsChangeEvent) => { const {checkoutSessionId, shippingDetails} = shippingDetailsChangeEvent; const response = await fetch("/calculate-shipping-options", { method: "POST", body: JSON.stringify({ checkout_session_id: checkoutSessionId, shipping_details: shippingDetails, }) }) if (response.type === 'error') { return Promise.resolve({type: "reject", errorMessage: response.message}); } else { return Promise.resolve({type: "accept"}); } }; // Initialize Checkout const checkout = await stripe.initEmbeddedCheckout({ fetchClientSecret, onShippingDetailsChange, }); // Mount Checkout checkout.mount('#checkout'); }

注意

onShippingDetailsChange 関数からは必ず Promise が返され、ResultAction オブジェクトで解決されます。

Checkout クライアントは、onShippingDetailsChange 関数の結果に基づいて UI を更新します。

  • 結果に type: "accept" が含まれる場合、Checkout UI はサーバーで設定した配送オプションを表示します。
  • 結果に type: "reject" が含まれる場合、Checkout UI は結果で設定したエラーメッセージを表示します。

必要に応じて、onShippingDetailsChange をリッスンし、複数の可能な住所から希望の住所を選択して確認するための、カスタム UI を作成できます。

Checkout は、HTTPS 接続を介して支払い情報をStripeに安全に送信する iframe でレンダリングされます。

よくある間違い

一部の支払い方法では、別のページにリダイレクトして支払いを確定する必要があるため、Checkout は別の iframe 内に配置しないでください。

実装をテストする

Follow these steps to test your integration, and ensure your custom shipping options work correctly.

  1. Set up a sandbox environment that mirrors your production setup. Use your Stripe sandbox API keys for this environment.

  2. Simulate various shipping addresses to verify that your calculateShippingOptions function handles different scenarios correctly.

  3. Verify server-side logic by using logging or debugging tools to confirm that your server:

    • Retrieves the Checkout Session.
    • Validates shipping details.
    • Calculates shipping options.
    • Updates the Checkout Session with new shipping details and options. Make sure the update response contains the new shipping details and options.
  4. Verify client-side logic by completing the checkout process multiple times in your browser. Pay attention to how the UI updates after entering shipping details. Make sure that:

    • The onShippingDetailsChange function is called when expected.
    • Shipping options update correctly based on the provided address.
    • Error messages display properly when shipping is unavailable.
  5. Enter invalid shipping addresses or simulate server errors to test error handling, both server-side and client-side.

このページはお役に立ちましたか。
はいいいえ
お困りのことがございましたら 、サポートにお問い合わせください。
早期アクセスプログラムにご参加ください。
変更ログをご覧ください。
ご不明な点がございましたら、お問い合わせください。
LLM ですか?llms.txt を読んでください。
Powered by Markdoc