UPI Payment Integration in React with Next.js

Learn upi payment integration in react with Next.js API routes, dynamic QR, UPI intent links, polling and HMAC webhooks for verified checkout.
A blue illustration of a React checkout screen, UPI QR code, smartphone and verified webhook checkmark.

UPI payment integration in react is safest when React handles the checkout screen and Next.js handles order creation and payment confirmation. This guide builds that split with a dynamic QR or hosted payment link, a server-side status check and an HMAC-verified webhook.

What you will build

The customer will click Pay by UPI in a React component. The browser calls your Next.js backend, which calculates the amount, creates one PaymentSetu order and returns only the payment details needed for the screen.

The complete flow is:

  1. Your server loads the cart and calculates the final amount from trusted product data.
  2. A Next.js Route Handler creates a unique client_txn_id with POST /api/create_order.
  3. The React page shows the returned dynamic QR or hosted payment URL. On a phone, it can also show the documented UPI intent link when the API response provides one.
  4. The customer pays directly into your connected Paytm Business or PhonePe Business merchant account.
  5. PaymentSetu matches the payment to the order and sends your webhook an HMAC-signed event.
  6. Your webhook checks the signature, order reference and amount, then marks the order paid once.

PaymentSetu is a payment verification service, not a payment gateway. It does not hold the money: the customer pays your own connected merchant account, while PaymentSetu matches the payment and notifies your application.

What you need before coding

Why: the integration is small, but the order, secret and webhook boundaries need to be decided before you write the button.

Prepare:

  • A Next.js App Router project using TypeScript and a database or durable store for orders.
  • A PaymentSetu account, an API key, a webhook signing secret and a connected Paytm Business or PhonePe Business merchant account.
  • A public HTTPS URL for your webhook, such as https://shop.example.com/api/webhooks/paymentsetu.
  • An order table with client_txn_id, amount in paisa, status, UTR and a processed-event or idempotency field.
  • A server-side product or cart lookup. The browser may send a product ID, but it must not be the authority for price.

Route Handlers live in the app directory and use the Web Request and Response APIs, as described in the Next.js Route Handlers documentation. Keep the PaymentSetu API key and webhook secret in server-only environment variables. Do not prefix them with NEXT_PUBLIC_.

For a growing custom checkout, PaymentSetu Pro is ₹999 per 30 days for 1,000 credits. One credit represents one successful payment verified; the plan includes dynamic QR, webhooks, REST API access, a unified dashboard and priority support. See the current PaymentSetu plans before choosing a credit level.

Step 1: Create the order on the server

Why: only the server can safely choose the amount, create the reference and use the API key.

Add these environment variables to your local .env.local and to your deployment secret store:

PAYMENTSETU_API_BASE=https://paymentsetu.com
PAYMENTSETU_API_KEY=replace-with-your-api-key
PAYMENTSETU_WEBHOOK_SECRET=replace-with-your-webhook-secret

Create app/api/checkout/route.ts. The example assumes your API account uses client_txn_id, an integer amount in paisa and a bearer API-key header. Keep this vendor mapping in one file so you can update a field from your account documentation without changing the React component.

import { randomUUID } from "node:crypto";
import { NextResponse } from "next/server";

const apiBase = process.env.PAYMENTSETU_API_BASE!;
const apiKey = process.env.PAYMENTSETU_API_KEY!;

export async function POST(request: Request) {
  const { productId } = await request.json();

  // Replace this with a database lookup. Never trust a total from the browser.
  const product = await products.findPayable(productId);
  if (!product) {
    return NextResponse.json({ error: "Product not found" }, { status: 404 });
  }

  const clientTxnId = `order_${randomUUID()}`;
  const amountInPaisa = Math.round(product.totalRupees * 100);

  await orders.insert({
    clientTxnId,
    amountInPaisa,
    status: "pending",
  });

  const response = await fetch(`${apiBase}/api/create_order`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      client_txn_id: clientTxnId,
      amount: amountInPaisa,
      webhook_url: "https://shop.example.com/api/webhooks/paymentsetu",
    }),
    cache: "no-store",
  });

  if (!response.ok) {
    // Keep the provider response in server logs only; do not expose secrets.
    await orders.markCreateFailed(clientTxnId);
    return NextResponse.json(
      { error: "Unable to prepare payment" },
      { status: 502 },
    );
  }

  const payment = await response.json();

  return NextResponse.json({
    clientTxnId,
    amountInPaisa,
    // Map only fields documented for your PaymentSetu account.
    paymentUrl: payment.payment_url,
    upiUri: payment.upi_uri ?? null,
  });
}

The products.findPayable, orders.insert and orders.markCreateFailed calls represent your own database layer. Save the pending row before the network request. If a request times out, reconcile the existing client_txn_id before creating a second order.

The response adapter deliberately returns a small, safe object. If your account returns a QR image URL or another documented field instead of payment_url or upi_uri, map that field here and keep the browser contract stable. Do not guess a QR value or generate a second QR for the same order.

Success looks like one pending local order, one unique client_txn_id and a response containing the exact amount plus the documented QR, hosted URL or intent data. The API key must not appear in the response or browser source.

Step 2: Render the dynamic QR or UPI intent link

Why: desktop visitors need a QR checkout, while mobile visitors benefit from a one-tap hand-off to a compatible UPI app.

Create a client component such as app/checkout/PayByUpi.tsx:

"use client";

import { createElement, useState } from "react";

type Payment = {
  clientTxnId: string;
  amountInPaisa: number;
  paymentUrl: string | null;
  upiUri: string | null;
};

export function PayByUpi({ productId }: { productId: string }) {
  const [payment, setPayment] = useState(null as Payment | null);
  const [message, setMessage] = useState("Ready to pay");
  const [busy, setBusy] = useState(false);

  async function startPayment() {
    setBusy(true);
    setMessage("Preparing your payment…");

    try {
      const response = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ productId }),
      });

      if (!response.ok) throw new Error("Could not create order");
      const nextPayment = (await response.json()) as Payment;
      setPayment(nextPayment);
      setMessage("Scan the QR or open the UPI payment link");
    } catch {
      setMessage("We could not prepare payment. Please try again.");
    } finally {
      setBusy(false);
    }
  }

  return createElement(
    "section",
    null,
    createElement(
      "button",
      { type: "button", onClick: startPayment, disabled: busy },
      busy ? "Preparing…" : "Pay by UPI",
    ),
    payment &&
    createElement(
        "div",
        { "aria-live": "polite" },
        createElement("p", null, message),
        createElement("p", null, `Reference: ${payment.clientTxnId}`),
        payment.upiUri &&
          createElement(
            "a",
            { href: payment.upiUri },
            "Open UPI app",
          ),
        payment.paymentUrl &&
          createElement(
            "a",
            { href: payment.paymentUrl },
            "Open QR checkout",
          ),
      ),
  );
}

The hosted paymentUrl is the QR checkout returned by the service. If the documented response includes a upi_uri, place it behind the mobile link. Keep both options visible when practical, and show the amount and merchant details from trusted server data before the customer confirms payment.

Do not use the browser link result, a UPI app return, or a customer screenshot to mark an order paid. Those events only move the customer back to your page. The order stays pending until your backend receives a valid verification result.

Success looks like a desktop customer seeing the order-specific QR checkout and a mobile customer getting a documented UPI intent link, with no private credential in the client bundle.

Step 3: Check status through your own Next.js route

Why: a customer may return before the webhook has been processed, so the checkout needs a modest server-side reconciliation path without exposing the API key.

Create app/api/orders/[clientTxnId]/route.ts:

import { NextResponse } from "next/server";

type RouteParams = { clientTxnId: string };

export async function GET(
  _request: Request,
  { params }: { params: Promise<RouteParams> },
) {
  const { clientTxnId } = await params;
  const localOrder = await orders.findByClientTxnId(clientTxnId);

  if (!localOrder) {
    return NextResponse.json({ error: "Order not found" }, { status: 404 });
  }

  if (localOrder.status === "paid") {
    return NextResponse.json({ status: "paid" });
  }

  const response = await fetch(
    `${process.env.PAYMENTSETU_API_BASE}/api/order_status/${encodeURIComponent(clientTxnId)}`,
    {
      headers: {
        Accept: "application/json",
        Authorization: `Bearer ${process.env.PAYMENTSETU_API_KEY}`,
      },
      cache: "no-store",
    },
  );

  if (!response.ok) {
    return NextResponse.json({ status: "pending" });
  }

  const providerStatus = await response.json();
  // Map the documented provider status into your own small status contract.
  return NextResponse.json({
    status: providerStatus.status === "success" ? "paid" : "pending",
  });
}

The route checks your database first, then calls GET /api/order_status/{client_txn_id} only when the order is still pending. If the provider response indicates a successful payment, apply the same amount, UTR and idempotency checks as the webhook before changing the local record; the shortened example above only illustrates the read path.

In the React component, poll your own route immediately after the customer returns and then at a modest interval, such as every five seconds, with a maximum number of attempts. Stop polling as soon as the status is paid, and let the customer tap Check again after the bounded loop. The webhooks versus polling guide explains why polling is a recovery path rather than the payment authority.

Success looks like the browser asking your backend for pending or paid; the browser never sends a secret to PaymentSetu and never invents a successful result.

Step 4: Verify the HMAC webhook in a Route Handler

Why: the signed server-to-server event is the confirmation boundary for fulfilment.

Create app/api/webhooks/paymentsetu/route.ts. Read the raw body first. Parsing JSON and serialising it again can change whitespace or key order, so it must not be the input to the HMAC calculation.

import { createHmac, timingSafeEqual } from "node:crypto";
import { NextResponse } from "next/server";

function validSignature(
  rawBody: string,
  timestamp: string,
  received: string,
  secret: string,
) {
  if (!timestamp || !/^\d+$/.test(timestamp) || !received) return false;

  const age = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (age > 300) return false;

  const expected = createHmac("sha256", secret)
    .update(`${timestamp}.${rawBody}`)
    .digest("hex");

  const receivedBytes = Buffer.from(received, "hex");
  const expectedBytes = Buffer.from(expected, "hex");
  return (
    receivedBytes.length === expectedBytes.length &&
    timingSafeEqual(receivedBytes, expectedBytes)
  );
}

