TakaElo

Search the docs

Pages, sections and error codes

Guides

Webhooks

Signed events for every step of a payment and every payment report. Pick the ones you need, verify, act once, reply 200.

When something happens to a payment or a payment report, TakaElo sends an HTTPS POST to your endpoint. Set the endpoint in Developers › Webhooks. Test and Live each have their own endpoint and their own secret: switch the dashboard to Test to set where test events go. A test event can never reach your live endpoint, or pass its signature check.

The events

The four outcome events are all most shops need, and every endpoint gets them by default. The rest are opt-in: the whole journey of a payment (so you see checkouts from payment links and invoices, and where customers drop off) and customer payment reports.

EventWhenSent
payment.createdA checkout was opened — by your server, a payment link or an invoice. Links and invoices are made inside TakaElo, so this is how your system first hears of them.Opt-in
payment.pendingThe customer chose a wallet and gave the number they pay from — they are paying now.Opt-in
payment.partially_paidPart of the money arrived and the payment is still open (the customer is sending the rest). Sent once per arrival.Opt-in
payment.completedThe money arrived and matched the checkout — or you approved a held payment.By default
payment.pending_reviewMoney arrived (or the customer says it did) but it needs your OK in the dashboard first.By default
payment.failedNo money is coming for this checkout.By default
payment.refundedYou recorded that the money went back to the customer (dashboard or POST /v1/payments/{id}/refund).By default
dispute.openedA customer reported a problem with a payment ("I paid but…"). You have 48 hours to answer in the dashboard before TakaElo steps in.Opt-in
dispute.updatedA report changed while still open: your team answered, the customer wrote again, or TakaElo stepped in.Opt-in
dispute.closedThe report ended — you settled it, the customer withdrew it, or TakaElo closed it.Opt-in

Choosing your events

Tick the events you want in Developers › Webhooks (or send events: [...] when saving the endpoint). Until you choose, an endpoint receives the four outcome events. An event you didn't choose is still kept in your delivery history, but never sent.

What arrives

The request
POST /webhooks/takaelo HTTP/1.1
Host: yourshop.com
Content-Type: application/json
User-Agent: TakaElo-Webhooks/1
TakaElo-Signature: t=1791641622,v1=5f2b9c0e7d4a…

{"id":"evt_8RwK2mZp5TqV9xLc3nB7yH1d","type":"payment.completed","created":1791641622,"livemode":true,"data":{…}}

The body is always the same envelope — id, type, created, livemode — and data is the full payment object at the moment of the event. Parse it as JSON: keys can arrive in any order.

Every event, in full

Pick an event to see when it fires, what your code should do, and a complete delivery. These payloads come from real deliveries and are checked against the live API on every change.

Opt-in — tick it in Developers › Webhooks to receive it.

When
A checkout was opened — by your server, a payment link or an invoice. Links and invoices are made inside TakaElo, so this is how your system first hears of them.
Your code
Record the payment against the order (or create the order, for a link). source says where it came from; link_id / invoice_id say which one.
payment.created — the full delivery
{
  "id": "evt_1Bq8Lw3Zn6Vc2Tx9Kp4Rm7Hd",
  "type": "payment.created",
  "created": 1791641454,
  "livemode": true,
  "data": {
    "id": "pay_5Rt8Kq2Wz7Nc1Vb4Lx9Hm3Pd",
    "object": "payment",
    "livemode": true,
    "status": "initiated",
    "failure_reason": null,
    "review_reason": null,
    "amount": 1250,
    "amount_received": null,
    "amount_due": 1250,
    "refund_due": 0,
    "currency": "BDT",
    "wallet": null,
    "sender": "",
    "trx_id": null,
    "reference": "Kurti — blue",
    "source": "link",
    "link_id": "lnk_9Vb3Qx7Lw2Zt5Nc8Kr1Hm4Pd",
    "invoice_id": null,
    "customer": { "name": "Rahim Uddin", "phone": "01712345678", "email": "" },
    "metadata": {},
    "url": "https://yourshop.takaelo.com/pay/pay_5Rt8Kq2Wz7Nc1Vb4Lx9Hm3Pd",
    "created": 1791641454,
    "expires_at": 1791643254,
    "completed_at": null,
    "refunded_at": null
  }
}

The order of events

