ラインアイテムの数量を調整可能にする
顧客が決済時にラインアイテムの数量を調整できるように Checkout セッションを設定します。
adjustable_quantity
を有効にして Checkout セッションを作成する
Checkout セッションを作成する際、line_items
に adjustable_quantity
を設定して、顧客が決済時にアイテムの数量を更新できるようにします。
adjustable_quantity.minimum
と adjustable_quantity.maximum
を設定することにより、指定できる最小/最大数量のデフォルト設定をカスタマイズできます。デフォルトでは、アイテムの調整可能な最小数量は 0
、調整可能な最大数量は 99
です。adjustable_quantity.maximum
には最大 999999
の値を指定できます。
line_items[].quantity
の値が 99
(デフォルトの調整可能な最大数量) よりも大きい数量を使用する場合は、adjustable_quantity.maximum
をそのアイテムの数量以上に設定してください。
調整可能な数量を使用する場合は、Checkout セッションの作成時に adjustable_quantity.maximum
を使用して、line_items
の数量の代わりに在庫数量をリザーブするように設定を変更します。
Checkout では、アイテムが残り 1 つの場合、顧客はそれを削除できません。
curl https://api.stripe.com/v1/checkout/sessions \
-u "sk_test_4eC39HqLyjWDarjtT1zdp7dc
:" \
-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][price_data][tax_behavior]"=exclusive \
-d "line_items[0][adjustable_quantity][enabled]"=true \
-d "line_items[0][adjustable_quantity][minimum]"=1 \
-d "line_items[0][adjustable_quantity][maximum]"=10 \
-d "line_items[0][quantity]"=1 \
-d "automatic_tax[enabled]"=true \
-d mode=payment \
--data-urlencode success_url="https://example.com/success" \
--data-urlencode cancel_url="https://example.com/cancel"
完了した取引を処理する
支払いが完了したら、確定済みのラインアイテムとその数量に対するリクエストを作成できます。顧客がラインアイテムを削除した場合、それはラインアイテムのレスポンスからも削除されます。完了した Checkout セッションを処理するイベントハンドラの作成方法については、フルフィルメントガイドをご覧ください。
Stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
require 'sinatra'
endpoint_secret = 'whsec_...'
post '/webhook' do
event = nil
begin
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
payload = request.body.read
event = Stripe::Webhook.construct_event(payload, sig_header, endpoint_secret)
rescue JSON::ParserError => e
return status 400
rescue Stripe::SignatureVerificationError => e
return status 400
end
if event['type'] == 'checkout.session.completed'
checkout_session = event['data']['object']
line_items = Stripe::Checkout::Session.list_line_items(checkout_session['id'], {limit: 100})
begin
fulfill_order(checkout_session, line_items)
rescue NotImplementedError => e
return status 400
end
end
status 200
end
def fulfill_order(checkout_session, line_items)
raise NotImplementedError.new(<<~MSG)
Given the Checkout Session "#{checkout_session.id}" load your internal order from the database here.
Then you can reconcile your order's quantities with the final line item quantity purchased. You can use `checkout_session.metadata` and `price.metadata` to store and later reference your internal order and item ids.
MSG
end