首页 > 解决方案 > 如何创建数量可变的 Stripe 订阅?

问题描述

现在,我正在成功创建具有硬编码数量的Stripe订阅:

customer = stripe.Customer.create(email=request.form['stripeEmail'], source=request.form['stripeToken'])

# For the moment, change the quantity parameter for each customer
subscription = stripe.Subscription.create(
    customer = customer.id,
    items = [
        {
            'plan': 'plan_*************',
            'quantity': 7,
        },
    ],
)

我们的想法是quantity从前端获取该值。我已经有一个以编程方式设置数量值的选​​择器,我实际上正在使用它在Stripe Checkout 中打印可变金额:

<script>
  var handler = StripeCheckout.configure({
    key: "{{pub_key}}",
    image: "https://stripe.com/img/documentation/checkout/marketplace.png",
    locale: "auto",
    zipCode: true,
    token: function(token) {
      // You can access the token ID with `token.id`.
      // Get the token ID to your server-side code for use.
    }
  });

  document.getElementById("customButton").addEventListener("click", function(e) {
    var quantity = document.getElementsByName("selectedQuantity")[0];
    var text = quantity.options[quantity.selectedIndex].text;
    // Open Checkout with further options:
    handler.open({
      name: "Company, Inc.",
      description: text + " Subscriptions",
      amount: 900 * text
    });
    e.preventDefault();
  });

  // Close Checkout on page navigation:
  window.addEventListener("popstate", function() {
    handler.close();
  });
</script>

请注意,我从后端获取公钥,但我不知道如何从后端的前端检索数量值。

我怎么做?

编辑:

当我不使用自定义 Checkout 集成时,我有一个可以执行此操作的表单:

<form action="{{ url_for('pay') }}" method="POST">

但是这里没有表格,所以我不确定下一步应该是什么。

标签: javascriptflaskstripe-payments

解决方案


您如何将令牌提交到后端服务器(即您是如何实现该token功能的)?完成后,您可以以相同的方式提交数量。

一种方法可能是使用表单,将 Stripe 令牌添加到该表单中的隐藏输入,然后使用 Javascript 提交。

这是一个例子:https ://jsfiddle.net/53u96kvw/

或者,如果您根本没有表单,您可以使用相同的信息发出 AJAX 请求:https ://jsfiddle.net/kcp12o3z/


推荐阅读