The paymentEvents you receive
The whole journey (opt-in events included)payment.created → payment.pending → (payment.partially_paid …) → payment.completed
Paid normallypayment.completed
Held for your OK, then approvedpayment.pending_review → payment.completed
Held for your OK, then rejectedpayment.pending_review → payment.failed (rejected)
Customer left, or the time ran outpayment.failed (cancelled / expired)
Paid, later refundedpayment.completed → payment.refunded

Verify the signature

Anyone can POST to your URL, so check every request came from TakaElo. The TakaElo-Signature header looks like t=1791641622,v1=5f2b9c…:

  1. Read the raw body — the exact bytes. A JSON body re-encoded by your framework won't match.
  2. Compute HMAC-SHA256 of "<t>.<raw body>" with your webhook secret (whsec_…), as hex.
  3. Compare it with each v1= value using a constant-time comparison.
  4. Reject it if t is more than 5 minutes from now: that stops someone replaying an old delivery.
Verify a webhook signature
# Check a signature by hand while debugging: HMAC-SHA256 of "<t>.<raw body>" with your webhook secret.
t=1760000000
body='{"id":"evt_test","type":"payment.completed"}'
printf '%s.%s' "$t" "$body" | openssl dgst -sha256 -hmac "whsec_test_secret" | sed 's/^.* //'
# 7f852f9c0d26b339c024880089f7e91038e764b64f8d7e3c2e46d9a5bcb77f1b
# It must equal one of the v1= values in the TakaElo-Signature header.
<?php
/** True only when the request really came from TakaElo in the last 5 minutes. */
function verifyTakaEloSignature(string $payload, string $header, string $secret, ?int $now = null): bool
{
    $now ??= time();
    $timestamp = 0;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($key === 't') {
            $timestamp = (int) $value;
        } elseif ($key === 'v1') {
            $signatures[] = $value;
        }
    }
    if ($timestamp === 0 || abs($now - $timestamp) > 300) {
        return false; // missing or stale: a replay of an old delivery
    }

    $expected = hash_hmac('sha256', $timestamp . '.' . $payload, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) { // constant-time compare
            return true;
        }
    }
    return false;
}
import crypto from "node:crypto";

