4. Implement Idempotency
Prevent duplicate payments for the same order:
async function getOrCreatePayment(orderId, paymentDetails) {
const order = await db.orders.get(orderId);
// Return existing payment if already created
if (order.paymentReference) {
return client.getPayment(order.paymentReference);
}
// Create new payment
const payment = await client.createPayment(paymentDetails);
// Store reference immediately
await db.orders.update(orderId, {
paymentReference: payment.payment.reference,
});
return payment;
}