Basic Payment
A complete example of creating and processing a payment.
import { PaymentError, ValidationError, ZenPays } from 'zenpays'
async function processPayment() {
const zenpays = new ZenPays({
apiKey: process.env.ZENPAYS_API_KEY!,
})
try {
// 1. Create a payment intent
const intent = await zenpays.payments.createPaymentIntent({
amount: 2999, // $29.99 in cents
currency: 'USD',
description: 'Pro Plan - Monthly',
customerDetails: {
name: 'John Doe',
email: 'john@example.com',
},
metadata: {
orderId: 'order_123',
userId: 'user_456',
},
})
console.log('Payment Intent created:', intent.intentId)
// 2. Confirm with payment details
const result = await zenpays.payments.confirmPayment(intent.intentId, {
customerDetails: {
name: 'John Doe',
email: 'john@example.com',
address: { country: 'US' },
},
paymentMethodDetails: {
type: 'credit_card',
cardNumber: '4111111111111111',
expiryMonth: '12',
expiryYear: '2026',
cvv: '123',
cardHolderName: 'John Doe',
},
})
// 3. Handle the result
switch (result.status) {
case 'succeeded':
console.log('Payment successful!')
console.log('Transaction ID:', result.externalTransactionId)
return { success: true, transactionId: result.externalTransactionId }
case 'processing':
console.log('Payment is processing...')
return { success: false, status: 'processing' }
case 'failed':
console.log('Payment failed:', result.message)
return { success: false, error: result.message }
default:
// Handle next actions (3D Secure, etc.)
if (result.nextAction) {
return handleNextAction(result.nextAction)
}
}
}
catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message)
return { success: false, error: 'Invalid payment details' }
}
if (error instanceof PaymentError) {
console.error('Payment error:', error.message)
return { success: false, error: 'Payment declined' }
}
throw error
}
}
function handleNextAction(nextAction: any) {
if (nextAction.type === 'redirect') {
console.log('Redirect required:', nextAction.redirectUrl)
return { success: false, redirect: nextAction.redirectUrl }
}
if (nextAction.type === 'three_ds') {
console.log('3D Secure required')
return { success: false, threeDsUrl: nextAction.threeDsUrl }
}
return { success: false, error: 'Unknown action required' }
}
// Run the example
processPayment()
.then(result => console.log('Result:', result))
.catch(console.error)