Choose your integration
There are three ways to use UPIDirect. Start with the one that fits you; you can add the others later.
How money flows
UPIDirect never touches the money. The payer’s bank sends it to your bank over UPI, to the UPI ID you set in Settings. We create the request, show the payment page, track the status and tell your systems.
payment_url and taps “Pay with UPI”paidpayment_request.paid reaches your serverhttps://upidirect.codepeacock.com/api. All amounts are in rupees, with up to 2 decimals: 2000, 2000.50 or 99.99. You may send a number or a string. The minimum is ₹1 and the maximum ₹5,00,000.Payment links (no code)
- Create an account and add your UPI ID under Settings.
- Click New payment link, enter the amount, what it is for and, if you like, the payer’s name and mobile number.
- Copy the link, or press WhatsApp to send it straight to the payer. The link page has a UPI button for phones and a QR code for computers.
- When the payer has paid and entered their UTR, the payment appears under To confirm. Check it in your bank app and press Received.
You can also put a link behind a “Pay now” button on any web page, in an email or in a PDF invoice. Each link is for one payment, so create a new link for each invoice or fee.
Keys and test mode
Create keys under Dashboard → Developers.
sk_test_…keys create test payments. The payment page shows Simulate successful payment instead of real UPI, and no money moves. Use these while you build.sk_live_…keys create real payments. They work after your UPI ID is set and we have approved your account.
Send the key in the Authorization header: Authorization: Bearer sk_test_…. Check that a key works with GET /v1/me.
Website checkout
The usual website flow is: the customer clicks “Pay”, your server creates a payment request and redirects them to payment_url. After paying, they can come back to your return_url. Your server marks the order paid only when the payment_request.paid webhook arrives, never because the browser came back.
curl -X POST https://upidirect.codepeacock.com/api/v1/payment_requests \
-H "Authorization: Bearer sk_test_..." \
-H "Content-Type: application/json" \
-H "Idempotency-Key: fee-stu_123-2026-12" \
-d '{
"amount": 2000.50,
"purpose": "December fee",
"customer": { "name": "Ravi Kumar", "phone": "9876543210", "external_ref": "stu_123" },
"external_ref": "invoice_789",
"return_url": "https://yoursite.com/fees/thanks",
"metadata": { "student_id": "stu_123", "month": "2026-12" }
}'// Express route: create the payment request, then send the payer to the payment page
app.post('/pay/:orderId', async (req, res) => {
const order = await db.orders.find(req.params.orderId)
const r = await fetch('https://upidirect.codepeacock.com/api/v1/payment_requests', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.UPIDIRECT_SECRET_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': `order-${order.id}`,
},
body: JSON.stringify({
amount: order.total, // rupees, e.g. 2000.50,
purpose: `Order #${order.id}`,
customer: { name: order.name, phone: order.phone },
external_ref: String(order.id),
return_url: `https://yoursite.com/orders/${order.id}`,
}),
})
if (!r.ok) return res.status(502).send('Could not start payment')
const pr = await r.json()
await db.orders.update(order.id, { upidirect_id: pr.id })
res.redirect(303, pr.payment_url)
})<?php
// pay.php: create the payment request, then send the payer to the payment page
$order = load_order($_GET['order']);
$ch = curl_init('https://upidirect.codepeacock.com/api/v1/payment_requests');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('UPIDIRECT_SECRET_KEY'),
'Content-Type: application/json',
'Idempotency-Key: order-' . $order['id'],
],
CURLOPT_POSTFIELDS => json_encode([
'amount' => $order['total'],
'purpose' => 'Order #' . $order['id'],
'customer' => ['name' => $order['name'], 'phone' => $order['phone']],
'external_ref' => (string) $order['id'],
'return_url' => 'https://yoursite.com/orders/' . $order['id'],
]),
]);
$pr = json_decode(curl_exec($ch), true);
header('Location: ' . $pr['payment_url'], true, 303);# Flask route: create the payment request, then send the payer to the payment page
import os, requests
from flask import redirect
@app.post("/pay/<order_id>")
def pay(order_id):
order = db.get_order(order_id)
r = requests.post(
"https://upidirect.codepeacock.com/api/v1/payment_requests",
headers={
"Authorization": f"Bearer {os.environ['UPIDIRECT_SECRET_KEY']}",
"Idempotency-Key": f"order-{order.id}",
},
json={
"amount": order.total,
"purpose": f"Order #{order.id}",
"customer": {"name": order.name, "phone": order.phone},
"external_ref": str(order.id),
"return_url": f"https://yoursite.com/orders/{order.id}",
},
timeout=15,
)
r.raise_for_status()
return redirect(r.json()["payment_url"], code=303)Create a payment request
POST /v1/payment_requests. Always send an Idempotency-Key header (for example your order ID). If you retry with the same key, you get the same request back instead of a duplicate.
| Field | Type | Description |
|---|---|---|
amount | number, required | Amount in rupees, up to 2 decimals, from 1 to 500000 (e.g. 2000.94). |
purpose | string, required | What the payment is for (up to 80 characters). Shown to the payer. |
customer | object | name, phone (10 to 15 digits), email, external_ref (your customer ID). |
external_ref | string | Your own ID for this payment, such as an order or invoice ID. Returned in webhooks. |
return_url | URL | Where the payer can continue after the payment is confirmed. |
expires_at | ISO 8601 date-time | When the link stops accepting payments. Default: 30 days. |
metadata | object | Up to 20 keys of your own data (strings, numbers, booleans). Returned unchanged. |
The response is 201 Created, or 200 when the same Idempotency-Key was used before.
The payment request object
{
"id": "4b1c2f0e-…",
"object": "payment_request",
"reference": "UPD-7K2M9QX4",
"mode": "test",
"status": "pending", // pending | paid | expired | cancelled | disputed
"amount": 2000.50,
"currency": "INR",
"purpose": "December fee",
"customer": { "name": "Ravi Kumar", "phone": "9876543210", "email": null, "external_ref": "stu_123" },
"external_ref": "invoice_789",
"metadata": { "student_id": "stu_123", "month": "2026-12" },
"payment_url": "https://upidirect.codepeacock.com/r/UPD-7K2M9QX4",
"upi_uri": null, // live mode: the raw upi://pay link
"awaiting_confirmation": false, // true once the payer has entered a UTR
"confirmation": null, // { "utr": "412345678901", … } when confirmed
"return_url": "https://yoursite.com/fees/thanks",
"expires_at": "2027-01-03T10:00:00.000Z",
"paid_at": null,
"created_at": "2026-12-04T10:00:00.000Z"
}upi_uri is only set in live mode. Mobile apps can open it directly to launch the payer’s UPI app.
All endpoints
| Method and path | What it does |
|---|---|
POST /v1/payment_requests | Create a payment request |
GET /v1/payment_requests/:id | Get one request |
GET /v1/payment_requests | List requests, newest first. Filters: status, external_ref, limit (up to 100), starting_after (an ID, for paging) |
POST /v1/payment_requests/:id/cancel | Cancel a pending request |
POST /v1/payment_requests/:id/confirm | Mark as received, optionally with { "utr": "412345678901" } |
GET /v1/webhook_endpoints | List webhook URLs |
POST /v1/webhook_endpoints | Add a webhook URL: { "url": "https://…" } |
DELETE /v1/webhook_endpoints/:id | Remove a webhook URL |
GET /v1/me | Check which account and mode a key belongs to |
Webhook events
Add your webhook URL under Dashboard → Developers (separately for test and live) and copy its signing secret (whsec_…).
| Event | When it is sent |
|---|---|
payment_request.paid | The payment is confirmed. Fulfil the order here. |
payment_request.utr_submitted | The payer says they have paid and entered a UTR. It is waiting for your check. |
payment_request.expired | The link expired before it was paid. |
payment_request.cancelled | The request was cancelled. |
Each delivery is a POST with a JSON body { id, type, mode, created_at, data }, where data is the payment request object. Headers: UPD-Signature, UPD-Event-Id and UPD-Event-Type.
Reply with any 2xx status within a few seconds. If your server fails or times out, we retry with increasing delays for 24 hours. Because of retries, the same event can arrive more than once: store UPD-Event-Id and ignore repeats, and make your update idempotent (for example UPDATE … WHERE status <> 'paid').
Verify webhook signatures
The UPD-Signature header looks like t=1764842400,v1=5f2b…. v1 is the hex HMAC-SHA256 of "{t}.{raw body}" with your signing secret. Always verify it, and reject events older than five minutes. Use the raw request body: parsing and re-serialising the JSON changes the bytes and the check fails.
import { createHmac, timingSafeEqual } from 'node:crypto'
function verifyUpiDirect(rawBody, header, secret) {
const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? '')
if (!m) return false
const [, t, sig] = m
if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false // older than 5 minutes
const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex')
return timingSafeEqual(Buffer.from(expected), Buffer.from(sig))
}
// Express: read the RAW body, never re-serialised JSON
app.post('/upidirect/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
const raw = req.body.toString('utf8')
if (!verifyUpiDirect(raw, req.get('UPD-Signature'), process.env.UPIDIRECT_WEBHOOK_SECRET)) return res.sendStatus(400)
const event = JSON.parse(raw)
if (await db.events.seen(event.id)) return res.sendStatus(200) // retries can repeat an event
if (event.type === 'payment_request.paid') {
await db.orders.markPaid(event.data.external_ref, { utr: event.data.confirmation?.utr })
}
await db.events.remember(event.id)
res.sendStatus(200)
})<?php
// webhook.php
function verify_upidirect(string $raw, ?string $header, string $secret): bool {
if (!preg_match('/^t=(\d+),v1=([0-9a-f]{64})$/', $header ?? '', $m)) return false;
if (abs(time() - (int) $m[1]) > 300) return false; // older than 5 minutes
$expected = hash_hmac('sha256', $m[1] . '.' . $raw, $secret);
return hash_equals($expected, $m[2]);
}
$raw = file_get_contents('php://input');
if (!verify_upidirect($raw, $_SERVER['HTTP_UPD_SIGNATURE'] ?? null, getenv('UPIDIRECT_WEBHOOK_SECRET'))) {
http_response_code(400); exit;
}
$event = json_decode($raw, true);
if ($event['type'] === 'payment_request.paid') {
// Idempotent: only flips orders that are not paid yet
mark_order_paid($event['data']['external_ref'], $event['data']['confirmation']['utr'] ?? null);
}
http_response_code(200);import hashlib, hmac, os, re, time
from flask import request
def verify_upidirect(raw: bytes, header: str | None, secret: str) -> bool:
m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")
if not m:
return False
t, sig = m.groups()
if abs(time.time() - int(t)) > 300: # older than 5 minutes
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, sig)
@app.post("/upidirect/webhook")
def upidirect_webhook():
raw = request.get_data() # raw bytes, before any JSON parsing
if not verify_upidirect(raw, request.headers.get("UPD-Signature"), os.environ["UPIDIRECT_WEBHOOK_SECRET"]):
return "", 400
event = request.get_json()
if event["type"] == "payment_request.paid":
mark_order_paid(event["data"]["external_ref"], (event["data"].get("confirmation") or {}).get("utr"))
return "", 200Example: Supabase Edge Functions
This is how School of Carnatic Music connects its fee system:
- Store the keys as secrets:
supabase secrets set UPIDIRECT_SECRET_KEY=sk_test_… UPIDIRECT_WEBHOOK_SECRET=whsec_… - Edge Function
create-fee-payment: checks the logged-in parent, loads the fee, callsPOST /v1/payment_requestswithexternal_refandIdempotency-Keyset to the fee ID, and returnspayment_urlto the app. - Edge Function
upidirect-webhook(public URL, added in the dashboard): verifies the signature with the Node.js code above (it works in Deno withnode:cryptoandnode:buffer), and onpayment_request.paidmarks the fee withid = data.external_refas paid. - Test end to end with a test key and the Simulate successful payment button, then switch to the live key.
How payments are confirmed
UPI does not send an automatic receipt to a personal or business UPI ID, so today a request becomes paid when:
- the payer enters the 12-digit UTR from their UPI app and you press Received under To confirm after checking your bank, or
- you mark it paid yourself in the dashboard or with
POST /confirm.
Next, we are adding automatic matching from your bank statement, and later direct bank connections for real-time confirmation. Your integration does not change: you always just listen for payment_request.paid.
Errors and retries
Errors always have the same shape:
{ "error": { "code": "invalid_request", "message": "amount: must be between ₹1 and ₹5,00,000" } }| Status | Meaning |
|---|---|
400 | The request is invalid. The message says which field. |
401 | The API key is missing, wrong or revoked. |
404 | No such payment request for this key’s account and mode. |
409 | The action does not fit the current status (for example cancelling a paid request). |
429 | Too many requests. Wait a moment and retry. |
5xx | Our side failed. Retry with the same Idempotency-Key. |
Go-live checklist
- Your UPI ID and the name payers see are set in Settings, and your account shows Active.
- The full flow works in test mode: create, pay with Simulate, webhook received, order marked paid.
- Your webhook handler verifies signatures, ignores repeated event IDs and replies
200quickly. - You have created a live key, stored it as a server secret, and added a live webhook URL.
- You made one small real payment (for example ₹1) to yourself and saw it marked paid.
Get help
Stuck on an integration? Write to info@codepeacock.com with your business name and, if you have one, the payment reference (UPD-…). Never send us your secret key.