Next.js App Router UPI Payment Gateway Integration: Route Handlers, sdk.js Modal & Webhooks

Full production Next.js App Router blueprint using server-only UPIGATEWAY_USER_TOKEN secrets, Route Handlers, `UPIGateway.open()` popup modal, and atomic webhook verification.

Why Server-Only Environment Separation Matters in Next.js

In Next.js App Router applications, React Client Components (`'use client'`) compile straight into browser JavaScript bundles. Exposing `NEXT_PUBLIC_UPIGATEWAY_USER_TOKEN` or accepting raw checkout rupee amounts from browser `fetch()` requests allows anyone with DevTools to extract merchant tokens or alter product prices. Always isolate `UPIGATEWAY_USER_TOKEN` inside server-only Route Handlers (`app/api/**/route.ts`) and derive authoritative pricing strictly from your backend catalog or PostgreSQL.

Step 1: Server Route Handler for Creating UPI Orders

// app/api/payments/create/route.ts
import { NextRequest, NextResponse } from "next/server";

const SERVER_PLAN_CATALOG_INR: Record<string, number> = {
  growth: 499,
  business: 600,
  enterprise: 999,
};

export async function POST(req: NextRequest) {
  const { planId, customerMobile, userId } = await req.json();
  const expectedAmount = SERVER_PLAN_CATALOG_INR[String(planId)];
  if (!expectedAmount) {
    return NextResponse.json({ error: "Invalid subscription tier" }, { status: 400 });
  }

  const orderId = `NX_${Date.now()}_${crypto.randomUUID().slice(0, 6).toUpperCase()}`;
  // Persist local order { orderId, userId, expectedAmount, status: "PENDING" } in DB first

  const resp = await fetch("https://upigateway.dev/api/create-order", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      user_token: process.env.UPIGATEWAY_USER_TOKEN,
      amount: String(expectedAmount),
      order_id: orderId,
      customer_mobile: String(customerMobile || "9999999999"),
      redirect_url: `${process.env.APP_URL}/checkout/complete?order_id=${encodeURIComponent(orderId)}`,
      remark1: `Plan:${planId}`,
      remark2: String(userId || ""),
    }),
  });

  const data = await resp.json();
  if (!data.status || !data.result?.payment_url) {
    return NextResponse.json({ error: data.message || "Gateway error" }, { status: 502 });
  }

  return NextResponse.json({
    orderId: data.result.orderId,
    paymentUrl: data.result.payment_url,
  });
}

Step 2: Rendering the Drop-In Popup Modal in Client Components

"use client";
import { useEffect, useState } from "react";

export function UpgradeCheckoutButton({ planId, mobile }: { planId: string; mobile: string }) {
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (document.getElementById("upigateway-sdk")) return;
    const s = document.createElement("script");
    s.id = "upigateway-sdk";
    s.src = "https://upigateway.dev/sdk.js";
    s.async = true;
    document.body.appendChild(s);
  }, []);

  async function startPayment() {
    setBusy(true);
    try {
      const r = await fetch("/api/payments/create", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ planId, customerMobile: mobile }),
      });
      const { paymentUrl, orderId } = await r.json();
      const sdk = (window as any).UPIGateway;
      if (sdk && paymentUrl) {
        sdk.open({
          payment_url: paymentUrl,
          order_id: orderId,
          theme: "default",
          onSuccess: (tx: { order_id: string }) => {
            window.location.href = `/checkout/complete?order_id=${encodeURIComponent(tx.order_id)}`;
          },
        });
      } else if (paymentUrl) {
        window.location.href = paymentUrl;
      }
    } finally {
      setBusy(false);
    }
  }

  return (
    <button type="button" onClick={startPayment} disabled={busy}>
      {busy ? "Preparing UPI Checkout..." : "Pay Instantly via UPI (0% Fee)"}
    </button>
  );
}

Step 3: Server Webhook & Return-Page Reconciliation

// app/api/payments/webhook/route.ts
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const payload = await req.json().catch(() => null);
  const orderId = payload?.order_id;
  if (!orderId || payload?.status !== "SUCCESS") {
    return NextResponse.json({ ignored: true });
  }

  const verifyResp = await fetch("https://upigateway.dev/api/check-order-status", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      user_token: process.env.UPIGATEWAY_USER_TOKEN,
      order_id: orderId,
    }),
  });
  const verify = await verifyResp.json();

  if (
    verify.status === true &&
    verify.result?.status === "SUCCESS" &&
    verify.result?.txnStatus === "COMPLETED" &&
    verify.result?.utr
  ) {
    // Compare Number(verify.result.amount) >= storedOrder.expectedAmount
    // Check UTR unused in PostgreSQL before updating user plan atomically
  }

  return NextResponse.json({ received: true });
}

Production Edge-Case & Security Rules

Related Integration Guides & Developer Resources

Explore more technical articles, code examples, and architecture guides on our official blog. Automate your Indian payment collection at zero percent fees with UPIGateway.dev.

We provide comprehensive developer documentation, ready-to-deploy SDKs for PHP and Node.js, and plug-and-play e-commerce plugins for WordPress and WooCommerce. Build modern payment checkout flows with direct bank settlement and full financial autonomy.

Back to Blog Index | Engineering Reports | View API Documentation | Explore Pricing Plans