【发布时间】:2021-09-23 03:19:47
【问题描述】:
我正在构建一个网站,其中包含一些使用 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 页面有一堆带有“购买按钮”类的产品按钮以及独特的按钮值和添加/减去购物车按钮。我能够跟踪需要为其创建结帐会话的产品数量和产品。我只是不知道如何用可以传递给我的 create_stripe_checkout_session() 函数的对象文字/字典或其他数据结构替换 JS productName 变量,以便我能够接收多种产品的付款,而不仅仅是一个。
<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>
【问题讨论】:
-
您可能需要在您的应用程序中为各种产品保留某种购物车状态,然后使用
body参数将它们作为有效负载发送到您的fetch中。然后,您可以将该有效负载作为行项目传递给您的 Checkout Session 调用! -
感谢@JonathanSteele。这确实是我需要做的。虽然,由于我对 JS 不熟悉,最终实现有点棘手。
标签: javascript python django stripe-payments