各 Checkout セッションのラインアイテムは、顧客が購入しようとしているものを追跡します。顧客が決済時にラインアイテムの数量を調整できるように、Checkout セッションを設定できます。
注
新しいラインアイテムの追加など、その他のラインアイテムの更新には、この実装は対応していません。
Checkout セッションを作成する際、line_items に adjustable_quantity を設定して、顧客が決済時にアイテムの数量を更新できるようにします。
const session = await stripe.checkout.sessions.create({
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'T-shirt',
},
unit_amount: 2000,
},
quantity: 1,
adjustable_quantity: {
enabled: true,
maximum: 100,
minimum: 0,
},
},
],
mode: 'payment',
ui_mode: 'custom',
return_url: '{{RETURN_URL}}'
});
adjustable_quantity.minimum と adjustable_quantity.maximum を設定することにより、指定できる最小 / 最大数量のデフォルト設定をカスタマイズできます。デフォルトでは、アイテムの調整可能な最小数量は 0、調整可能な最大数量は 99 です。adjustable_quantity.maximum
には最大 999999 の値を指定できます。
Checkout では、アイテムが残り 1 つの場合、顧客はそれを削除できません。
updateLineItemQuantity を使用して、数量を増やすボタンなど、顧客の操作に応じてラインアイテムの数量を変更します。ラインアイテム ID と新しい数量を渡します。
import React from 'react';
import {useCheckout} from '@stripe/react-stripe-js';
const IncrementLineItemButton = (props) => {
const {updateLineItemQuantity} = useCheckout();
const handleClick = () => {
updateLineItemQuantity({
lineItem: props.lineItem,
quantity: props.quantity + 1,
});
};
return <button onClick={handleClick}>+</button>;
};
export default IncrementLineItemButton;
完了した取引を処理する
After the payment completes, you can make a request for the finalized line items and their quantities. If your customer removes a line item, it is also removed from the line items response. See the Fulfillment guide to learn how to create an event handler to handle completed Checkout Sessions.
Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"
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