3: 接收消息
网关通过向您应用中的 webhook route 发送 POST 请求来传递每个传入消息。您验证共享密钥,然后可以随意处理该消息。
3.1: Webhook 路由
route both POST receive {
$given = (string)($_SERVER['HTTP_SECRET'] ?? '')
if ($this->secret === '' || !hash_equals($this->secret, $given)) return output(['error' => 'unauthorized'], code: 401)
$data = json_decode((string)file_get_contents('php://input'), true) ?: []
type_message::create(sender: (string)($data['from'] ?? ''), kind: (string)($data['type'] ?? 'text'), body: (string)($data['text'] ?? ''), ts: time())
return output(['ok' => true])
}
两个细节很重要:
- 使用
hash_equals进行密钥检查,绝不要使用==,以避免时间泄漏。 - 使用
php://input读取原始主体;网关发送的是 JSON,而不是表单。
3.2: 处理消息
在 webhook 内部,您可以访问完整的应用程序。像上面那样记录它,使用 WhatsApp 资源自动回复,将其路由到人工处理,或通过 Phlo Realtime 将其分发到实时收件箱。演示记录到 JSON 模型并渲染一个收件箱;只需将网关的 webhook 指向 /receive,消息就会出现。