# TakaElo payments in this project

This project takes payments with TakaElo (bKash, Nagad and Rocket into the shop's own number; Next.js). Whenever you add or change payment code, follow these rules and facts.

## How it works
1. Your server creates a checkout (`POST /v1/checkouts`) and gets back a payment with a `url`.
2. The customer pays on that page, from their bKash, Nagad or Rocket.
3. TakaElo sends `payment.completed` to your webhook endpoint, signed with your webhook secret; you mark the order paid.
4. The customer comes back to your `success_url`.

## Rules (follow every one)
- The secret key (`sk_test_…` / `sk_live_…`) lives only on the server, in an environment variable named `TAKAELO_SECRET_KEY`. Never put it in browser code, a mobile app, a public env var (e.g. `NEXT_PUBLIC_…`, `VITE_…`), a log line or the repository.
- Never ask the developer to paste a key or secret into this chat. Read them from environment variables and tell the developer which variables to set and where to find the values (Dashboard › Developers).
- Create the checkout on the server (`POST /v1/checkouts`) with the order's amount and your order id as `reference`; the price always comes from your own database, never from the browser.
- Send an `Idempotency-Key` on every POST, one per attempt, e.g. `order-<id>-<n>`: a retry with the same key and body gets the first answer for 24 hours, so a new attempt for the same order needs a new key.
- Send the customer to the checkout's `url`. Don't build checkout URLs yourself.
- Reaching `success_url` proves nothing: anyone can open it. Show "we're confirming your payment" there and wait for the webhook.
- `success_url` and `cancel_url` must be https addresses on one of the shop's own websites (Dashboard › Settings). Test keys may also use `http://localhost`. `{PAYMENT_ID}` in them is filled in.
- Mark an order paid only from a verified `payment.completed` webhook (or by retrieving the payment with your key), never from the redirect or the browser.
- Verify `TakaElo-Signature` on the RAW request body, before any JSON parsing: HMAC-SHA256 of `"<t>.<raw body>"` with the webhook secret (`TAKAELO_WEBHOOK_SECRET`), hex, compared in constant time. Accept any of the `v1=` values (two arrive while a secret is being changed). Reject when `|now − t| > 300` seconds. Answer 400 to a bad signature.
- Test and live each have their own webhook address and secret. Still check `livemode` against your own key: a live server (`sk_live_…`) acts only on `livemode: true`, a test one only on `false`; otherwise answer 200 and do nothing.
- Before fulfilling, check the payment's `amount` and `reference` against your order (or retrieve the payment with `GET /v1/payments/{id}` and use that). A different amount never completes an order.
- Webhooks can arrive more than once and out of order. Store each event `id` and act on it once: record the id and change the order in ONE database transaction (a unique key on the id), so two copies arriving together can't both act. Never let a later `payment.pending` undo a `payment.completed`.
- Answer the webhook with 2xx within 10 seconds, then do slow work (emails, stock) after answering or in a queue. Anything else is retried after 1 min, 5 min, 30 min, 2 h, 6 h and 24 h.
- `payment.pending_review` means hold the order ("on hold"), not cancel it: the shop owner looks and approves or rejects, and `payment.completed` or `payment.failed` follows.
- Amounts in requests are whole taka (integers, 1 to 1,000,000), not poisha. Responses may carry decimals in `amount_received`.
- Every error answer is `{ success: false, message, code, error_sources?, request_id }`: branch on `code`, show `message` to people, log `request_id`. On 429 wait `Retry-After` seconds.
- Send `User-Agent: TakaElo-Prompt/nextjs-1` with every request to the TakaElo API (you may add your own product after it), so TakaElo support can see how the integration was built.
- Build and test with a test key first. Test with amounts up to ৳20,000 (above that a payment waits for review, as real money would). Go live by switching to the `sk_live_` key and the Live webhook secret; no code changes.

## API reference
- Base URL `https://api.takaelo.com/v1`. Keep the address in one place; if the project needs it configurable, read `TAKAELO_API_BASE` (default `https://api.takaelo.com`, WITHOUT `/v1`: every path below starts with `/v1/`). Auth: `Authorization: Bearer <secret key>`. JSON in, JSON out.
- Success: `{ success: true, message, data }`. Lists: `data = { object: "list", data: [...], has_more }`.
- The full machine-readable contract: https://takaelo.com/openapi.json (OpenAPI 3.1).

| Method | Path | What |
|---|---|---|
| POST | `/v1/checkouts` | Create a checkout: Creates a payment page for one order and returns the payment, with the url to send the customer to. |
| GET | `/v1/payments/{id}` | Retrieve a payment: Returns one payment by its id, as it is right now. |
| GET | `/v1/payments` | List payments: Returns your payments, newest first, a page at a time. |
| POST | `/v1/payments/{id}/refund` | Record a refund: Marks a completed payment refunded after you sent the money back from your wallet. |
| GET | `/v1/disputes/{id}` | Retrieve a dispute: Returns one payment report — what the dispute.* webhooks carry — as it is right now. |
| GET | `/v1/payments/{id}/webhooks` | A payment's webhook log: Every webhook event of one payment, sent or not and why, with each attempt and what your server answered. |
| POST | `/v1/test_helpers/payments/{id}/pay` | Pay a test checkout: Test helper: pays a test checkout as if the customer sent the money, so your code can test itself end to end. |

### The payment object
- `id` (string): `pay_` + 24 characters.
- `object` (string): Always `payment`.
- `livemode` (boolean): `false` for test payments.
- `status` (string): `initiated` · `pending` · `completed` · `pending_review` · `failed` · `refunded`. See [Payments](https://takaelo.com/en/docs/payments#statuses).
- `failure_reason` (string | null): When `failed`: `expired`, `cancelled` or `rejected`.
- `review_reason` (string | null): When `pending_review`: `above_limit`, `trx_claim`, `amount_mismatch`, `overpaid` or `late`.
- `amount` (number): What the checkout asked for, in taka.
- `amount_received` (number | null): Everything counted for this payment so far. `null` until money arrives.
- `amount_due` (number): Still to pay (a short payment waiting for the rest). 0 once paid.
- `refund_due` (number): Received more than asked and not yet returned by you. Usually 0.
- `currency` (string): Always `BDT`.
- `wallet` (string | null): How the customer paid, once chosen: `bkash`, `nagad`, `rocket`, `upay`, `cellfin`, `okwallet`, `pathaopay`, `tap`, `banglaqr` or `bank`. bKash, Nagad and Rocket complete from the shop's phone; the others wait for the shop to confirm.
- `sender` (string): The customer's wallet number. Empty until they choose a wallet.
- `trx_id` (string | null): The wallet's TrxID, once the money is matched.
- `reference` (string): Your order number, as you sent it (a link's title, an invoice's number).
- `source` (string): Where it started: `api` (your server), `link` (a payment link), `invoice`, or `sandbox` (a dashboard test payment).
- `link_id` (string | null): The payment link it came from (`lnk_…`), when `source` is `link`.
- `invoice_id` (string | null): The invoice it pays (`inv_…`), when `source` is `invoice`.
- `customer` (object): `name`, `phone`, `email` — as you sent them (empty strings when not).
- `metadata` (object): Your key/value pairs, as you sent them.
- `url` (string): The checkout page, on your checkout address.
- `created` (integer): Unix seconds.
- `expires_at` (integer): When the checkout times out (moves forward once a wallet is chosen).
- `completed_at` (integer | null): When the money was matched or approved.
- `refunded_at` (integer | null): When you recorded a refund.

### Webhook events
Each delivery is a POST with body `{ id, type, created, livemode, data }` (`data` = the payment object, or the dispute object for `dispute.*`) and the header `TakaElo-Signature: t=<unix seconds>,v1=<hex signature>`. The shop chooses its events in Dashboard › Developers › Webhooks; until then only the four default ones are sent.
- `payment.created` (only if ticked): 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. → 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.pending` (only if ticked): The customer chose a wallet and gave the number they pay from — they are paying now. → Show the order as "waiting for your bKash payment". Together with `payment.failed` this tells you exactly where people drop off: before choosing a wallet, or after.
- `payment.partially_paid` (only if ticked): Part of the money arrived and the payment is still open (the customer is sending the rest). Sent once per arrival. → Don't fulfil yet. `amount_received` is what arrived, `amount_due` what is still to come; `payment.completed` follows when it's all there.
- `payment.completed` (sent by default): The money arrived and matched the checkout — or you approved a held payment. → Mark the order paid and fulfil it. `amount_received` is what really arrived; `refund_due` > 0 means the customer paid more than asked and you owe them the difference.
- `payment.pending_review` (sent by default): Money arrived (or the customer says it did) but it needs your OK in the dashboard first. → Optional: show the order as "payment being checked". Don't fulfil yet — `payment.completed` or `payment.failed` follows when you decide.
- `payment.failed` (sent by default): No money is coming for this checkout. → Release reserved stock and let the customer try again with a new checkout.
- `payment.refunded` (sent by default): You recorded that the money went back to the customer (dashboard or `POST /v1/payments/{id}/refund`). → Mark the order refunded. `refunded_at` says when.
- `dispute.opened` (only if ticked): A customer reported a problem with a payment ("I paid but…"). You have 48 hours to answer in the dashboard before TakaElo steps in. → Alert your support team, or open a ticket. `payment_id` links it to the payment when the customer came from one; `trx_id` and `sender` are what they say they sent.
- `dispute.updated` (only if ticked): A report changed while still open: your team answered, the customer wrote again, or TakaElo stepped in. → Refresh your ticket. The messages themselves stay in the dashboard — the event never carries them.
- `dispute.closed` (only if ticked): The report ended — you settled it, the customer withdrew it, or TakaElo closed it. → Close your ticket. If `resolution` is `paid_confirmed`, the order can go ahead.

Signature test vector: secret `whsec_test_secret`, `t=1760000000`, body `{"id":"evt_test","type":"payment.completed"}` → `v1=7f852f9c0d26b339c024880089f7e91038e764b64f8d7e3c2e46d9a5bcb77f1b`. Your verifier must produce exactly this.

## Next.js
- `app/api/checkout/route.ts` (or a Server Action): creates the checkout and returns its `url`.
- `app/api/webhooks/takaelo/route.ts`: the webhook endpoint (a Route Handler, `POST`).
- `lib/takaelo.ts`: the API calls and the signature check, imported only by server code (add `import "server-only"`).
- The order page shows "confirming your payment" until the webhook marks the order paid.
- Read the raw body with `await request.text()` in the Route Handler and verify that string; parse JSON only after the signature passes.
- Keep the Node.js runtime for the webhook route (the default); the signature check uses `node:crypto`.
- Environment variables: `TAKAELO_SECRET_KEY` and `TAKAELO_WEBHOOK_SECRET` in `.env.local`, never prefixed `NEXT_PUBLIC_`.
- Webhook routes must not be cached or statically rendered: they read the request, so they are dynamic.
- Next.js 16 apps from create-next-app have `cacheComponents: true`: don't add `export const dynamic` or other route segment config (the build fails); a page that reads orders puts that part inside `<Suspense>`.
- Redirect the customer with `redirect(url)` from a Server Action, or return `{ url }` and set `window.location`.
- Run: `npm run dev`; tests with the project's runner (e.g. Vitest).

## Tested code to start from (Node.js)
These run against the real API on every docs change. Adapt them to this project's structure; keep their checks.

Create a checkout:
```js
// 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);
```

Verify the webhook signature:
```js
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);
  });
}
```

Handle the webhook:
```js
// 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);
```

## Test it end to end (with the test key)
1. **Unit-test the webhook handler** with events you sign yourself (the algorithm above, your `TAKAELO_WEBHOOK_SECRET`): a valid `payment.completed` marks the order paid once; the same event again changes nothing; a changed body, a wrong secret or a timestamp older than 5 minutes gets 400; `livemode` from the other mode is ignored. A real `payment.completed` body (from a live payment; your test events say `livemode: false`):
```json
{
  "id": "evt_8RwK2mZp5TqV9xLc3nB7yH1d",
  "type": "payment.completed",
  "created": 1791641622,
  "livemode": true,
  "data": {
    "id": "pay_3kT9xQm2LrV8nB4cW7yZ1aPd",
    "object": "payment",
    "livemode": true,
    "status": "completed",
    "failure_reason": null,
    "review_reason": null,
    "amount": 1250,
    "amount_received": 1250,
    "amount_due": 0,
    "refund_due": 0,
    "currency": "BDT",
    "wallet": "bkash",
    "sender": "01712345678",
    "trx_id": "BK7Q2M9XLA",
    "reference": "ORD-4821",
    "source": "api",
    "link_id": null,
    "invoice_id": null,
    "customer": { "name": "Rahim Uddin", "phone": "01712345678", "email": "" },
    "metadata": { "order_id": "4821" },
    "url": "https://yourshop.takaelo.com/pay/pay_3kT9xQm2LrV8nB4cW7yZ1aPd",
    "created": 1791641454,
    "expires_at": 1791642354,
    "completed_at": 1791641621,
    "refunded_at": null
  }
}
```
2. **Pay a test checkout from code**, no person needed: create a checkout with the test key, then call the test helper (it works with `sk_test_` keys only):
```js
const id = "pay_3kT9xQm2LrV8nB4cW7yZ1aPd";
const res = await fetch(`https://api.takaelo.com/v1/test_helpers/payments/${id}/pay`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.TAKAELO_SECRET_KEY}`, // a sk_test_ key
    "Idempotency-Key": `testpay-${id}`,
  },
});
const body = await res.json();
if (!body.success) throw new Error(`${body.code}: ${body.message}`);

console.log(body.data.status); // "completed"
```
3. **Read what TakaElo sent**: `GET /v1/payments/{id}/webhooks` lists each event with its `status` (`delivered`, `retrying`, `failed`, `no_endpoint` = no Test webhook address yet, `skipped` = event not ticked) and `attempts`; each try is in its `deliveries[]` with the `url`, your server's `response_code` and any `error`.
4. **Real deliveries to a local server** need a public https address (TakaElo's servers can't reach `localhost` on the developer's computer). Ask the developer to run a tunnel (`cloudflared tunnel --url http://localhost:<port>` or `ngrok http <port>`), then in the dashboard switch to **Test**, open Developers › Webhooks, set `https://<tunnel>/<your webhook path>` and copy the secret it shows into `TAKAELO_WEBHOOK_SECRET`. Then repeat step 2 and check step 3 says `delivered` with `200`.
5. The developer can also press **Simulate payment** on a test checkout page; it does exactly what step 2 does.

## If the TakaElo MCP server is connected
Use it to look things up and to run the end-to-end test instead of writing throwaway scripts. Its tools: `search_docs` (search the TakaElo docs), `get_doc_page` (read one docs page as Markdown), `get_integration_guide` (this brief, for any framework), `list_webhook_events` (every webhook event and what to do with it), `create_test_checkout` (create a checkout with your test key), `pay_test_checkout` (pay it as if the customer sent the money), `get_payment` (read a payment), `list_payments` (list payments), `get_payment_webhooks` (what TakaElo sent to your server for a payment, and what it answered). The test tools work only with a test key, which the developer sets in the MCP client, never in this chat.

## More
- Every docs page as Markdown: https://takaelo.com/llms.txt (index) and https://takaelo.com/llms-full.txt (everything).
- The webhooks guide: https://takaelo.com/en/docs/webhooks.md?code=node
- Testing: https://takaelo.com/en/docs/testing.md
- This brief: https://takaelo.com/ai/nextjs.md (version 1).
