Home > database >  Issue sending a JSON object to Stripe
Issue sending a JSON object to Stripe

Time:12-04

I am trying to send a JSON Object to Stripe, but I am always receiving an error from the response.

API resolved without sending a response for /api/ctrlpnl/products_submit, this may result in stalled requests. { error: { code: 'parameter_unknown', doc_url: 'https://stripe.com/docs/error-codes/parameter-unknown', message: 'Received unknown parameter: {"name":"dasdas"}', param: '{"name":"dasdas"}', type: 'invalid_request_error' } }

My code is below:

 import Stripe from 'stripe';
 import { NextApiRequest, NextApiResponse } from 'next';

 const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
     apiVersion: '2020-08-27'
 });

 export default async function handler(req: NextApiRequest, res: NextApiResponse) {

   if (req.method === 'POST') {
     try {   
       const name = { name: req.body.name };

       fetch(`${process.env.BASE_URL}/v1/products`, {
    
         method: 'POST',
         body: JSON.stringify(name),
         headers: {
             'Accept': 'application/json',
             "content-type": 'application/x-www-form-urlencoded',
             Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
         }
         }).then((response) => {
             return response.json();
         }).then(data => {
             console.log(data);
             res.status(200).json(data)
         })

 } catch (err) {
     res.status(err.statusCode || 500).json(err.message);
 }
  } else {
     res.setHeader('Allow', 'POST');
     res.status(405).end('Method Not Allowed');
 }
 }

CodePudding user response:

The content-type of the fetch is correctly set to application/x-www-form-urlencoded, but the body contains a json. So Stripe is unable to parse the body parameters.

To fix that, you need to replace JSON.stringify by new URLSearchParams:

const name = { name: req.body.name };

fetch(`${process.env.BASE_URL}/v1/products`, { 
    method: 'POST',
    body: new URLSearchParams(name), // ← this will return "name=xxxx"
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
    }
});

Note that I recommend using the Stripe library which is much simpler to use: stripe.products.create(name);, especially since you already included it in your code.

  • Related