Webhooks are HTTP callbacks — GitHub pushes code, Stripe processes a payment, WeChat Pay confirms an order, and they POST a JSON payload to your endpoint. A production webhook server on a Hong Kong VPS must verify signatures, respond within the provider’s timeout (5–30 seconds), queue processing to avoid blocking, and handle duplicate delivery and retries reliably.
Step 1: Core Webhook Handler (Node.js)
<code"># npm install express raw-body crypto bull ioredis
const express = require('express')
const crypto = require('crypto')
const { Queue } = require('bull')
const app = express()
const webhookQueue = new Queue('webhooks', { redis: { host: '127.0.0.1', port: 6379 }})
// CRITICAL: use raw body parser for webhook signature verification
// express.json() MUST NOT run before webhook routes
app.use('/webhook', express.raw({ type: 'application/json' }))
app.use(express.json()) // For all other routes
Step 2: GitHub Webhook
<code"># Verify GitHub HMAC-SHA256 signature
function verifyGitHubSignature(payload, signature, secret) {
const expected = 'sha256=' + crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex')
return crypto.timingSafeEqual(
Buffer.from(expected),
Buffer.from(signature || '')
)
}
app.post('/webhook/github', async (req, res) => {
const signature = req.headers['x-hub-signature-256']
const event = req.headers['x-github-event']
if (!verifyGitHubSignature(req.body, signature, process.env.GITHUB_WEBHOOK_SECRET)) {
return res.status(401).json({ error: 'Invalid signature' })
}
// Respond immediately — process async
res.status(200).json({ received: true })
const payload = JSON.parse(req.body)
await webhookQueue.add('github', { event, payload }, {
attempts: 3,
backoff: { type: 'exponential', delay: 5000 }
})
})
Step 3: Stripe Webhook
<code"># npm install stripe
const Stripe = require('stripe')
const stripe = Stripe(process.env.STRIPE_SECRET_KEY)
app.post('/webhook/stripe', async (req, res) => {
const sig = req.headers['stripe-signature']
let event
try {
event = stripe.webhooks.constructEvent(
req.body, sig, process.env.STRIPE_WEBHOOK_SECRET
)
} catch (err) {
return res.status(400).json({ error: err.message })
}
res.status(200).json({ received: true })
await webhookQueue.add('stripe', { type: event.type, data: event.data }, {
attempts: 5,
backoff: { type: 'exponential', delay: 10000 }
})
})
Step 4: WeChat Pay Webhook
<code"># WeChat Pay uses AES-GCM encryption — decrypt and verify
const crypto = require('crypto')
app.post('/webhook/wechat', express.json(), async (req, res) => {
try {
const { resource } = req.body
const decipher = crypto.createDecipheriv(
'aes-256-gcm',
Buffer.from(process.env.WECHAT_API_V3_KEY),
Buffer.from(resource.nonce, 'utf8')
)
decipher.setAuthTag(Buffer.from(resource.ciphertext, 'base64').slice(-16))
let decrypted = decipher.update(
Buffer.from(resource.ciphertext, 'base64').slice(0, -16), null, 'utf8'
)
decrypted += decipher.final('utf8')
const payment = JSON.parse(decrypted)
res.json({ code: 'SUCCESS', message: '成功' })
if (payment.trade_state === 'SUCCESS') {
await webhookQueue.add('wechat_payment', payment, { attempts: 3 })
}
} catch (err) {
res.json({ code: 'FAIL', message: err.message })
}
})
Step 5: Queue Workers
<code"># workers/webhook-processor.js
const { Worker } = require('bull')
const worker = new Worker('webhooks', async (job) => {
const { event, payload, type, data } = job.data
switch (job.name) {
case 'github':
if (event === 'push' && payload.ref === 'refs/heads/main') {
await triggerDeploy(payload.repository.name)
}
break
case 'stripe':
if (type === 'payment_intent.succeeded') {
await fulfillOrder(data.object.metadata.order_id, data.object.amount)
} else if (type === 'customer.subscription.deleted') {
await downgradeAccount(data.object.customer)
}
break
case 'wechat_payment':
await fulfillOrder(job.data.out_trade_no, job.data.amount.total / 100)
break
}
}, {
concurrency: 5,
redis: { host: '127.0.0.1', port: 6379 }
})
worker.on('failed', (job, err) => {
console.error(`Webhook job ${job.id} failed: ${err.message}`)
})
// Idempotency — prevent duplicate processing
async function fulfillOrder(orderId, amount) {
const key = `webhook:fulfilled:${orderId}`
const alreadyDone = await redis.set(key, '1', 'NX', 'EX', 86400)
if (!alreadyDone) return // Already processed
await Order.findByIdAndUpdate(orderId, {
status: 'paid',
amount_paid: amount,
paid_at: new Date(),
})
}
Step 6: Nginx Configuration
<code">cat > /etc/nginx/sites-available/webhooks << 'EOF'
server {
listen 443 ssl http2;
server_name hooks.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/hooks.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/hooks.yourdomain.com/privkey.pem;
# Webhooks must respond within provider timeouts
proxy_read_timeout 30s;
# Preserve raw body for signature verification
location /webhook/ {
proxy_pass http://127.0.0.1:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto https;
proxy_request_buffering off;
client_max_body_size 10m;
}
}
EOF
Webhook Testing
<code"># Test locally with ngrok (expose local port to internet for webhook testing)
ngrok http 3001
# Ngrok gives you: https://xxxx.ngrok.io → configure in GitHub/Stripe settings
# Or test with curl, simulating GitHub webhook:
PAYLOAD='{"ref":"refs/heads/main","repository":{"name":"myapp"}}'
SIG=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "your_secret" | awk '{print "sha256="$2}')
curl -X POST https://hooks.yourdomain.com/webhook/github \
-H "X-GitHub-Event: push" \
-H "X-Hub-Signature-256: $SIG" \
-H "Content-Type: application/json" \
-d "$PAYLOAD"
Conclusion
A production webhook server on a Hong Kong VPS handles GitHub deployments, Stripe payments, WeChat Pay order confirmations, and custom events from any provider — responding immediately to satisfy timeouts while processing asynchronously via a Redis-backed queue. Signature verification on every webhook prevents spoofed requests; idempotency keys in Redis prevent double-processing on retries. The HK VPS location ensures WeChat Pay and Alipay callbacks arrive at 15–30ms from mainland provider servers.
Handle webhooks reliably: Browse Server.HK Hong Kong VPS plans — a 2 GB plan runs your webhook server, Bull queue workers, and Redis comfortably alongside your main application.