1
votes

I have a form and I want to submit its data only when the stripe payment has been made. The stripe payment corresponds to this JS script:

// Get Stripe publishable key
fetch("/config")
.then((result) => { return result.json(); })
.then((data) => {
  // Initialize Stripe.js
  const stripe = Stripe(data.publicKey);

  // new
  // Event handler
  document.querySelector("#submitBtn").addEventListener("click", () => {
    // Get Checkout Session ID
    fetch("/create-checkout-session")
    .then((result) => { return result.json(); })
    .then((data) => {
      console.log(data);
      // Redirect to Stripe Checkout
      return stripe.redirectToCheckout({sessionId: data.sessionId})
    })
    .then((res) => {
      console.log(res);
    });
  });
document.getElementById("form_post").submit();
});

What I've done so far is to add document.getElementById("form_post").submit(); at the end of the JS script as you can see but it does not work. With this code, the stripe payment can be made but my form is not submitted.

Here is the HTML part with the form:

{% extends 'base.html' %}

{% block content %}
<script src="https://js.stripe.com/v3/"></script>
<script src="{{ url_for('static', filename='main.js') }}"></script>
<script defer src="https://use.fontawesome.com/releases/v5.14.0/js/all.js"></script>
  <form id="form_post" method="post" enctype=multipart/form-data>
    <label for="sername">Nom de l'entreprise</label>
    <input name="username" id="username" value="{{ request.form['username'] }}" required>
    </form>

    <section class="section">
      <div class="container">
        <button class="button is-primary" id="submitBtn">Purchase!</button>
      </div>
    </section>

{% endblock %}

For information, I'm using python's framework Flask.

1

1 Answers

1
votes

That won't work because Stripe redirects you to another page for the checkout session, so your code after the redirect will never run unless the redirect fails because of a network issue or some other reason.

When Stripe returns you to your site, after the payment is complete, they attach a query parameter to the redirect URL you provide. You can grab that query parameter and submit it to your server to do any processing.

Anything you need to store about the user from the form you should do ahead of time before redirecting. Then validate that the payment was successful after the fact on the server side by handling the webhook that Stripe sends or by checking the status of that checkout session.