/** True only when the request really came from TakaElo in the last 5 minutes. */
export function verifyTakaEloSignature(payload, header, secret, now = Math.floor(Date.now() / 1000)) {
  let timestamp = 0;
  const signatures = [];
  for (const part of (header ?? "").split(",")) {
    const [key, value] = part.trim().split("=", 2);
    if (key === "t") timestamp = Number(value);
    if (key === "v1") signatures.push(value);
  }
  if (!timestamp || Math.abs(now - timestamp) > 300) return false; // missing or stale: a replay

  const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.`).update(payload).digest();
  return signatures.some((signature) => {
    const received = Buffer.from(signature ?? "", "hex");
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}
import hashlib
import hmac
import time


def verify_takaelo_signature(payload: bytes, header: str, secret: str, now: int | None = None) -> bool:
    """True only when the request really came from TakaElo in the last 5 minutes."""
    now = int(time.time()) if now is None else now
    timestamp, signatures = 0, []
    for part in (header or "").split(","):
        key, _, value = part.strip().partition("=")
        if key == "t" and value.isdigit():
            timestamp = int(value)
        elif key == "v1":
            signatures.append(value)
    if not timestamp or abs(now - timestamp) > 300:
        return False  # missing or stale: a replay of an old delivery

    expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + payload, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, s) for s in signatures)
package webhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"
)

// VerifyTakaEloSignature is true only when the request really came from TakaElo in the last 5 minutes.
func VerifyTakaEloSignature(payload []byte, header, secret string, now time.Time) bool {
	var timestamp int64
	var signatures []string
	for _, part := range strings.Split(header, ",") {
		key, value, _ := strings.Cut(strings.TrimSpace(part), "=")
		switch key {
		case "t":
			timestamp, _ = strconv.ParseInt(value, 10, 64)
		case "v1":
			signatures = append(signatures, value)
		}
	}
	if age := now.Unix() - timestamp; timestamp == 0 || age > 300 || age < -300 {
		return false // missing or stale: a replay of an old delivery
	}

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(strconv.FormatInt(timestamp, 10) + "."))
	mac.Write(payload)
	expected := mac.Sum(nil)
	for _, s := range signatures {
		if received, err := hex.DecodeString(s); err == nil && hmac.Equal(received, expected) {
			return true
		}
	}
	return false
}
require "openssl"

# True only when the request really came from TakaElo in the last 5 minutes.
def verify_takaelo_signature(payload, header, secret, now: Time.now.to_i)
  timestamp = 0
  signatures = []
  header.to_s.split(",").each do |part|
    key, value = part.strip.split("=", 2)
    timestamp = value.to_i if key == "t"
    signatures << value.to_s if key == "v1"
  end
  return false if timestamp.zero? || (now - timestamp).abs > 300 # missing or stale: a replay

  expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp}.#{payload}")
  signatures.any? { |signature| secure_compare(expected, signature) }
end

# Constant-time compare (in Rails: ActiveSupport::SecurityUtils.secure_compare).
def secure_compare(a, b)
  return false unless a.bytesize == b.bytesize

  a.bytes.zip(b.bytes).reduce(0) { |diff, (x, y)| diff | (x ^ y) }.zero?
end
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class TakaEloWebhook {
    /** True only when the request really came from TakaElo in the last 5 minutes. */
    public static boolean verify(byte[] payload, String header, String secret, long now) {
        long timestamp = 0;
        List<String> signatures = new ArrayList<>();
        for (String part : (header == null ? "" : header).split(",")) {
            String[] kv = part.trim().split("=", 2);
            if (kv.length != 2) continue;
            if (kv[0].equals("t")) {
                try { timestamp = Long.parseLong(kv[1]); } catch (NumberFormatException e) { return false; }
            } else if (kv[0].equals("v1")) {
                signatures.add(kv[1]);
            }
        }
        if (timestamp == 0 || Math.abs(now - timestamp) > 300) return false; // missing or stale: a replay

        byte[] expected;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
            expected = mac.doFinal(payload);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new IllegalStateException(e);
        }
        for (String signature : signatures) {
            try {
                if (MessageDigest.isEqual(HexFormat.of().parseHex(signature), expected)) return true; // constant-time
            } catch (IllegalArgumentException ignored) {
                // not hex: not ours
            }
        }
        return false;
    }
}
using System.Security.Cryptography;
using System.Text;

public static class TakaEloWebhook
{
    /// <summary>True only when the request really came from TakaElo in the last 5 minutes.</summary>
    public static bool Verify(byte[] payload, string? header, string secret, long? now = null)
    {
        var current = now ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        long timestamp = 0;
        var signatures = new List<string>();
        foreach (var part in (header ?? "").Split(','))
        {
            var kv = part.Trim().Split('=', 2);
            if (kv.Length != 2) continue;
            if (kv[0] == "t") long.TryParse(kv[1], out timestamp);
            else if (kv[0] == "v1") signatures.Add(kv[1]);
        }
        if (timestamp == 0 || Math.Abs(current - timestamp) > 300) return false; // missing or stale: a replay

        var signed = Encoding.UTF8.GetBytes($"{timestamp}.").Concat(payload).ToArray();
        var expected = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signed);
        foreach (var signature in signatures)
        {
            byte[] received;
            try { received = Convert.FromHexString(signature); } catch (FormatException) { continue; }
            if (CryptographicOperations.FixedTimeEquals(received, expected)) return true; // constant-time
        }
        return false;
    }
}

Handle the event

A complete webhook endpoint
# Send your own endpoint a correctly signed event — the same bytes TakaElo would send.
secret='whsec_...'   # Developers › Webhooks in the dashboard
body='{"id":"evt_local_1","type":"payment.completed","created":1791533264,"livemode":false,"data":{"id":"pay_3kT9xQm2LrV8nB4cW7yZ1aPd","status":"completed","amount":1250,"currency":"BDT","reference":"ORD-4821"}}'
t=$(date +%s)
sig=$(printf '%s.%s' "$t" "$body" | openssl dgst -sha256 -hmac "$secret" | sed 's/^.* //')

curl http://localhost:3000/webhooks/takaelo \
  -H "Content-Type: application/json" \
  -H "TakaElo-Signature: t=$t,v1=$sig" \
  -d "$body"
<?php
// webhooks/takaelo.php — plain PHP. In Laravel, read $request->getContent() instead of php://input.
$payload = file_get_contents('php://input'); // the raw bytes, never a re-encoded array
$header = $_SERVER['HTTP_TAKAELO_SIGNATURE'] ?? '';

if (!verifyTakaEloSignature($payload, $header, getenv('TAKAELO_WEBHOOK_SECRET'))) {
    http_response_code(400);
    exit;
}

$event = json_decode($payload, true);
// Test and live events come with their own secret; never act on the other mode's events.
if ($event['livemode'] !== str_starts_with(getenv('TAKAELO_SECRET_KEY'), 'sk_live_')) {
    http_response_code(200);
    exit;
}
if (!startEvent($event['id'])) { // BEGIN a transaction and record the event id (unique key); false = already handled, retries carry the same id
    http_response_code(200);
    exit;
}

$payment = $event['data'];
switch ($event['type']) {
    case 'payment.completed':      markOrderPaid($payment['reference'], $payment); break; // checks the amount against the order's total
    case 'payment.pending_review': markOrderOnHold($payment['reference']); break;
    case 'payment.failed':         releaseOrder($payment['reference'], $payment['failure_reason']); break;
    case 'payment.refunded':       markOrderRefunded($payment['reference']); break;
}
finishEvent($event['id']); // COMMIT: the event id and the order change are saved together, so two copies can't both act
http_response_code(200);
// Express. The route reads the RAW body: JSON re-serialised by a parser won't match the signature.
import express from "express";
import { verifyTakaEloSignature } from "./takaelo-webhook.js";

const app = express();

app.post("/webhooks/takaelo", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verifyTakaEloSignature(req.body, req.get("TakaElo-Signature"), process.env.TAKAELO_WEBHOOK_SECRET)) {
    return res.sendStatus(400);
  }

  const event = JSON.parse(req.body);
  // Test and live events come with their own secret; never act on the other mode's events.
  if (event.livemode !== process.env.TAKAELO_SECRET_KEY.startsWith("sk_live_")) return res.sendStatus(200);
  if (!(await startEvent(event.id))) return res.sendStatus(200); // BEGIN a transaction and record the event id (unique key); false = already handled, retries carry the same id

  const payment = event.data;
  switch (event.type) {
    case "payment.completed": await markOrderPaid(payment.reference, payment); break; // checks the amount against the order's total
    case "payment.pending_review": await markOrderOnHold(payment.reference); break;
    case "payment.failed": await releaseOrder(payment.reference, payment.failure_reason); break;
    case "payment.refunded": await markOrderRefunded(payment.reference); break;
  }
  await finishEvent(event.id); // COMMIT: the event id and the order change are saved together, so two copies can't both act
  res.sendStatus(200);
});

app.listen(3000);
# Flask. request.get_data() is the raw body — never verify request.json.
import json
import os

from flask import Flask, abort, request

app = Flask(__name__)


@app.post("/webhooks/takaelo")
def takaelo_webhook():
    payload = request.get_data()
    header = request.headers.get("TakaElo-Signature", "")
    if not verify_takaelo_signature(payload, header, os.environ["TAKAELO_WEBHOOK_SECRET"]):
        abort(400)

    event = json.loads(payload)
    # Test and live events come with their own secret; never act on the other mode's events.
    if event["livemode"] != os.environ["TAKAELO_SECRET_KEY"].startswith("sk_live_"):
        return "", 200
    if not start_event(event["id"]):  # BEGIN a transaction and record the event id (unique key); false = already handled, retries carry the same id
        return "", 200

    payment = event["data"]
    if event["type"] == "payment.completed":
        mark_order_paid(payment["reference"], payment)  # checks the amount against the order's total
    elif event["type"] == "payment.pending_review":
        mark_order_on_hold(payment["reference"])
    elif event["type"] == "payment.failed":
        release_order(payment["reference"], payment["failure_reason"])
    elif event["type"] == "payment.refunded":
        mark_order_refunded(payment["reference"])

    finish_event(event["id"])  # COMMIT: the event id and the order change are saved together, so two copies can't both act
    return "", 200
package main

import (
	"encoding/json"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	"yourshop/webhooks"
)

type Event struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Livemode bool   `json:"livemode"`
	Data     struct {
		ID            string  `json:"id"`
		Reference     string  `json:"reference"`
		Amount        float64 `json:"amount"`
		FailureReason *string `json:"failure_reason"`
	} `json:"data"`
}

func main() {
	http.HandleFunc("POST /webhooks/takaelo", func(w http.ResponseWriter, r *http.Request) {
		payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil {
			http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
			return
		}
		if !webhooks.VerifyTakaEloSignature(payload, r.Header.Get("TakaElo-Signature"), os.Getenv("TAKAELO_WEBHOOK_SECRET"), time.Now()) {
			http.Error(w, "bad signature", http.StatusBadRequest)
			return
		}

		var event Event
		if err := json.Unmarshal(payload, &event); err != nil {
			http.Error(w, "bad json", http.StatusBadRequest)
			return
		}
		// Test and live events come with their own secret; never act on the other mode's events.
		if event.Livemode != strings.HasPrefix(os.Getenv("TAKAELO_SECRET_KEY"), "sk_live_") {
			w.WriteHeader(http.StatusOK)
			return
		}
		if !startEvent(event.ID) { // BEGIN a transaction and record the event id (unique key); false = already handled, retries carry the same id
			w.WriteHeader(http.StatusOK)
			return
		}
		switch event.Type {
		case "payment.completed":
			markOrderPaid(event.Data.Reference, event.Data.Amount) // checks the amount against the order's total
		case "payment.pending_review":
			markOrderOnHold(event.Data.Reference)
		case "payment.failed":
			releaseOrder(event.Data.Reference)
		case "payment.refunded":
			markOrderRefunded(event.Data.Reference)
		}
		finishEvent(event.ID) // COMMIT: the event id and the order change are saved together, so two copies can't both act
		w.WriteHeader(http.StatusOK)
	})
	http.ListenAndServe(":3000", nil)
}
# Rails. request.raw_post is the raw body — never verify params.
class TakaEloWebhooksController < ActionController::API
  def create
    payload = request.raw_post
    unless verify_takaelo_signature(payload, request.headers["TakaElo-Signature"], ENV.fetch("TAKAELO_WEBHOOK_SECRET"))
      return head :bad_request
    end

    event = JSON.parse(payload)
    # Test and live events come with their own secret; never act on the other mode's events.
    return head :ok if event["livemode"] != ENV.fetch("TAKAELO_SECRET_KEY").start_with?("sk_live_")
    return head :ok unless start_event(event["id"]) # BEGIN a transaction and record the event id (unique key); false = already handled, retries carry the same id

    payment = event["data"]
    case event["type"]
    when "payment.completed" then mark_order_paid(payment["reference"], payment) # checks the amount against the order's total
    when "payment.pending_review" then mark_order_on_hold(payment["reference"])
    when "payment.failed" then release_order(payment["reference"], payment["failure_reason"])
    when "payment.refunded" then mark_order_refunded(payment["reference"])
    end
    finish_event(event["id"])  # COMMIT: the event id and the order change are saved together, so two copies can't both act
    head :ok
  end
end
// Spring Boot. @RequestBody byte[] keeps the raw bytes the signature covers.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.time.Instant;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class TakaEloWebhookController {
    private final ObjectMapper json = new ObjectMapper();

    @PostMapping("/webhooks/takaelo")
    public ResponseEntity<Void> receive(@RequestBody byte[] payload,
                                        @RequestHeader(value = "TakaElo-Signature", defaultValue = "") String signature) throws IOException {
        String secret = System.getenv("TAKAELO_WEBHOOK_SECRET");
        if (!TakaEloWebhook.verify(payload, signature, secret, Instant.now().getEpochSecond())) {
            return ResponseEntity.badRequest().build();
        }

        JsonNode event = json.readTree(payload);
        // Test and live events come with their own secret; never act on the other mode's events.
        boolean live = System.getenv("TAKAELO_SECRET_KEY").startsWith("sk_live_");
        if (event.get("livemode").asBoolean() != live) return ResponseEntity.ok().build();
        String eventId = event.get("id").asText();
        if (!startEvent(eventId)) return ResponseEntity.ok().build(); // BEGIN a transaction and record the event id (unique key); false = already handled, retries carry the same id

        String reference = event.at("/data/reference").asText();
        switch (event.get("type").asText()) {
            case "payment.completed" -> markOrderPaid(reference, event.get("data")); // checks the amount against the order's total
            case "payment.pending_review" -> markOrderOnHold(reference);
            case "payment.failed" -> releaseOrder(reference, event.at("/data/failure_reason").asText());
            case "payment.refunded" -> markOrderRefunded(reference);
            default -> { }
        }
        finishEvent(eventId); // COMMIT: the event id and the order change are saved together, so two copies can't both act
        return ResponseEntity.ok().build();
    }
}
// ASP.NET Core minimal API. Read the raw body: the signature covers those exact bytes.
using System.Text.Json;

var app = WebApplication.Create(args);

app.MapPost("/webhooks/takaelo", async (HttpRequest request) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer);
    var payload = buffer.ToArray();

    var secret = Environment.GetEnvironmentVariable("TAKAELO_WEBHOOK_SECRET")!;
    if (!TakaEloWebhook.Verify(payload, request.Headers["TakaElo-Signature"], secret))
        return Results.BadRequest();

    var evt = JsonDocument.Parse(payload).RootElement;
    // Test and live events come with their own secret; never act on the other mode's events.
    var live = Environment.GetEnvironmentVariable("TAKAELO_SECRET_KEY")!.StartsWith("sk_live_");
    if (evt.GetProperty("livemode").GetBoolean() != live) return Results.Ok();
    var eventId = evt.GetProperty("id").GetString()!;
    if (!await StartEvent(eventId)) return Results.Ok(); // BEGIN a transaction and record the event id (unique key); false = already handled, retries carry the same id

    var payment = evt.GetProperty("data");
    var reference = payment.GetProperty("reference").GetString()!;
    switch (evt.GetProperty("type").GetString())
    {
        case "payment.completed": await MarkOrderPaid(reference, payment); break; // checks the amount against the order's total
        case "payment.pending_review": await MarkOrderOnHold(reference); break;
        case "payment.failed": await ReleaseOrder(reference, payment.GetProperty("failure_reason").GetString()); break;
        case "payment.refunded": await MarkOrderRefunded(reference); break;
    }
    await FinishEvent(eventId); // COMMIT: the event id and the order change are saved together, so two copies can't both act
    return Results.Ok();
});

app.Run();

Before you fulfil an order

  • Check livemode against your own key: a live server (sk_live_…) acts only on livemode: true. Each mode has its own secret, so this is a second lock, not the only one.
  • Check the amount against the order's total (amount is what the customer was asked for, amount_received what arrived). A payment for a different amount never completes an order.
  • When in doubt, ask TakaElo: retrieve the payment with your own key and use its status, amount and reference.

Process each event once

A retry carries the same event id. Save the ids you have handled (a unique column is enough) and reply 200 straight away for one you've seen. Marking an already-paid order paid again should also be harmless.

What to store

  • The event id — to process each delivery once.
  • data.id (the payment) next to your order — to retrieve it any time.
  • data.reference — your own order number, as you sent it when creating the checkout.
  • data.trx_id and data.sender — what your customer support needs when someone asks about a payment.

Reply fast

Reply with any 2xx within 10 seconds. Slow work — emails, invoices, shipping labels — belongs in a background job after you reply.

Retries

Anything other than a 2xx (or no answer in 10 seconds) is retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 24 hours. After that the delivery is marked failed. Developers › Webhooks lists every delivery with its status code, and Re-send sends any of them again.

Changing the secret

Press Make a new secret in Developers › Webhooks and you get a new whsec_…. For the next 24 hours each request carries two v1= values — one per secret — so the verifier above keeps working while you deploy the new secret. After 24 hours only the new one signs.

Test your endpoint

  • Send test event in the dashboard posts a signed payment.completed whose payment id is pay_test_sample.
  • Paying a test checkout with Simulate payment sends the real sequence of events, with livemode: false.
  • From your laptop: expose it with a tunnel (ngrok, Cloudflare Tunnel) — or use the cURL tab above to send yourself a correctly signed request without TakaElo at all.
  • In production the endpoint must be https.

Reference vector

InputValue
Secretwhsec_test_secret
t1760000000
Raw body{"id":"evt_test","type":"payment.completed"}
v17f852f9c0d26b339c024880089f7e91038e764b64f8d7e3c2e46d9a5bcb77f1b

Pass t as "now" (every function above takes one for exactly this) and your verifier must accept it.