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) 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 }