62ea110605
Lets the broker's ZarinPal merchant / sandbox / amount-unit be set from Admin → درگاه پرداخت (persisted in payment.settings) instead of env + redeploy, and adds a per-app "test payment" button that mints a real ZarinPal StartPay link straight from the panel — no site wiring needed. - migration 33_payment_settings.sql: singleton payment.settings + a transactions.is_test column. (33, not 32 — 32 is content_render_engine.) - broker read-path precedence: per-client override > DB settings > env. - POST /v1/admin/clients/:id/test-payment + GET/PUT /v1/admin/settings. - admin UI: «تنظیمات زرینپال» tab + «پرداخت آزمایشی» button. Adversarial-review fixes (2 confirmed HIGH): - do NOT pre-seed the settings row — a seeded sandbox=TRUE default would override a production ZARINPAL_SANDBOX=false env and silently route real payments to sandbox.zarinpal.com until an admin untouched the toggle. No row → env governs until an admin saves. - test transactions are tagged is_test and the webhook dispatcher skips them, so an admin smoke-test can never notify (or credit) a real client, regardless of metadata. Broker-authoritative, not consumer-dependent. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
140 lines
3.6 KiB
Go
140 lines
3.6 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, or if this is an admin
|
|
// smoke-test transaction (broker-authoritative: a test must never notify — and
|
|
// therefore never credit — a real client, regardless of metadata).
|
|
func (d *Dispatcher) Enqueue(ctx context.Context, client *models.ClientApp, t *models.Transaction, nowUnix int64) {
|
|
if t.IsTest {
|
|
return
|
|
}
|
|
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)
|
|
id, err := d.store.EnqueueWebhook(ctx, t.ID, *client.WebhookURL, body, sig)
|
|
if err != nil {
|
|
log.Printf("webhook enqueue failed for txn %s: %v", t.ID, err)
|
|
return
|
|
}
|
|
// Best-effort immediate delivery so the client credits near-instantly; the
|
|
// retry loop (Run) still covers it if this attempt fails.
|
|
go func() {
|
|
bg, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
if w, err := d.store.GetWebhook(bg, id); err == nil && w != nil {
|
|
d.deliver(bg, w)
|
|
}
|
|
}()
|
|
}
|
|
|
|
// 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
|
|
}
|