# Receive the notice

When a payment is approved or fails, EvePay calls an address of yours. It is the only signal you should ship an order on.

## Register your endpoint

In the portal, under **Settings → Webhook endpoint**, or over the API with `POST /v1/webhook-endpoint`. When you register it we give you a **secret** that is shown only once: that is what you will verify the notice is ours with.

## What reaches you

```json
{
  "id": "0b0e...",
  "created": 1791068547,
  "type": "payment.completed",
  "data": {
    "paymentId": "44444444-4444-4444-8444-444444444444",
    "reference": "pedido-4417",
    "monto": 89000,
    "currency": "COP",
    "estado": "aprobado"
  }
}
```

`type` is `payment.completed` or `payment.failed`. `created` is epoch in seconds.

`id` is the delivery's identifier and **it repeats across retries**: the three calls of the same notice carry the same one. It works for discarding duplicates, but it is safer to store the `paymentId`, which also covers the case of one payment generating two separate deliveries.

With these headers:

| Header               | What it carries                                                |
| -------------------- | -------------------------------------------------------------- |
| `evepay-signature`   | `t=<epoch>,v1=<hmac-sha256 in hex>`                            |
| `evepay-event`       | The type, repeated, so you can route without opening the body. |
| `evepay-delivery-id` | The delivery id. Two deliveries of the same event share it.    |

## The events that exist today

Two, and no more:

| Event               | When                                       |
| ------------------- | ------------------------------------------ |
| `payment.completed` | The bank approved. This is where you ship. |
| `payment.failed`    | The payment did not complete.              |

**There is no refund event and no expiry event.** If a charge is refunded —today EvePay does it from its console, at your request— no notice reaches you: the change is visible by querying `GET /v1/pagos/:id`, where the state becomes `reembolsado`. We say so because it is the kind of thing one assumes exists and finds out about late.

A cash charge does not report in when the voucher's deadline passes either: it stays `pendiente`.

## Verify the signature before doing anything

`<timestamp>.<raw body>` is signed with HMAC-SHA256 and your secret. The body has to be **the text exactly as it arrived**: if you parse it into an object and serialise it again, the signature will not match.

```php
<?php
$crudo    = file_get_contents("php://input");
$cabecera = $_SERVER["HTTP_EVEPAY_SIGNATURE"] ?? "";

parse_str(str_replace(",", "&", $cabecera), $partes);

// With no header there is nothing to verify. Checking first stops PHP from
// warning about missing indexes, and answers a clean 400, which is what a
// malformed notice deserves.
if (empty($partes["t"]) || empty($partes["v1"])) {
    http_response_code(400);
    exit("Firma ausente");
}

$esperada = hash_hmac("sha256", $partes["t"] . "." . $crudo, getenv("EVEPAY_SECRETO"));

// hash_equals compares in constant time: see the warning at the end.
if (!hash_equals($esperada, $partes["v1"])) {
    http_response_code(400);
    exit("Firma inválida");
}

// Reject old notices: an attacker cannot reuse a captured one.
if (abs(time() - (int) $partes["t"]) > 300) {
    http_response_code(400);
    exit("Aviso vencido");
}

$evento = json_decode($crudo, true);

// We retry up to 3 times, so the same payment can reach you more than once.
if (yaProcesado($evento["data"]["paymentId"])) {
    http_response_code(200);
    exit;
}

// ONLY payment.completed ships. With payment.failed the bank did NOT charge:
// shipping here is giving the merchandise away.
if ($evento["type"] === "payment.completed") {
    marcarPedidoPagado($evento["data"]["reference"]);
} elseif ($evento["type"] === "payment.failed") {
    marcarPedidoFallido($evento["data"]["reference"]);
}

registrarProcesado($evento["data"]["paymentId"]);
http_response_code(200);
```

```js
import crypto from "node:crypto";

// Careful: you need the RAW body, not the already parsed one.
app.post("/webhooks/evepay", express.raw({ type: "application/json" }), async (req, res) => {
  const cabecera = req.headers["evepay-signature"] ?? "";
  const partes = Object.fromEntries(
    String(cabecera)
      .split(",")
      .map((p) => p.split("="))
  );

  const esperada = crypto
    .createHmac("sha256", process.env.EVEPAY_SECRETO)
    .update(`${partes.t}.${req.body.toString()}`)
    .digest("hex");

  // timingSafeEqual THROWS if the two buffers are different lengths, and an
  // exception here is a 500 instead of a 400: comparing the length first avoids it.
  const recibida = partes.v1 ?? "";
  const ok =
    recibida.length === esperada.length &&
    crypto.timingSafeEqual(Buffer.from(esperada), Buffer.from(recibida));

  if (!ok) return res.status(400).send("Firma inválida");
  if (Math.abs(Date.now() / 1000 - Number(partes.t)) > 300) {
    return res.status(400).send("Aviso vencido");
  }

  const evento = JSON.parse(req.body.toString());

  // We retry up to 3 times, so the same payment can reach you more than once.
  if (await yaProcesado(evento.data.paymentId)) return res.sendStatus(200);

  // ONLY payment.completed ships. With payment.failed the bank did NOT charge:
  // shipping here is giving the merchandise away.
  if (evento.type === "payment.completed") {
    await marcarPedidoPagado(evento.data.reference);
  } else if (evento.type === "payment.failed") {
    await marcarPedidoFallido(evento.data.reference);
  }

  await registrarProcesado(evento.data.paymentId);
  res.sendStatus(200);
});
```

> **Look at `type` before shipping.** Both events arrive at the same address, and
> `payment.failed` means the bank did **not** charge. A handler that ships without
> checking the type hands out merchandise for the payments that failed —the same
> mistake you avoid by not shipping on the buyer's return, except this one costs
> the same and shows up later.

> **Compare with a constant-time function** —`hash_equals` in PHP, `timingSafeEqual` in Node—. Comparing with `==` lets someone measure how long it takes to fail, and that is enough to guess the signature byte by byte.

## Answer fast and be idempotent

Answer `200` as soon as you have stored the event, and do the heavy work afterwards. If you do not answer `2xx`, we retry **up to 3 times** with waits of 1, 5 and 25 seconds — so the same payment can reach you more than once. Store the `paymentId` you already processed and discard the duplicates.

## If the notice never arrives

It can happen: your server was down for more than 31 seconds, or you changed domain. The real state can always be queried with `GET /v1/pagos/:id`. The sensible thing is a periodic sweep of the orders that have been `pendiente` for hours, not polling in a loop.

**After the third attempt the notice is discarded.** It is not stored, there is no resend and there is no way to query deliveries: that sweep is not prudence, it is the only recovery there is.

> **Do not ship when the buyer returns to your page.** The buyer's return is a courtesy, not proof: they could have closed the tab, or opened that address by hand. It also travels empty — we checked by paying for real in the gateway's test environment: the redirect arrives without a single parameter, so that page does not even know what was paid for.
