关于 replicate-webhooks
面向构建 Replicate Webhook 处理程序的开发者,介绍预测生命周期事件、签名验证和载荷处理,并列出多种框架的实现参考。
主要功能
- 01处理预测状态事件
- 02验证 Webhook 签名
- 03了解事件载荷结构
- 04查看 Express、Next.js 和 FastAPI 实现参考
- 05使用本地隧道测试
适用场景
- 01处理预测完成或失败通知
- 02根据预测状态更新界面或处理输出
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ hookdeck/ webhook-skills --skill replicate-webhooks安装后在 Claude Code 中输入/replicate-webhooks确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
TODO.mdexamples/express/.env.examplejest.config.jspackage.jsonREADME.mdexamples/express/src/index.jsexamples/express/test/webhook.test.jsexamples/fastapi/.env.examplemain.pyREADME.mdrequirements.txttest_webhook.pyexamples/nextjs/.env.examplepackage.jsonREADME.mdvitest.config.tsexamples/nextjs/app/webhooks/replicate/route.tsexamples/nextjs/test/webhook.test.tsreferences/overview.mdsetup.mdverification.md详细介绍
Replicate Webhooks
何时使用此技能
- 设置 Replicate Webhook 处理程序
- 调试签名验证失败的问题
- 了解 Replicate 事件类型和负载
- 处理预测生命周期事件(启动、输出、日志、完成)
核心代码(请使用)
Express Webhook 处理程序
const express = require('express');
const crypto = require('crypto');
const app = express();
// CRITICAL: Use express.raw() for webhook endpoint - Replicate needs raw body
app.post('/webhooks/replicate',
express.raw({ type: 'application/json' }),
async (req, res) => {
// Get webhook headers
const webhookId = req.headers['webhook-id'];
const webhookTimestamp = req.headers['webhook-timestamp'];
const webhookSignature = req.headers['webhook-signature'];
// Verify we have required headers
if (!webhookId || !webhookTimestamp || !webhookSignature) {
return res.status(400).json({ error: 'Missing required webhook headers' });
}
// Manual signature verification (recommended approach)
const secret = process.env.REPLICATE_WEBHOOK_SECRET; // whsec_xxxxx from Replicate
const signedContent = `${webhookId}.${webhookTimestamp}.${req.body}`;
try {
// Extract base64 secret after 'whsec_' prefix
const secretBytes = Buffer.from(secret.split('_')[1], 'base64');
const expectedSignature = crypto
.createHmac('sha256', secretBytes)
.update(signedContent)
.digest('base64');
// Replicate can send multiple signatures, check each one
const signatures = webhookSignature.split(' ').map(sig => {
const parts = sig.split(',');
return parts.length > 1 ? parts[1] : sig;
});
const isValid = signatures.some(sig => {
try {
return crypto.timingSafeEqual(
Buffer.from(sig),
Buffer.from(expectedSignature)
);
} catch {
return false; // Different lengths = invalid
}
});
if (!isValid) {
return res.status(400).json({ error: 'Invalid signature' });
}
// Check timestamp to prevent replay attacks (5-minute window)
const timestamp = parseInt(webhookTimestamp, 10);
const currentTime = Math.floor(Date.now() / 1000);
if (currentTime - timestamp > 300) {
return res.status(400).json({ error: 'Timestamp too old' });
}
} catch (err) {
console.error('Signature verification error:', err);
return res.status(400).json({ error: 'Invalid signature' });
}
// Parse the verified webhook body
const prediction = JSON.parse(req.body.toString());
// Handle the prediction based on its status
console.log('Prediction webhook received:', {
id: prediction.id,
status: prediction.status,
version: prediction.version
});
switch (prediction.status) {
case 'starting':
console.log('Prediction starting:', prediction.id);
break;
case 'processing':
console.log('Prediction processing:', prediction.id);
if (prediction.logs) {
console.log('Logs:', prediction.logs);
}
break;
case 'succeeded':
console.log('Prediction completed successfully:', prediction.id);
console.log('Output:', prediction.output);
break;
case 'failed':
console.log('Prediction failed:', prediction.id);
console.log('Error:', prediction.error);
break;
case 'canceled':
console.log('Prediction canceled:', prediction.id);
break;
default:
console.log('Unknown status:', prediction.status);
}
res.status(200).json({ received: true });
}
);
常见预测状态
| 状态 | 描述 | 常见用例 |
|---|---|---|
starting | 预测正在初始化 | 在 UI 中显示加载状态 |
processing | 模型正在运行 | 显示进度;如果有日志,则显示日志 |
succeeded | 预测已成功完成 | 处理最终输出,更新 UI |
failed | 预测遇到错误 | 向用户显示错误消息 |
canceled | 预测已取消 | 清理资源,通知用户 |
环境变量
# Your webhook signing secret from Replicate
REPLICATE_WEBHOOK_SECRET=whsec_your_secret_here
本地开发
如需在本地测试 Webhook,请安装 Hookdeck CLI:
然后启动隧道:
npx hookdeck-cli listen 3000 replicate --path /webhooks/replicate
无需账号。提供本地隧道和 Web UI,可用于检查请求。
参考资料
- 什么是 Replicate Webhook — 事件类型和负载结构
- 设置 Webhook — 控制面板配置和签名密钥
- 签名验证 — 验证算法和常见问题
实现资源
框架示例
- Express 实现 — 使用 Express 的 Node.js
- Next.js 实现 — 带有 API 路由的 React 框架
- FastAPI 实现 — Python 异步框架
文档
推荐:webhook-handler-patterns
使用以下模式增强你的 Webhook 实现:
相关技能
- stripe-webhooks - Stripe 支付 Webhook
- github-webhooks - GitHub 仓库事件
- shopify-webhooks - Shopify 商店事件
- clerk-webhooks - Clerk 身份验证事件
- webhook-handler-patterns - 幂等性、错误处理、重试逻辑
- hookdeck-event-gateway - 可替代队列的 Webhook 基础设施——为 Webhook 处理程序提供可靠投递、自动重试、重放、速率限制和可观测性
评论
支持 Markdown