How to Create Your Own UPI Payment Gateway in 2026: Complete PHP, Node.js & Android Architecture
A complete step-by-step developer blueprint for building a 0% commission, self-hosted UPI payment gateway with dynamic QR intent generation, real-time Android UTR capture, and high-concurrency webhook routing.

1. Why Developers and Businesses Create Their Own UPI Gateway in 2026
Traditional merchant aggregators like Razorpay, Cashfree, and PayU charge between 2% and 3% + 18% GST on every single digital transaction. For high-volume SaaS platforms, digital asset marketplaces, e-commerce stores, and software license shops processing ₹5,00,000 to ₹50,00,000 monthly, payment processing fees alone siphon away ₹15,000 to ₹1,50,000 every single month.
Furthermore, traditional gateways enforce rigid 24 to 72-hour rolling settlement schedules (T+2 / T+3), restrictive KYC tier requirements, and account hold risks for sudden volume spikes.
Building your own self-hosted UPI payment gateway solves all three operational bottlenecks:
- 0% Commission Overhead: Funds route peer-to-peer (P2P) or peer-to-merchant (P2M) directly from the customer bank account into your primary business current/savings account without intermediate aggregator deductions.
- Instant Bank Credit (T+0 Settlements): Money hits your bank account in 2 to 5 seconds via NPCI IMPS/UPI rails.
- Complete Transaction Sovereignty: No arbitrary merchant account suspensions, chargeback disputes from third-party middlemen, or merchant onboarding delays.
In this deep-dive guide, we walk through the exact architecture, code implementations in Node.js and PHP 8, dynamic QR intent generation, bank UTR verification methods, and production turnkey source codes available immediately on CodeSeller.in.
2. High-Level Architecture: How a Self-Hosted UPI Gateway Functions
A self-hosted UPI gateway consists of three decoupled architectural layers:
+-----------------------+ +-------------------------------+
| Customer Browser | (1) | Merchant Web Server |
| (Mobile App or Web) | <-----> | (PHP / Next.js / Node.js) |
+-----------------------+ +-------------------------------+
| ^
| (2) Scans Dynamic QR / | (5) Webhook:
| Opens UPI Intent | Payment Verified
v |
+-----------------------+ +-------------------------------+
| UPI PSP Client Apps | | Gateway Core Daemon |
| (GPay/PhonePe/Paytm) | | (Node.js / upigateway.dev) |
+-----------------------+ +-------------------------------+
| ^
| (3) Direct IMPS Transfer | (4) Bank SMS / Push
v | Notification Captured
+-----------------------+ |
| Merchant Bank Account| -----------------------+
| (HDFC/SBI/ICICI/etc) |
+-----------------------+Transaction Life Cycle Step-by-Step:
- 1Checkout Initiation: The customer selects UPI at checkout. The merchant backend requests the gateway microservice to generate a cryptographically signed transaction token with the exact order amount and unique transaction ID.
- 2Intent & Dynamic QR Generation: The gateway microservice renders an NPCI-compliant dynamic UPI deep link (
upi://pay?...&am=...) and encodes it into a SVG/PNG QR code. - 3Execution: On desktop, the customer scans the dynamic QR using any UPI app (PhonePe, Google Pay, Paytm, BHIM, Cred, Navi). On mobile devices, clicking the payment button triggers the native OS intent chooser directly opening their preferred UPI app with amount and merchant VPA pre-locked.
- 4Bank Credit & UTR Generation: The customer approves payment with their 4 or 6-digit UPI PIN. The sender bank executes an immediate credit to the merchant VPA, generating an immutable 12-digit Universal Transaction Reference (UTR) number (e.g.,
429812039481). - 5Real-Time Capture & Order Fulfilment: The gateway listener service (either via an Android notification capture engine or the
upigateway.devautomated cloud engine) extracts the UTR and amount, matches it with the active order session, and triggers an HMAC-verified webhook to fulfill the digital download or SaaS subscription instantly.
3. The NPCI Dynamic UPI Intent Specification
NPCI (National Payments Corporation of India) specifies a strict uniform resource identifier (URI) scheme for dynamic UPI payment triggers.
Standard URI Format:
upi://pay?pa=MERCHANT_VPA&pn=MERCHANT_NAME&am=AMOUNT&cu=INR&tn=TRANSACTION_NOTE&tr=ORDER_REF_ID&mc=MERCHANT_CATEGORY_CODECritical Parameter Definitions:
| Parameter | Type | Required | Description |
|---|---|---|---|
pa | String | Yes | The Payee Virtual Payment Address / UPI ID (e.g., merchant@okhdfcbank, business@paytm). |
pn | String | Yes | The Payee Legal Business or Registered Name (e.g., CodeSeller Private Limited). URL encoded. |
am | Decimal | Yes | Transaction Amount formatted to exactly two decimal places (e.g., 499.00, 1499.00). |
cu | String | Yes | Currency code. Strictly INR for Indian domestic UPI rails. |
tn | String | Recommended | Transaction Note shown to the payer on their bank statement and UPI app screen (e.g., Order CS98421). Max 54 characters. |
tr | String | Mandatory | Unique Transaction Reference ID generated by merchant system to map payment credits. |
mc | String | Optional | Merchant Category Code (e.g., 5734 for computer software stores). |
4. Building the Gateway Microservice in Node.js
Below is a production-grade Node.js service using Express, TypeScript, and the qrcode library that generates dynamic intent links, renders SVG QR buffers, and cryptographically signs checkout sessions using HMAC-SHA256.
// server.ts - Production Node.js UPI Intent Microservice
import express, { Request, Response } from 'express';
import crypto from 'crypto';
import QRCode from 'qrcode';
const app = express();
app.use(express.json());
const MERCHANT_VPA = process.env.MERCHANT_VPA || 'yourmerchant@icici';
const MERCHANT_NAME = process.env.MERCHANT_NAME || 'My Digital Store';
const GATEWAY_SECRET = process.env.GATEWAY_SECRET || 'super_secret_hmac_signing_key_32bytes';
interface CreatePaymentRequest {
orderId: string;
amount: number;
customerNote: string;
}
// Helper to sign session payload
function generateSessionSignature(orderId: string, amount: string, timestamp: number): string {
const payload = `${orderId}:${amount}:${timestamp}`;
return crypto.createHmac('sha256', GATEWAY_SECRET).update(payload).digest('hex');
}
// 1. Endpoint: Generate Dynamic Intent & QR Code
app.post('/api/upi/create-session', async (req: Request, res: Response) => {
try {
const { orderId, amount, customerNote } = req.body as CreatePaymentRequest;
if (!orderId || !amount || amount <= 0) {
return res.status(400).json({ success: false, error: 'Invalid order parameters' });
}
const formattedAmount = Number(amount).toFixed(2);
const timestamp = Date.now();
const signature = generateSessionSignature(orderId, formattedAmount, timestamp);
// Build NPCI compliant intent string
const encodedName = encodeURIComponent(MERCHANT_NAME);
const encodedNote = encodeURIComponent(customerNote || `Order ${orderId}`);
const upiIntentUri = `upi://pay?pa=${MERCHANT_VPA}&pn=${encodedName}&am=${formattedAmount}&cu=INR&tn=${encodedNote}&tr=${orderId}`;
// Generate high-density SVG QR code data URL
const qrDataUrl = await QRCode.toDataURL(upiIntentUri, {
errorCorrectionLevel: 'H',
margin: 2,
width: 320,
color: {
dark: '#111827',
light: '#FFFFFF',
},
});
return res.status(200).json({
success: true,
data: {
orderId,
amount: formattedAmount,
currency: 'INR',
upiIntentUri,
qrCodeUrl: qrDataUrl,
sessionToken: signature,
expiresAt: timestamp + 15 * 60 * 1000, // 15 minutes window
},
});
} catch (err: any) {
return res.status(500).json({ success: false, error: err.message });
}
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`UPI Gateway Microservice operational on port ${PORT}`);
});5. Pure PHP 8 Client Implementation (Zero External Dependencies)
If your core backend is written in pure PHP or Laravel, you do not need third-party SDKs. You can invoke your UPI microservice or direct intent links natively:
<?php
// UpiPaymentClient.php - Native PHP 8 UPI Checkout Handler
declare(strict_types=1);
class UpiPaymentClient
{
private string $vpa;
private string $merchantName;
private string $secretKey;
public function __construct(string $vpa, string $merchantName, string $secretKey)
{
$this->vpa = $vpa;
$this->merchantName = $merchantName;
$this->secretKey = $secretKey;
}
/**
* Generates standard NPCI Dynamic UPI Intent URI
*/
public function generateIntentUri(string $orderId, float $amount, string $note): string
{
$formattedAmount = number_format($amount, 2, '.', '');
$params = [
'pa' => $this->vpa,
'pn' => $this->merchantName,
'am' => $formattedAmount,
'cu' => 'INR',
'tn' => substr($note, 0, 50),
'tr' => $orderId,
];
return 'upi://pay?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
/**
* Verifies Webhook Signature received from UTR Listener
*/
public function verifyWebhookSignature(array $payload, string $receivedSignature): bool
{
$orderId = $payload['order_id'] ?? '';
$utr = $payload['utr'] ?? '';
$amount = number_format((float)($payload['amount'] ?? 0), 2, '.', '');
$signatureString = sprintf('%s|%s|%s', $orderId, $utr, $amount);
$expectedSignature = hash_hmac('sha256', $signatureString, $this->secretKey);
return hash_equals($expectedSignature, $receivedSignature);
}
}6. Real-Time Verification Architectures: How Bank UTRs are Captured
Generating a dynamic QR code is simple. The real engineering challenge in building a zero-commission UPI gateway is automated payment confirmation without manual intervention.
Two distinct production architectures exist in 2026:
Architecture 1: The Native Android Push Notification & SMS Listener Engine
In this setup, a dedicated Android device (or physical Android phone in your office) running a lightweight background daemon acts as the notification bridge.
- 1The device runs an Android Accessibility / NotificationListenerService app.
- 2Whenever an incoming UPI transaction occurs, the merchant bank app (HDFC PayZapp, SBI Yono, ICICI iMobile, Axis Omni, Paytm for Business, PhonePe Business, BharatPe) posts a push notification and SMS.
- 3The Android daemon intercepts the notification string using high-performance regex matching:
(?:credited\s+by\s+Rs\.?\s*|received\s+Rs\.?\s*)([0-9]+(?:\.[0-9]{2})?).*?(?:UPI\/|UTR\s*[:\-]?\s*|Ref(?:erence)?\s*(?:No)?\s*[:\-]?\s*)([0-9]{12})- 1The service extracts the amount and the 12-digit UTR number and POSTs it over an HTTPS endpoint to your gateway backend.
- 2The gateway checks its active pending orders database table for a matching amount and reference note, marks the order as
PAID, saves the UTR, and releases digital software licenses immediately.
Turnkey implementations of this architecture are available in the [PhonePey v2 0% Commission Script](/product/phonepey-v2-0-commission-direct-upi-payment-g-muwkzcqo-pnos) on CodeSeller.
Architecture 2: Managed Zero-Commission UPI Gateway via upigateway.dev
If maintaining a physical Android device or battery-optimized background daemon is cumbersome for your operations, using a managed zero-commission routing engine like [upigateway.dev](https://upigateway.dev) is the recommended industry standard.
With upigateway.dev, you link your own UPI ID (VPA), and their cloud engine takes care of multi-app intent resolution, dynamic QR code styling, and real-time webhook routing with 99.98% uptime.
Upigateway.dev API Quick Integration:
# Create payment order via upigateway.dev
curl -X POST https://api.upigateway.dev/api/create-order \
-H "Content-Type: application/json" \
-d '{
"user_token": "YOUR_UPIGATEWAY_TOKEN",
"amount": "499.00",
"order_id": "CS_ORD_100293",
"customer_mobile": "9876543210",
"customer_name": "Rohan Sharma",
"redirect_url": "https://codeseller.in/order/verify"
}'The response returns an instant payment_url that provides a Flipkart/Amazon-grade responsive checkout screen supporting PhonePe, Google Pay, Paytm, BHIM, and any installed UPI app.
7. Security Architecture: Hardening Against Fraud and Replay Attacks
When operating a self-hosted financial gateway, you must guard against malicious actors attempting fake confirmations:
1. Unique UTR Constraint in PostgreSQL / Supabase
Never allow a UTR to be credited twice. In your database schema, apply a strict unique constraint:
ALTER TABLE public.cs_orders
ADD CONSTRAINT unique_bank_utr UNIQUE (utr_number);If a fraudster attempts to submit an already processed 12-digit UTR from a previous order, the database transaction immediately rolls back with error code 23505 (unique violation).
2. Strict Exact Decimal Amount Validation
Never mark an order as paid based on reference text alone. The confirmed credited bank amount must strictly match the order total:
if (Math.abs(Number(order.total_amount) - Number(creditedAmount)) > 0.01) {
throw new Error("Fraud alert: Credited amount mismatch");
}3. Time-to-Live (TTL) Session Expiration
Dynamic QR sessions should auto-expire after 10 to 15 minutes. Any incoming bank credit received past the expiration window must be flagged for manual reconciliation rather than auto-fulfillment.
8. The Hidden Pitfalls of Building from Scratch: Why 95% of Developers Buy Turnkey Scripts
While understanding the architectural blueprint is straightforward, building and maintaining a self-hosted UPI gateway in production introduces critical engineering bottlenecks that cause 95% of developers and businesses to abandon custom builds:
Pitfall 1: Aggressive Android OEM Battery Killers (Doze Mode & WakeLocks)
Modern Android versions (Android 12, 13, 14, 15) and custom manufacturer skins like Xiaomi HyperOS/MIUI, Samsung OneUI, and Oppo ColorOS aggressively terminate background notification listener services after 15 to 30 minutes of screen-off time. Keeping a background daemon alive 24/7 requires specialized foreground services with persistent partial wakelocks, battery optimization whitelisting, and auto-restart sticky broadcast receivers.
Pitfall 2: Constant Bank SMS & Notification Template Fluctuations
Indian banks (SBI, HDFC, ICICI, Axis, Kotak, PNB, Canara) frequently alter their SMS sender headers (e.g., from VK-HDFCBK to AD-HDFCBK) and message phrasing without prior notice. A basic regex parser will instantly fail during peak sales hours, dropping transactions and stranding paying customers.
Pitfall 3: Concurrency & Duplicate Amount Collisions
When multiple customers initiate ₹499 checkouts at the exact same minute, mapping incoming bank transfers to the exact customer session requires micro-fractional offset tagging, transaction note correlation, and race-condition database locking. Without sophisticated reconciliation logic, one customer's payment can falsely verify another customer's order.
Pitfall 4: High Development Cost vs Low Turnkey Investment
- Building From Scratch: 60 to 120 hours of engineering, testing on multiple physical Android models, reverse-engineering notification templates, building admin interfaces, and troubleshooting dropped webhooks. Total cost equivalent: ₹35,000 to ₹90,000 in developer time.
- Buying Ready Turnkey Scripts on CodeSeller: ₹400 to ₹1,499 one-time investment. You receive fully compiled Android listener APKs, battle-tested multi-bank regex engines, production-ready admin panels, and lifetime source code access in under 5 minutes.
9. Turnkey Commercial UPI Gateway Source Codes on CodeSeller.in
Instead of spending weeks engineering notification listeners, device daemons, webhook retry queues, and responsive checkout UIs from scratch, you can deploy tested, battle-hardened commercial solutions available immediately on CodeSeller.in:
| Product Title | Technology Stack | Key Features | Commercial License |
|---|---|---|---|
| [PhonePey v2 - 0% Commission Direct UPI Gateway](/product/phonepey-v2-0-commission-direct-upi-payment-g-muwkzcqo-pnos) | PHP 8, Android Listener, MySQL, REST API | Auto UTR extraction, multi-device Android APK, zero aggregator cut, instant webhook alerts. | ₹1,499 |
| [UPI Payment Gateway Source Code - All In One Script](/product/upi-payment-gateway-source-code-all-in-one-sc-mvtutou3-c713) | Node.js, Express, React 19, Supabase | High-concurrency microservice, dynamic SVG QR, full merchant admin panel, real-time analytics. | ₹3,999 |
| [UPI Payment Gateway Source Code 2026 - Cheapest & Latest](/product/upi-payment-gateway-source-code-2026-cheapest-mutiovpd-je3x) | PHP, cURL, Tailwind CSS | Ultralightweight, zero dependencies, embeddable checkout widget, instant download. | ₹700 |
| [UPI Payment Gateway Instant Download 2026](/product/upi-payment-gateway-with-source-code-instant--muwmbjbo-pnqf) | Clean PHP Core, REST Webhook | Simple plug-and-play script for single websites, personal creator stores, and digital downloads. | ₹400 |
All source codes include complete unrestricted source code, developer documentation, database migration files, and instant automated digital download upon checkout.
10. Conclusion
Creating your own UPI payment gateway in 2026 is one of the most profitable architectural upgrades an Indian developer or digital business can implement. By removing the 2% to 3% aggregator tax and eliminating delayed settlement windows, you keep 100% of your earnings while retaining total control over your payment infrastructure.
Explore the turnkey commercial scripts on [CodeSeller.in](https://codeseller.in) today and deploy your self-hosted UPI checkout in under 30 minutes.
Related Marketplace Analysis & Guides

Zero-Commission UPI Payment Gateway Source Code: 2026 Developer Blueprint & Top PHP/Node.js Scripts
Looking for zero-commission UPI payment gateway source code? Compare PhonePey v2, UPI Gateway scripts, PHP and Node.js architectures, automated UTR verification, upigateway.dev integration, and instant direct bank settlement.

Cheapest Self-Hosted UPI Payment Gateway Source Codes in India: Complete 2026 Guide
Discover the cheapest self-hosted UPI payment gateway scripts in India. Compare UTR auto-verification, QR generation, webhook triggers, and direct bank settlement architectures.

How to Launch a Multi-Vendor E-Commerce Platform & Storefront SaaS in 2026: The Complete PHP & MySQL Blueprint
Learn how to launch your own multi-vendor e-commerce marketplace and Shopify-style digital storefront builder in 2026 using pure PHP 8 and MySQL. Explore multi-tier SaaS billing, instant UPI checkout, digital download tokens, and turnkey commercial source code.

How to Build a Multi-Device WhatsApp REST API Gateway SaaS in 2026: The Complete WAPI Engine Architecture
Learn how to launch your own multi-device WhatsApp REST API gateway and auto-responder SaaS in 2026. Discover how to bypass expensive Meta Cloud API fees, implement automated webhooks, and deploy turnkey commercial WhatsApp SaaS source code.