Sunday 29 November 2020

Error implementing stripe payment in deployment (Heroku)

I am trying to implement Stripe payment system in my Heroku web application. Below you can see a html file which has a 'Purchase' button, which calls the javascript function 'MyFunction()' when clicked. After this happens, the javascript function calls the create_checkout_session() function in Flask (the Python file), which returns a session checkout ID to the javascript function, which redirects to the payment page. For some reason, the below process works perfectly on localhost, but fails when I deploy to Heroku. I get an error 500 in Heroku for some reason.

enter image description here

html file

  <section class="section">
    <div class="container">
      <button class="btn btn-outline-info" onclick="myFunction()" id="stripePay">Purchase!</button>
    </div>
  </section>


  <script>
    function myFunction() {


    //stripe
    // Get Stripe publishable key
      // Initialize Stripe.js
      const stripe = Stripe('pk_test_zcqqggPiGsbFA49H0BE4Mxj200AyZDDWnN');

      // new
      // Event handler
        // 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(data)
        })
    };
</script>

Python file

@app.route("/create-checkout-session")
def create_checkout_session():
    domain_url = "http://localhost:5000/"
    stripe.api_key = stripe_keys["secret_key"]

        # Create new Checkout Session for the order
        # Other optional params include:
        # [billing_address_collection] - to display billing address details on the page
        # [customer] - if you have an existing Stripe Customer ID
        # [payment_intent_data] - capture the payment later
        # [customer_email] - prefill the email input in the form
        # For full details see https://stripe.com/docs/api/checkout/sessions/create

        # ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
        checkout_session = stripe.checkout.Session.create(
            success_url=domain_url + "success?session_id={CHECKOUT_SESSION_ID}",
            cancel_url=domain_url + "cancelled",
            payment_method_types=["card"],
            mode="payment",
            line_items=[
                {
                    "name": "T-shirt",
                    "quantity": 1,
                    "currency": "usd",
                    "amount": "2000",
                }
            ]
        )
        return jsonify({"sessionId": checkout_session["id"]})


from Error implementing stripe payment in deployment (Heroku)

No comments:

Post a Comment