AGENTS.md template
AI coding agents read an AGENTS.md file in the root of your repository before they change code. This template holds the TapPay integration rules.
Where to put it
Save the file as AGENTS.md in the root of your repository. For Claude Code, add the line @AGENTS.md to your CLAUDE.md. For Cursor, add a rule in .cursor/rules that points to AGENTS.md.
What it covers
- MUST and MUST NOT rules for confirming payments, the
Idempotency-Keyheader, webhook signatures, keys and theTapPay-Versionheader. - Wrong and right code in Node.js, PHP and Python for four mistakes. They are trusting the redirect, a missing
Idempotency-Key, verifying webhooks without the raw body, and a secret key in the browser. - How to test with a sandbox key, the simulator and the playground.
The right webhook code is tested against the same signature test vectors as the TapPay API.
Template
# TapPay integration — rules for AI coding agents
<!-- tappay-agents-template v1 · source: https://docs.tappay.mn/AGENTS.md -->
Copy this file to the root of your repository as `AGENTS.md`. AI coding agents (Claude Code, Cursor, Codex and others) read it before they change your TapPay integration.
## Context
- Docs for AI tools: https://docs.tappay.mn/llms.txt lists every page, https://docs.tappay.mn/llms-full.txt has all guides and the API reference in one file, and every page has a Markdown version at the same URL with `.md` (for example https://docs.tappay.mn/guides/webhooks.md).
- MCP server: `npx -y @tappay-mn/mcp` searches the docs and calls the sandbox. Give it only a sandbox secret key (`sk_test_`) in `TAPPAY_SECRET_KEY`.
- Every request sends the `TapPay-Version` header. The API reference shows the latest version.
- Keys: `sk_test_` and `pk_test_` are sandbox keys, `sk_live_` and `pk_live_` are production keys. The secret key (`sk_`) is for your server only. The publishable key (`pk_`) is for the browser and works only for checkout.
## SDK
Use the official SDKs for Node.js (`@tappay-mn/node`), PHP (`tappay-mn/tappay-php`, namespace `TapPay\`) and Python (`tappay-mn`, `import tappay`) (https://docs.tappay.mn/sdks.md). Do not write the HTTP calls by hand: the SDK sends `TapPay-Version`, signs requests (HMAC, `TAPPAY_SIGNING_SECRET`), adds and reuses `Idempotency-Key` on retries, retries safely, pages through lists and verifies webhooks over the raw body. Configure it with environment variables: `TAPPAY_SECRET_KEY`, `TAPPAY_SIGNING_SECRET`, `TAPPAY_WEBHOOK_SECRET`.
```bash
npm install @tappay-mn/node
composer require tappay-mn/tappay-php
pip install tappay-mn
```
```js
import { TapPay } from '@tappay-mn/node';
const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
```
```php
<?php
require 'vendor/autoload.php';
use TapPay\TapPay;
$tappay = new TapPay(['apiKey' => getenv('TAPPAY_SECRET_KEY')]);
```
```python
import os
import tappay
client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
```
## MUST
1. Confirm an order or payment only from a webhook or from a `GET` request on your server. Never trust the customer's return to `returnUrl` (https://docs.tappay.mn/guides/checkout.md#confirm-the-session).
2. Send an `Idempotency-Key` header with every `POST`. On a retry, send the same key with the same body. A different body with the same key returns `409` (https://docs.tappay.mn/concepts/idempotency.md).
3. Verify the webhook signature over the raw request body, before any JSON parsing. `TapPay-Signature` holds one or more `v1=<base64 HMAC-SHA256>` values, and one match is enough (secret rotation). The signed string is `POST\n<path?query>\n<TapPay-Timestamp>\n<TapPay-Nonce>\n<hex SHA-256 of the raw body>`. Reject a `TapPay-Timestamp` older or newer than 300 seconds. Compare in constant time (https://docs.tappay.mn/guides/webhooks.md#verify-the-signature).
4. A webhook payload is thin: `{ id, type, objectId }`. Read the object with `GET` and take its status from there. Process each event `id` only once (https://docs.tappay.mn/concepts/events.md).
5. Keep the secret key on the server and read it from an environment variable or a secret store. The browser gets only the publishable key (`pk_`) for checkout.
6. Use only sandbox keys (`sk_test_`) for development, tests and AI tools.
7. Set the `TapPay-Version` header on every request (https://docs.tappay.mn/concepts/versioning.md).
8. In Node.js, PHP and Python use the official SDK (`@tappay-mn/node`, `tappay-mn/tappay-php`, `tappay-mn`). Pass the raw request body to the SDK's `constructEvent` to verify a webhook (https://docs.tappay.mn/sdks.md).
## MUST NOT
- Mark an order as paid because the customer reached your return page.
- Give `returnUrl` or `cancelUrl` an `http://` (production), `javascript:` or `data:` address — only `https://` or an app scheme (https://docs.tappay.mn/guides/checkout.md#return-urls).
- Put a secret key (`sk_`) in frontend code, a mobile app, the repository or logs.
- Verify a webhook signature over parsed and serialised JSON.
- Retry a `POST` without an `Idempotency-Key`, or with a new key.
- Give a production key to an AI tool or to the MCP server.
- Hardcode a key or a secret in code.
## Wrong ↔ right
### Trusting the redirect {#redirect}
```js wrong
// Express: the return page marks the order as paid.
app.get('/checkout/return', async (req, res) => {
await orders.markPaid(req.query.orderId);
res.redirect('/thank-you');
});
```
```js right
import { TapPay } from '@tappay-mn/node';
const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
// Express: the return page only reads the status from TapPay; the webhook does the same.
app.get('/checkout/return', async (req, res) => {
const order = await orders.find(req.query.orderId);
const session = await tappay.checkoutSessions.retrieve({ id: order.sessionId });
if (session.status === 'COMPLETE') await orders.markPaid(order.id);
res.redirect(session.status === 'COMPLETE' ? '/thank-you' : '/payment-pending');
});
```
```php wrong
<?php
// return.php: the return page marks the order as paid.
markOrderPaid($_GET['orderId']);
header('Location: /thank-you');
```
```php right
<?php
require 'vendor/autoload.php';
use TapPay\TapPay;
$tappay = new TapPay(['apiKey' => getenv('TAPPAY_SECRET_KEY')]);
// return.php: read the session status from TapPay before you change the order.
$order = findOrder($_GET['orderId']);
$session = $tappay->checkoutSessions->retrieve(['id' => $order['sessionId']]);
if ($session['status'] === 'COMPLETE') {
markPaid($order['id']);
}
header('Location: ' . ($session['status'] === 'COMPLETE' ? '/thank-you' : '/payment-pending'));
```
```python wrong
# Flask: the return page marks the order as paid.
@app.get("/checkout/return")
def checkout_return():
orders.mark_paid(request.args["orderId"])
return redirect("/thank-you")
```
```python right
# Flask: read the session status from TapPay before you change the order.
import os
import tappay
from flask import Flask, redirect, request
app = Flask(__name__)
client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
@app.get("/checkout/return")
def checkout_return():
order = orders.find(request.args["orderId"])
session = client.checkout_sessions.retrieve({"id": order.session_id})
if session["status"] == "COMPLETE":
orders.mark_paid(order.id)
return redirect("/thank-you" if session["status"] == "COMPLETE" else "/payment-pending")
```
### Missing Idempotency-Key {#idempotency}
```js wrong
// A retry without a key can create a second invoice.
const res = await fetch(`${process.env.TAPPAY_BASE_URL}/api/v1/invoices`, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.TAPPAY_SECRET_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify(invoice),
});
```
```js right
import { TapPay } from '@tappay-mn/node';
const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
// The SDK sends an Idempotency-Key and reuses it on its own retries. For your own retry of the
// same order, pass the key you saved with the order and the same body.
const invoice = await tappay.invoices.create(
{ body: order.invoiceBody },
{ idempotencyKey: order.invoiceIdempotencyKey }, // crypto.randomUUID() once, saved with the order
);
```
```php wrong
<?php
// A retry without a key can create a second invoice.
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . getenv('TAPPAY_SECRET_KEY'), 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($invoice));
```
```php right
<?php
require 'vendor/autoload.php';
use TapPay\TapPay;
$tappay = new TapPay(['apiKey' => getenv('TAPPAY_SECRET_KEY')]);
// The SDK sends an Idempotency-Key and reuses it on its own retries. For your own retry of the
// same order, pass the key you saved with the order and the same body.
$invoice = $tappay->invoices->create(
['body' => $order['invoiceBody']],
['idempotencyKey' => $order['invoiceIdempotencyKey']], // bin2hex(random_bytes(16)) once, saved with the order
);
```
```python wrong
# A retry without a key can create a second invoice.
requests.post(f"{base}/api/v1/invoices", json=invoice, headers={"Authorization": f"Bearer {os.environ['TAPPAY_SECRET_KEY']}"})
```
```python right
import os
import tappay
client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
# The SDK sends an Idempotency-Key and reuses it on its own retries. For your own retry of the
# same order, pass the key you saved with the order and the same body.
invoice = client.invoices.create(
{"body": order.invoice_body},
idempotency_key=order.invoice_idempotency_key, # str(uuid.uuid4()) once, saved with the order
)
```
### Verifying webhooks without the raw body {#raw-body}
```js wrong
// express.json() parses first; JSON.stringify(req.body) is not the bytes TapPay signed.
app.post('/webhooks/tappay', express.json(), (req, res) => {
const expected = 'v1=' + createHmac('sha256', secret).update(JSON.stringify(req.body)).digest('base64');
if (req.get('TapPay-Signature') !== expected) return res.sendStatus(400);
res.sendStatus(200);
});
```
```js right
import express from 'express';
import { TapPay, SignatureVerificationError, verifyWebhookSignature } from '@tappay-mn/node';
// The same check as constructEvent, without the event: raw bytes, 300 s window, every v1= value, constant time.
export function verifyWebhook(rawBody, { signature, timestamp, nonce }, secret, path, now) {
try {
verifyWebhookSignature({ body: rawBody, signature, timestamp, nonce, secrets: [secret], path, now });
return true;
} catch (e) {
if (e instanceof SignatureVerificationError) return false;
throw e;
}
}
let client;
const tappay = () => (client ??= new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY }));
const app = express();
// express.raw keeps req.body as the exact bytes (Buffer) that TapPay signed.
app.post('/webhooks/tappay', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = tappay().webhooks.constructEvent(req.body, req.headers, {
secrets: [process.env.TAPPAY_WEBHOOK_SECRET], // during a rotation: [new, previous]
path: req.originalUrl,
});
} catch (e) {
if (e instanceof SignatureVerificationError) return void res.sendStatus(400);
throw e;
}
queue.add(event.id, event); // process each event id once; read the object with tappay().events.retrieveObject(event)
res.sendStatus(200);
});
```
```php wrong
<?php
// json_decode + json_encode changes the bytes, so the signature never matches the original.
$event = json_decode(file_get_contents('php://input'), true);
$expected = 'v1=' . base64_encode(hash_hmac('sha256', json_encode($event), getenv('TAPPAY_WEBHOOK_SECRET'), true));
if ($_SERVER['HTTP_NODE_SIGNATURE'] !== $expected) {
http_response_code(400);
exit;
}
```
```php right
<?php
require 'vendor/autoload.php';
use TapPay\Core\Webhooks;
use TapPay\Exception\SignatureVerificationError;
use TapPay\TapPay;
// The same check as constructEvent, without the event: raw bytes, 300 s window, every v1= value, constant time.
function verifyWebhook(string $rawBody, ?string $signature, ?string $timestamp, ?string $nonce, string $secret, string $path, ?int $now = null): bool
{
try {
Webhooks::verifySignature($path, $timestamp, $nonce, $signature, $rawBody, [$secret], 300, $now ?? time());
return true;
} catch (SignatureVerificationError $e) {
return false;
}
}
// Call from your webhook route.
function handleTapPayWebhook(): void
{
$tappay = new TapPay(['apiKey' => getenv('TAPPAY_SECRET_KEY')]);
try {
$event = $tappay->webhooks->constructEvent(
file_get_contents('php://input'), // the exact bytes TapPay signed
getallheaders(),
['secrets' => [getenv('TAPPAY_WEBHOOK_SECRET')], 'path' => $_SERVER['REQUEST_URI']], // rotation: [new, previous]
);
} catch (SignatureVerificationError $e) {
http_response_code(400);
return;
}
enqueueEvent($event->id, $event); // process each event id once; read the object with $tappay->events->retrieveObject($event)
http_response_code(200);
}
```
```python wrong
# request.get_json() parses first; json.dumps() of it is not the bytes TapPay signed.
@app.post("/webhooks/tappay")
def tappay_webhook():
body = json.dumps(request.get_json()).encode()
expected = "v1=" + base64.b64encode(hmac.new(secret, body, hashlib.sha256).digest()).decode()
if request.headers.get("TapPay-Signature") != expected:
abort(400)
return "", 200
```
```python right
import json
import os
import tappay
from flask import Flask, abort, request
app = Flask(__name__)
_client = None
def client() -> tappay.TapPay:
global _client
if _client is None:
_client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
return _client
# The check construct_event runs: raw bytes, 300 s window, every v1= value, constant time.
def verify_webhook(raw_body: bytes, signature, timestamp, nonce, secret: str, path: str, now=None) -> bool:
try:
headers = {"TapPay-Event-Id": json.loads(raw_body).get("id"), "TapPay-Signature": signature, "TapPay-Timestamp": timestamp, "TapPay-Nonce": nonce}
client().webhooks.construct_event(raw_body, {k: v for k, v in headers.items() if v is not None}, secrets=[secret], path=path, tolerance=300, now=now)
return True
except (tappay.SignatureVerificationError, ValueError): # ValueError: body is not JSON
return False
@app.post("/webhooks/tappay")
def tappay_webhook():
try:
event = client().webhooks.construct_event(
request.get_data(), # the exact bytes TapPay signed
request.headers,
secrets=[os.environ["TAPPAY_WEBHOOK_SECRET"]], # during a rotation: [new, previous]
path=request.full_path.rstrip("?"),
)
except tappay.SignatureVerificationError:
abort(400)
enqueue_event(event.id, event) # process each event id once; read the object with client().events.retrieve_object(event)
return "", 200
```
### Secret key in the browser {#secret-key}
```js wrong
// Browser code: anyone can read this key and call the API as you.
const res = await fetch('https://api.tappay.mn/api/v1/checkout/sessions', {
method: 'POST',
headers: { Authorization: 'Bearer sk_test_YOUR_SECRET_KEY' },
body: JSON.stringify(cart),
});
```
```js right
import { TapPay } from '@tappay-mn/node';
// Server only: the SDK refuses a secret key in the browser (BROWSER_SECRET_KEY).
const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
// The server creates the session; the browser gets only clientSecret + publishable key.
app.post('/api/checkout', async (req, res) => {
const session = await tappay.checkoutSessions.create(
{ body: await buildSession(req.body.cartId) },
{ idempotencyKey: req.body.cartId },
);
res.json({ clientSecret: session.clientSecret }); // browser: TapPay.checkout.mount('#checkout', { clientSecret, publishableKey: 'pk_test_YOUR_PUBLISHABLE_KEY' })
});
```
```php wrong
<?php // checkout.php renders the secret key into the page ?>
<script>
fetch('https://api.tappay.mn/api/v1/checkout/sessions', { method: 'POST', headers: { Authorization: 'Bearer <?= getenv('TAPPAY_SECRET_KEY') ?>' } });
</script>
```
```php right
<?php
require 'vendor/autoload.php';
use TapPay\TapPay;
// api/checkout.php: the secret key stays on the server; the page gets only clientSecret.
$tappay = new TapPay(['apiKey' => getenv('TAPPAY_SECRET_KEY')]);
$session = $tappay->checkoutSessions->create(['body' => buildSession($cart)], ['idempotencyKey' => $cart['id']]);
header('Content-Type: application/json');
echo json_encode(['clientSecret' => $session['clientSecret']]); // the page mounts checkout with pk_test_YOUR_PUBLISHABLE_KEY
```
```python wrong
# Template sends the secret key to the browser.
return render_template("checkout.html", tappay_key=os.environ["TAPPAY_SECRET_KEY"])
```
```python right
import os
import tappay
from flask import Flask, request
app = Flask(__name__)
client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"]) # server only
# The secret key stays on the server; the page gets only clientSecret and the publishable key.
@app.post("/api/checkout")
def create_checkout():
cart = carts.get(request.json["cartId"])
session = client.checkout_sessions.create({"body": build_session(cart)}, idempotency_key=cart.id)
return {"clientSecret": session["clientSecret"]} # page: publishableKey pk_test_YOUR_PUBLISHABLE_KEY
```
## Common mistakes
1. Trusting the redirect: the customer reached `returnUrl`, so the order is marked paid. See [Trusting the redirect](#redirect).
2. A `POST` without an `Idempotency-Key`, or a retry with a new key. See [Missing Idempotency-Key](#idempotency).
3. Verifying a webhook without the raw body (parsed and serialised JSON). See [Verifying webhooks without the raw body](#raw-body).
4. A secret key in the browser, a mobile app or the repository. See [Secret key in the browser](#secret-key).
5. Trusting the thin webhook payload as the final state instead of reading the object with `GET`.
6. Processing the same event twice: deduplicate by the event `id`.
7. Not checking `TapPay-Timestamp`, so an old signed request can be replayed.
## Testing
- Use a sandbox secret key (`sk_test_`) from the sandbox portal. Sandbox data never reaches production.
- Simulate payments with the sandbox simulator and the test cards: https://docs.tappay.mn/testing.md.
- Try requests in the playground (https://docs.tappay.mn/playground.md) and read delivered webhooks in its inbox.
- MCP tools (`@tappay-mn/mcp`): `search_docs`, `read_page`, `read_operation`, `create_invoice`, `create_checkout_session`, `simulate_payment`, `list_events`, `verify_webhook_signature` (https://docs.tappay.mn/ai/mcp.md).