TakaElo

Search the docs

Pages, sections and error codes

Guides

Payments

Statuses, held payments, short and over payments, finding payments and recording refunds.

Every checkout is a payment. Its status tells you where it is; a webhook fires each time it reaches a status you need to act on.

Statuses

initiatedcheckout created
pendingwallet chosen, waiting
completedfulfil the order
refunded
pending_reviewyou approve or reject
completed or failed
failedexpired · cancelled · rejected
A checkout can also fail straight from initiated (the customer leaves, or the time runs out).
StatusMeansWebhook
initiatedCreated; the customer hasn't chosen a wallet yet.—
pendingWallet chosen; waiting for the money.—
completedMoney arrived and matched. Fulfil the order.payment.completed
pending_reviewMoney arrived but needs your OK in the dashboard. review_reason says why.payment.pending_review
failedNo money is coming. failure_reason says why.payment.failed
refundedYou sent the money back and recorded it.payment.refunded

Why a payment is held

review_reasonWhenWhat you do
above_limitThe amount is above the wallet number's auto-approve limit (৳20,000 unless you change it).Check your wallet app, then approve or reject.
trx_claimThe customer typed a TrxID because the payment message hadn't arrived.Approve once you see the money; reject if you don't.
amount_mismatchThe customer sent a different amount and you handle differences by hand.Approve, or reject and send it back.
overpaidMore than the amount arrived and you approve those by hand.Approve; send the extra back.
lateThe money arrived after the checkout expired (within 24 hours).Approve to fulfil, or reject and send it back.

Approving sends payment.completed; rejecting sends payment.failed with failure_reason: "rejected". Your code doesn't need to treat a held payment specially — just wait for one of those two.

Why a payment failed

failure_reasonMeans
expiredThe time ran out with no money.
cancelledThe customer left with "Cancel and go back to the shop".
rejectedYou rejected a held payment.

Short and over payments

People mistype amounts. amount_received is everything counted for the payment so far, so you always see what really arrived:

  • Too little: the payment stays pending with amount_due > 0 and the checkout asks for just the rest, from the same number. (If you handle differences by hand, it goes to pending_review with amount_mismatch instead.)
  • Too much: the payment completes and refund_due is the extra you owe the customer. You send it back from your own wallet and mark it returned in the dashboard; refund_due drops to 0.

Get one payment

Retrieve a payment
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")}");

List payments

Newest first. Filter by status and by time with created[gte] / created[lte] (unix seconds). Up to 100 per page; when has_more is true, ask again with starting_after set to the last id you got.

List completed payments, page by page
# Completed payments since a moment (unix seconds), 100 per page.
curl -G https://api.takaelo.com/v1/payments \
  -H "Authorization: Bearer $TAKAELO_SECRET_KEY" \
  -d status=completed \
  -d limit=100 \
  --data-urlencode "created[gte]=1791100000"

# Next page: pass the last id you received.
#   -d starting_after=pay_3kT9xQm2LrV8nB4cW7yZ1aPd
<?php
// Every completed payment of the last 7 days, page by page.
$since = time() - 7 * 24 * 3600;
$startingAfter = null;

do {
    $query = ['status' => 'completed', 'limit' => 100, 'created[gte]' => $since];
    if ($startingAfter !== null) {
        $query['starting_after'] = $startingAfter;
    }
    $ch = curl_init('https://api.takaelo.com/v1/payments?' . http_build_query($query));
    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']);
    }

    $page = $body['data'];
    foreach ($page['data'] as $payment) {
        echo "{$payment['id']} {$payment['amount']} {$payment['reference']}" . PHP_EOL;
    }
    $startingAfter = $page['has_more'] ? end($page['data'])['id'] : null;
} while ($startingAfter !== null);
// Every completed payment of the last 7 days, page by page.
const since = Math.floor(Date.now() / 1000) - 7 * 24 * 3600;
let startingAfter;

do {
  const query = new URLSearchParams({ status: "completed", limit: "100", "created[gte]": String(since) });
  if (startingAfter) query.set("starting_after", startingAfter);

  const res = await fetch(`https://api.takaelo.com/v1/payments?${query}`, {
    headers: { Authorization: `Bearer ${process.env.TAKAELO_SECRET_KEY}` },
  });
  const body = await res.json();
  if (!body.success) throw new Error(`${body.code}: ${body.message}`);

  const page = body.data;
  for (const payment of page.data) console.log(payment.id, payment.amount, payment.reference);
  startingAfter = page.has_more ? page.data.at(-1).id : undefined;
} while (startingAfter);
import json
import os
import time
import urllib.parse
import urllib.request

# Every completed payment of the last 7 days, page by page.
since = int(time.time()) - 7 * 24 * 3600
starting_after = None

