简体   繁体   English

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

[英]How can I Create Stripe Checkout Session for multiple products with Django and JavaScript?

I'm building a site with a few products for purchase using Django and Stripe Checkout.我正在使用 Django 和 Stripe Checkout 构建一个包含一些产品的网站。 I can get the checkout page for one product without a problem.我可以毫无问题地获得一种产品的结帐页面。 But what I would like to do is create a checkout page with multiple products.但我想做的是创建一个包含多个产品的结帐页面。 This is my function in my Django views.py.这是我在 Django views.py 中的函数。 Note that it takes product name as a parameter.请注意,它以产品名称作为参数。 If I hard code my stripe products into the line_items I can get a checkout session with multiple products.如果我将条纹产品硬编码到 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)

Where I'm struggling is with my JavaScript fetch.我挣扎的地方是我的 JavaScript 提取。 My .html page has a bunch of product buttons with class 'buy-button' as well as unique button values and add/subtract to cart buttons.我的 .html 页面有一堆带有“buy-button”类的产品按钮以及唯一的按钮值和添加/减去购物车按钮。 I'm able to keep track of how many and which products I need to create a checkout session for.我能够跟踪我需要为其创建结帐会话的数量和产品。 I just can't figure out how to replace the JS productName variable with an object literal/dictionary or other data structure that I can pass to my create_stripe_checkout_session() function so that I am able to receive payment for multiple products instead of just one.我只是不知道如何用对象文字/字典或其他数据结构替换 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>


So I finally figured out how to complete this using the fetch body parameter.所以我终于想出了如何使用 fetch body 参数来完成这个。 Hopefully, others will find this useful because it took me a while and I couldn't find any documentation about how to do it after a pretty extensive search.希望其他人会发现这很有用,因为我花了一段时间,而且在进行了相当广泛的搜索后,我找不到任何有关如何执行此操作的文档。 I'm using an event listener to grab item_1 and item_2 values which I'm tracking with cart button click counters.我正在使用事件侦听器来获取 item_1 和 item_2 值,我正在使用购物车按钮点击计数器跟踪这些值。 This information is passed with fetch via the data variable.此信息通过数据变量与 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);
    });

    });

    }

Back in my views.py file I can now access the data as a dictionary and pass it into the line_items parameter within the create_stripe_checkout_session() function.回到我的 views.py 文件中,我现在可以将数据作为字典访问并将其传递到 create_stripe_checkout_session() 函数中的 line_items 参数中。 This overrides the productName variable that is used to make the original checkout session request.这将覆盖用于发出原始结帐会话请求的 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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM