# AI agents

Let your AI agent send a payment QR code or a payment link inside the conversation, in whatever channel the customer is chatting on, and confirm the order once it's paid.

K-LINK Pay has no special "agent API": your agent uses the same REST API as any server. You give the model a `create_payment` tool, your code calls [POST /v1/payments](/api/payments.md#create-a-payment), and the agent sends the payment into the chat: either the `qr_payload` rendered as a QR image, or the `checkout_url` (or a payment link). Because the result is an image or a link, it works in any channel that can show one: Facebook Messenger, WhatsApp, LINE, Viber, Instagram, Telegram, your own web chat. No channel-specific integration is needed.

## How the flow works

1. The customer confirms an order in the chat. The agent calls your `create_payment` tool.
2. Your tool handler looks up the order and calls `POST /v1/payments` with the order's total. The payment comes back with a `qr_payload` and a `checkout_url`.
3. The agent sends the payment in the conversation, in one of two ways:**A QR image.** Render `qr_payload` into a PNG and send it with the channel's image-message API. The customer scans it with their banking or wallet app, or saves it and picks it from their gallery to pay on the same phone.**A link.** Send the `checkout_url` or a payment link. The customer taps it and the mobile-first hosted checkout opens in the channel's in-app browser, with the QR, a save-image button and the live status.
4. K-LINK Pay sends a signed `payment.succeeded` webhook. Your server verifies it and the agent confirms the order in the same conversation.

## 1. Create a restricted key for the agent

Don't give the agent's runtime your secret key. Create a [restricted key](/authentication.md#restricted-keys) under **Developers → API keys** with only the permissions it needs:

| Permission | Why the agent needs it |
|---|---|
| `payments:write` | Create a payment for an order. |
| `payments:read` | Check a payment's status when the customer asks "did it go through?" |
| `payment_links:write` | Only if you use payment links instead of payments. |

A restricted key can't refund, read payouts or change webhook endpoints; anything outside its permissions returns `403 forbidden`. Build with an `rk_test_…` key and switch to `rk_live_…` once your account is active.

## 2. Define the tool

A JSON Schema function definition. Most LLM APIs accept this shape; some call the schema `parameters`, others `input_schema`. The model chooses _which order_ to charge; it never decides the price.

```json title="create_payment tool"
{
  "name": "create_payment",
  "description": "Create a K-LINK Pay payment for the customer's confirmed order and return a checkout_url to send in this conversation. Call it only after the customer has confirmed the order and the total.",
  "parameters": {
    "type": "object",
    "properties": {
      "reference": {
        "type": "string",
        "description": "The id of the order being paid, e.g. order-1001."
      },
      "amount": {
        "type": "integer",
        "description": "The total you quoted to the customer, in the smallest currency unit (1300 = SGD 13.00; MMK has no decimals, so 15200 = MMK 15,200). Checked against the order on the server."
      },
      "description": {
        "type": "string",
        "description": "Short text shown on the checkout, e.g. 2 x Large milk tea."
      }
    },
    "required": ["reference", "amount"]
  }
}
```

## 3. The full flow in Node.js

Tool handlers for `create_payment` and `get_payment_status`, and the webhook that closes the loop. The conversation id goes into the payment's `metadata`, which comes back on every event, so the webhook knows which chat to reply in.

```javascript title="agent-payments.js"
// agent-payments.js: Node 18+ (built-in fetch), Express for the webhook.
import crypto from "node:crypto";
import express from "express";

const API = "https://api.klinkpay.net/v1";
// A restricted key with only payments:write and payments:read.
// rk_test_… while you build, rk_live_… in production.
const KEY = process.env.KLINK_PAY_AGENT_KEY;
const WEBHOOK_SECRET = process.env.KLINK_PAY_WEBHOOK_SECRET;

async function klinkPay(method, path, body, idempotencyKey) {
  const res = await fetch(API + path, {
    method,
    headers: {
      Authorization: `Bearer ${KEY}`,
      ...(body ? { "Content-Type": "application/json" } : {}),
      ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const json = await res.json();
  if (!res.ok) throw Object.assign(new Error(json.error.message), { code: json.error.code });
  return json;
}

// 1. Tools you give the model (JSON Schema; rename "parameters" if your LLM API expects another key).
export const tools = [
  {
    name: "create_payment",
    description:
      "Create a payment for the customer's confirmed order and return a checkout_url to send in this conversation.",
    parameters: {
      type: "object",
      properties: {
        reference: { type: "string", description: "The id of the order being paid." },
        amount: { type: "integer", description: "The total quoted to the customer, smallest currency unit." },
        description: { type: "string", description: "Short text shown on the checkout." },
      },
      required: ["reference", "amount"],
    },
  },
  {
    name: "get_payment_status",
    description: "Check whether the customer's payment for an order has been paid.",
    parameters: {
      type: "object",
      properties: { reference: { type: "string", description: "The id of the order." } },
      required: ["reference"],
    },
  },
];

// 2. Tool handlers. `convo` comes from your agent runtime, never from the model.
export const handlers = {
  async create_payment({ reference, amount, description }, convo) {
    const order = await orders.get(reference, { conversation: convo.id });
    if (!order) return { error: "unknown_order" };
    if (order.status === "paid") return { error: "already_paid" };
    // Never let the model set the price: compare with the order and charge the order's total.
    if (amount !== order.total) return { error: "amount_mismatch", total: order.total };

    const payment = await klinkPay(
      "POST",
      "/payments",
      {
        amount: order.total,
        currency: "MMK",
        reference: order.id,
        description: description ?? order.summary,
        expires_in_minutes: 30,
        metadata: { conversation_id: convo.id, channel: convo.channel },
      },
      // Retries of the same tool call return the same payment instead of a second one.
      // Add an attempt number when you deliberately create a new payment (e.g. the last one expired).
      `${convo.id}:${order.id}:${order.paymentAttempt}`,
    );
    await orders.update(order.id, { paymentId: payment.id });
    return {
      checkout_url: payment.checkout_url, // send this link in the chat
      amount: payment.amount,
      currency: payment.currency,
      expires_at: payment.expires_at,
    };
  },

  async get_payment_status({ reference }, convo) {
    const order = await orders.get(reference, { conversation: convo.id });
    if (!order?.paymentId) return { status: "no_payment" };
    const payment = await klinkPay("GET", `/payments/${order.paymentId}`);
    return { status: payment.status }; // pending | succeeded | failed | expired | canceled
  },
};

// 3. The webhook closes the loop: verify it, then confirm in the same conversation.
const app = express();
app.post("/webhooks/klink-pay", express.raw({ type: "application/json" }), async (req, res) => {
  const parts = Object.fromEntries((req.get("Klink-Signature") ?? "").split(",").map((p) => p.split("=", 2)));
  const t = Number(parts.t);
  const body = req.body.toString("utf8");
  const expected = crypto.createHmac("sha256", WEBHOOK_SECRET).update(`${t}.${body}`).digest("hex");
  const given = Buffer.from(parts.v1 ?? "", "hex");
  const valid =
    given.length === expected.length / 2 &&
    crypto.timingSafeEqual(given, Buffer.from(expected, "hex")) &&
    Math.abs(Date.now() / 1000 - t) <= 300;
  if (!valid) return res.status(400).send("bad signature");

  const event = JSON.parse(body);
  res.sendStatus(200); // answer fast, then do the work
  if (await processedEvents.has(event.id)) return; // deliveries can repeat
  await processedEvents.add(event.id);

  const payment = event.data.object;
  const order = await orders.get(payment.reference);
  if (!order || payment.amount !== order.total) return; // not ours, or not the amount we expect

  if (event.type === "payment.succeeded") {
    await orders.update(order.id, { status: "paid" });
    await channels.send(payment.metadata.conversation_id, `Payment received, thank you! Order ${order.id} is confirmed.`);
  } else if (event.type === "payment.expired" || event.type === "payment.failed") {
    await orders.update(order.id, { paymentAttempt: order.paymentAttempt + 1 });
    await channels.send(payment.metadata.conversation_id, "That payment didn't go through. Shall I send you a new link?");
  }
});
app.listen(3000);

// `orders`, `processedEvents` and `channels` are your own order store, dedup store and
// messaging-channel client (Messenger, WhatsApp, LINE, Viber, Telegram, web chat, …).
```

### Sending a payment link instead

If your channel or agent platform can only share a URL, a [payment link](/api/payment-links.md) works too: a fixed-amount page that creates the payment when the customer presses Pay. Use `single_use: true` for one order. Payments made through a link carry its id in `payment_link`, so store the link id with the order.

```bash title="Create a single-use payment link"
curl https://api.klinkpay.net/v1/payment_links \
  -H "Authorization: Bearer rk_test_…" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: conv_8812:order-1001" \
  -d '{
    "amount": 15200,
    "description": "2 x Large milk tea",
    "single_use": true,
    "metadata": { "conversation_id": "conv_8812", "order_id": "order-1001" }
  }'

# → { "id": "plink_…", "url": "https://checkout.klinkpay.net/l/plink_…", … }
# Send "url" in the chat. Payments made through it carry "payment_link": "plink_…".
```

### Send the QR as an image

In channels that show images, turn `qr_payload` into a PNG with the `qrcode` npm package and send the buffer through the channel's image-message API. Send the `checkout_url` as a caption or a follow-up message too, so a customer who can't scan (they're on the same phone) can tap it instead.

```javascript title="send-payment-qr.js"
import QRCode from "qrcode";

// After POST /v1/payments: `payment` is the created payment.
async function sendPaymentInChat(convo, payment) {
  if (payment.qr_payload) {
    // A PNG Buffer, large enough to scan from a phone screen.
    const png = await QRCode.toBuffer(payment.qr_payload, { type: "png", width: 600, margin: 2 });
    // Your channel client's image-message call (Messenger, WhatsApp, LINE, Viber, Telegram, web chat, …).
    await channels.sendImage(convo.id, png, {
      filename: `pay-${payment.id}.png`,
      caption: `Scan to pay with your banking or wallet app, or tap: ${payment.checkout_url}`,
    });
  } else {
    // No QR for this method (e.g. wallet push): send the hosted checkout link.
    await channels.sendText(convo.id, `You can pay here: ${payment.checkout_url}`);
  }
}

// Some channels only take an image URL, not a file: upload the PNG to your own storage
// first, or send the checkout_url / a payment link instead.
```

`qr_payload` is only set for QR payments; for wallet push it is `null`, so send the link. Don't crop or restyle the QR, and keep the quiet margin around it so banking apps can read it.

## Safety rules

- **Use a restricted key.** `payments:write` and `payments:read` only. Keep the key on your server, never in a prompt or a client.
- **Idempotency key = conversation + order id.** Agents retry: a tool call can time out, or the model can call the tool twice. Send `Idempotency-Key: <conversation id>:<order id>` so a retry returns the same payment instead of a second one. When you deliberately need a new payment for the same order (the last one expired), add an attempt number. See [Idempotency](/concepts/idempotency.md).
- **Never let the model choose the amount freely.** Compute the amount on your server from the order. If the model passes an amount, only compare it with the order's total and refuse a mismatch; always charge the total from your own data.
- **Only the webhook says "paid".** Verify the `Klink-Signature` header, check the amount and reference against your order, then tell the customer. Never trust a customer's "I paid" message, a screenshot, or the model's own belief. See [Verifying signatures](/guides/webhooks.md#verifying-signatures).
- **Deduplicate events.** Webhooks can arrive more than once; store the event `id` so the agent doesn't confirm an order twice.
- **Handle the other outcomes.** On `payment.expired` or `payment.failed`, let the agent offer a new link. Set `expires_in_minutes` to match how long a chat order should stay open.
- **Keep refunds out of the agent.** Refunds are requests processed by K-LINK; start them from your dashboard or back office with a separate key, not from a model.

## Testing your agent

With an `rk_test_…` key every payment is a test payment. Open its `checkout_url` and press **Simulate payment** or **Simulate failure**: your webhook gets the event exactly as in live mode, so you can test the whole conversation without moving real money. See [Test mode](/testing.md).

> [!NOTE]
> **Payment methods and currencies** K-LINK Pay takes QR payments on Southeast Asia's national QR standards, wallet push and cards. Each payment is in the currency of one of your currency accounts, and a currency works in live mode once its account is active. See [Amounts and currencies](/concepts/currencies.md). Every method uses the same API and webhooks, so the flow above stays the same.
