0
votes

enter image description hereI'm not getting any response from postman due to this error. I tried to add app.use(express.json()); in index.js but still not working. Any idea on how to solve this?

const stripeAPI = require('../stripe');

async function createCheckoutsession(res, req) {
  const domainUrl = process.env.WEB_APP_URL;
  const { line_items, customer_email } = req.body;
  if (!line_items || !customer_email) {
    return res.status(400).json({ error: 'missing required session paramaters' });
  }
  
  let session;
  
  try {
    session = await stripeAPI.checkout.sessions.create({
      payment_method_types: ['card'],
      mode: 'payment',
      line_items,
      customer_email,
      success_url: `${domainUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${domainUrl}/canceled`,
      shipping_address_collection: { allowed_countries: ['GB', 'US'] }
    });
    res.status(200).json({ sessionId: session.id, });
  } catch (error) {
    console.log(error);
    res.status(400).json({ error: 'an error occurred, unable to create session' });
  }
}

module.exports = createCheckoutsession;

(index.js)

const express = require('express'); const cors = require('cors');

require('dotenv').config({ path: './.env' });

const createCheckoutSession = require('./api//checkout');

const app = express();

const port = 8080;

app.use(express.json());

app.use(cors({origin: true}));

app.get('/', (req, res) => res.send('HELLO WORLD!'));

app.post('/create-checkout-session', createCheckoutSession);

app.listen(port, () => console.log('server listening on port', port));

(stripe.js)

const stripeAPI = require('stripe')(process.env.SECRET_KEY);

module.exports = stripeAPI;enter code here

2
{ "line_items": [ { "quantity": 1, "price_data": { "currency": "usd", "unit_amount": 2800, "product_data": { "name": "Cumulus", "description": "Light as air", "images": [ "i.ibb.co/NtpJ0XQ/cumulus-olive.png" ] } } } ], "customer_email": "[email protected]" }Kenna
Hi Phil, I've uploaded the screenshot from postmanKenna
Ok, everything looks fine there. Can you show where you add app.use(express.json()) and where you bind createCheckoutsession to the /create-checkout-session path? Note that your JSON middleware should be registered before app.post("/create-checkout-session", createCheckoutsession) (or however you've set up that handler)Phil
app.use(express.json()) is in index.js, I've updated it here so that you can see.. it is stated before app.post("/create-checkout-session"Kenna

2 Answers

0
votes

I assume you are using Express server?

Your route handler is using wrong parameters:

// Wrong
async function createCheckoutsession(res, req) {
}

// Correct 
async function createCheckoutsession(req, res) {
}
-1
votes

Try

app.use(bodyParser.urlEncoded({extended:false}))