Home > Software design >  How pass a variable in stripe CLI post request
How pass a variable in stripe CLI post request

Time:07-08

I want to save a variable and be able to pass it further after the page has been reloaded. So i want to get the req.session.variable and be able to use it in router.post('/webhook', ...) which is controled by Stripe CLI. Inside of this post request the req.session.variable is unavailable because the site has redirected the user to another website which clears the req.session content, moreove the content of req.body inside the post request is by default in req.rawBody format. Is there a way i can pass this variable into the request and use it with ease?

let express = require('express');
let router = express.Router();
let postMong = require('./post')
require("dotenv").config()
router.use(express.json());
const YOUR_DOMAIN = 'http://localhost:4242';
const stripe = require('stripe')(process.env.PUBLIC_KEY);
const endpointSecret = 'whsec_1c7320d5c8878c54d6f99e0d5dcd441008c79b76ddb0a09727a4fd977d3ac1ed';
const fulfillOrder = (ses) => {
  console.log("Order Completed")
}


router.post('/checkout/create-order', async (req, res) => {
  const price = req.body.order.stripe_price || undefined,
        product = req.body.order.stripe_product || undefined
  const session = await stripe.checkout.sessions.create({
    //shipping_address_collection: {
    //  allowed_countries: ['US', 'CA'],
    //},
    //shipping_options: [
    //  {
    //    shipping_rate_data: {
    //      type: 'fixed_amount',
    //      fixed_amount: {
    //        amount: 2499,
    //        currency: 'usd',
    //      },
    //      display_name: 'International Shipping',
    //      // Delivers between 5-7 business days
    //      delivery_estimate: {
    //        minimum: {
    //          unit: 'week',
    //          value: 2,
    //        },
    //      }
    //    }
    //  },
    //],
    line_items: [
      {
        price: price,
        quantity: 1,
      },
    ],
    payment_method_types: ["card", 'us_bank_account'],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}/success.html`,
    cancel_url: `${YOUR_DOMAIN}/index.html`,
  });

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


router.post('/webhook', (request, response) => {
  const payload = request.body;
let username = request.session.username; // returns undefined because the session is empty after the redirect
  const sig = request.headers['stripe-signature'];
  let event;
  try {
    event = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
  } catch (err) {
    console.log(err.message)
    return response.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    fulfillOrder(session);
  }

  response.status(200);
});

module.exports = router

CodePudding user response:

Depending on what you need to store as information you have a couple of different options, but in all cases it’s best if you use the Checkout Session Object[0] to store what you need. If you’re looking to pass a reference id (e.g. customer id or cart id from your app) you can use client_reference_id[1]. If you need to pass more info than you can rely to the metadata[2] hash where you can input as much information as you need.

Since you’ve already got a webhook endpoint configured, you will have access to both of these fields in your session object after the session is complete.

[0] https://stripe.com/docs/api/checkout/sessions/object

[1] https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-client_reference_id

[2] https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-metadata

  • Related