Skip to main content

Refund Flow

Process refunds for transactions.

import { NotFoundError, ZenPays } from 'zenpays'

async function processRefund(transactionId: string, reason: string) {
const zenpays = new ZenPays({
apiKey: process.env.ZENPAYS_API_KEY!,
})

// 1. Get the original transaction
const transaction = await zenpays.payments.getTransaction(transactionId)

console.log('Original transaction:')
console.log(' Amount:', transaction.amount)
console.log(' Currency:', transaction.currency)
console.log(' Status:', transaction.status)

// 2. Create the refund
const refund = await zenpays.refunds.create({
transactionId,
reason,
// Omit amount for full refund, or specify for partial
// amount: 500, // Partial refund of $5.00
})

console.log('Refund created:', refund.id)
console.log('Status:', refund.status)

// 3. Wait for refund to process
const waitForRefund = async (refundId: string): Promise<boolean> => {
const r = await zenpays.refunds.get(refundId)

if (r.status === 'completed') {
console.log('Refund completed!')
return true
}

if (r.status === 'failed') {
console.log('Refund failed:', r.failureReason)
return false
}

console.log('Refund status:', r.status)
await new Promise(resolve => setTimeout(resolve, 2000))
return waitForRefund(refundId)
}

return waitForRefund(refund.id)
}

// Batch refund example
async function processBatchRefunds() {
const zenpays = new ZenPays({
apiKey: process.env.ZENPAYS_API_KEY!,
})

const result = await zenpays.refunds.createBatch({
refunds: [
{ transactionId: 'txn_1', reason: 'Customer request' },
{ transactionId: 'txn_2', reason: 'Duplicate charge' },
{ transactionId: 'txn_3', amount: 500, reason: 'Partial refund' },
],
})

console.log('Batch results:')
console.log(' Total:', result.total)
console.log(' Succeeded:', result.succeeded)
console.log(' Failed:', result.failed)

result.results.forEach((r) => {
if (r.status === 'success') {
console.log(` ${r.transactionId}: Refund ${r.refundId}`)
}
else {
console.log(` ${r.transactionId}: Failed - ${r.error}`)
}
})
}

// Get refund statistics
async function getRefundStats() {
const zenpays = new ZenPays({
apiKey: process.env.ZENPAYS_API_KEY!,
})

const stats = await zenpays.refunds.getStats('2024-01-01', '2024-12-31')

console.log('Refund Statistics:')
console.log(' Total refunds:', stats.totalCount)
console.log(' Total amount:', stats.totalAmount)
console.log(' Pending:', stats.pendingCount, '($', stats.pendingAmount, ')')
console.log(' Completed:', stats.completedCount, '($', stats.completedAmount, ')')
}

processRefund('txn_xxx', 'Customer requested refund')