Integrate zero-fee Indian UPI payments across custom backends (PHP, Node.js, Python, Java, C#, Go), mobile apps (Android, iOS), WooCommerce, WHMCS, SMM panels, and game top-up stores with production-ready code.
The UPIGateway.dev platform operates on a high-speed, direct server-to-server REST architecture. Every checkout workflow is designed for maximum speed and bank-grade security:
Your backend sends a POST request with order amount, unique order ID, and user token. You receive a dynamic hosted payment URL.
Customer scans the dynamic QR code or taps UPI Intent (PhonePe, GPay, Paytm, BHIM). Funds credit directly into your linked bank account with 0% gateway deductions.
Our engine validates the UPI UTR in real-time and sends an HTTP POST webhook to your server so you can auto-fulfill orders instantly.
user_token. Keep this token strictly on your backend server.
Every SDK includes helper classes for creating orders, validating transaction statuses, and securely parsing incoming webhook callbacks.
Zero-touch dynamic UPI QR checkout with automated WooCommerce order completion.
Complete WHMCS payment gateway. Automatically marks invoices Paid upon UPI settlement.
cURL client, webhook validator, and status checker for Laravel, CodeIgniter, or vanilla PHP.
Async client for Express, Next.js, and serverless runtimes with webhook signature validation.
Synchronous & async client for FastAPI, Django, Flask, and automation scripts.
Retrofit 2 client and UPI deep-link Intent caller for PhonePe, Google Pay, and Paytm apps.
Enterprise Spring Boot SDK with pom.xml, RestTemplate client, and WebhookController.
ASP.NET Core package with HttpClient wrappers, async order creation, and callback models.
Modern coroutines-based Kotlin client for Android Compose and multiplatform setups.
iOS Swift Package Manager (SPM) SDK supporting UPI URL schemes and callback delegates.
Ruby gem for Rails apps, providing payment intents, webhook handlers, and error resilience.
High-performance C++ integration library for POS machines, self-checkout kiosks, and IoT devices.
<?php
/**
* UPIGateway PHP Integration (Create Order & Webhook Listener)
*/
// A. Initiate Order & Redirect Customer
$apiUrl = "https://online.upigateway.dev/api/create-order";
$userToken = getenv('UPI_USER_TOKEN') ?: "YOUR_MERCHANT_API_TOKEN";
$payload = [
"customer_mobile" => "9876543210",
"user_token" => $userToken,
"amount" => "299.00",
"order_id" => "UPG_" . time() . rand(100, 999),
"redirect_url" => "https://yourdomain.com/payment-complete.php",
"remark1" => "User_102",
"remark2" => "VIP_Pass"
];
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if (!empty($result['status']) && !empty($result['result']['payment_url'])) {
header("Location: " . $result['result']['payment_url']);
exit;
}
// B. Webhook Listener (webhook.php)
$input = file_get_contents('php://input');
$event = json_decode($input, true);
if (!empty($event) && $event['status'] === 'SUCCESS') {
$orderId = $event['orderId'];
$utr = $event['utr'];
$amount = $event['amount'];
// Prevent double-spend: ensure UTR is unique in DB
// $pdo->prepare("UPDATE orders SET status='PAID', utr=? WHERE order_id=?")->execute([$utr, $orderId]);
http_response_code(200);
echo json_encode(['status' => true, 'message' => 'Order fulfilled']);
exit;
}
?>
const express = require('express');
const app = express();
app.use(express.json());
const CONFIG = {
apiUrl: 'https://online.upigateway.dev/api',
token: process.env.UPI_USER_TOKEN || 'YOUR_USER_TOKEN'
};
// 1. Create Order
app.post('/api/create-payment', async (req, res) => {
const response = await fetch(`${CONFIG.apiUrl}/create-order`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
customer_mobile: req.body.mobile || '9876543210',
user_token: CONFIG.token,
amount: req.body.amount || '299',
order_id: `UPG_${Date.now()}`,
redirect_url: 'https://yourdomain.com/payment-complete',
remark1: req.body.userId || 'User_102'
})
});
const data = await response.json();
res.json(data);
});
// 2. Webhook Listener
app.post('/api/upi-webhook', async (req, res) => {
const { status, orderId, utr, amount } = req.body;
if (status === 'SUCCESS') {
// Fulfill order & record UTR idempotently
console.log(`Order ${orderId} completed with UTR: ${utr}`);
return res.status(200).json({ status: true });
}
res.status(200).json({ status: true, received: true });
});
app.listen(3000, () => console.log('UPI server ready on :3000'));
import requests
import time
from fastapi import FastAPI, Request
app = FastAPI()
API_BASE = "https://online.upigateway.dev/api"
TOKEN = "YOUR_MERCHANT_TOKEN"
def create_payment(amount: float, mobile: str):
res = requests.post(f"{API_BASE}/create-order", json={
"customer_mobile": mobile,
"user_token": TOKEN,
"amount": str(amount),
"order_id": f"UPG_{int(time.time())}",
"redirect_url": "https://mysite.com/complete",
"remark1": "FastAPI_Client"
})
return res.json()
@app.post("/webhook")
async def handle_webhook(request: Request):
payload = await request.json()
if payload.get("status") == "SUCCESS":
order_id = payload["orderId"]
utr = payload.get("utr")
# Fulfill customer purchase
return {"status": True, "message": "Fulfilled"}
return {"status": True}
// Java Spring Boot Integration
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.*;
@RestController
@RequestMapping("/api/upi")
public class UpiController {
private final String API_URL = "https://online.upigateway.dev/api/create-order";
private final String TOKEN = "YOUR_MERCHANT_TOKEN";
@PostMapping("/create")
public Map<String, Object> createOrder(@RequestBody Map<String, Object> req) {
RestTemplate rest = new RestTemplate();
Map<String, Object> body = new HashMap<>();
body.put("customer_mobile", req.getOrDefault("mobile", "9876543210"));
body.put("user_token", TOKEN);
body.put("amount", req.get("amount"));
body.put("order_id", "UPG_" + System.currentTimeMillis());
body.put("redirect_url", "https://mysite.com/paid");
return rest.postForObject(API_URL, body, Map.class);
}
@PostMapping("/webhook")
public Map<String, Object> webhook(@RequestBody Map<String, Object> event) {
if ("SUCCESS".equals(event.get("status"))) {
// Auto-credit user or dispatch services
}
return Collections.singletonMap("status", true);
}
}
// ASP.NET Core Controller
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Json;
[ApiController]
[Route]("api/[controller]")
public class PaymentController : ControllerBase
{
private readonly HttpClient _http = new HttpClient();
private const string API = "https://online.upigateway.dev/api/create-order";
private const string TOKEN = "YOUR_MERCHANT_TOKEN";
[HttpPost]("create")
public async Task<IActionResult> CreateOrder([FromBody] OrderDto req)
{
var body = new {
customer_mobile = req.Mobile,
user_token = TOKEN,
amount = req.Amount.ToString(),
order_id = $"UPG_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}",
redirect_url = "https://mysite.com/callback"
};
var res = await _http.PostAsJsonAsync(API, body);
var data = await res.Content.ReadFromJsonAsync<dynamic>();
return Ok(data);
}
}
# 1. Create Order
curl -X POST https://online.upigateway.dev/api/create-order \
-H "Content-Type: application/json" \
-d '{
"customer_mobile": "9876543210",
"user_token": "YOUR_MERCHANT_TOKEN",
"amount": "199.00",
"order_id": "UPG_CLI_10293",
"redirect_url": "https://yourdomain.com/payment-complete",
"remark1": "Terminal_CLI",
"remark2": "Test"
}'
# 2. Check Order Status
curl -X POST https://online.upigateway.dev/api/check-order-status \
-H "Content-Type: application/json" \
-d '{
"user_token": "YOUR_MERCHANT_TOKEN",
"order_id": "UPG_CLI_10293"
}'
Test how your backend handles incoming callbacks. Switch between success and failure states, change parameters, and inspect the resulting JSON payload.
upigateway_woocommerce_plugin.zip (contains upigateway-woocommerce folder)./wp-admin).https://yourdomain.com/?wc-api=upigateway_webhook. When a customer scans the dynamic QR and approves payment in any UPI app, WooCommerce updates the order status from Pending to Processing / Completed instantly!
WHMCS integration allows Indian web hosting companies, domain registrars, and cloud providers to accept direct UPI payments with zero payment gateway charges.
Extract upigateway_whmcs_module.zip and upload:
• upigateway.php to modules/gateways/
• callback/upigateway.php to modules/gateways/callback/
In WHMCS Admin, go to Configuration > System Settings > Payment Gateways. Under "All Payment Gateways", click UPIGateway to activate it.
Enter your Merchant API Token. When customers click "Pay with UPI", scan the QR, WHMCS automatically calls addInvoicePayment() to mark the invoice "Paid" and instantly provisions hosting!
In SMM Panels, users add funds to their wallet. With UPIGateway.dev, deposits are credited to the user's balance automatically with zero fee deductions. If your panel base currency is USD ($), auto-conversion to INR (₹) is built-in.
<?php
/**
* SMM Panel Automated UPI Add-Funds Gateway
* Place in your SMM payment modules directory or add_funds controller
*/
// 1. Handle User Deposit Request
if (isset($_POST['add_funds_upi'])) {
$userId = $_SESSION['user_id'];
$amountInr = floatval($_POST['amount_inr']); // Or convert USD: $amountUsd * 85.0
$userMobile = $_SESSION['user_mobile'] ?? '9876543210';
$orderId = 'UPG_SMM_' . $userId . '_' . time();
$postData = [
'customer_mobile' => $userMobile,
'user_token' => 'YOUR_UPIGATEWAY_TOKEN',
'amount' => strval($amountInr),
'order_id' => $orderId,
'redirect_url' => 'https://your-smm.com/addfunds?status=success',
'remark1' => 'SMM_USER_' . $userId,
'remark2' => strval($amountInr)
];
$ch = curl_init('https://online.upigateway.dev/api/create-order');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!empty($res['result']['payment_url'])) {
header('Location: ' . $res['result']['payment_url']);
exit;
}
}
// 2. SMM Webhook Callback (Auto Credit User Balance)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['upi_callback'])) {
$webhookData = json_decode(file_get_contents('php://input'), true);
if (!empty($webhookData) && $webhookData['status'] === 'SUCCESS') {
$utr = $webhookData['utr'];
$amount = floatval($webhookData['amount']);
$remark1 = $webhookData['remark1'];
$userId = intval(str_replace('SMM_USER_', '', $remark1));
// Check if UTR already exists in transactions table
$checkUtr = $db->query("SELECT id FROM transaction_logs WHERE utr = '$utr' LIMIT 1");
if ($checkUtr->num_rows == 0) {
// Credit user's wallet
$db->query("UPDATE users SET balance = balance + $amount WHERE id = '$userId'");
$db->query("INSERT INTO transaction_logs (user_id, amount, utr, type, status, created_at) VALUES ('$userId', '$amount', '$utr', 'UPI', 'COMPLETED', NOW())");
}
echo json_encode(['status' => true]);
exit;
}
}
?>
Game top-up platforms sell digital goods (e.g., FreeFire Diamonds, BGMI Unknown Cash, Valorant Points). With instant webhook callbacks, players receive their items in-game within seconds of paying via UPI.
<?php
/**
* Game Top-up Flow (Player ID + Package -> Instant Webhook Delivery)
*/
// Step 1: Gamer submits Player ID & Selects Pack
if (isset($_POST['buy_diamonds'])) {
$playerId = trim($_POST['player_uid']); // e.g., "198274619"
$packageId = trim($_POST['package_id']); // e.g., "520_diamonds"
$price = trim($_POST['price']); // e.g., "399.00"
$gamerPhone = trim($_POST['gamer_whatsapp']);
$orderId = 'UPG_GAME_' . time() . rand(10, 99);
$postData = [
'customer_mobile' => $gamerPhone,
'user_token' => 'YOUR_UPIGATEWAY_TOKEN',
'amount' => $price,
'order_id' => $orderId,
'redirect_url' => 'https://yourgamestore.com/order-status.php?oid=' . $orderId,
'remark1' => $playerId, // Player ID
'remark2' => $packageId // Package ID
];
$ch = curl_init('https://online.upigateway.dev/api/create-order');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!empty($res['result']['payment_url'])) {
header('Location: ' . $res['result']['payment_url']);
exit;
}
}
// Step 2: Top-up Webhook Listener (Auto-Deliver Diamonds to Player)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['topup_webhook'])) {
$data = json_decode(file_get_contents('php://input'), true);
if (!empty($data) && $data['status'] === 'SUCCESS') {
$playerId = $data['remark1'];
$packageId = $data['remark2'];
$utr = $data['utr'];
// Check idempotency before calling game API
if (!checkTopupProcessed($utr)) {
// Call Game Provider API (SmileOne / UniPin / Moogold)
deliverGameCredits($playerId, $packageId);
logTopupSuccess($playerId, $packageId, $utr);
}
echo json_encode(['status' => true, 'delivered' => true]);
exit;
}
}
?>
When building mobile applications, the smoothest checkout experience is launching the customer's preferred UPI app directly via standard UPI Intent URI:
// Launch UPI App Directly from Android Activity
val upiUri = Uri.parse("upi://pay?pa=YOUR_UPI_ID&pn=MERCHANT_NAME&tr=ORDER_ID&am=199.00&cu=INR")
val upiIntent = Intent(Intent.ACTION_VIEW, upiUri)
val chooser = Intent.createChooser(upiIntent, "Pay with UPI")
if (upiIntent.resolveActivity(packageManager) != null) {
startActivityForResult(chooser, UPI_PAYMENT_REQUEST_CODE)
} else {
Toast.makeText(this, "No UPI app found on your phone", Toast.LENGTH_SHORT).show()
}
// Handle Intent Result in onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == UPI_PAYMENT_REQUEST_CODE && data != null) {
val response = data.getStringExtra("response") ?: ""
// Example response: "txnId=...&responseCode=00&Status=SUCCESS&txnRef=..."
if (response.contains("Status=SUCCESS", ignoreCase = true)) {
verifyStatusWithBackend(orderId)
}
}
}
In India, customers appreciate receiving an instant WhatsApp confirmation after scanning a QR code. Using our sister platform WAPI (wapi.lushai.dev), you can send automated WhatsApp notifications with bold formatting, emojis, and transaction details.
<?php
/**
* Send Automated WhatsApp Receipt via WAPI (wapi.lushai.dev)
* Trigger this inside your payment webhook upon SUCCESS
*/
function sendWhatsAppReceipt($mobileNumber, $orderId, $amount, $utr) {
$wapiUrl = "https://wapi.lushai.dev/api/send-message";
$wapiToken = "YOUR_WAPI_BEARER_KEY"; // From wapi.lushai.dev
// Format Indian phone number (must include country code e.g. 91...)
$cleanMobile = preg_replace('/[^0-9]/', '', $mobileNumber);
if (strlen($cleanMobile) === 10) {
$cleanMobile = '91' . $cleanMobile;
}
$messageText = "🎉 *Payment Received Successfully!*\n\n"
. "📦 *Order ID:* #" . $orderId . "\n"
. "💰 *Amount Paid:* ₹" . $amount . "\n"
. "🏛 *Bank UTR:* " . $utr . "\n"
. "⏰ *Date:* " . date('d M Y, h:i A') . "\n\n"
. "Your order is now being processed. Thank you for choosing us! 🚀";
$postData = [
"number" => $cleanMobile,
"message" => $messageText,
"type" => "text"
];
$ch = curl_init($wapiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . $wapiToken,
"Content-Type: application/json"
]);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
?>
| Best Practice | Description | Recommended Action |
|---|---|---|
| Idempotency with UTR | Every UPI payment produces a unique 12-digit Bank Reference Number (UTR). | Add a UNIQUE index on utr in your database. If a webhook retries, do not dispense goods twice. |
| Server-to-Server Verification | Never trust user browser redirects alone for order fulfillment. | Always rely on the asynchronous server-side POST webhook or verify via /api/check-order-status. |
Keep Token in .env |
Your user_token authorizes payment requests and balance operations. |
Never commit token to public Git repositories or front-end client-side HTML bundles. |
| HTTPS Webhook Endpoints | Prevent Man-in-the-Middle (MITM) interception of payment notifications. | Ensure your webhook URL begins with https:// with a valid SSL/TLS certificate. |
| HTTP Code | Message | Meaning & Resolution |
|---|---|---|
200 OK |
Order Created Successfully |
Order created. Redirect customer to the returned payment_url. |
400 Bad Request |
Invalid user token |
Your user_token is missing or invalid. Check dashboard API settings. |
400 Bad Request |
Order ID already exists |
The order_id sent was already used. Always generate a unique string (e.g. UPG_...). |
400 Bad Request |
Amount must be greater than 0 |
Check your amount field. Decimals (e.g. 199.50) are supported. |