Event Handling
Guide for handling webhook events with concise processing logic and synchronization tips.
Event Handling
Implement distinct handlers for each event type:
async function processWebhookEvent(webhook) {
const { event_type, data } = webhook;
console.log(`Processing ${event_type} for order ${data.id}`);
switch (event_type) {
case 'order.created':
await handleOrderCreated(data);
break;
case 'order.success':
await handleOrderSuccess(data);
break;
case 'order.failed':
await handleOrderFailed(data);
break;
case 'order.updated':
await handleOrderUpdated(data);
break;
default:
throw new Error(`Unknown event type: ${event_type}`);
}
}
async function handleOrderCreated(orderData) {
console.log('New order:', orderData.id);
const response = await fetch('https://your-api.com/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.YOUR_API_TOKEN}`
},
body: JSON.stringify(orderData)
});
if (!response.ok) throw new Error(`Order creation failed: ${response.statusText}`);
return await response.json();
}
async function handleOrderSuccess(orderData) {
console.log('Payment success:', orderData.id);
const response = await fetch(`https://your-api.com/orders/${orderData.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.YOUR_API_TOKEN}`
},
body: JSON.stringify({ status: 'paid', payment_confirmed: true })
});
if (!response.ok) throw new Error(`Order update failed: ${response.statusText}`);
return await response.json();
}
async function handleOrderFailed(orderData) {
console.log('Payment failed:', orderData.id);
const response = await fetch(`https://your-api.com/orders/${orderData.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.YOUR_API_TOKEN}`
},
body: JSON.stringify({ status: 'failed', payment_failed: true })
});
if (!response.ok) throw new Error(`Order update failed: ${response.statusText}`);
return await response.json();
}
async function handleOrderUpdated(orderData) {
console.log('Order update:', orderData.id);
const response = await fetch(`https://your-api.com/orders/${orderData.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.YOUR_API_TOKEN}`
},
body: JSON.stringify(orderData)
});
if (!response.ok) throw new Error(`Order sync failed: ${response.statusText}`);
return await response.json();
}Order Identification
Identify orders using:
data.id- Amwal's order IDdata.ref_id- Your order referencedata.merchant_order_id- Your order ID
Data Synchronization
Sync these fields with your system:
- Order Status: Align with Amwal
- Payment Info: Transaction ID, method, amount
- Customer Details: Email, phone, address
- Order Metadata: Custom fields, integration details
Updated about 15 hours ago