0

I am trying to get a user entered amount from my checkout.html file ( below ) so that I can use it in the Stripe code on the server.js node server.

I wasn't able to get the amount field from the form to work so I disabled it and am working with console.log and variables. I was trying to make it work with a global variable passing the value.

These 2 files from the example on the Stripe website ( you select 'node' and 'html' from the page, and click 'prebuilt' also )

https://stripe.com/docs/checkout/integration-builder

My alterations ( sorry the var assignments numbers are all just random for testing )

**server.js** 

( lines 8-9 )
var test = 2242;
// console.log( amountglobal);


( line 22 )
unit_amount: test, 


**checkout.html** (line 47 )

amountglobal = 67865555;

My issue is that if I uncomment line 9 ( with the aim of trying to use the amountglobal gloabal var in line 22 ) then for some reason the server wont start, saying amountglobal is not defined ... so I possibly have the global variable wrong in checkout.html, it's

amountglobal = 67865555;

... and maybe there's a better way of doing this in the first place, I understand global variables are not the ideal usually.

The end result here is to be a payment form where the user can type in their own ( previously agreed) price.

Thanks.


FULL FILES

server.js

const stripe = require('stripe')

('sk_test_51IAvl4KYIMptSkmlXwuihwZa8jtdIrnD79kSQcnhvQKbg9dbAXiZisFmasrKHIK9B75d9jgeyYK8MULLbFGrGBpU00uQgDvtnJ');
const express = require('express');
const app = express();
app.use(express.static('.'));

const YOUR_DOMAIN = 'http://localhost:4242';

var test = 2242;
console.log( amountglobal);

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'Stubborn Attachments',
            images: ['https://i.imgur.com/EHyR2nP.png'],
          },
          unit_amount: test,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}/success.html`,
    cancel_url: `${YOUR_DOMAIN}/cancel.html`,
  });

  res.json({ id: session.id });
});

app.listen(4242, () => console.log('Running on port 4242'));

Checkout.html

<!DOCTYPE html>
<html>
  <head>
    <title>Buy cool new product</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <script src="https://js.stripe.com/v3/"></script>
  </head>
  <body>
    <section>
      <div class="product">
        <img
          src="https://i.imgur.com/EHyR2nP.png"
          alt="The cover of Stubborn Attachments"
        />
        <div class="description">
          <h3>Stubborn Attachments</h3>
          <h5>$20.00</h5>
          
        </div>
      </div>
   


   
    <form id="frm12" action="#">

   First name: <input type="text" name="amount" value = "435"><br> 
<!-- <input type="button" onclick="myFunction()" value="Submit"> -->
    <input type="submit" id="checkout-button" value="Checkout">
</form>

    </section>
  </body>
  <script type="text/javascript">
    function myFunction() {
      console.log("test");
      document.getElementById("frm1").submit();
    }


    // Create an instance of the Stripe object with your publishable API key
    var stripe = Stripe("pk_test_51IAvl4KYIMptSkmlAwhNvG0CDJRnr2hyrJuRnfdnfaEEhHPwCWsr9QK183a1pKUQ4PLrrtEqiElFLTVHIiSueX6r00TyXooIcu");
    var checkoutButton = document.getElementById("checkout-button");
    var amount = document.getElementById("amount");

    amountglobal = 67865555;

    // console.log(amount);

    checkoutButton.addEventListener("click", function () {
      fetch("/create-checkout-session", {
        method: "POST",
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          console.log('here');
          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>
</html>
byronyasgur
  • 4,627
  • 13
  • 52
  • 96
  • It appears that perhaps you don't understand that your browser client Javascript runs in a completely different world (different computer, different network, different process, different JS engine) from your server Javascript. You cannot share globals between them. Even if you wanted to and even if you could, it would be the wrong design anyway. Instead, you must send data from the client to the server. – jfriend00 Feb 05 '21 at 07:17
  • In a form, you would POST the form to your server (either using an HTML form and the appropriate form action or by using an Ajax call with Javascript) and then properly read the form body and parse it on your server to get the data out of it. You can then use that data to carry out whatever operation on your server and then return some sort of result back to the client. Server and client are completely separate Javascript worlds. They share data only by sending data from one to the other. – jfriend00 Feb 05 '21 at 07:18
  • got this sorted in the end - took a bit of study and T&E - thank for help these comments helped. gonna post the finished code on code review in accordance with meta advice before production just tidying etc and style ;-) – byronyasgur Mar 10 '21 at 02:55

1 Answers1

1

You need to POST the data from your client side code to your server side code, and then use a JSON body parser with Express so that it ends up in the server-side request.

floatingLomas
  • 8,553
  • 2
  • 21
  • 27
  • I decided to switch to the php example. I think I know what you mean here but would the same principle apply here using the php version or how would that differ – byronyasgur Feb 09 '21 at 02:57