feat(payments): settle the direct rail through YooKassa
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 25s
CI / ui (pull_request) Successful in 1m17s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m50s

Replace Robokassa with YooKassa as the RUB direct-rail provider. The wallet
model is untouched: one `direct` segment, the same spend wall, the same
per-channel merchant shops (D42) and `shop` on the order (D44).

The two providers are not shaped alike, and that drives the change:

- Opening a purchase is now an outbound API call (`POST /v3/payments`,
  single-stage capture, redirect confirmation). The order id is both the
  `Idempotence-Key` and `metadata.order_id`, so a retried create cannot mint a
  second payment and a notification always resolves to its order.
- YooKassa does NOT sign notifications, so the body is never evidence: it only
  names a payment, which is re-read with `GET /v3/payments/{id}`, and only that
  answer is acted on. Two guards ride on it — the payment's metadata must name
  the order, and its `test` flag must match the shop's, so a test-shop payment
  can never credit real chips. The sender address is checked against YooKassa's
  published ranges first, which stops a forger turning each fabricated
  notification into an outbound call of ours.
- A notification lost for good would leave the money taken and the chips unowed,
  silently. The existing pending-order reaper now asks the provider about each
  order that reached its expiry age carrying a payment id, and credits the ones
  really paid — one request per order over its whole life, not polling.
- `payment.canceled` records a `failed` event, so a declined payment is finally
  surfaced to the customer as PAYMENTS.md §9 already specified.
- The admin refund moves the money through `POST /v3/refunds` before recording
  anything; a failed call records nothing, so the ledger cannot claim a refund
  that did not happen, and the recorded id is the provider's own.
- YooKassa has no cabinet-side generic receipt: «Чеки от ЮKassa» registers one
  only if the request carries it, so every payment and refund now sends an
  itemized `receipt` to the D36 confirmed email. The VAT rate code is a deploy
  variable; the settlement subject and method are constants.

Robokassa is retired, not deleted: the direct rail falls back to it when no
YooKassa shop is configured and no deployment sets its credentials, so reviving
it is a credentials change rather than a code change. Its variables are removed
from compose, .env.example, write-prod-env.sh and the three workflows, and
recorded in backend/internal/robokassa/README.md together with the cabinet
configuration and the revival steps. Ledger rows keep `provider = 'robokassa'`;
that literal is load-bearing for the idempotency index.

No migration and no wire change: `orders.provider_payment_id` already existed,
and the client is rail-agnostic.

