Files
flatrender/deploy/sdk/flatpay.js
T
soroush.asadi ec51e87d2d feat(payment): standalone ZarinPal broker on pay.flatrender.ir
A generic multi-client payment gateway so FlatRender, meezi.ir and
bargevasat.ir can all pay through ZarinPal's single verified callback
domain (pay.flatrender.ir).

New Go service services/payment (clones the notification skeleton +
vendored deps):
- migration 31_payment_broker.sql — `payment` schema: client_apps,
  transactions, webhook_deliveries.
- ZarinPal v4 client ported from the proven identity PaymentService
  (request.json -> StartPay -> verify.json; codes 100/101).
- client API: POST /v1/pay/request + /v1/pay/inquiry, authed by
  X-Api-Key + HMAC body signature; GET /callback/zarinpal (the single
  verified endpoint) verifies, then 302s the user back to the site's
  return_url (signed) and fires a signed, retried webhook.
- per-client ZarinPal merchant override (default = shared merchant);
  amount stored canonically in Rial, unit to ZarinPal env-configurable.
- admin API /v1/admin/* (FlatRender admin JWT): client-app CRUD +
  key issue/rotate + transactions list.

Deploy wiring: payment-svc in docker-compose.v2.yml (host port 1607),
pay.flatrender.ir server block in mirror-nginx conf, ENV_FILE +
README updates (cert SAN + manual migration note).

Admin UI: src/components/admin/PaymentsAdmin.tsx (client apps with
one-time key reveal + rotate, transactions table) + /admin/payments
page + nav link + fa/en strings; pay-admin proxy route to payment-svc.

Docs/SDK: deploy/PAYMENTS.md (integration contract) + deploy/sdk/flatpay.js
(zero-dep Node client + webhook verifier) for meezi/any site.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 23:59:54 +03:30

113 lines
3.9 KiB
JavaScript

// FlatRender Pay — drop-in Node client for the ZarinPal broker (pay.flatrender.ir).
// Zero dependencies: Node 18+ (global fetch) + built-in crypto. CommonJS.
//
// const { FlatPay } = require("./flatpay");
// const pay = new FlatPay({ apiKey: process.env.FLATPAY_KEY, secret: process.env.FLATPAY_SECRET });
//
// // 1. create + redirect
// const r = await pay.createPayment({ amount: 50000, currency: "IRT",
// description: "اشتراک", clientRef: order.id, returnUrl: "https://meezi.ir/pay/return",
// metadata: { userId: user.id } });
// res.redirect(r.payment_url);
//
// // 2. on your return_url handler — confirm authoritatively
// const txn = await pay.inquire(req.query.id);
// if (txn.status === "Paid") { /* grant */ }
//
// // 3. webhook (recommended) — Express:
// app.post("/flatpay/webhook", express.raw({ type: "*/*" }), (req, res) => {
// if (!pay.verifyWebhook(req.body, req.get("X-FlatPay-Signature"))) return res.sendStatus(401);
// const ev = JSON.parse(req.body.toString("utf8"));
// if (ev.status === "Paid") { /* idempotent grant keyed on ev.id / ev.client_ref */ }
// res.sendStatus(200);
// });
const crypto = require("crypto");
const DEFAULT_BASE = "https://pay.flatrender.ir";
function hmac(secret, message) {
return crypto.createHmac("sha256", secret).update(message).digest("hex");
}
function timingSafeEqualHex(a, b) {
try {
const ba = Buffer.from(a, "hex");
const bb = Buffer.from(b, "hex");
return ba.length === bb.length && crypto.timingSafeEqual(ba, bb);
} catch {
return false;
}
}
class FlatPay {
constructor({ apiKey, secret, baseUrl = DEFAULT_BASE } = {}) {
if (!apiKey || !secret) throw new Error("FlatPay: apiKey and secret are required");
this.apiKey = apiKey;
this.secret = secret;
this.baseUrl = baseUrl.replace(/\/+$/, "");
}
async _signedPost(path, payload) {
const body = JSON.stringify(payload);
const res = await fetch(this.baseUrl + path, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Api-Key": this.apiKey,
"X-Signature": hmac(this.secret, body),
},
body,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.message || `FlatPay ${path} failed (${res.status})`);
err.code = data.code;
err.status = res.status;
throw err;
}
return data;
}
/** Create a payment. Returns { id, status, payment_url, authority, amount_rial }. */
createPayment({ amount, currency = "IRR", description, clientRef, returnUrl, mobile, email, metadata }) {
if (!returnUrl) throw new Error("FlatPay: returnUrl is required");
return this._signedPost("/v1/pay/request", {
amount,
currency,
description,
client_ref: clientRef,
return_url: returnUrl,
mobile,
email,
metadata,
});
}
/** Authoritative server-side status check. Returns the full transaction. */
inquire(id) {
return this._signedPost("/v1/pay/inquiry", { id });
}
/**
* Verify the signed return-redirect query.
* Pass the query params { id, status, ref_id, sign } AND the amount_rial you got
* from createPayment/inquire (the redirect itself doesn't carry the amount).
*/
verifyRedirect({ id, status, ref_id = "", sign }, amountRial) {
const message = `${id}.${status}.${ref_id}.${amountRial}`;
return !!sign && timingSafeEqualHex(hmac(this.secret, message), sign);
}
/**
* Verify a webhook. `rawBody` MUST be the exact bytes received (Buffer or string —
* do not re-stringify a parsed object, signatures won't match).
*/
verifyWebhook(rawBody, signatureHeader) {
const msg = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(String(rawBody), "utf8");
return !!signatureHeader && timingSafeEqualHex(hmac(this.secret, msg), signatureHeader);
}
}
module.exports = { FlatPay, hmac };