v(i)b(e)c(o)d(e)4u.com
Назад на форум vbcd4u.com
🔥 Нейросети2026-11-17T09:04:00.000Z▲ 0 upvotes

Kaspi QR payment webhook: idempotency, signature verification and protection against double issuance

@murdasoftРедакция vbcd4u · MurdaSoft
Открыть все обсуждения →

First, let's clarify the terms

“Double debiting” and “double processing” are different problems. Money is debited twice when two payment requests are created for one order (the buyer clicked “Pay” twice and you issued the QR twice). Double processing - when the payment system sends the notification again, and you charge the balance twice or ship the order twice. They are solved in different places, and the article covers both.

Take the request format, signature header name and set of fields from the integration documentation that you receive when connecting to Kaspi. Below names like X-Signature, paymentId, amount are placeholders: replace them with actual ones. If the provider does not sign the notifications, below is described how to compensate for this.

Tables

CREATE TABLE payments (
  id            bigserial PRIMARY KEY,
  order_id      bigint NOT NULL REFERENCES orders(id),
  provider      text   NOT NULL DEFAULT 'kaspi',
  external_id   text,                         -- идентификатор платежа у провайдера
  amount_tiyn   bigint NOT NULL,              -- сумма в минимальных единицах, без float
  status        text   NOT NULL CHECK (status IN ('pending','paid','failed','expired')),
  created_at    timestamptz NOT NULL DEFAULT now(),
  paid_at       timestamptz
);

-- один активный платёж на заказ: защита от двойного выставления
CREATE UNIQUE INDEX payments_one_pending_per_order
  ON payments (order_id) WHERE status = 'pending';

-- одно уведомление обрабатывается один раз
CREATE TABLE webhook_events (
  provider     text NOT NULL,
  event_key    text NOT NULL,
  received_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, event_key)
);

A partial unique index will not allow creating a second pending-payment for an order, even if two requests arrive at the same time. The billing code in case of conflict simply returns the already existing QR.

Handler in Next.js

// app/api/webhooks/kaspi/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { pool } from "@/lib/db";

export const runtime = "nodejs";

function verify(rawBody: string, signature: string | null): boolean {
  if (!signature) return false;
  const expected = createHmac("sha256", process.env.KASPI_WEBHOOK_SECRET!)
    .update(rawBody, "utf8")
    .digest("hex");
  const a = Buffer.from(expected, "hex");
  const b = Buffer.from(signature, "hex");
  return a.length === b.length && timingSafeEqual(a, b);
}

export async function POST(req: Request) {
  const raw = await req.text();                    // подпись считается по сырому телу
  if (!verify(raw, req.headers.get("x-signature"))) {
    return new Response("bad signature", { status: 401 });
  }

  const evt = JSON.parse(raw) as { paymentId: string; orderId: string; amount: number; status: string };
  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    const inserted = await client.query(
      `INSERT INTO webhook_events (provider, event_key) VALUES ('kaspi', $1)
       ON CONFLICT DO NOTHING RETURNING event_key`,
      [`${evt.paymentId}:${evt.status}`]
    );
    if (inserted.rowCount === 0) {            // уже обработано
      await client.query("ROLLBACK");
      return Response.json({ ok: true, duplicate: true });
    }

    const { rows } = await client.query(
      `SELECT id, amount_tiyn, status FROM payments
       WHERE order_id = $1 AND provider = 'kaspi' FOR UPDATE`,
      [evt.orderId]
    );
    const payment = rows[0];
    if (!payment) throw new Error("unknown order");

    if (evt.status === "paid" && payment.status === "pending") {
      if (BigInt(payment.amount_tiyn) !== BigInt(Math.round(evt.amount * 100))) {
        throw new Error("amount mismatch");
      }
      await client.query(
        `UPDATE payments SET status = 'paid', external_id = $2, paid_at = now() WHERE id = $1`,
        [payment.id, evt.paymentId]
      );
      await client.query(`UPDATE orders SET state = 'paid' WHERE id = $1`, [evt.orderId]);
    }

    await client.query("COMMIT");
    return Response.json({ ok: true });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("kaspi webhook", e);
    return new Response("error", { status: 500 });  // провайдер повторит доставку
  } finally {
    client.release();
  }
}

Key decisions:

  • Write to `webhook_events` and change status in one transaction. If processing fails, the event key will be rolled back along with it, and the redelivery will be processed again.
  • `FOR UPDATE` locks the payment line so two parallel notifications will not pass the status = 'pending' check at the same time.
  • State transition is forward only. Notifying paid after expired or repeating paid does not change anything.
  • The amount is verified with the amount that you yourself wrote down when issuing the invoice. The amount field from a webhook is never used as a source of truth.
  • Shipment, letters, accruals - not inside the processor. Place the task in a queue (or in an outbox table) in the same transaction, and execute it separately. The handler must respond quickly, otherwise the provider will consider the delivery unsuccessful and repeat it.

If there is no signature

Some integrations do not sign notifications or sign them differently than body HMAC. Then treat the webhook as a “check payment” signal: having received it, request the status via the provider’s API using your identifier and change the status only based on the API response. Additionally, limit incoming addresses if the provider publishes a list of them.

Common errors

  • The signature is counted from JSON.stringify(await req.json()). The order of the keys and spaces are different from the original, and the signature does not match. We need raw body text.
  • Comparison of signatures via ===. Use timingSafeEqual and check the length of the buffers before calling, otherwise it will throw an exception.
  • Amounts in float. Store in tiyns or numeric.
  • Idempotency at the code level (if (order.paid) return) without transaction. Two simultaneous requests will both see paid = false.

When less is enough

If you accept single payments and process orders manually, a unique key using external_id and manual reconciliation in the seller's personal account is sufficient. The event table, queue and outbox pay off where something happens automatically after payment.

Обсуждение (0)

Ещё на vbcd4u.com