Decisions D47-D51 (revising D41) and stage E12 are baked into the docs.
This commit is contained in:
Ilia Denisov
2026-07-28 08:51:31 +02:00
parent 985ed40639
commit 92ba527575
37 changed files with 2638 additions and 171 deletions
+18 -5
View File
@@ -11,11 +11,24 @@ import (
// one manual full refund per order.
const providerAdmin = "admin"
// RefundOrderFull refunds a paid order in full at the operator's request: it revokes the funded
// chips best-effort (floored at 0, never negative — D27), records a refund ledger row, and is
// idempotent (a second call reports AlreadyRefunded). The operator performs the actual money refund
// on the rail (Robokassa cabinet / VK support / Telegram refundStarPayment); this records it.
// RefundOrderFull refunds a paid order in full at the operator's request, recording the reversal
// only. It is for the rails that have no refund API of our own to call: the operator performs the
// actual money refund there by hand (VK support, Telegram refundStarPayment, the Robokassa cabinet),
// and this records it under the operator's own idempotency key.
func (s *Service) RefundOrderFull(ctx context.Context, orderID uuid.UUID) (RefundOutcome, error) {
return s.RefundOrderFullAs(ctx, orderID, providerAdmin, orderID.String())
}
// RefundOrderFullAs refunds a paid order in full and records it under the given provider and refund
// id: it revokes the funded chips best-effort (floored at 0, never negative — D27), appends a refund
// ledger row and is idempotent on (provider, providerRefundID), so a second call reports
// AlreadyRefunded. Callers whose rail moved the money through an API pass that rail's own refund id,
// which keeps the ledger reconcilable against the provider's records; the refund id is distinct from
// the fund's payment id, so the two rows coexist under the same partial-unique index.
//
// The provider-side money movement must already have succeeded when this is called — the ledger must
// never claim a refund that did not happen.
func (s *Service) RefundOrderFullAs(ctx context.Context, orderID uuid.UUID, provider, providerRefundID string) (RefundOutcome, error) {
o, err := s.store.orderByID(ctx, orderID)
if err != nil {
return RefundOutcome{}, err
@@ -24,7 +37,7 @@ func (s *Service) RefundOrderFull(ctx context.Context, orderID uuid.UUID) (Refun
if err != nil {
return RefundOutcome{}, err
}
return s.store.refund(ctx, orderID, providerAdmin, orderID.String(), refunded, s.clock())
return s.store.refund(ctx, orderID, provider, providerRefundID, refunded, s.clock())
}
// LedgerExportRow is one append-only ledger row for the tax / reconciliation export, carrying the
@@ -64,6 +64,83 @@ func directShop(cxt Context) string {
return ""
}
// AttachProviderPayment records the provider's own payment identifier on a pending order, right
// after the provider mints it and before the customer has paid. Two later paths depend on it: the
// reconcile sweep, which asks the provider what became of an order no callback ever confirmed, and a
// refund, which must address the original payment. It does not credit anything and does not change
// the order status.
func (s *Service) AttachProviderPayment(ctx context.Context, orderID uuid.UUID, provider, providerPaymentID string) error {
return s.store.attachProviderPayment(ctx, orderID, provider, providerPaymentID, s.clock())
}
// OrderRef identifies a stored order to a provider: which rail settles it, that rail's own payment
// id, the merchant shop channel it was issued through, and the amount and account it belongs to. It
// is what the reconcile sweep and the refund path need without giving them the whole order.
type OrderRef struct {
OrderID uuid.UUID
AccountID uuid.UUID
Provider string
PaymentID string
Shop string
Amount Money
Status string
}
// orderRef projects a stored order onto an OrderRef.
func orderRef(o orderRow) (OrderRef, error) {
amount, err := MoneyFromMinor(o.expectedAmount, Currency(o.currency))
if err != nil {
return OrderRef{}, err
}
return OrderRef{
OrderID: o.orderID,
AccountID: o.accountID,
Provider: o.provider,
PaymentID: o.paymentID,
Shop: o.shop,
Amount: amount,
Status: o.status,
}, nil
}
// OrderProviderRef reads how an order reaches its provider — the rail, that rail's payment id and
// the shop it was issued through. The refund path uses it to call the right merchant account.
func (s *Service) OrderProviderRef(ctx context.Context, orderID uuid.UUID) (OrderRef, error) {
o, err := s.store.orderByID(ctx, orderID)
if err != nil {
return OrderRef{}, err
}
return orderRef(o)
}
// reconcileBatch bounds one reconcile sweep, so a backlog cannot turn a periodic tick into a long
// run of provider calls.
const reconcileBatch = 50
// PendingForReconcile returns the pending orders that have reached their expiry age while carrying a
// provider payment id — the ones where the money may well have moved but no callback ever told us.
// The caller asks the provider for each one's real outcome before ExpireOrders writes them off.
// Orders that never reached a payment are not returned: there is nothing to ask about.
func (s *Service) PendingForReconcile(ctx context.Context) ([]OrderRef, error) {
ttl, err := s.store.orderTTL(ctx)
if err != nil {
return nil, err
}
rows, err := s.store.pendingForReconcile(ctx, ttl, s.clock(), reconcileBatch)
if err != nil {
return nil, err
}
out := make([]OrderRef, 0, len(rows))
for _, r := range rows {
ref, err := orderRef(r)
if err != nil {
return nil, err
}
out = append(out, ref)
}
return out, nil
}
// OrderItem returns a pending order's human title and the amount it charges, in the order's own
// currency — the details a provider's item-lookup phase needs (VK's get_item). It reads the order
// and the pack title, honouring the pack even if it was later deactivated (mirrors Fund).
+63 -1
View File
@@ -182,6 +182,9 @@ type orderRow struct {
currency string
origin string
status string
provider string
paymentID string
shop string
}
// orderByID reads an order, or ErrOrderNotFound.
@@ -198,6 +201,12 @@ func (s *Store) orderByID(ctx context.Context, orderID uuid.UUID) (orderRow, err
if err != nil {
return orderRow{}, fmt.Errorf("payments: load order %s: %w", orderID, err)
}
return newOrderRow(o), nil
}
// newOrderRow projects a stored order onto the intake's view of it, flattening the nullable provider
// columns to their empty strings.
func newOrderRow(o model.Orders) orderRow {
return orderRow{
orderID: o.OrderID,
accountID: o.AccountID,
@@ -206,7 +215,60 @@ func (s *Store) orderByID(ctx context.Context, orderID uuid.UUID) (orderRow, err
currency: o.Currency,
origin: o.Origin,
status: o.Status,
}, nil
provider: derefString(o.Provider),
paymentID: derefString(o.ProviderPaymentID),
shop: o.Shop,
}
}
// derefString reads a nullable text column as a plain string, treating NULL as empty.
func derefString(p *string) string {
if p == nil {
return ""
}
return *p
}
// attachProviderPayment records the provider's own payment id on a pending order, as soon as the
// provider mints it. It is what later lets an unattended order be re-checked against the provider
// and a refund address the right payment; fund overwrites it with the same value when the callback
// lands. It never changes the order status.
func (s *Store) attachProviderPayment(ctx context.Context, orderID uuid.UUID, provider, providerPaymentID string, now time.Time) error {
_, err := table.Orders.
UPDATE(table.Orders.Provider, table.Orders.ProviderPaymentID, table.Orders.UpdatedAt).
SET(postgres.String(provider), postgres.String(providerPaymentID), postgres.TimestampzT(now)).
WHERE(table.Orders.OrderID.EQ(postgres.UUID(orderID))).
ExecContext(ctx, s.db)
if err != nil {
return fmt.Errorf("payments: attach provider payment to order %s: %w", orderID, err)
}
return nil
}
// pendingForReconcile reads the pending orders that have reached their expiry age and carry a
// provider payment id — the ones whose real outcome is still unknown to us because no callback ever
// arrived. The caller asks the provider what happened before the order is written off as expired.
// Orders with no provider payment id are skipped: the customer never got as far as a payment.
func (s *Store) pendingForReconcile(ctx context.Context, ttlSeconds int, now time.Time, limit int) ([]orderRow, error) {
cutoff := now.Add(-time.Duration(ttlSeconds) * time.Second)
var rows []model.Orders
err := postgres.SELECT(table.Orders.AllColumns).
FROM(table.Orders).
WHERE(table.Orders.Status.EQ(postgres.String("pending")).
AND(table.Orders.CreatedAt.LT(postgres.TimestampzT(cutoff))).
AND(table.Orders.ProviderPaymentID.IS_NOT_NULL()).
AND(table.Orders.ProviderPaymentID.NOT_EQ(postgres.String("")))).
ORDER_BY(table.Orders.CreatedAt.ASC()).
LIMIT(int64(limit)).
QueryContext(ctx, s.db, &rows)
if err != nil && !errors.Is(err, qrm.ErrNoRows) {
return nil, fmt.Errorf("payments: load orders for reconcile: %w", err)
}
out := make([]orderRow, 0, len(rows))
for _, r := range rows {
out = append(out, newOrderRow(r))
}
return out, nil
}
// FundOutcome reports the result of an intake credit: whose balance, which segment and how many