MercadoPago接口请求报Bad JSON format错误排查求助
MercadoPago支付接口返回"Bad JSON format"错误排查
此前正常运行的Node.js集成MercadoPago创建支付偏好的代码,近期用ThunderClient测试时返回{"error": "Bad JSON format"}错误。已排查中间件、简化代码及JSON结构,仍未解决,请求协助排查。
代码实现
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 };
测试传入的JSON
[ { "name": "Mouse chingon", "quantity": 1, "price": 165, "currency": "MEX", "img": "https://i.imgur.com/RdwnTcv.png", "description": "Es un mouse bien chingon" } ]
排查建议
- 检查货币代码:MercadoPago官方支持的墨西哥比索代码是
MXN而非MEX,currency_id传入错误值可能触发格式校验失败。 - 确认请求头:ThunderClient发送请求时必须设置
Content-Type: application/json,否则后端无法正确解析请求体,导致后续参数格式错误。 - 打印最终请求参数:在调用
payment.create(preference)前添加console.log(JSON.stringify(preference)),检查生成的JSON是否存在语法错误、值类型不匹配(比如quantity是否为数字)。 - 验证请求体解析:确保
express.json()中间件正确配置在路由之前,保证req.body被解析为JSON对象而非原始字符串。 - 测试最简请求:手动构造符合官方文档的偏好对象(跳过从
req.body映射的步骤),直接调用payment.create,排查是否是参数映射环节出现问题。
内容的提问来源于stack exchange,提问作者Juan Manuel Rodriguez Hurtado
相关产品推荐
相关产品推荐

