TakaElo

Search the docs

Pages, sections and error codes

Get started

Quickstart: your first payment in 5 minutes

Create a test checkout, pay it with one click, and receive the signed webhook — in the language you already use.

Everything here runs in test mode: no phone, no real money, nothing to install except your usual language. Pick your language on any code block — every block on the site switches with it.

  1. 1

    Get a test key

    Sign up (free), switch the dashboard to Test, open Developers › API keys and create a key. It starts with sk_test_ and is shown once — keep it in an environment variable, never in your code: export TAKAELO_SECRET_KEY=sk_test_…

  2. 2

    Create a checkout

    Your server asks TakaElo for a checkout: the amount in whole taka, your order number, and where to send the customer afterwards. Test keys may send customers back to http://localhost, so you can try this on your laptop.

    curl https://api.takaelo.com/v1/checkouts \
      -H "Authorization: Bearer $TAKAELO_SECRET_KEY" \
      -H "Idempotency-Key: order-4821-1" \
      -H "Content-Type: application/json" \
      -d '{
        "amount": 1250,
        "reference": "ORD-4821",
        "success_url": "https://yourshop.com/orders/4821/thanks",
        "cancel_url": "https://yourshop.com/cart",
        "customer": { "name": "Rahim Uddin", "phone": "01712345678" },
        "metadata": { "order_id": "4821" }
      }'
    <?php
    $ch = curl_init('https://api.takaelo.com/v1/checkouts');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . getenv('TAKAELO_SECRET_KEY'),
            'Idempotency-Key: order-4821-1',
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'amount'      => 1250,
            'reference'   => 'ORD-4821',
            'success_url' => 'https://yourshop.com/orders/4821/thanks',
            'cancel_url'  => 'https://yourshop.com/cart',
            'customer'    => ['name' => 'Rahim Uddin', 'phone' => '01712345678'],
            'metadata'    => ['order_id' => '4821'],
        ]),
    ]);
    $body = json_decode(curl_exec($ch), true);
    
    if (empty($body['success'])) {
        throw new RuntimeException($body['code'] . ': ' . $body['message']);
    }
    
    $checkout = $body['data'];
    echo $checkout['id'] . ' ' . $checkout['url'] . PHP_EOL;
    // In a web request, send the customer to pay:
    // header('Location: ' . $checkout['url'], true, 303);
    // Node 18+ (built-in fetch). Save as checkout.mjs and run: node checkout.mjs
    const res = await fetch("https://api.takaelo.com/v1/checkouts", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.TAKAELO_SECRET_KEY}`,
        "Idempotency-Key": "order-4821-1",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        amount: 1250,
        reference: "ORD-4821",
        success_url: "https://yourshop.com/orders/4821/thanks",
        cancel_url: "https://yourshop.com/cart",
        customer: { name: "Rahim Uddin", phone: "01712345678" },
        metadata: { order_id: "4821" },
      }),
    });
    const body = await res.json();
    if (!body.success) throw new Error(`${body.code}: ${body.message}`);
    
    const checkout = body.data;
    console.log(checkout.id, checkout.url);
    // In Express: res.redirect(303, checkout.url);
    import json
    import os
    import urllib.error
    import urllib.request
    
    payload = {
        "amount": 1250,
        "reference": "ORD-4821",
        "success_url": "https://yourshop.com/orders/4821/thanks",
        "cancel_url": "https://yourshop.com/cart",
        "customer": {"name": "Rahim Uddin", "phone": "01712345678"},
        "metadata": {"order_id": "4821"},
    }
    request = urllib.request.Request(
        "https://api.takaelo.com/v1/checkouts",
        method="POST",
        data=json.dumps(payload).encode(),
        headers={
            "Authorization": "Bearer " + os.environ["TAKAELO_SECRET_KEY"],
            "Idempotency-Key": "order-4821-1",
            "Content-Type": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(request) as response:
            checkout = json.load(response)["data"]
    except urllib.error.HTTPError as e:
        error = json.load(e)
        raise SystemExit(f"{error['code']}: {error['message']}")
    
    print(checkout["id"], checkout["url"])
    # In Django / Flask: return redirect(checkout["url"])
    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    )
    
    func main() {
    	payload, _ := json.Marshal(map[string]any{
    		"amount":      1250,
    		"reference":   "ORD-4821",
    		"success_url": "https://yourshop.com/orders/4821/thanks",
    		"cancel_url":  "https://yourshop.com/cart",
    		"customer":    map[string]string{"name": "Rahim Uddin", "phone": "01712345678"},
    		"metadata":    map[string]string{"order_id": "4821"},
    	})
    	req, _ := http.NewRequest(http.MethodPost, "https://api.takaelo.com/v1/checkouts", bytes.NewReader(payload))
    	req.Header.Set("Authorization", "Bearer "+os.Getenv("TAKAELO_SECRET_KEY"))
    	req.Header.Set("Idempotency-Key", "order-4821-1")
    	req.Header.Set("Content-Type", "application/json")
    
    	res, err := http.DefaultClient.Do(req)
    	if err != nil {
    		log.Fatal(err)
    	}
    	defer res.Body.Close()
    
    	var body struct {
    		Success bool   `json:"success"`
    		Message string `json:"message"`
    		Code    string `json:"code"`
    		Data    struct {
    			ID  string `json:"id"`
    			URL string `json:"url"`
    		} `json:"data"`
    	}
    	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
    		log.Fatal(err)
    	}
    	if !body.Success {
    		log.Fatalf("%s: %s", body.Code, body.Message)
    	}
    	fmt.Println(body.Data.ID, body.Data.URL)
    	// In a handler: http.Redirect(w, r, body.Data.URL, http.StatusSeeOther)
    }
    require "json"
    require "net/http"
    
    uri = URI("https://api.takaelo.com/v1/checkouts")
    request = Net::HTTP::Post.new(uri,
      "Authorization" => "Bearer #{ENV.fetch("TAKAELO_SECRET_KEY")}",
      "Idempotency-Key" => "order-4821-1",
      "Content-Type" => "application/json")
    request.body = {
      amount: 1250,
      reference: "ORD-4821",
      success_url: "https://yourshop.com/orders/4821/thanks",
      cancel_url: "https://yourshop.com/cart",
      customer: { name: "Rahim Uddin", phone: "01712345678" },
      metadata: { order_id: "4821" }
    }.to_json
    
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
    body = JSON.parse(response.body)
    raise "#{body["code"]}: #{body["message"]}" unless body["success"]
    
    checkout = body["data"]
    puts "#{checkout["id"]} #{checkout["url"]}"
    # In Rails: redirect_to checkout["url"], allow_other_host: true
    // Java 11+ HttpClient; JSON with Jackson (com.fasterxml.jackson.core:jackson-databind).
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.util.Map;
    
    public class CreateCheckout {
        public static void main(String[] args) throws Exception {
            ObjectMapper json = new ObjectMapper();
            String payload = json.writeValueAsString(Map.of(
                "amount", 1250,
                "reference", "ORD-4821",
                "success_url", "https://yourshop.com/orders/4821/thanks",
                "cancel_url", "https://yourshop.com/cart",
                "customer", Map.of("name", "Rahim Uddin", "phone", "01712345678"),
                "metadata", Map.of("order_id", "4821")));
    
            HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.takaelo.com/v1/checkouts"))
                .header("Authorization", "Bearer " + System.getenv("TAKAELO_SECRET_KEY"))
                .header("Idempotency-Key", "order-4821-1")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .build();
            HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
    
            JsonNode body = json.readTree(response.body());
            if (!body.path("success").asBoolean()) {
                throw new IllegalStateException(body.path("code").asText() + ": " + body.path("message").asText());
            }
            JsonNode checkout = body.get("data");
            System.out.println(checkout.get("id").asText() + " " + checkout.get("url").asText());
            // In Spring: return "redirect:" + checkout.get("url").asText();
        }
    }
    // .NET 6+ top-level program: dotnet new console, paste into Program.cs, dotnet run
    using System.Net.Http.Headers;
    using System.Net.Http.Json;
    using System.Text.Json;
    
    var http = new HttpClient();
    http.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("TAKAELO_SECRET_KEY"));
    
    var request = new HttpRequestMessage(HttpMethod.Post, "https://api.takaelo.com/v1/checkouts")
    {
        Content = JsonContent.Create(new
        {
            amount = 1250,
            reference = "ORD-4821",
            success_url = "https://yourshop.com/orders/4821/thanks",
            cancel_url = "https://yourshop.com/cart",
            customer = new { name = "Rahim Uddin", phone = "01712345678" },
            metadata = new Dictionary<string, string> { ["order_id"] = "4821" },
        }),
    };
    request.Headers.Add("Idempotency-Key", "order-4821-1");
    
    using var response = await http.SendAsync(request);
    var body = await response.Content.ReadFromJsonAsync<JsonElement>();
    if (!body.GetProperty("success").GetBoolean())
        throw new Exception($"{body.GetProperty("code")}: {body.GetProperty("message")}");
    
    var checkout = body.GetProperty("data");
    Console.WriteLine($"{checkout.GetProperty("id")} {checkout.GetProperty("url")}");
    // In ASP.NET Core: return Results.Redirect(checkout.GetProperty("url").GetString()!);
  3. 3

    Pay it

    Open the url from the reply. Because this is a test checkout, the page has a Simulate payment button: it pays the checkout as if a customer sent money from bKash, with a TEST… TrxID. The page turns green and sends the customer to your success_url.

  4. 4

    Check it on your server

    Ask for the payment by its id. status is now completed, with the wallet, the sender's number and the TrxID filled in.

    curl https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd \
      -H "Authorization: Bearer $TAKAELO_SECRET_KEY"
    <?php
    $ch = curl_init('https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . getenv('TAKAELO_SECRET_KEY')],
    ]);
    $body = json_decode(curl_exec($ch), true);
    if (empty($body['success'])) {
        throw new RuntimeException($body['code'] . ': ' . $body['message']);
    }
    
    $payment = $body['data'];
    if ($payment['status'] === 'completed') {
        echo "Paid {$payment['amount']} {$payment['currency']} by {$payment['wallet']} (TrxID {$payment['trx_id']})" . PHP_EOL;
    }
    const res = await fetch("https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd", {
      headers: { Authorization: `Bearer ${process.env.TAKAELO_SECRET_KEY}` },
    });
    const body = await res.json();
    if (!body.success) throw new Error(`${body.code}: ${body.message}`);
    
    const payment = body.data;
    console.log(payment.status, payment.amount, payment.trx_id);
    import json
    import os
    import urllib.request
    
    request = urllib.request.Request(
        "https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd",
        headers={"Authorization": "Bearer " + os.environ["TAKAELO_SECRET_KEY"]},
    )
    with urllib.request.urlopen(request) as response:
        payment = json.load(response)["data"]
    
    print(payment["status"], payment["amount"], payment["trx_id"])
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    )
    
    type Payment struct {
    	ID        string  `json:"id"`
    	Status    string  `json:"status"`
    	Amount    float64 `json:"amount"`
    	Wallet    *string `json:"wallet"`
    	TrxID     *string `json:"trx_id"`
    	Reference string  `json:"reference"`
    }
    
    func main() {
    	req, _ := http.NewRequest(http.MethodGet, "https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd", nil)
    	req.Header.Set("Authorization", "Bearer "+os.Getenv("TAKAELO_SECRET_KEY"))
    
    	res, err := http.DefaultClient.Do(req)
    	if err != nil {
    		log.Fatal(err)
    	}
    	defer res.Body.Close()
    
    	var body struct {
    		Success bool    `json:"success"`
    		Code    string  `json:"code"`
    		Message string  `json:"message"`
    		Data    Payment `json:"data"`
    	}
    	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
    		log.Fatal(err)
    	}
    	if !body.Success {
    		log.Fatalf("%s: %s", body.Code, body.Message)
    	}
    	fmt.Println(body.Data.Status, body.Data.Amount, body.Data.Reference)
    }
    require "json"
    require "net/http"
    
    uri = URI("https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd")
    request = Net::HTTP::Get.new(uri, "Authorization" => "Bearer #{ENV.fetch("TAKAELO_SECRET_KEY")}")
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
    body = JSON.parse(response.body)
    raise "#{body["code"]}: #{body["message"]}" unless body["success"]
    
    payment = body["data"]
    puts "#{payment["status"]} #{payment["amount"]} #{payment["trx_id"]}"
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    
    public class RetrievePayment {
        public static void main(String[] args) throws Exception {
            HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd"))
                .header("Authorization", "Bearer " + System.getenv("TAKAELO_SECRET_KEY"))
                .build();
            HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
    
            JsonNode body = new ObjectMapper().readTree(response.body());
            if (!body.path("success").asBoolean()) {
                throw new IllegalStateException(body.path("code").asText() + ": " + body.path("message").asText());
            }
            JsonNode payment = body.get("data");
            System.out.println(payment.get("status").asText() + " " + payment.get("amount").asText());
        }
    }
    using System.Net.Http.Headers;
    using System.Net.Http.Json;
    using System.Text.Json;
    
    var http = new HttpClient();
    http.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("TAKAELO_SECRET_KEY"));
    
    var body = await http.GetFromJsonAsync<JsonElement>("https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd");
    var payment = body.GetProperty("data");
    Console.WriteLine($"{payment.GetProperty("status")} {payment.GetProperty("amount")}");
  5. 5

    Receive the webhook

    In Developers › Webhooks, set your endpoint URL and copy the signing secret (whsec_…). Every event is signed with it; this function is all you need to check one:

    # 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;
        }
    }
  6. 6

    Fulfil the order

    Your endpoint reads the raw body, checks the signature, and acts on the event. Reply with any 2xx within 10 seconds. To try it from your laptop, use Send test event in the dashboard with a tunnel such as ngrok — or the cURL tab, which signs a request to your local server itself.

    # 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();

Next