export async function POST(request: Request) {
  const rawBody = await request.text();
  const timestamp = request.headers.get("x-paymentsetu-timestamp") ?? "";
  const signature = request.headers.get("x-paymentsetu-signature") ?? "";
  const secret = process.env.PAYMENTSETU_WEBHOOK_SECRET;

  if (!secret || !validSignature(rawBody, timestamp, signature, secret)) {
    return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
  }

  let event: {
    client_txn_id?: string;
    order_id?: string;
    amount?: number | string;
    status?: string;
    txn_utr?: string;
  };

  try {
    event = JSON.parse(rawBody);
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const clientTxnId = event.client_txn_id ?? event.order_id;
  const order = clientTxnId
    ? await orders.findByClientTxnId(clientTxnId)
    : null;

  if (!order || Number(event.amount) !== order.amountInPaisa) {
    return NextResponse.json({ error: "Order mismatch" }, { status: 400 });
  }

  if (event.status === "success") {
    await orders.markPaidOnce(order.id, {
      utr: event.txn_utr ?? null,
      rawEvent: event,
    });
  }

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

This example follows the documented timestamp-plus-body HMAC pattern and the X-PaymentSetu-Timestamp / X-PaymentSetu-Signature headers. Confirm the exact header names, digest encoding, timestamp rule and secret shown in your PaymentSetu account before deploying; the Node.js crypto documentation covers createHmac and timingSafeEqual.

orders.markPaidOnce must be a database transaction, not an in-memory Boolean. It should update only a pending order, reject a UTR already attached to another order and make a repeated valid webhook a harmless success. Trigger fulfilment after that idempotent state change, or enqueue it with a unique order key.

If you maintain a PHP service alongside your Next.js app, the UPI payment integration in PHP guide shows the same order, hosted QR and webhook boundaries. For support and reconciliation teams, the UTR number guide explains the transaction reference that should be stored with the local order.

Success looks like an invalid signature receiving a 401, a mismatched amount receiving a 400, and one valid event changing one matching order to paid exactly once.

Step 5: Deploy on Vercel or your own VPS

Why: webhook delivery requires a public, durable HTTPS endpoint, while serverless deployment changes how you should store state.

Before launch:

  1. Add PAYMENTSETU_API_BASE, PAYMENTSETU_API_KEY and PAYMENTSETU_WEBHOOK_SECRET to the deployment’s server environment, then redeploy.
  2. Replace the example webhook_url with the real public HTTPS route and register that URL in your PaymentSetu configuration.
  3. Use a database for orders, idempotency and UTRs. Do not rely on a local file, process memory or a module-level Map between webhook attempts.
  4. Set a reasonable outbound request timeout and return a non-2xx response when the event cannot be safely recorded, so it can be retried according to the configured webhook behaviour.
  5. Keep API calls in Route Handlers or another server-only module. The Next.js backend-for-frontend guidance notes that deployed Route Handlers may run as short-lived functions and cannot be treated as shared long-running processes.
  6. Confirm that your checkout page is not statically exporting the payment route. Dynamic order creation and webhook handling need a runtime server.

On a VPS, run the Next.js server behind HTTPS and ensure the reverse proxy forwards POST requests and the X-PaymentSetu-* headers unchanged. On Vercel or another function host, keep the webhook handler short: verify, validate, persist and enqueue any longer fulfilment work.

Success looks like a public webhook returning 2xx after the database transaction, with secrets absent from page source, client bundles and logs.

Verify the complete React and Next.js flow

Run this checklist in a safe test environment before connecting fulfilment:

  1. Click the React button and confirm the server creates one pending row with a unique reference.
  2. Confirm that the displayed amount is calculated by the server and is the same amount sent to create_order.
  3. Check that the browser response contains only the order reference and documented QR, hosted URL or intent data.
  4. Scan the dynamic QR from a separate device, or open the documented intent link on a compatible mobile device.
  5. Confirm that the payment reaches your own connected merchant account.
  6. Deliver a signed webhook and verify the order reference, amount, status and UTR before fulfilment.
  7. Replay the same signed event and confirm that the second delivery does not send a second product, seat or account activation.
  8. Return to the checkout page early and confirm that it stays pending until the backend has a verified result.
  9. Call GET /api/check_credits from an admin-only server task so your team can monitor verification credits without exposing account data.

For a ready-made WordPress checkout, use the PaymentSetu WooCommerce plugin to connect your store to a verified UPI flow. For a custom React or Next.js site, create your PaymentSetu account and keep the API adapter behind your server boundary.

Troubleshooting common integration errors

The browser exposes the API key. The PaymentSetu request is running in a client component or uses a NEXT_PUBLIC_ variable. Move it to a Route Handler, remove the exposed variable and rotate the key if it was already published.

The QR or intent link is empty. Log the provider response on the server without secrets and compare its documented field name with the adapter. Return only the mapped field that your account actually provides; do not create a second QR from incomplete data.

The amount is rejected. Check the unit expected by your account and convert once on the server. In the example above, ₹249 becomes 24900 paisa. Never send a formatted string such as ₹249 or calculate the final amount in editable browser state.

The webhook returns “Invalid signature”. Hash the exact raw request body, use the timestamp string exactly as received, check the configured secret and confirm the header and digest format. Do not parse and re-serialise JSON before hashing.

The customer paid but the order is still pending. Treat the return page as navigation only. Check that the webhook URL is public HTTPS, the handler returns 2xx after persistence and the event reference and amount match the local order. Use order_status from your server as a reconciliation check.

The order is fulfilled twice. Put the paid transition and UTR or event uniqueness check in one database transaction. A duplicate valid webhook should return safely without running fulfilment again.

FAQ

Can I integrate UPI payments in a React app without putting the API key in JavaScript?

Yes. The React component should call your own Next.js Route Handler. That server route creates the order and calls PaymentSetu, while the browser receives only the QR, hosted URL or intent data needed to start payment.

Is PaymentSetu a payment gateway for Next.js?

No. PaymentSetu is a payment verification service. The customer pays directly into your connected Paytm Business or PhonePe Business merchant account, and PaymentSetu matches the payment and sends your server a webhook.

Should I mark an order paid when the UPI app returns?

No. The app return only tells your page that the customer has come back. Keep the order pending until your backend accepts a valid signed webhook or completes a server-side status reconciliation with the same amount and reference checks.

Can I show a dynamic QR on desktop and a UPI link on mobile?

Yes. Return the documented QR or hosted payment URL for the desktop checkout and the documented UPI intent URI when your account response provides one. Keep both behind your server-created order and show a pending state until verification completes.

Which PaymentSetu plan fits a custom React checkout?

PaymentSetu Pro costs ₹999 per 30 days and includes 1,000 credits, with one credit representing one successful payment verified. It also includes dynamic QR, webhooks, REST API access, a unified dashboard and priority support.

The implementation boundary is simple: React starts the checkout, Next.js protects the API call, and the signed webhook controls fulfilment. Keep that boundary intact and your custom UPI checkout can remain small, auditable and easy to reconcile.

DONE upi-payment-integration-react-nextjs words=2166

Previous Article

UPI Payment Integration in Flutter: Order, Intent and Webhook

Next Article

How to Sell Online Courses in India With UPI

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *