mercadoPago { "error": "Bad JSON format" }

87 views Asked by At

So, I've been working with the following code:

    require("dotenv").config();
    const { MercadoPagoConfig, Preference } = require("mercadopago");
    const { Product } = require("../../models/Product"); 
    const { User } = require("../../models/User"); 

    require("../../db"); 

    const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
    const client = new MercadoPagoConfig({ accessToken: ACCESS_TOKEN });
    const payment = new Preference(client);

    const placeOrder = async (req, res) => {
    try {
    
    const cart = req.body;
    console.log(cart);

    let items = cart.map((product) => ({
      title: product.name,
      quantity: product.quantity,
      unit_price: product.price,
      currency_id: product.currency, 
      image: product.img,
      description: product.description,
    }));

    let preference = {
      items: items,
      back_urls: {
        failure: "http://localhost:3001",
        pending: "http://localhost:3001",
        success: "http://localhost:3001",
      },
    };

    const response = await payment.create(preference);
    res.status(200).send(response);
    console.log(response);
    } catch (error) {
    res.status(400).json({ error: error.message });
    }
    };

    const successfulPurchase = async (req, res) => {
    try {
 
    res.status(200).send("Purchase completed successfully");
    } catch (error) {
    res.status(400).json({ error: error.message });
    }
    };

    module.exports = { placeOrder, successfulPurchase };

This code used to work fine but then I tried it again in thunderclient and boom:

{ "error": "Bad JSON format" }

However the JSON is actually fine:

    [
    {
    "name": "Mouse chingon",
    "quantity": 1,
    "price": 165,
    "currency": "MEX",
    "img": "https://i.imgur.com/RdwnTcv.png",
    "description": "Es un mouse bien chingon"
    }
    ]

I've been checking up and down until breaking my books and windows, I have no idea where or even what to move anymore

I've moved the JSON around simplified, checked the middlewares, went ahead and simplify the code, and everything just broke, hell I broke down in tears after 12 hours just fighting with this

1

There are 1 answers

0
Richard Arevalo On

Replace:

const response = await payment.create(preference);

With:

const response = await payment.create({ body: preference });

This ensures that the preference object is correctly structured when making the request to payment.create. You can find more details in the MercadoPago Node.js SDK documentation