UPI Payment Integration in Java: Spring Boot Example

Learn upi payment integration in java with Spring Boot: create a QR order, verify HMAC webhooks, update orders once, check credits and reconcile safely.
A blue Java Spring Boot payment integration illustration with a phone, UPI QR code and webhook verification checkmark.

UPI payment integration in java is easiest to maintain when your Spring Boot server owns the order, amount and confirmation state. This guide builds a plain REST integration with RestClient: create an order, redirect to the hosted QR, verify the HMAC-signed webhook, update the order idempotently and check API credits.

What you will build

The finished flow has a checkout endpoint, a webhook endpoint and a server-side status fallback:

  1. Your application calculates the payable amount and saves a pending order.
  2. Spring Boot calls POST /api/create_order with a unique order_id and the amount in integer paisa.
  3. PaymentSetu returns a payment_url; your application redirects the customer to the hosted QR page.
  4. The customer pays by UPI directly into your connected Paytm Business or PhonePe Business merchant account.
  5. PaymentSetu matches the payment to the order and sends an HMAC-signed JSON webhook.
  6. Your webhook controller verifies the raw request, checks the order and amount, and marks it paid once.
  7. A scheduled job or return page can use GET /api/order_status/{client_txn_id} to reconcile a pending record.

PaymentSetu is a payment verification service, not a payment gateway. The customer’s payment goes to your own merchant account; PaymentSetu matches the UTR and amount to the order and sends your application the verification event. It does not hold the money.

For a ready-made platform integration, see the PaymentSetu WooCommerce plugin. This article is for a custom Java or Spring Boot checkout where you control the database and fulfilment logic.

What you need before starting

Why: the API key, webhook secret, order reference and expected amount must be decided before code changes payment state.

Prepare:

  • A Spring Boot MVC application with HTTPS and Jackson, using a Spring version that provides RestClient.
  • Java 21 or another supported Java version with javax.crypto.Mac available.
  • A PaymentSetu account with a connected Paytm Business or PhonePe Business merchant account.
  • An API key and the webhook signing value shown in your PaymentSetu configuration. If your account uses the API key to sign webhooks, use that same server-side value for both.
  • A public HTTPS endpoint such as https://shop.example.com/webhooks/paymentsetu.
  • An orders table containing your reference, expected amount in paisa, status and UTR.

Keep secrets outside application.properties committed to source control. Environment variables are enough for a small deployment:

PAYMENTSETU_API_KEY=replace-with-your-api-key
PAYMENTSETU_WEBHOOK_SECRET=replace-with-your-webhook-secret

Set PAYMENTSETU_WEBHOOK_SECRET to the documented signing value for your account; it may be the same value as PAYMENTSETU_API_KEY. Never send either value to the browser.

PaymentSetu Pro is ₹999 per 30 days for 1,000 credits, with one credit representing one successful payment verified. It includes dynamic QR, webhooks, REST API access and the unified dashboard. Compare the available plans in the PaymentSetu pricing section, or create an account before you begin.

Spring’s official REST client reference describes RestClient as a synchronous fluent client with JSON message conversion. Java’s official Mac documentation documents HmacSHA256, init and doFinal, which are the primitives used below.

Step 1: Configure a reusable RestClient

Why: one configured client keeps the base URL and bearer authentication in one server-side place, so individual calls cannot accidentally expose the API key to the browser.

Create a bean. The Authorization header is added only to server-to-server calls:

package com.example.payments;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestClient;

@Configuration
public class PaymentSetuConfig {

    @Bean
    RestClient paymentSetuClient(
            @Value("${paymentsetu.api-key}") String apiKey,
            @Value("${paymentsetu.base-url:https://paymentsetu.com/api}") String baseUrl) {
        return RestClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .defaultHeader(HttpHeaders.ACCEPT, "application/json")
                .build();
    }
}

Map the environment variables into your deployment configuration rather than placing literal secrets in the repository. For example, the property names above can be supplied as PAYMENTSETU_API_KEY and PAYMENTSETU_WEBHOOK_SECRET by Spring’s relaxed environment-variable binding.

Success looks like this: the application starts with a configured RestClient, and no API key appears in page source, JavaScript, logs or a response sent to the customer.

Step 2: Call create_order with RestClient

Why: the unique order reference and server-calculated amount connect your local order to the hosted QR and later webhook.

Use a record for the request and a small JSON tree for the response. PaymentSetu expects amount in paisa, so ₹249 becomes 24900. Save the local order as PENDING before the external call.

package com.example.payments;

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

@Service
public class PaymentSetuService {

    private final RestClient client;

    public PaymentSetuService(RestClient paymentSetuClient) {
        this.client = paymentSetuClient;
    }

    public String createOrder(LocalOrder order) {
        CreateOrderRequest request = new CreateOrderRequest(
                order.id(),
                order.amountPaise(),
                "https://shop.example.com/payment-return",
                order.customerName(),
                order.customerEmail(),
                order.customerMobile(),
                "Order " + order.id());

        JsonNode response = client.post()
                .uri("/create_order")
                .contentType(MediaType.APPLICATION_JSON)
                .body(request)
                .retrieve()
                .body(JsonNode.class);

        if (response == null || !response.path("status").asBoolean(false)) {
            throw new IllegalStateException("PaymentSetu did not create the order");
        }

        String paymentUrl = response.path("payment_url").asText("");
        if (paymentUrl.isBlank()) {
            throw new IllegalStateException("PaymentSetu response has no payment_url");
        }
        return paymentUrl;
    }

    public record CreateOrderRequest(
            String order_id,
            long amount,
            String redirect_url,
            String customer_name,
            String customer_email,
            String customer_mobile,
            String remarks) {}

    public record LocalOrder(
            String id,
            long amountPaise,
            String customerName,
            String customerEmail,
            String customerMobile) {}
}

The record field names intentionally match the API’s JSON keys. If your project uses JavaBeans instead of records, use Jackson annotations or matching getter names. RestClient.retrieve().body(JsonNode.class) lets Jackson convert the JSON response; Spring documents this message-conversion pattern in its REST client reference.

Your controller should create the order from a trusted cart or invoice ID, not from an amount supplied by the browser:

@PostMapping("/checkout/{cartId}")
public ResponseEntity<Void> checkout(@PathVariable String cartId) {
    LocalOrder order = orderService.createPendingOrderFromCart(cartId);
    String paymentUrl = paymentSetuService.createOrder(order);
    return ResponseEntity.status(HttpStatus.SEE_OTHER)
            .location(URI.create(paymentUrl))
            .build();
}

In these snippets, LocalOrder and OrderService represent your application’s domain and repository types. If you keep the sample record nested inside PaymentSetuService, refer to it as PaymentSetuService.LocalOrder from another class.

The createPendingOrderFromCart method should calculate the total from your catalogue and save the expected paisa amount. Do not trust a hidden field such as amount=24900; customers can edit it. If the API call fails, leave the record available for reconciliation and show a generic checkout message rather than exposing credentials or a stack trace.

Success looks like this: a pending local order has one unique ID and amount, the API returns status: true and payment_url, and the customer reaches the hosted QR page. The redirect back to redirect_url is only navigation, not proof that the payment succeeded.

Step 3: Show the QR or intent link safely

Why: the browser needs only a payment URL; your API key and webhook secret must remain on the Spring Boot server.

The simplest checkout is the 303 See Other redirect shown above. If you need a custom waiting page, return the URL from your own backend and redirect in the browser:

public record CheckoutResponse(String orderId, String paymentUrl) {}

@PostMapping("/checkout")
public CheckoutResponse createCheckout(@RequestBody CartRequest request) {
    LocalOrder order = orderService.createPendingOrderFromCart(request.cartId());
    return new CheckoutResponse(
            order.id(),
            paymentSetuService.createOrder(order));
}

Your frontend can navigate to paymentUrl or display it as a link. Do not try to call paymentsetu.com/api/create_order from browser JavaScript. A bearer key in a browser bundle can be copied and used by anyone.

The customer sees the hosted QR and pays into your connected merchant account. After paying, the customer may return to your waiting page. That page can say “We are checking your payment” and poll your own order endpoint, but it must never mark the order paid because a redirect occurred or because the customer uploaded a screenshot.

Success looks like this: the QR page opens with the order’s amount, your application still shows PENDING, and only the webhook path can trigger fulfilment.

Step 4: Verify the HMAC webhook in a controller

Why: a signed webhook gives your server an authenticated event, while a browser callback is only a client-side navigation event.

Read the body as byte[] and calculate the signature before parsing JSON. The PaymentSetu webhook uses these headers:

  • X-PaymentSetu-Timestamp: the Unix timestamp for the signed request.
  • X-PaymentSetu-Signature: the hexadecimal HMAC-SHA256 value.

The signed message is timestamp + "." + raw JSON body. The timestamp check below uses a five-minute freshness window; keep it aligned with the webhook contract configured for your account.

package com.example.payments;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.time.Instant;

@RestController
@RequestMapping("/webhooks/paymentsetu")
public class PaymentSetuWebhookController {

    private final ObjectMapper objectMapper;
    private final OrderService orders;
    private final String webhookSecret;

    public PaymentSetuWebhookController(
            ObjectMapper objectMapper,
            OrderService orders,
            @Value("${paymentsetu.webhook-secret}") String webhookSecret) {
        this.objectMapper = objectMapper;
        this.orders = orders;
        this.webhookSecret = webhookSecret;
    }

    @PostMapping
    public ResponseEntity<String> receive(
            @RequestHeader(value = "X-PaymentSetu-Timestamp", required = false)
            String timestamp,
            @RequestHeader(value = "X-PaymentSetu-Signature", required = false)
            String signature,
            @RequestBody byte[] rawBody) {

        if (!isValidSignature(timestamp, signature, rawBody)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body("invalid webhook");
        }

        try {
            JsonNode event = objectMapper.readTree(rawBody);
            String orderId = event.path("order_id").asText("");
            String status = event.path("status").asText("").toLowerCase();
            long amountPaise = event.path("amount").asLong(-1);
            String utr = event.path("txn_utr").asText("");

            if (orderId.isBlank() || amountPaise < 0 || utr.isBlank()) {
                return ResponseEntity.badRequest().body("incomplete event");
            }

            LocalOrder order = orders.findById(orderId);
            if (order == null || order.amountPaise() != amountPaise) {
                return ResponseEntity.badRequest().body("order mismatch");
            }

            if ("success".equals(status)) {
                // This method must use one transaction and a unique UTR/event key.
                orders.markPaidOnce(orderId, amountPaise, utr);
            }

            return ResponseEntity.ok("accepted");
        } catch (Exception exception) {
            return ResponseEntity.badRequest().body("invalid event");
        }
    }

    private boolean isValidSignature(String timestamp, String received,
                                     byte[] rawBody) {
        if (timestamp == null || !timestamp.matches("\\d+")
                || received == null || received.isBlank()) {
            return false;
        }

        long sentAt;
        try {
            sentAt = Long.parseLong(timestamp);
        } catch (NumberFormatException exception) {
            return false;
        }

        if (Math.abs(Instant.now().getEpochSecond() - sentAt) > 300) {
            return false;
        }

        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(
                    webhookSecret.getBytes(StandardCharsets.UTF_8),
                    "HmacSHA256"));
            byte[] prefix = (timestamp + ".").getBytes(StandardCharsets.UTF_8);
            byte[] signed = new byte[prefix.length + rawBody.length];
            System.arraycopy(prefix, 0, signed, 0, prefix.length);
            System.arraycopy(rawBody, 0, signed, prefix.length, rawBody.length);

            byte[] expected = mac.doFinal(signed);
            byte[] actual = hexToBytes(received);
            return actual != null && MessageDigest.isEqual(expected, actual);
        } catch (GeneralSecurityException exception) {
            return false;
        }
    }

    private static byte[] hexToBytes(String value) {
        if (!value.matches("(?i)[0-9a-f]{64}")) return null;
        byte[] result = new byte[32];
        for (int i = 0; i < result.length; i++) {
            result[i] = (byte) Integer.parseInt(
                    value.substring(i * 2, i * 2 + 2), 16);
        }
        return result;
    }
}

MessageDigest.isEqual compares the digest bytes without an ordinary early-exit string comparison. Never parse the JSON and serialise it again before calculating HMAC: whitespace, escaping and property order can change the signed bytes.

If your account’s API documentation specifies a different header encoding or a documented prefix, follow that contract exactly. Do not silently trim, lowercase or Base64-decode a value unless the contract says to do so.

Success looks like this: a valid request passes the signature and timestamp checks, an altered body returns 401, and no order update happens before verification and amount validation.

For a deeper explanation of raw-body HMAC handling, see Verify Webhook Signature HMAC in PHP, Python and Node.js. The language changes, but the security order is the same.

Step 5: Make order updates idempotent

Why: a valid webhook may be delivered again, and a retry must not fulfil the same order twice.

Signature verification proves integrity and authenticity; it does not replace a database transaction. Your markPaidOnce operation should:

  1. Load the order by your saved order_id.
  2. Compare the event amount in paisa with the stored amount.
  3. Require status=success and a non-empty UTR.
  4. Insert the UTR or event identifier into a column with a unique constraint.
  5. Change PENDING to PAID only if the current state is still PENDING.
  6. Commit before sending goods, access, email or a booking confirmation.

A repository method can express the transition like this:

@Transactional
public boolean markPaidOnce(String orderId, long amountPaise, String utr) {
    int changed = jdbc.update("""
        UPDATE orders
           SET status = 'PAID', txn_utr = ?
         WHERE order_id = ?
           AND amount_paise = ?
           AND status = 'PENDING'
        """, utr, orderId, amountPaise);

    return changed == 1;
}

In production, also enforce uniqueness for txn_utr or the provider’s event ID. If changed is zero because the order is already paid, acknowledge the repeated event without running fulfilment again. If your database sees two requests concurrently, the conditional update and unique constraint decide the winner.

Do not mark an order paid just because the customer returns from the QR page. A screenshot, a front-end callback and an HTTP redirect are not substitutes for a verified event.

Success looks like this: the first valid event changes one row and triggers fulfilment once; the same event again returns safely with no second side effect.

Step 6: Check status and credits from the server

Why: status checks help reconcile a return page or pending queue, while the credits check helps your operations screen know whether new orders can be created.

Call the status endpoint with the same authenticated RestClient. Encode the local ID because it becomes part of a URL path:

public JsonNode getOrderStatus(String clientTxnId) {
    return client.get()
            .uri(uriBuilder -> uriBuilder
                    .path("/order_status/{client_txn_id}")
                    .build(clientTxnId))
            .retrieve()
            .body(JsonNode.class);
}

public JsonNode getCredits() {
    return client.get()
            .uri("/check_credits")
            .retrieve()
            .body(JsonNode.class);
}

Use getOrderStatus from a scheduled reconciliation job or your own authenticated order-status endpoint. Inspect the documented response, then apply the same local order, amount, UTR and idempotency checks used by the webhook path before changing state. Do not let a browser call the PaymentSetu endpoint with your API key.

The credits response can be logged or displayed as a small operational value. Do not hard-code the remaining balance because it changes as payment links are created. A plan credit represents one successful payment verified.

Success looks like this: a pending order can be reconciled from your server, and your operations view reads the current credit response rather than a stale number.

Verify the integration end to end

Run these checks in a test environment before enabling fulfilment:

  • Create a cart and confirm the database stores one pending order with the correct amount in paisa.
  • Confirm the create_order response contains status: true and a non-empty payment_url.
  • Open the URL and check that the displayed amount matches your local order.
  • Send a valid signed webhook fixture and confirm that one database row changes to PAID.
  • Send the same fixture again and confirm that fulfilment does not run twice.
  • Change one byte of the raw JSON and confirm the controller rejects it before parsing or updating.
  • Send the right body with the wrong secret and confirm it is rejected.
  • Call your own status endpoint after returning from the hosted page; verify it reads server state.
  • Call check_credits from the server and record the response without exposing the API key.

Log an internal order ID and result, not the API key, webhook secret or complete payment payload. Keep the return page useful for the customer, but make the signed webhook and database transition the source of fulfilment truth.

Troubleshooting

Every webhook has an invalid signature

Confirm that the controller receives the original body as byte[], that the timestamp is included in the signed message, and that you use the exact header names. Check whether your account specifies hexadecimal or another digest representation. Do not calculate HMAC from JsonNode.toString() after parsing.

The API returns an error from create_order

Check the bearer header, JSON content type, unique order ID and integer paisa amount. Also confirm that the API key is active and that your plan has available credits. Log the HTTP status and a safe provider message on the server, not the credential.

The customer paid but the order is still pending

Treat the browser return as navigation only. Check your HTTPS webhook route, inspect the server’s signature result and use order_status/{client_txn_id} from a server-side reconciliation task. Before changing state, compare the returned order ID, amount and UTR with your local record.

The same order is fulfilled twice

Move the state transition into one database transaction and add a unique constraint for the UTR or event ID. The method must return a “changed one row” result; only that result may call fulfilment.

FAQ

Is PaymentSetu a Java payment gateway?

No. PaymentSetu is a payment verification service. Your customer pays by UPI into your own connected Paytm Business or PhonePe Business merchant account, while PaymentSetu matches the payment to the order and sends a webhook.

How do I create a UPI QR order in Spring Boot?

Save a pending order, calculate the total in integer paisa and call POST /api/create_order with the bearer API key. Redirect the customer to the returned payment_url; keep order confirmation on your signed webhook path.

Should the Java webhook parse JSON before checking HMAC?

No. Read the raw request body as byte[], verify the timestamped HMAC-SHA256 value, and parse the JSON only after the signature passes. Re-serialising parsed JSON can change the bytes and invalidate the signature check.

How do I stop duplicate webhook processing in Spring Boot?

Use a database transaction, a unique UTR or event identifier, and a conditional PENDING to PAID update. If the update changes zero rows because the event was already accepted, return success without running fulfilment again.

Which PaymentSetu plan suits a Spring Boot integration?

PaymentSetu Pro is ₹999 per 30 days with 1,000 verified-payment credits, API access, webhooks and priority support. Smaller projects can compare Starter at ₹399 per 30 days, while higher-volume systems can review Business at ₹1,499 per 30 days on the pricing page.

Previous Article

WHMCS Automation Settings: Invoices, Reminders & Suspensions

Next Article

Callback URL vs Webhook vs Return URL in Payments

Write a Comment

Leave a Comment

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