Order Deleted Event
Documentation for the order.deleted webhook event
The order.deleted event is triggered when an order is permanently deleted from the system.
Event Type
order.deletedWhen It's Triggered
This event is sent when:
- An admin permanently deletes an order
- An order is purged after cancellation
- System cleanup removes old test orders
- Fraudulent orders are removed
Note: This is different from order cancellation. Cancelled orders trigger an order.updated event with status: "CANCELLED". The order.deleted event means the order has been completely removed from the system.
Webhook Payload Structure
The payload contains the complete order data at the time of deletion:
{
"event": "order.deleted",
"timestamp": "2026-02-15T16:20:00.000Z",
"data": {
"orderGroupId": "og_abc123xyz",
"orderGroupCode": "ORD-2026-001",
"deliveryCharge": 50,
"advancedPayment": 500,
"advancedPaymentId": "pay_xyz789",
"customer": {
"id": "cust_123",
"name": "John Doe",
"email": "john@example.com",
"phoneNumber": "+1234567890",
"shippingAddress": "123 Main St, City, Country"
},
"status": "CANCELLED",
"paymentMethods": [],
"purchaseIntent": "BROWSING",
"platform": "MESSENGER",
"facebookPageId": "page_123",
"whatsappAccountId": null,
"totalQuantity": 3,
"orderCount": 2,
"createdAt": "2026-02-15T10:30:00.000Z",
"updatedAt": "2026-02-15T14:45:00.000Z",
"dateTime": "2026-02-15T10:30:00.000Z",
"notes": "Order cancelled by customer",
"orders": [
{
"id": "item_1",
"productId": "prod_abc",
"productName": "Wireless Headphones",
"variant": "Black",
"quantity": 2,
"extra": {
"color": "Midnight Black",
"engraving": "John D."
},
"productImages": ["https://example.com/image1.jpg"],
"product": {
"id": "prod_abc",
"name": "Wireless Headphones",
"retailPrice": 2500,
"wholesalePrice": 2000,
"description": "Premium wireless headphones with noise cancellation",
"images": ["https://example.com/image1.jpg"]
}
}
]
}
}Field Descriptions
All fields are identical to the Order Created Event. The event field will be "order.deleted".
Important Considerations
Data Retention
When an order is deleted:
- The complete order data is sent one final time in the webhook
- This is your last chance to archive or backup order information
- The order will no longer be retrievable from our API
- Related data like customer information may still exist separately
Inventory Implications
If the order was in PENDING or PROCESSING state when deleted:
- Allocated inventory should be released
- Reserved stock should be returned to available inventory
- Any holds or reservations should be cleared
Example Handlers
Basic Deletion Handler
app.post('/webhooks/orders', async (req, res) => {
const { event, timestamp, data } = req.body;
if (event === 'order.deleted') {
console.log(`Order deleted: ${data.orderGroupCode}`);
console.log(`Order ID: ${data.orderGroupId}`);
console.log(`Status at deletion: ${data.status}`);
// Archive order data
await archiveOrder(data);
// Release inventory if needed
if (['PENDING', 'PROCESSING'].includes(data.status)) {
await releaseInventory(data);
}
// Cleanup related records
await cleanupRelatedData(data.orderGroupId);
// Update our database
await deleteOrderFromDatabase(data.orderGroupId);
}
res.status(200).json({ received: true });
});Archive Before Deleting
async function handleOrderDeleted(orderData) {
// Archive to long-term storage
await archiveStorage.save({
collection: 'deleted_orders',
id: orderData.orderGroupId,
data: {
...orderData,
deletedAt: new Date().toISOString(),
archivedBy: 'webhook'
}
});
// Keep a record in the database
await db.deletedOrders.create({
data: {
orderGroupId: orderData.orderGroupId,
orderGroupCode: orderData.orderGroupCode,
customerId: orderData.customer.id,
customerName: orderData.customer.name,
totalQuantity: orderData.totalQuantity,
status: orderData.status,
deletedAt: new Date(),
originalData: orderData
}
});
// Remove from active orders
await db.orders.delete({
where: { orderGroupId: orderData.orderGroupId }
});
console.log(`Order ${orderData.orderGroupCode} archived and deleted`);
}Common Use Cases
1. Inventory Release
Release any allocated inventory:
async function releaseInventory(orderData) {
for (const item of orderData.orders) {
try {
// Return items to available inventory
await db.inventory.increment({
where: { productId: item.productId },
data: {
availableQuantity: item.quantity,
reservedQuantity: -item.quantity
}
});
console.log(
`Released ${item.quantity} units of ${item.productName} (${item.productId})`
);
} catch (error) {
console.error(`Failed to release inventory for ${item.productId}:`, error);
// Log for manual review
await logInventoryIssue(item, error);
}
}
}2. Financial Reconciliation
Handle payment and refund tracking:
async function handleFinancialCleanup(orderData) {
// If there was an advance payment
if (orderData.advancedPayment > 0) {
// Check if refund was processed
const refund = await db.refunds.findFirst({
where: {
orderId: orderData.orderGroupId,
paymentId: orderData.advancedPaymentId
}
});
if (!refund) {
// Flag for manual review
await flagForRefundReview({
orderGroupId: orderData.orderGroupId,
amount: orderData.advancedPayment,
paymentId: orderData.advancedPaymentId,
customer: orderData.customer
});
}
}
// Record in financial journal
await db.financialJournal.create({
data: {
type: 'ORDER_DELETED',
orderGroupId: orderData.orderGroupId,
amount: orderData.advancedPayment || 0,
timestamp: new Date(),
metadata: {
orderCode: orderData.orderGroupCode,
status: orderData.status
}
}
});
}3. Customer Communication
Notify relevant parties:
async function notifyDeletion(orderData) {
// If order was active (not already cancelled)
if (!['CANCELLED', 'RETURNED'].includes(orderData.status)) {
// Notify customer
if (orderData.customer.email) {
await emailService.send({
to: orderData.customer.email,
template: 'order-cancelled',
data: {
orderCode: orderData.orderGroupCode,
refundAmount: orderData.advancedPayment,
reason: 'Order has been cancelled'
}
});
}
}
// Notify internal teams
await slackService.send({
channel: '#order-deletions',
message: `Order ${orderData.orderGroupCode} deleted`,
data: {
orderId: orderData.orderGroupId,
customer: orderData.customer.name,
items: orderData.totalQuantity,
status: orderData.status
}
});
}4. Analytics and Reporting
Track deletion metrics:
async function trackDeletion(orderData) {
await analytics.track({
event: 'Order Deleted',
properties: {
orderId: orderData.orderGroupId,
orderCode: orderData.orderGroupCode,
status: orderData.status,
totalValue: calculateOrderValue(orderData),
itemCount: orderData.totalQuantity,
platform: orderData.platform,
daysSinceCreation: calculateDaysSince(orderData.createdAt),
deletionReason: inferDeletionReason(orderData)
}
});
// Update deletion statistics
await db.stats.updateMany({
where: { metric: 'orders_deleted', date: today() },
data: { count: { increment: 1 } }
});
}
function inferDeletionReason(orderData) {
if (orderData.status === 'CANCELLED') return 'cancelled';
if (orderData.status === 'PENDING' &&
daysSince(orderData.createdAt) > 30) return 'abandoned';
return 'manual_deletion';
}5. Cleanup Related Records
Remove or archive associated data:
async function cleanupRelatedData(orderGroupId) {
// Archive shipping labels
const labels = await db.shippingLabels.findMany({
where: { orderGroupId }
});
for (const label of labels) {
await archiveStorage.save({
collection: 'archived_labels',
id: label.id,
data: label
});
}
// Remove shipping labels
await db.shippingLabels.deleteMany({
where: { orderGroupId }
});
// Archive tracking info
await archiveStorage.save({
collection: 'archived_tracking',
id: orderGroupId,
data: await db.tracking.findMany({
where: { orderGroupId }
})
});
// Remove tracking records
await db.tracking.deleteMany({
where: { orderGroupId }
});
// Clean up temporary files
await deleteOrderAttachments(orderGroupId);
console.log(`Cleaned up related data for order ${orderGroupId}`);
}6. Audit Trail
Maintain deletion audit trail:
async function recordDeletion(orderData, deletedBy = 'system') {
await db.orderDeletionLog.create({
data: {
orderGroupId: orderData.orderGroupId,
orderGroupCode: orderData.orderGroupCode,
deletedAt: new Date(),
deletedBy,
orderSnapshot: orderData,
metadata: {
customerName: orderData.customer.name,
customerEmail: orderData.customer.email,
totalQuantity: orderData.totalQuantity,
status: orderData.status,
platform: orderData.platform,
createdAt: orderData.createdAt,
lastUpdatedAt: orderData.updatedAt
}
}
});
console.log(`Deletion recorded for order ${orderData.orderGroupCode}`);
}Reconciliation Example
Complete reconciliation handler:
async function handleOrderDeleted(orderData) {
const deletionId = generateDeletionId();
try {
console.log(`Processing deletion for ${orderData.orderGroupCode} (${deletionId})`);
// 1. Archive the order
await archiveOrder(orderData);
// 2. Release inventory if needed
if (['PENDING', 'PROCESSING'].includes(orderData.status)) {
await releaseInventory(orderData);
}
// 3. Handle financial cleanup
await handleFinancialCleanup(orderData);
// 4. Notify relevant parties
await notifyDeletion(orderData);
// 5. Track in analytics
await trackDeletion(orderData);
// 6. Cleanup related data
await cleanupRelatedData(orderData.orderGroupId);
// 7. Record deletion in audit log
await recordDeletion(orderData);
// 8. Remove from active database
await db.orders.delete({
where: { orderGroupId: orderData.orderGroupId }
});
console.log(`Successfully processed deletion ${deletionId}`);
} catch (error) {
console.error(`Error processing deletion ${deletionId}:`, error);
// Log for manual review
await logDeletionError(deletionId, orderData, error);
// Don't throw - we still want to acknowledge the webhook
}
}Best Practices
1. Always Archive First
Never delete without archiving:
async function safeDelete(orderData) {
// Archive first
const archived = await archiveOrder(orderData);
// Only delete if archive succeeded
if (archived) {
await deleteOrderFromDatabase(orderData.orderGroupId);
} else {
throw new Error('Archive failed, aborting deletion');
}
}2. Check Dependencies
Verify no active dependencies before deleting:
async function checkDependencies(orderGroupId) {
const dependencies = {
activeShipments: await db.shipments.count({
where: { orderGroupId, status: 'IN_TRANSIT' }
}),
pendingRefunds: await db.refunds.count({
where: { orderGroupId, status: 'PENDING' }
}),
openDisputes: await db.disputes.count({
where: { orderGroupId, status: 'OPEN' }
})
};
const hasActiveDependencies = Object.values(dependencies).some(count => count > 0);
if (hasActiveDependencies) {
await flagForManualReview(orderGroupId, dependencies);
}
return dependencies;
}3. Graceful Error Handling
Handle errors without losing data:
async function handleOrderDeleted(orderData) {
try {
await processOrderDeletion(orderData);
} catch (error) {
// Still acknowledge webhook
console.error('Deletion processing failed:', error);
// Save for retry
await saveFailedDeletion(orderData, error);
// Alert team
await alertTeam('Order deletion failed', {
orderGroupId: orderData.orderGroupId,
error: error.message
});
}
}