Reputation: 99
Im trying to save the Order with a payment property Payment._id but cant get the the capture id in the create route. Is there a way to pass some id through paypal and then get that ID in the capture? and is this a good idea to save the Order and Payment in the capture route?
The Payment Model stores the paypal capture
router.post("/order/create", async (req, res) => {
const { items, payment_method, price } = req.body;
try {
//Document just for validation that doesn't save
const newOrder = new Order({
items,
payment_method,
price,
});
const validationError = await newOrder.validate();
if (validationError !== undefined) throw Error("Validation Failed");
let request = new paypalSDK.orders.OrdersCreateRequest();
const body = {
intent: "CAPTURE",
purchase_units: [
{
items: paypalItems(newOrder.items),
amount: {
currency_code: "USD",
value: newOrder.price,
breakdown: {
item_total: {
currency_code: "USD",
value: newOrder.price,
},
},
},
},
]
};
request.prefer("return=representation");
request.requestBody(body);
const order = await client.execute(request);
res.status(200).json({
orderID: order.result.id,
});
} catch (e) {
console.error(e);
res.status(500);
}
});
router.post("/order/capture", async (req, res) => {
const { items, payment_method, price } = req.body;
const orderID = req.body.orderID;
const request = new paypalSDK.orders.OrdersCaptureRequest(orderID);
request.requestBody({});
try {
const capture = await client.execute(request);
const captureID = capture.result.purchase_units[0].payments.captures[0].id;
const newPayment = new Payment(capture.result);
const savedPayment = await newPayment.save();
const newOrder = new Order({
items,
payment_method,
price,
payment: savedPayment._id,
});
await newOrder.save();
} catch (err) {
console.error(err);
return res.sendStatus(500);
}
res.status(200).json({});
});
Upvotes: 0
Views: 545
Reputation: 30477
In the purchase_units[0]
of your orders create request body, you can include a unique** invoice_id
(visible to the payer, indexed for searching), or an arbitrary custom_id
(only visible to the receiver, not indexed).
*The invoice ID should never have been used before for a successfully captured payment, or this will result in a Duplicate Invoice ID error in the default configuration (to prevent accidental duplicate payments for the same thing)
When you capture an order successfully, the PayPal transaction ID will be at purchase_units[0].payments.captures[0].id
. Store this in your database for future reference.
Upvotes: 2