Esteban Vargas
Esteban Vargas

Reputation: 594

How to create a Stripe subscription with a variable quantity?

Right now I'm successfully creating a Stripe subscription that has a hardcoded quantity:

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,
        },
    ],
)

The idea would be to obtain that value for quantity from the frontend. I already have a selector that sets the quantity value programmatically and I'm actually using it to print variable amounts in 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>

Notice that I'm getting the public key from the backend, but I don't know how to retrieve the quantity value from the frontend in the backend.

How do I do that?

EDIT:

When I wasn't using a custom Checkout integration I had a form that would do this:

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

But there is no form here, so I'm not sure what should the next step be.

Upvotes: 0

Views: 402

Answers (1)

Karl Reid
Karl Reid

Reputation: 2217

How are you submitting the token to your backend server(i.e. how have you implemented the token function)? Once you've done that, you can just submit the quantity in the same way.

One way to do this might be to use a form, add the Stripe token to a hidden input in that form, and then submit it with Javascript.

Here's an example : https://jsfiddle.net/53u96kvw/

Or if you don't have a form at all, you can make an AJAX request with the same information : https://jsfiddle.net/kcp12o3z/

Upvotes: 1

Related Questions