ec51e87d2d
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>
124 lines
3.1 KiB
Go
124 lines
3.1 KiB
Go
package handlers
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/flatrender/payment-svc/internal/db"
|
|
"github.com/flatrender/payment-svc/internal/models"
|
|
"github.com/flatrender/payment-svc/internal/signing"
|
|
)
|
|
|
|
// Dispatcher delivers signed webhooks to client sites with retry/backoff.
|
|
type Dispatcher struct {
|
|
store *db.Store
|
|
http *http.Client
|
|
}
|
|
|
|
func NewDispatcher(store *db.Store) *Dispatcher {
|
|
return &Dispatcher{store: store, http: &http.Client{Timeout: 15 * time.Second}}
|
|
}
|
|
|
|
// Enqueue builds the signed payload for a finished transaction and queues delivery.
|
|
// No-op if the client has no webhook_url configured.
|
|
func (d *Dispatcher) Enqueue(ctx context.Context, client *models.ClientApp, t *models.Transaction, nowUnix int64) {
|
|
if client.WebhookURL == nil || *client.WebhookURL == "" {
|
|
return
|
|
}
|
|
event := "payment.failed"
|
|
if t.Status == models.StatusPaid {
|
|
event = "payment.paid"
|
|
}
|
|
payload := models.WebhookPayload{
|
|
Event: event,
|
|
ID: t.ID,
|
|
Status: t.Status,
|
|
AmountRial: t.AmountRial,
|
|
Currency: t.Currency,
|
|
Metadata: t.Metadata,
|
|
CreatedAtTs: nowUnix,
|
|
PaidAt: t.PaidAt,
|
|
}
|
|
if t.ClientRef != nil {
|
|
payload.ClientRef = *t.ClientRef
|
|
}
|
|
if t.RefID != nil {
|
|
payload.RefID = *t.RefID
|
|
}
|
|
if t.Authority != nil {
|
|
payload.Authority = *t.Authority
|
|
}
|
|
if t.CardPan != nil {
|
|
payload.CardPan = *t.CardPan
|
|
}
|
|
body, _ := json.Marshal(payload)
|
|
sig := signing.Sign(client.Secret, body)
|
|
if _, err := d.store.EnqueueWebhook(ctx, t.ID, *client.WebhookURL, body, sig); err != nil {
|
|
log.Printf("webhook enqueue failed for txn %s: %v", t.ID, err)
|
|
}
|
|
}
|
|
|
|
// Run starts the delivery loop until ctx is cancelled.
|
|
func (d *Dispatcher) Run(ctx context.Context) {
|
|
ticker := time.NewTicker(10 * time.Second)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
d.tick(ctx)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (d *Dispatcher) tick(ctx context.Context) {
|
|
due, err := d.store.ClaimDueWebhooks(ctx, 20)
|
|
if err != nil {
|
|
log.Printf("webhook claim failed: %v", err)
|
|
return
|
|
}
|
|
for _, w := range due {
|
|
d.deliver(ctx, w)
|
|
}
|
|
}
|
|
|
|
func (d *Dispatcher) deliver(ctx context.Context, w *db.WebhookDelivery) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.URL, bytes.NewReader(w.Payload))
|
|
if err != nil {
|
|
_ = d.store.MarkWebhookFailed(ctx, w.ID, 0, err.Error(), backoff(w.Attempts))
|
|
return
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("X-FlatPay-Signature", w.Signature)
|
|
req.Header.Set("X-FlatPay-Event", "payment")
|
|
|
|
resp, err := d.http.Do(req)
|
|
if err != nil {
|
|
_ = d.store.MarkWebhookFailed(ctx, w.ID, 0, err.Error(), backoff(w.Attempts))
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
|
_ = d.store.MarkWebhookDelivered(ctx, w.ID, resp.StatusCode)
|
|
return
|
|
}
|
|
_ = d.store.MarkWebhookFailed(ctx, w.ID, resp.StatusCode, "non-2xx response", backoff(w.Attempts))
|
|
}
|
|
|
|
// backoff: 30s, 1m, 2m, 4m, 8m, ... capped at 1h.
|
|
func backoff(attempts int) time.Duration {
|
|
d := 30 * time.Second
|
|
for i := 0; i < attempts; i++ {
|
|
d *= 2
|
|
if d >= time.Hour {
|
|
return time.Hour
|
|
}
|
|
}
|
|
return d
|
|
}
|