UPI Payment Integration in Android (Kotlin) With Auto-Verification

Learn upi payment integration in android with Kotlin, UPI intent, server-created orders, signed webhooks and safe auto-verification step by step.
A blue illustration of an Android phone launching a UPI payment beside a server, QR code and verified webhook checkmark.

UPI payment integration in android is straightforward to start with an intent, but the intent result is not proof that money reached your account. This guide shows a Kotlin flow that creates an order on your server, launches an order-specific UPI payment, and marks the order paid only after server-side verification.

The important separation is simple: Android starts the payment experience; your backend decides whether the order is paid. PaymentSetu is a payment verification service, not a payment gateway. The customer pays directly into your own connected Paytm Business or PhonePe Business merchant account, while PaymentSetu matches the payment to the order and sends your webhook.

What you need

Why this matters: an Android app can display a payment request, but it should not hold credentials or make the final payment decision.

Prepare these pieces before writing the Kotlin screen:

  1. An Android Studio project using Kotlin and AndroidX Activity.
  2. A PaymentSetu account with an API key and webhook secret kept on your server.
  3. A connected Paytm Business or PhonePe Business merchant account that should receive the customer’s payment.
  4. A backend database record for the order amount, currency, unique client_txn_id, payment status and UTR.
  5. A public HTTPS webhook endpoint.

For a custom app, PaymentSetu exposes POST /api/create_order, GET /api/order_status/{client_txn_id} and GET /api/check_credits. API-key authentication belongs on your backend, never in the APK. The service uses HMAC-signed webhooks, so your endpoint can verify that a notification came from the configured integration before changing an order.

If you are building a website rather than a native app, see our guide to creating a UPI payment link. The same rule applies: a link starts payment, while a trusted server event confirms it.

How UPI intent works on Android

Why this matters: knowing the hand-off boundary prevents you from treating an app switch as a successful transaction.

Android’s implicit ACTION_VIEW intent lets your app pass a URI to another installed app that can handle it. A UPI payment URI commonly uses the upi://pay scheme and carries values such as the payee, amount, currency and transaction reference. Android then lets the customer choose an available UPI app and authorise the payment there.

The Android common intents documentation describes ACTION_VIEW, URI data and checking resolveActivity() before launching. NPCI also lists intent as one of the merchant UPI integration modes in its UPI FAQ.

For an order-based flow, the URI should contain values generated from the server’s order record. A typical shape looks like this:

upi://pay?pa=merchant%40bank&pn=Example%20Store&am=1299.00&cu=INR&tr=ORD-20261029-1042&tn=Order%201042

Do not build the payee, price or order reference from an untrusted amount supplied by the app. Your server should create the order, calculate the final amount, and return either the payment URI or the payment data needed by your integration. Encode each URI value once; an ampersand inside a note must not become a new query parameter.

Success looks like this: tapping Pay opens a compatible UPI app with the expected merchant and amount visible, and your app still shows the order as pending until the backend confirms it.

Why the intent response is not proof of payment

Why this matters: a return code describes the hand-off between apps, not the final credit in your merchant account.

The UPI app can return control to your activity after the customer cancels, completes, or leaves the payment screen. Even an Activity.RESULT_OK value is not your accounting record. It does not, on its own, prove the correct amount reached the correct merchant account or that the reference has not already been used.

Google recommends the AndroidX Activity Result APIs for receiving activity results, and notes that the callback should be registered every time the activity is created because the process can be recreated while another activity is open. See Get a result from an activity for the current pattern.

Use the result only to update the interface:

  • RESULT_OK or a returned data value can trigger a “checking payment” state.
  • RESULT_CANCELED can return the user to the payment screen without changing the order.
  • A missing or unexpected result should also leave the order pending.
  • Only a verified backend event should unlock a product, confirm a booking or activate an account.

This is also why a customer screenshot should not be your success signal. Your server should compare the expected amount, the intended merchant account, the verified UTR and the current order state. The update must be idempotent, so the same event cannot fulfil the order twice.

Step 1: Create the order on your server

Why this matters: the server must own the amount and reference before the app opens a UPI app.

When the customer taps your app’s Pay button, call your own backend, for example POST /mobile/payments. The app sends a product or cart identifier, not a trusted final price. Your backend should:

  1. Load the product or cart from your database.
  2. Calculate the amount using server-side rules.
  3. Generate a unique client_txn_id, such as android-20261029-8f21c6.
  4. Save the order as pending before calling the payment verification service.
  5. Call POST /api/create_order with the current request format from your PaymentSetu API documentation.
  6. Return only the order reference, payment URI or QR data, and a display amount to the Android app.

