如何使用Django和JavaScript为多个产品创建Stripe Checkout会话



我正在构建一个网站,其中包含一些使用Django和Stripe Checkout购买的产品。我可以毫无问题地获得一种产品的结账页面。但我想做的是创建一个包含多个产品的结账页面。这是我在Django views.py中的函数。注意,它将产品名称作为参数。如果我将条纹产品硬编码到line_items中,我可以获得多个产品的结账会话。

def create_stripe_checkout_session(request, product_name):
domain_url = 'http://localhost:5000/'
try:
checkout_session = stripe.checkout.Session.create(
payment_method_types=['card'],
shipping_rates=[''],
shipping_address_collection={'allowed_countries': ['US', 'CA']},
metadata={'product_name': product_name, },
line_items=[{'price': PRODUCTS_STRIPE_PRICING_ID[product_name],
'quantity': 1, 'adjustable_quantity': {'enabled': True, 'minimum': 1, 'maximum': 10, }, }],
mode='payment',
success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=domain_url + 'cancelled.html',)
return JsonResponse({'id': checkout_session.id})
except Exception as e:
print(e)
raise SuspiciousOperation(e)

我在JavaScript获取方面遇到了困难。我的.html页面有一堆产品按钮,类为"购买按钮",还有唯一的按钮值和添加/减去购物车按钮。我能够跟踪我需要为多少产品以及哪些产品创建结账会话。我只是不知道如何将JS productName变量替换为对象文字/字典或其他数据结构,我可以将其传递给我的create_stripe_checkout_session((函数,这样我就可以收到多个产品的付款,而不是一个。


<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe('pk_test_6O........................4u00tQlwvoa9');

// Gets all buy buttons
var buttons = document.getElementsByClassName('buy-button');
for (i = 0; i < buttons.length; i++) {
// for every button we will add a Stripe POST request action
buttons[i].addEventListener('click', function(event) {
var targetElement = event.target || event.srcElement;
var productName =  targetElement.value;
console.log('Buying: ' + productName);
// Our endpoint with the chosen product name
var url = '/create-checkout-session/' + productName
console.log(url);
// Create a new Checkout Session
fetch(url, {
method: 'POST',
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error('Error:', error);
});
});
}
</script>

所以我终于找到了如何使用fetch-body参数来完成这项工作。希望其他人会觉得这很有用,因为我花了一段时间,经过广泛的搜索,我找不到任何关于如何做到这一点的文档。我正在使用事件侦听器获取item_1和item_2值,我正在使用购物车按钮点击计数器跟踪这些值。此信息通过数据变量与fetch一起传递。

<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe('pk_test_51IuUC4K.........voa9');
// Gets all buy buttons
var buttons = document.getElementsByClassName('buy-button');
for (i = 0; i < buttons.length; i++) {
// for every button we will add a Stripe POST request action
buttons[i].addEventListener('click', function(event) {
var targetElement = event.target || event.srcElement;
var productName =  targetElement.value;
console.log('Buying: ' + productName);
var data = JSON.stringify({
item: ["item_1", "item_2"],
item_quantity: [1, 3]
})
// Our endpoint with the chosen product name
var url = '/create-checkout-session/' + productName
console.log(url);
// Create a new Checkout Session
fetch(url, {
method: 'POST',
body: data,
headers: { 'Accept': 'application/json, text/plain, */*','Content-Type': 'application/json'
}
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error('Error:', error);
});
});
}

回到我的views.py文件中,我现在可以将数据作为字典访问,并将其传递到create_stripe_checkout_session((函数中的line_items参数中。这将覆盖用于发出原始签出会话请求的productName变量。

def create_stripe_checkout_session(request, product_name):
domain_url = 'http://localhost:5000/'
data = json.loads(request.body.decode("utf-8"))
item = data['item']
item_quantity = data['item_quantity']
line_items_list = []
for i, q in zip(item, item_quantity):
line_items_list.append({'price': PRODUCTS_STRIPE_PRICING_ID[i],
'quantity': q, 'adjustable_quantity': {'enabled': True, 'minimum': 1, 'maximum': 10, }, })
try:
checkout_session = stripe.checkout.Session.create(
payment_method_types=['card'],
shipping_rates=['shr_1J9fRXKMrN2iY6OwFXjmnVQP'],
shipping_address_collection={'allowed_countries': ['US', 'CA']},
line_items=line_items_list,
mode='payment',
success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=domain_url + 'cancelled.html',)
return JsonResponse({'id': checkout_session.id})

最新更新