Webhook

Sự kiện giao email

Nhận thông báo theo thời gian thực về tình trạng giao email. Cấu hình URL webhook trong dashboard. Mọi sự kiện đều được ký bằng HMAC-SHA256 để bảo mật.

POSThttps://your-server.com/webhook/email/delivery
!

Luôn xác minh chữ ký webhook. Tạo secret webhook trong dashboard và dùng nó để xác minh yêu cầu đến. Tính HMAC trên body thô của yêu cầu, không phải JSON đã tuần tự hóa lại.

Bắt đầu nhanh

Một listener xác minh chữ ký rồi xử lý sự kiện. Trả lời với trạng thái 2xx khi sự kiện được chấp nhận.

const express = require('express');
const crypto = require('crypto');

const app = express();
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;

function verifySignature(rawBody, signature) {
  if (!signature) return false;

  const expected = 'sha256=' + crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(rawBody)
    .digest('hex');

  const a = Buffer.from(signature);
  const b = Buffer.from(expected);
  // timingSafeEqual throws when the lengths differ
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// express.raw keeps the body as a Buffer, exactly as it was sent
app.post('/webhook/email/delivery', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifySignature(req.body, req.headers['x-webhook-signature'])) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  const { event, emailId, data } = JSON.parse(req.body.toString('utf8'));

  console.log('[Email Delivery] ' + event + ' - ' + emailId);

  if (event === 'delivered') {
    console.log('   Recipient: ' + data.recipientEmail);
  } else if (event === 'bounced') {
    console.log('   Reason: ' + data.reason);
  }

  res.status(200).json({ received: true });
});

app.listen(3001, () => {
  console.log('Email delivery webhook listener on port 3001');
  console.log('   POST /webhook/email/delivery');
});

Header

  • X-Webhook-Signaturestringbắt buộc

    Chữ ký HMAC-SHA256 của body yêu cầu. Định dạng: sha256=hex_digest

Thử với ngrok

Đưa listener cục bộ ra internet và đăng ký URL được tạo làm URL webhook trong dashboard.

ngrok http 3001
# Your webhook URL:
# https://abc123.ngrok.io/webhook/email/delivery

Sự kiện

Mỗi sự kiện là một đối tượng JSON có event, timestamp và một đối tượng data. Mở một sự kiện để xem đầy đủ payload và trường.

Endpoint lỗi quá thường xuyên? Trong dashboard bạn xem được trạng thái từng webhook, kích hoạt lại và thử lại các lần giao thất bại. Mở Webhook trong dashboard