Home > Back-end >  Nodejs Stripe how to dynamically pass the Stripe price ID to my server after clicking the purchase b
Nodejs Stripe how to dynamically pass the Stripe price ID to my server after clicking the purchase b

Time:11-05

I am working on my first dynamic website using HTML, Express & node.js. Reading through the Stripe documentation and other sources I've come across various examples but my main goal is to use my Stripe API key and each item price ID's in my server and not in my front end code so no one can temper with them. I've successfully use my Stripe API key on my backend and used the .post method to redirect the user after pressing the Buy Now button to the checkout page as shown below:

Node.js

const stripe = require('stripe')('sk_test_key');
const express = require('express');
const app = express();
app.use(express.static('public'));

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

app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
line_items: [
  {
    
    price: 'price_priceKey',
    quantity: 1,
  },
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}/success.html`,
cancel_url: `${YOUR_DOMAIN}/cancel.html`,
});

res.redirect(303, session.url);
});

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

HTML

<!DOCTYPE html>
<html>
<head>
<link
  href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
  rel="stylesheet"
  integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6 fzT"
  crossorigin="anonymous"
/>
<title>Product Page</title>
<link rel="stylesheet" href="style.css" />
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<div >
  <div >
    <section>
      <div >
        <img
          
          src="image"
          alt="product-image"
        />
        <div >
          <h3>Leather Collar</h3>
          <h5>$9.99</h5>
        </div>
      </div>
      <form action="/create-checkout-session" method="POST">
        <button type="submit" id="checkout-button">Checkout</button>
      </form>
    </section>
  </div>
  <div >
    <section>
      <div >
        <img
          
          src="image2"
          alt="product-image2"
        />
        <div >
          <h3>Comsos Collar</h3>
          <h5>$19.99</h5>
        </div>
      </div>
      <form action="/create-checkout-session" method="POST">
        <button type="submit" id="checkout-button">Buy Now</button>
      </form>
    </section>
  </div>
</div>
</body>
</html>

My problem is I've only figure how to hardcode the price ID for a product inside my line_items object in node.js so when the user clicks the Buy Now button it will only add to the checkout page the items that I added. I've come across examples of adding the price ID to the attribute "data-price-id" inside each button element so that each item has a button that contains its correct price but that exposes all my price ID's to my frontend code. I already tried hiding the ID in my frontend using EJS and the dotenv module in node.js but this was futile. I would really appreciate if someone could point me the right direction or sample code on how to pass these different price ID's after user clicks on each button of each item back to my server.

CodePudding user response:

It's okay to expose the Price IDs to the front-end code. Nobody can do anything with those Prices without access to your API keys, so it's okay if they show up on the front-end.

That being said, you can dynamically pass an ID from back-end to front-end via a number of different methods. The one I would recommend would be document.querySelector()[0]. This allows you to dynamically set an HTML element's value using Javascript.

An example might look like this: document.querySelector("#price-id").value = somePriceID;

The above snippet looks for an HTML element called price-id and assigns the value from the somePriceID variable to it.

[0] https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

CodePudding user response:

I see you're not using a DB.

One approach you could make is just create an object on the server such as:

const PRODUCT_IDS = {
    toaster-x1000: {
        price_id: 'toaster-price-id'
    }
};

That way, you can just use your own codes on the HTML sites and find the Stripe code on the backend when you need it.

For example, if they want the toaster, you would send "toaster-x1000" and just grab that ID from the list:

const ID_RECEIVED = "toaster-x1000";
const CORRECT_STRIPE_ID = PRODUCT_IDS[ID_RECEIVED].price_id;

That would give you the price id you need for the API call.

  • Related