/* * PayNode webhook handler for Node.js websites (Node 18 or newer, no extra packages). * * Run it on its own: PAYNODE_WEBHOOK_SECRET=... PAYNODE_API_KEY=... node paynode.js * (listens on port 3001, or PORT if set; point your webhook URL at it through your web server) * Or inside Express: const paynode = require("./paynode"); * app.post("/paynode-webhook", express.raw({ type: "*" + "/" + "*" }), paynode.express); * * Then fill in the two parts marked "REPLACE THIS" with your own database code. * * It already checks the signature, refuses old or replayed messages, ignores repeats, * and asks PayNode to confirm a payment before you credit anyone. * Keep the secret and key on your server only - never in a browser or app. */ const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); const SECRET = process.env.PAYNODE_WEBHOOK_SECRET || "PASTE_YOUR_WEBHOOK_SECRET_HERE"; const API_KEY = process.env.PAYNODE_API_KEY || "PASTE_YOUR_API_KEY_HERE"; // a normal API key is enough // Remembers which messages were already handled, so a retry never credits twice. const SEEN_FILE = process.env.PAYNODE_SEEN_FILE || path.join(__dirname, "paynode-seen.txt"); async function paynodeGet(p) { try { const r = await fetch("https://paynode.space" + p, { headers: { Authorization: "Bearer " + API_KEY } }); return r.ok ? await r.json() : null; } catch { return null; } // PayNode unreachable: answer 503 so PayNode tries again later } /** Handles one webhook. Returns [httpStatus, text]. `raw` is the exact body as a Buffer. */ async function handle(raw, headers) { const h = (n) => headers[n.toLowerCase()] || ""; const ts = h("X-PayNode-Timestamp"), sig = h("X-PayNode-Signature"), delivery = h("X-PayNode-Delivery"); // 1. Check it really came from PayNode const expected = crypto.createHmac("sha256", SECRET).update(ts + "." + raw.toString("utf8")).digest("hex"); const sigOk = expected.length === sig.length && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig)); if (!sigOk || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return [400, "bad signature or too old"]; let event; try { event = JSON.parse(raw.toString("utf8")); } catch { return [400, "bad body"]; } // 2. Ignore repeats const id = delivery || crypto.createHash("sha256").update(raw).digest("hex"); const seen = fs.existsSync(SEEN_FILE) ? fs.readFileSync(SEEN_FILE, "utf8").split("\n") : []; if (seen.includes(id)) return [200, "already handled"]; // 3. Act on it switch (event.event) { case "invoice.settled": { // Never trust the message alone: fetch the payment from PayNode and check it. const inv = await paynodeGet("/api/invoices/" + encodeURIComponent(event.invoice_id)); if (!inv) return [503, "could not reach PayNode - will retry"]; if (inv.status !== "settled" || inv.live !== true || inv.sandbox) break; // credit nothing // ======================= REPLACE THIS (1 of 2) ======================= // Credit your user ONCE. Look up your own deposit by inv.order_id (the order_id you sent // when creating the payment) and check the coin and amount match what you expected: // inv.asset_key e.g. "eip155:56:0x55d398...7955" (USDT on BNB Chain) // inv.expected_display e.g. "25" // Save inv.id in a column with a UNIQUE rule, so a repeat can never credit twice. // ===================================================================== break; } case "payout.failed": // ======================= REPLACE THIS (2 of 2) ======================= // A payout you asked for did not go out. Nothing left your PayNode wallet. // Put the amount back in your user's balance. Find your withdrawal by event.reference // (the reference you sent with the payout). // ===================================================================== break; case "payout.confirmed": // The payout arrived. Mark your withdrawal event.reference as done if you like. break; default: // invoice.confirming, invoice.underpaid, invoice.confirmed, invoice.settling, // invoice.expired, invoice.failed and "test" need nothing. Credit only on invoice.settled. break; } // 4. Remember it, answer OK fs.appendFileSync(SEEN_FILE, id + "\n"); return [200, "ok"]; } /** Express route handler. Use with express.raw() so the body is the exact bytes PayNode signed. */ async function express(req, res) { try { const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from(req.body || ""); const [status, text] = await handle(raw, req.headers); res.status(status).send(text); } catch (e) { console.error("PayNode webhook:", e); res.status(500).send("error"); // PayNode will try again later } } module.exports = { handle, express }; // Run on its own when started directly: node paynode.js if (require.main === module) { require("http").createServer((req, res) => { if (req.method !== "POST") { res.writeHead(405); return res.end(); } const chunks = []; req.on("data", (c) => chunks.push(c)); req.on("end", async () => { let status = 500, text = "error"; try { [status, text] = await handle(Buffer.concat(chunks), req.headers); } catch (e) { console.error("PayNode webhook:", e); } res.writeHead(status, { "Content-Type": "text/plain" }); res.end(text); }); }).listen(Number(process.env.PORT) || 3001, () => console.log("PayNode webhook handler listening")); }