指南
处理网络钩子
复制页面
一个完整的网络钩子处理程序。检查原始正文上的签名,用API检查,执行一次,并快速回答。
Lia发送 charge.paid, charge.refunded 和 reward.paid 到你的网络钩子地址,用你的网络钩子密钥签名。参见 网络钩子 对于每个字段。
#Node.js 与 Express
阅读正文原始:签名是在发送的精确字节 Lia 上,所以在任何 JSON 解析之前检查它。
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";
import { lia } from "./lia.js";
const app = express();
function verified(rawBody, header, secret) {
const parts = Object.fromEntries((header ?? "").split(",").map((part) => part.split("=")));
const t = Number(parts.t);
if (!t || !parts.v1 || Math.abs(Date.now() / 1000 - t) > 300) return null;
const expected = Buffer.from(createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex"));
const given = Buffer.from(parts.v1);
if (expected.length !== given.length || !timingSafeEqual(expected, given)) return null;
return JSON.parse(rawBody);
}
app.post("/lia/webhook", express.raw({ type: "application/json" }), async (req, res) => {
const event = verified(req.body.toString("utf8"), req.get("Lia-Signature"), process.env.LIA_WEBHOOK_SECRET);
if (!event) return res.status(400).end();
// Answer first; do the work after.
res.status(200).end();
if (event.type === "charge.paid") {
// A nudge: check with Lia, then grant once per charge.
const { charge } = await lia("GET", `/charges/${event.data.id}`);
if (charge.status !== "paid") return;
await db.grantOnce(charge.id, charge.playerId, () => grant(charge.playerId, charge.productId));
await lia("POST", `/charges/${charge.id}/deliver`);
}
if (event.type === "charge.refunded") {
await db.takeBack(event.data.id); // if you'd already given it
}
if (event.type === "reward.paid") {
await db.noteReward(event.data.key, event.data.playerId, event.data.amount);
}
});#Cloudflare 工作者
async function verified(request, secret) {
const rawBody = await request.text();
const parts = Object.fromEntries((request.headers.get("Lia-Signature") ?? "").split(",").map((part) => part.split("=")));
const t = Number(parts.t);
if (!t || !parts.v1 || Math.abs(Date.now() / 1000 - t) > 300) return null;
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
const signature = new Uint8Array(parts.v1.match(/../g).map((byte) => parseInt(byte, 16)));
const ok = await crypto.subtle.verify("HMAC", key, signature, new TextEncoder().encode(`${t}.${rawBody}`));
return ok ? JSON.parse(rawBody) : null;
}
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/lia/webhook") {
const event = await verified(request, env.LIA_WEBHOOK_SECRET);
if (!event) return new Response(null, { status: 400 });
ctx.waitUntil(handle(event, env)); // the work, after answering
return new Response(null, { status: 200 });
}
return new Response("Not found", { status: 404 });
},
};#经验法则
- 检查签名,然后用API检查。 一个网络钩子表示发生了某事;
GET /charges/:id说些什么'现在是真实的。 - 立即行动。 网络钩子可能会多次到达,您的页面可能已经交付了。请根据交易 ID 或奖励密钥来确定您要执行的操作。
- 答案
2xx快速地。 Lia会立即尝试两次webhook,然后放弃。在回答之后进行缓慢的工作。 - 不'仅依赖网络钩子。 赶上
Lia.charges()当玩家打开你的应用时,因此即使错过网络钩子也不会丢失销售。 - 注意模式。 测试事件到达同一地址:检查
data.mode. - 忽略你不需要的类型'不要知道,并仍然回答
200.
#测试你的处理程序
作为测试者进行一次测试购买(参见 测试):它会发送一个真实、已签名的 charge.paid 与 mode: "test"。要在您的计算机上试用,请将本地服务器置于https隧道后,并让Lia团队将您的webhook地址指向此处。
自动翻译。英语是真实来源。 阅读英文