while True:
    query = {"status": "completed", "limit": 100, "created[gte]": since}
    if starting_after:
        query["starting_after"] = starting_after
    request = urllib.request.Request(
        "https://api.takaelo.com/v1/payments?" + urllib.parse.urlencode(query),
        headers={"Authorization": "Bearer " + os.environ["TAKAELO_SECRET_KEY"]},
    )
    with urllib.request.urlopen(request) as response:
        page = json.load(response)["data"]

    for payment in page["data"]:
        print(payment["id"], payment["amount"], payment["reference"])
    if not page["has_more"]:
        break
    starting_after = page["data"][-1]["id"]
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"time"
)

type Payment struct {
	ID        string  `json:"id"`
	Amount    float64 `json:"amount"`
	Reference string  `json:"reference"`
}

// Every completed payment of the last 7 days, page by page.
func main() {
	since := time.Now().Add(-7 * 24 * time.Hour).Unix()
	startingAfter := ""

	for {
		query := url.Values{"status": {"completed"}, "limit": {"100"}, "created[gte]": {strconv.FormatInt(since, 10)}}
		if startingAfter != "" {
			query.Set("starting_after", startingAfter)
		}
		req, _ := http.NewRequest(http.MethodGet, "https://api.takaelo.com/v1/payments?"+query.Encode(), nil)
		req.Header.Set("Authorization", "Bearer "+os.Getenv("TAKAELO_SECRET_KEY"))

		res, err := http.DefaultClient.Do(req)
		if err != nil {
			log.Fatal(err)
		}
		var body struct {
			Success bool   `json:"success"`
			Code    string `json:"code"`
			Message string `json:"message"`
			Data    struct {
				Data    []Payment `json:"data"`
				HasMore bool      `json:"has_more"`
			} `json:"data"`
		}
		err = json.NewDecoder(res.Body).Decode(&body)
		res.Body.Close()
		if err != nil {
			log.Fatal(err)
		}
		if !body.Success {
			log.Fatalf("%s: %s", body.Code, body.Message)
		}

		for _, p := range body.Data.Data {
			fmt.Println(p.ID, p.Amount, p.Reference)
		}
		if !body.Data.HasMore {
			break
		}
		startingAfter = body.Data.Data[len(body.Data.Data)-1].ID
	}
}
require "json"
require "net/http"

# Every completed payment of the last 7 days, page by page.
since = Time.now.to_i - 7 * 24 * 3600
starting_after = nil

loop do
  uri = URI("https://api.takaelo.com/v1/payments")
  query = { "status" => "completed", "limit" => 100, "created[gte]" => since }
  query["starting_after"] = starting_after if starting_after
  uri.query = URI.encode_www_form(query)

  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"]

  page = body["data"]
  page["data"].each { |payment| puts "#{payment["id"]} #{payment["amount"]} #{payment["reference"]}" }
  break unless page["has_more"]

  starting_after = page["data"].last["id"]
end
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Instant;

// Every completed payment of the last 7 days, page by page.
public class ListPayments {
    public static void main(String[] args) throws Exception {
        HttpClient http = HttpClient.newHttpClient();
        ObjectMapper json = new ObjectMapper();
        long since = Instant.now().getEpochSecond() - 7 * 24 * 3600;
        String startingAfter = null;

        do {
            String query = "status=completed&limit=100&" + URLEncoder.encode("created[gte]", StandardCharsets.UTF_8) + "=" + since;
            if (startingAfter != null) query += "&starting_after=" + startingAfter;

            HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.takaelo.com/v1/payments?" + query))
                .header("Authorization", "Bearer " + System.getenv("TAKAELO_SECRET_KEY"))
                .build();
            JsonNode body = json.readTree(http.send(request, HttpResponse.BodyHandlers.ofString()).body());
            if (!body.path("success").asBoolean()) {
                throw new IllegalStateException(body.path("code").asText() + ": " + body.path("message").asText());
            }

            JsonNode page = body.get("data");
            for (JsonNode payment : page.get("data")) {
                System.out.println(payment.get("id").asText() + " " + payment.get("amount").asText());
                startingAfter = payment.get("id").asText();
            }
            if (!page.get("has_more").asBoolean()) startingAfter = null;
        } while (startingAfter != null);
    }
}
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"));

// Every completed payment of the last 7 days, page by page.
var since = DateTimeOffset.UtcNow.AddDays(-7).ToUnixTimeSeconds();
string? startingAfter = null;

