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>
This commit is contained in:
soroush.asadi
2026-06-15 23:59:54 +03:30
parent 896ce3dfa9
commit ec51e87d2d
1830 changed files with 899129 additions and 8 deletions
+11
View File
@@ -22,6 +22,7 @@ EDGE_BIND=0.0.0.0
# nginx-facing host ports (must be free on 171.22.25.73 — :3000 is Gitea, avoid it).
FRONTEND_PORT=1600
GATEWAY_PORT=1605
PAY_PORT=1607
MINIO_PORT=1610
MINIO_CONSOLE_PORT=1611
@@ -58,10 +59,20 @@ MINIO_HOST_USE_SSL=true
RENDER_DEV_WORKER=false
RENDER_DEV_SNAPSHOTS=false
# ── Payment broker (pay.flatrender.ir) ───────────────────────────────────────
# Standalone ZarinPal gateway shared by FlatRender + meezi.ir + bargevasat.ir.
# ZARINPAL_MERCHANT_ID below is the SHARED merchant (verified domain = pay.flatrender.ir).
PAY_PUBLIC_URL=https://pay.flatrender.ir
# Unit ZarinPal expects in `amount`: "rial" (official v4) or "toman".
# ⚠️ Your identity service historically sends Toman — confirm with one sandbox
# payment which unit YOUR merchant settles in, then set this to match.
ZARINPAL_AMOUNT_UNIT=rial
# ── Payments (fill the providers you use; leave others blank) ────────────────
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
STRIPE_PUBLISHABLE_KEY=
# Shared ZarinPal merchant — used by BOTH the identity service and the pay broker.
ZARINPAL_MERCHANT_ID=
ZARINPAL_CALLBACK_URL=https://api.flatrender.ir/v1/payments/callback/zarinpal
ZARINPAL_SANDBOX=false
+149
View File
@@ -0,0 +1,149 @@
# FlatRender Pay — ZarinPal Broker Integration Guide
`pay.flatrender.ir` is a **standalone, multi-client ZarinPal gateway**. Any site
(FlatRender, meezi.ir, bargevasat.ir, …) routes payments through it, because
ZarinPal only accepts callbacks on the single verified domain `pay.flatrender.ir`.
```
your site ──POST /v1/pay/request──► pay.flatrender.ir ──► ZarinPal request.json
▲ (api key + HMAC) │ │
│ ▼ authority
└──◄ 302 return_url (signed) ◄── /callback/zarinpal ◄── user pays on ZarinPal
└──◄ POST webhook_url (signed) ◄────────┘ (verify.json → ref_id)
```
You get a **client app** from the FlatRender admin (Admin → پرداخت → اپلیکیشن‌ها):
- `api_key` — public id, sent as `X-Api-Key` (e.g. `pk_…`)
- `secret` — shown **once**; signs your requests AND verifies broker callbacks (`sk_…`)
- `webhook_url` — optional server-to-server result endpoint
- `allowed_return_origins` — the origins your `return_url` may use (empty = any)
---
## 1. Create a payment
`POST https://pay.flatrender.ir/v1/pay/request`
Headers:
| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
| `X-Api-Key` | your `api_key` |
| `X-Signature` | `hex( HMAC_SHA256(secret, <raw request body bytes>) )` |
Body:
```json
{
"amount": 50000,
"currency": "IRT",
"description": "خرید اشتراک طلایی",
"client_ref": "order-1234",
"return_url": "https://meezi.ir/payment/return",
"mobile": "09120000000",
"email": "user@example.com",
"metadata": { "user_id": "42", "plan": "gold" }
}
```
- `amount` — integer. `currency` is `"IRR"` (Rial, default) or `"IRT"` (Toman). The
broker stores the canonical Rial value and converts for ZarinPal.
- `client_ref` — your own order id (echoed back everywhere).
- `return_url` — where the user's browser is sent after payment. Must match an
`allowed_return_origins` entry if you configured any.
- `metadata` — arbitrary JSON, echoed back in the redirect signature scope + webhook.
Response `200`:
```json
{
"id": "9b2c…", // broker transaction id
"status": "Pending",
"payment_url": "https://www.zarinpal.com/pg/StartPay/A000…",
"authority": "A000…",
"amount_rial": 500000
}
```
**Redirect the user's browser to `payment_url`.**
---
## 2. The user comes back (browser redirect)
After ZarinPal, the broker verifies the payment and `302`-redirects the browser to
your `return_url` with a **signed** result appended:
```
https://meezi.ir/payment/return?status=Paid&id=9b2c…&ref_id=123456789&sign=<hex>
```
- `status``Paid` | `Failed` | `Cancelled`
- `ref_id` — ZarinPal receipt (only when paid)
- `sign``hex( HMAC_SHA256(secret, "{id}.{status}.{ref_id}.{amount_rial}") )`
⚠️ The redirect is **not** proof of payment on its own (a user can craft a URL).
Treat it as a UX hint, then **confirm with the webhook (§3) or the inquiry API (§4)**.
To verify the redirect signature you need `amount_rial`; fetch it via the inquiry
API, or just rely on the webhook / inquiry as the source of truth.
---
## 3. Webhook (recommended — the source of truth)
If `webhook_url` is set, the broker POSTs a **signed** JSON body to it when a payment
finishes (with retry + exponential backoff up to ~1h):
Headers: `X-FlatPay-Signature: <hex>`, `X-FlatPay-Event: payment`
```json
{
"event": "payment.paid",
"id": "9b2c…",
"status": "Paid",
"amount_rial": 500000,
"currency": "IRR",
"client_ref": "order-1234",
"ref_id": "123456789",
"authority": "A000…",
"card_pan": "6037********1234",
"metadata": { "user_id": "42", "plan": "gold" },
"paid_at": "2026-06-15T14:00:00Z",
"ts": 1750000000
}
```
Verify: `HMAC_SHA256(secret, <raw body bytes>) == X-FlatPay-Signature`. Respond `2xx`
to acknowledge (anything else is retried). Make handling **idempotent** (keyed on
`id` or `client_ref`) — duplicate deliveries are possible.
---
## 4. Inquiry (authoritative pull)
`POST https://pay.flatrender.ir/v1/pay/inquiry` (same `X-Api-Key` + `X-Signature` as §1)
```json
{ "id": "9b2c…" }
```
Returns the full transaction (status, `ref_id`, `amount_rial`, …). Use this from your
`return_url` handler to confirm before granting the user anything.
---
## Reference signature recipe
```
signature = hex( HMAC_SHA256(client_secret, message_bytes) )
```
- **request / inquiry**: `message_bytes` = the exact raw JSON body you send.
- **return redirect**: `message_bytes` = UTF-8 of `"{id}.{status}.{ref_id}.{amount_rial}"`.
- **webhook**: `message_bytes` = the exact raw JSON body received.
See [`sdk/flatpay.js`](./sdk/flatpay.js) for a drop-in Node client + Express webhook
verifier.
+18 -7
View File
@@ -14,17 +14,27 @@ Stack: gateway · identity · content · studio (.NET/Go) · file · render · n
mirror-nginx (:443, /etc/ssl/flatrender)
flatrender.ir → 171.22.25.73:1600 (fr2-frontend)
api.flatrender.ir → 171.22.25.73:1605 (fr2-gateway)
pay.flatrender.ir → 171.22.25.73:1607 (fr2-payment, ZarinPal broker)
storage.flatrender.ir → 171.22.25.73:1610 (fr2-minio)
```
The **payment broker** (`fr2-payment`, `pay.flatrender.ir`) is a standalone generic
ZarinPal gateway shared by FlatRender + meezi.ir + bargevasat.ir — ZarinPal only
accepts callbacks on that one verified domain. It does NOT sit behind the API
gateway (clients authenticate with an API key + HMAC). See
[`PAYMENTS.md`](./PAYMENTS.md) for the integration contract. The `payment` schema
is migration `31_payment_broker.sql` — on an existing DB volume it must be applied
manually (migrations only auto-run on first volume creation):
`docker exec -i fr2-postgres psql -U postgres -d flatrender < backend/db/migrations/31_payment_broker.sql`.
## One-time setup (do these BEFORE the first `git push gitea master`)
1. **DNS** — this box sits BEHIND NAT: its interface IP is `171.22.25.73` (private),
public NAT IPs are `31.171.101.127/.211`, and inbound 443 normally arrives via the
edge/CDN `185.239.1.100` (same entry your other sites use, e.g. `meezi.ir`). So a new
domain must enter the SAME way the others do — either:
- register `flatrender.ir` + `api` + `storage` + `www` in that edge/CDN (origin = this
server) and point DNS there, **or**
- register `flatrender.ir` + `api` + `pay` + `storage` + `www` in that edge/CDN (origin =
this server) and point DNS there, **or**
- bypass the CDN and point DNS straight at the server's public IP (like the hokm `api`
subdomain does — "must bypass").
Pointing DNS at a random/registrar IP shows that host's default page (e.g. a "not
@@ -37,7 +47,7 @@ Stack: gateway · identity · content · studio (.NET/Go) · file · render · n
cp <yourcert>/fullchain.pem /etc/ssl/soroushasadi/flatrender/
cp <yourcert>/privateKey.pem /etc/ssl/soroushasadi/flatrender/
```
Cert must cover `flatrender.ir` + `api.` + `storage.` (wildcard `*.flatrender.ir` + apex, or SAN).
Cert must cover `flatrender.ir` + `api.` + `pay.` + `storage.` (wildcard `*.flatrender.ir` + apex, or SAN).
3. **mirror-nginx** — add the server blocks from [`mirror-nginx-flatrender.conf`](./mirror-nginx-flatrender.conf)
to the proxy's `http{}` (the host file is `/root/mirror-server/nginx/nginx.conf`), then:
`docker exec mirror-nginx nginx -t && docker exec mirror-nginx nginx -s reload`.
@@ -63,10 +73,11 @@ blocks (step 3) and visit `https://flatrender.ir`.
## Host ports (must be free on 171.22.25.73)
`1600` frontend · `1605` gateway · `1610` MinIO · `1611` MinIO console. Postgres (5432)
and render (5010) bind to `127.0.0.1` only. Avoid `:3000` (Gitea), `:8081-8083` (Nexus),
`:1500/1505/1520` (bargevasat), `:3010/3101-3103/5080/5081` (meezi), `:3020`, `:2569`.
Change them via `FRONTEND_PORT`/`GATEWAY_PORT`/`MINIO_PORT` in the secret if any collide.
`1600` frontend · `1605` gateway · `1607` payment broker · `1610` MinIO · `1611` MinIO
console. Postgres (5432) and render (5010) bind to `127.0.0.1` only. Avoid `:3000` (Gitea),
`:8081-8083` (Nexus), `:1500/1505/1520` (bargevasat), `:3010/3101-3103/5080/5081` (meezi),
`:3020`, `:2569`. Change them via `FRONTEND_PORT`/`GATEWAY_PORT`/`PAY_PORT`/`MINIO_PORT` in
the secret if any collide.
## First-run notes
+21 -1
View File
@@ -29,7 +29,7 @@
server {
listen 80;
server_name flatrender.ir www.flatrender.ir api.flatrender.ir storage.flatrender.ir;
server_name flatrender.ir www.flatrender.ir api.flatrender.ir storage.flatrender.ir pay.flatrender.ir;
return 301 https://$host$request_uri;
}
@@ -87,3 +87,23 @@ server {
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# ── Payment broker (→ PAY_PORT) — pay.flatrender.ir ───────────────────────
# The single ZarinPal-verified callback domain. ZarinPal redirects users to
# pay.flatrender.ir/callback/zarinpal; the broker then bounces them to the
# originating site's return_url. Must NOT be cached by any upstream CDN.
server {
listen 443 ssl; http2 on;
server_name pay.flatrender.ir;
client_max_body_size 5m;
ssl_certificate /etc/ssl/soroushasadi/flatrender/fullchain.pem;
ssl_certificate_key /etc/ssl/soroushasadi/flatrender/privateKey.pem;
location / {
proxy_pass http://171.22.25.73:1607;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
+112
View File
@@ -0,0 +1,112 @@
// 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 };