如何将自定义数据绑定到paypal-rest-sdk?动态数据绑定报错求助
Hey there, let's break down why your custom req.body.totalPrice is throwing errors while hardcoded values work fine. Here are the most common fixes:
1. Check the Data Type & Format of totalPrice
PayPal’s API strictly requires the amount.total field to be a string with exactly two decimal places (e.g., "5.00" instead of 5 or "5"). If req.body.totalPrice is a number, or a string with fewer/more than two decimals, PayPal will reject it immediately.
Fix:
Convert and format the value properly before passing it to the JSON object:
// Validate and format the total price const rawTotal = req.body.totalPrice; let formattedTotal; // Make sure it's a valid number first if (!isNaN(parseFloat(rawTotal)) && isFinite(rawTotal)) { // Convert to two decimal places as a string formattedTotal = parseFloat(rawTotal).toFixed(2); } else { // Handle invalid input (return an error to the client) return res.status(400).send("Invalid total price provided"); }
2. Ensure req.body is Being Parsed Correctly
If req.body.totalPrice is undefined or null, that means your server isn’t parsing the incoming request body properly. This usually happens if you’re using Express without the right middleware.
Fix:
Add the body parsing middleware to your Express setup (place this before your route handlers):
// For JSON requests app.use(express.json()); // For form-urlencoded requests (if your frontend sends data this way) app.use(express.urlencoded({ extended: true }));
3. Validate the Input Value
Sometimes req.body.totalPrice might contain non-numeric characters (like commas instead of periods, or extra text) that break PayPal’s validation.
Fix:
Add a regex check to ensure the input is a valid currency format:
const currencyRegex = /^\d+(\.\d{1,2})?$/; if (!currencyRegex.test(rawTotal)) { return res.status(400).send("Total price must be a valid number with up to two decimals"); }
Modified Working Code
Putting it all together, here’s your updated payment JSON setup:
const rawTotal = req.body.totalPrice; let formattedTotal; // Validate input format const currencyRegex = /^\d+(\.\d{1,2})?$/; if (!currencyRegex.test(rawTotal) || isNaN(parseFloat(rawTotal))) { return res.status(400).send("Invalid total price format"); } // Format to two decimal places as string formattedTotal = parseFloat(rawTotal).toFixed(2); var create_payment_json = { "intent": "sale", "payer": { "payment_method": "paypal" }, "redirect_urls": { "return_url": "http://return.url", "cancel_url": "http://cancel.url" }, "transactions": [{ "item_list": { "items": [{ "name": "item", "sku": "item", "price": "1.00", "currency": "USD", "quantity": 1 }] }, "amount": { "currency": "USD", "total": formattedTotal // Now using the properly formatted value }, "description": "This is the payment description." }] };
One last tip: Check your server logs or PayPal’s API response for the exact error message—PayPal usually tells you exactly what’s wrong (like "Invalid amount format" or "Missing required field") which will speed up troubleshooting.
内容的提问来源于stack exchange,提问作者Pedro Castillo