do
{
    var url = $"https://api.takaelo.com/v1/payments?status=completed&limit=100&created%5Bgte%5D={since}";
    if (startingAfter != null) url += $"&starting_after={startingAfter}";

    var body = await http.GetFromJsonAsync<JsonElement>(url);
    var page = body.GetProperty("data");
    foreach (var payment in page.GetProperty("data").EnumerateArray())
    {
        Console.WriteLine($"{payment.GetProperty("id")} {payment.GetProperty("amount")}");
        startingAfter = payment.GetProperty("id").GetString();
    }
    if (!page.GetProperty("has_more").GetBoolean()) startingAfter = null;
} while (startingAfter != null);

Record a refund

TakaElo never holds money, so it can't send money back for you. When you return a payment from your wallet app, record it: the payment becomes refunded and payment.refunded fires (useful when your shop and your accounts are separate systems). Only completed payments can be refunded; anything else gets 409 PAYMENT_STATE.

Record a refund
# Record that you sent the money back (TakaElo never holds or moves money).
curl -X POST https://api.takaelo.com/v1/payments/pay_3kT9xQm2LrV8nB4cW7yZ1aPd/refund \
  -H "Authorization: Bearer $TAKAELO_SECRET_KEY" \
  -H "Idempotency-Key: refund-pay_3kT9xQm2LrV8nB4cW7yZ1aPd"
<?php
$id = 'pay_3kT9xQm2LrV8nB4cW7yZ1aPd';
$ch = curl_init("https://api.takaelo.com/v1/payments/$id/refund");
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer ' . getenv('TAKAELO_SECRET_KEY'),
        "Idempotency-Key: refund-$id",
    ],
]);
$body = json_decode(curl_exec($ch), true);
if (empty($body['success'])) {
    throw new RuntimeException($body['code'] . ': ' . $body['message']);
}
echo $body['data']['status'] . PHP_EOL; // "refunded"
const id = "pay_3kT9xQm2LrV8nB4cW7yZ1aPd";
const res = await fetch(`https://api.takaelo.com/v1/payments/${id}/refund`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.TAKAELO_SECRET_KEY}`,
    "Idempotency-Key": `refund-${id}`,
  },
});
const body = await res.json();
if (!body.success) throw new Error(`${body.code}: ${body.message}`);

console.log(body.data.status); // "refunded"
import json
import os
import urllib.error
import urllib.request

payment_id = "pay_3kT9xQm2LrV8nB4cW7yZ1aPd"
request = urllib.request.Request(
    f"https://api.takaelo.com/v1/payments/{payment_id}/refund",
    method="POST",
    headers={
        "Authorization": "Bearer " + os.environ["TAKAELO_SECRET_KEY"],
        "Idempotency-Key": f"refund-{payment_id}",
    },
)
try:
    with urllib.request.urlopen(request) as response:
        payment = json.load(response)["data"]
except urllib.error.HTTPError as e:
    error = json.load(e)
    raise SystemExit(f"{error['code']}: {error['message']}")

print(payment["status"])  # "refunded"
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	id := "pay_3kT9xQm2LrV8nB4cW7yZ1aPd"
	req, _ := http.NewRequest(http.MethodPost, "https://api.takaelo.com/v1/payments/"+id+"/refund", nil)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("TAKAELO_SECRET_KEY"))
	req.Header.Set("Idempotency-Key", "refund-"+id)

	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    struct {
			Status string `json:"status"`
		} `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) // "refunded"
}
require "json"
require "net/http"

id = "pay_3kT9xQm2LrV8nB4cW7yZ1aPd"
uri = URI("https://api.takaelo.com/v1/payments/#{id}/refund")
request = Net::HTTP::Post.new(uri,
  "Authorization" => "Bearer #{ENV.fetch("TAKAELO_SECRET_KEY")}",
  "Idempotency-Key" => "refund-#{id}")
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"]

puts body["data"]["status"] # "refunded"
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 RefundPayment {
    public static void main(String[] args) throws Exception {
        String id = "pay_3kT9xQm2LrV8nB4cW7yZ1aPd";
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.takaelo.com/v1/payments/" + id + "/refund"))
            .header("Authorization", "Bearer " + System.getenv("TAKAELO_SECRET_KEY"))
            .header("Idempotency-Key", "refund-" + id)
            .POST(HttpRequest.BodyPublishers.noBody())
            .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());
        }
        System.out.println(body.get("data").get("status").asText()); // "refunded"
    }
}
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 id = "pay_3kT9xQm2LrV8nB4cW7yZ1aPd";
var request = new HttpRequestMessage(HttpMethod.Post, $"https://api.takaelo.com/v1/payments/{id}/refund");
request.Headers.Add("Idempotency-Key", $"refund-{id}");

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")}");

Console.WriteLine(body.GetProperty("data").GetProperty("status")); // "refunded"