The API key and webhook secret must never be returned to the app. Keep the vendor-specific mapping in one backend adapter so your mobile client does not depend on a response wrapper or field name.

A server adapter has this shape. The endpoint and authentication are fixed integration boundaries; use the exact payload and response fields shown in your current PaymentSetu account documentation:

<?php
// Your backend: POST /mobile/payments
$clientTxnId = 'android-' . bin2hex(random_bytes(8));
$amount = lookupFinalAmountFromYourDatabase($_POST['cart_id'] ?? '');

// Persist clientTxnId, amount and status=pending before the API request.
$payload = [
    'client_txn_id' => $clientTxnId,
    'amount' => number_format($amount, 2, '.', ''),
    // Add the webhook URL and any other fields required by your API setup.
];

// Send $payload to POST /api/create_order with your server-side API key.
// Map the documented response to your own stable response:
// {"client_txn_id":"...", "upi_uri":"...", "amount":"..."}

Do not let the app call create_order directly. A public API key can be extracted from an APK, and a client-calculated amount can be changed before the order is created.

Success looks like this: your database contains one pending order with a unique reference and exact amount, and the app receives a payment request associated with that same reference.

Step 2: Launch the UPI app from Kotlin

Why this matters: the Android layer should launch the payment request and handle the return without claiming that the order is paid.

Register an AndroidX activity-result launcher in your Activity or Fragment:

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts

class CheckoutActivity : ComponentActivity() {

    private val upiLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        // This is only a client-side return. It is not payment confirmation.
        if (result.resultCode == Activity.RESULT_OK) {
            showPaymentState("Checking payment…")
        } else {
            showPaymentState("Payment not confirmed yet")
        }

        // Ask your backend for the order state; do not mark it paid here.
        refreshOrderFromServer()
    }

    fun launchUpiPayment(upiUriFromYourServer: String) {
        val paymentIntent = Intent(
            Intent.ACTION_VIEW,
            Uri.parse(upiUriFromYourServer)
        )

        if (paymentIntent.resolveActivity(packageManager) == null) {
            showPaymentState("No compatible UPI app found")
            return
        }

        upiLauncher.launch(
            Intent.createChooser(paymentIntent, "Pay with UPI")
        )
    }

    private fun showPaymentState(message: String) {
        // Update your view model or Compose state here.
    }

    private fun refreshOrderFromServer() {
        // GET your own /mobile/payments/{client_txn_id}/status endpoint.
    }
}

Call launchUpiPayment() only with the URI returned by your backend. If your server response contains QR data rather than a URI, show the QR as a separate option or have your backend provide the app-ready payment data according to your configured flow. Do not silently construct a new payee or amount in the app.

The customer can return to your app before the verification event reaches your backend. Keep the screen in a pending state and let your status endpoint read your database, rather than accepting a value supplied in the activity result.

Step 3: Confirm with the webhook and order status

Why this matters: the webhook is the server-side signal that connects the verified payment to the order; the status endpoint is useful for a controlled re-check.

Configure your PaymentSetu webhook URL on the server. On each notification, process the raw request in this order:

  1. Read the raw request body without reserialising it.
  2. Read the signature header configured for your webhook.
  3. Calculate the HMAC using the webhook secret and the exact raw body.
  4. Compare signatures in constant time and reject an invalid signature.
  5. Parse the event and load the local order by client_txn_id.
  6. Compare the verified amount with the stored amount.
  7. Check that the UTR has not already been applied to another order.
  8. In one database transaction, record the UTR and change the order from pending to paid.
  9. Make a repeated event a harmless no-op and return a successful response after the existing paid record is confirmed.

The HMAC check is intentionally shown as an algorithm rather than a made-up header name or JSON shape:

expected = HMAC-SHA256(webhook_secret, raw_request_body)
accept only when constant_time_compare(expected, configured_signature)

Your Android status endpoint can now return pending or paid from your own database. If a webhook has not yet been observed, your backend can call GET /api/order_status/{client_txn_id} using the API key and update the local record after applying the same amount, UTR and idempotency checks. The app should never call that vendor endpoint with the API key.

For a website or existing checkout, the same pattern can be added without building a native screen. Our guide to accepting UPI payments on a website without a gateway explains the direct-to-merchant verification model.

Success looks like this: the UPI app’s return only starts a refresh, while the backend changes the order to paid after a valid signed event and a matching amount.

Step 4: Keep the Android UI honest

Why this matters: clear states stop customers and support staff from confusing “app closed” with “payment verified”.

Use a small state machine rather than a single Boolean:

App stateWhat it meansAllowed action
creatingYour backend is creating the orderDisable duplicate taps
readyThe server returned a payment requestLaunch the UPI intent
checkingThe customer returned or the app is refreshingQuery your backend
paidYour backend received and applied a verified eventFulfil once
pendingNo verified event is recorded yetKeep the order open and allow a safe refresh

Keep the client_txn_id in the screen’s state or saved-state model so a process recreation does not cause a second order accidentally. When the app resumes, fetch the order from your backend. Do not create a replacement order merely because the first activity result was empty.

Success looks like this: every screen state comes from the order reference and your backend, so reopening the app cannot accidentally fulfil or duplicate the order.

Show the merchant name and amount before the customer confirms payment. Never place API keys, webhook secrets or bank-login credentials in strings resources, build constants, logs or analytics events.

Step 5: Test on a real Android device

Why this matters: intent handling depends on the installed UPI apps and the customer’s device, so an emulator-only check is incomplete.

Use a controlled test order and verify each boundary:

  1. Create an order from the app and confirm the backend stored the expected amount and unique reference.
  2. Check that the returned URI shows the intended payee and amount in the selected UPI app.
  3. Complete a controlled low-value payment and confirm the money reaches your own connected merchant account.
  4. Confirm that the webhook signature is checked against the raw body.
  5. Confirm that the matching UTR changes only the intended order to paid.
  6. Relaunch the app and verify that it reads the existing order rather than creating a duplicate.
  7. Deliver the same webhook event again and confirm that fulfilment happens once.
  8. Call your status endpoint for a pending reference and confirm that the API key remains server-side.

Test the return path as well: close the UPI app without authorising, return to your app, and make sure the order remains pending. The customer-facing screen can offer “Check payment status” while your backend continues to rely on the signed verification flow.

Success looks like this: a real-device payment can be traced from the app’s order reference to the verified UTR, and replaying the webhook does not repeat fulfilment.

Troubleshooting

The UPI app does not open

Log the scheme and check that your URI begins with upi://pay. Keep resolveActivity() in place and provide a QR or another payment surface when no compatible handler is installed. Also check that you are testing on a device with a UPI app configured for payments.

The app returns but the order is still pending

That return is not the payment confirmation. Show a checking state, ask your own backend for the order status, and let the webhook or verified order_status result update the order. Do not change the status from the Kotlin callback.

The amount or merchant name looks wrong

Inspect the server’s stored order and the URI it returned. Check that the amount was formatted as a plain decimal such as 1299.00, that each parameter value was encoded once, and that the app did not rebuild the URI from stale cart data.

The webhook is rejected

Compare the HMAC input byte-for-byte with the raw request body and use the secret configured for this endpoint. Do not parse and reserialise JSON before calculating the signature. After the signature passes, verify client_txn_id, amount, status and UTR before applying the event.

FAQ

How do I integrate UPI payments in an Android Kotlin app?

Create the order on your backend, return an order-specific UPI payment request, and launch it with an Android ACTION_VIEW intent. After the customer pays, confirm the order through a signed server webhook or a server-side status check; do not trust the activity result alone.

Can I mark an order paid from Activity.RESULT_OK?

No. The result only describes what happened during the activity hand-off. Mark the order paid after your backend verifies the matching amount and UTR for the intended merchant account and processes the event idempotently.

Should the Android app call PaymentSetu directly?

No. Keep the PaymentSetu API key and webhook secret on your server. The app should call your own backend, which creates the order, returns safe payment data, and exposes a status endpoint that contains only the information the app needs.

Is PaymentSetu a payment gateway for Android apps?

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

Which PaymentSetu plan suits a growing Android app?

PaymentSetu Pro costs ₹999 per 30 days and includes 1,000 credits, with one credit representing one successful payment verified. It includes dynamic QR, webhooks, REST API access and priority support; compare the current plans before choosing your volume.

Previous Article

How to Choose a Payment Gateway: 12-Point Checklist

Next Article

Payment Gateway KYC Documents in India: Checklist

Write a Comment

Leave a Comment

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