---
updatedAt: 2026-09-24T06:38:11.000Z
agentTools:
  projectIndex: https://docs.payu.in/llms.txt
---

# UPI TPV Integration - Partner Payments 

Partner Payments UPI TPV (Third-Party Verification) enables partners to initiate UPI payments with beneficiary account validation. Unlike standard UPI Intent, TPV ensures that the payment is made from a specific verified bank account by validating the customer's UPI account against the beneficiary details you provide.

This is critical for regulatory compliance scenarios where you need to ensure funds originate from an authorized account, such as loan repayments where the borrower must pay from their registered account, or vendor payments where the vendor must use their verified business account.

**Key Benefits:**

* **Account validation** — Ensures payment comes from the authorized beneficiary account
* **Regulatory compliance** — Meets KYC and anti-money laundering requirements
* **Fraud prevention** — Prevents payments from unauthorized accounts
* **Audit trail** — Complete record of which account was used for payment
* **Secure S2S flow** — Direct UPI app invocation with account verification

This integration is ideal for:

* **Loan repayments** — EMI collections from borrower's registered account
* **Vendor payments** — Ensure payments come from vendor's verified business account
* **Refund collections** — Collect refunds to the original payment account
* **Compliance-heavy industries** — NBFC, lending, insurance, government payments

***

## How It Works

The Partner Payments UPI TPV flow follows these steps:

1. **Get the Access Token** — Obtain an access token with scope: `hub_session`

2. **Initiate UPI TPV Payment** — POST a payment request with:
   * `txn_s2s_flow=4` (enables UPI S2S flow)
   * Beneficiary account details (`beneficiarydetail` with IFSC, account number, account holder name)
   * Customer device details (`s2s_client_ip`, `s2s_device_info`)
   * Computed hash

3. **Receive intentURIData** — PayU returns a UPI deep link string and sets `bankcode=INTTPV`, `api_version=6` internally

4. **Invoke UPI App** — Customer's UPI app opens with pre-filled payment details

5. **Account Validation** — PayU validates the customer's UPI account against beneficiary details provided

6. **Customer Authenticates** — If account matches, customer enters UPI PIN; if mismatch, payment is rejected

7. **Receive Webhook** — PayU sends payment status notification with `bankcode=INTTPV`

8. **Verify Payment** — Call Verify Payment API to confirm final transaction status

***

## Prerequisites

Before you begin, ensure you have:

* **Partner OAuth Application** registered with PayU with the above scopes enabled
* **OAuth Credentials:** `client_id` and `client_secret`
* **Merchant Credentials:** `merchant_id` (PayU merchant ID) and `reseller_id` (partner UUID)
* **UPI TPV Enabled** — Your account must be enabled for UPI TPV transactions (contact PayU)
* **S2S Flow Enabled** — Support for `txn_s2s_flow=4`
* **Partner Webhook URLs** configured (`partner_webhook_success`, `partner_webhook_failure`, `partner_webhook_cancelled`)
* **Beneficiary Account Details:**
  * IFSC code
  * Account number
  * Account holder name
* **Ability to Capture:**
  * Customer IP address (`s2s_client_ip`)
  * Device user-agent string (`s2s_device_info`)
* **Test Environment Access** to `https://test-partnerapilayer.payu.in`

<Warning>
**Critical Requirements for UPI TPV:**
- `txn_s2s_flow` MUST be set to `"4"`
- `beneficiarydetail` is **mandatory** for TPV (contains IFSC, account number, account holder name)
- `s2s_client_ip` and `s2s_device_info` are **mandatory** when txn_s2s_flow=4
- `beneficiarydetail` is **NOT included in hash calculation**
- All hash computations use OAuth `client_secret` (NOT merchant salt)
- When beneficiarydetail is present with txn_s2s_flow=4, PayU automatically sets `bankcode=INTTPV` and `api_version=6`
</Warning>

***

## Step 1: Get the Access Token

The `auth_code` is received on the configured redirect URI. Validate this auth\_code using the [Validate Auth Code and Client API](https://docs.payu.in/reference-link/validate-auth-code-and-client). If you already have the `access_token`, skip this step and proceed to Step 2.

You will receive an `access_token`.&#x20;

<Accordion title="Request Parameters" icon="far fa-abacus">
  | Parameter       | Required | Description                                                                                                                | Example value            |
  | --------------- | -------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
  | `client_id`     | Yes      | Client identifier.                                                                                                         | `{{client_id}}`          |
  | `client_secret` | Yes      | Client secret code.                                                                                                        | `{{client_secret}}`      |
  | `grant_type`    | Yes      | Grant type used to obtain an access token in this flow. Must be `authorization_code`.                                      | `authorization_code`     |
  | `code`          | Yes      | Authorization code received on the redirect URI.                                                                           | `{{authorization_code}}` |
  | `redirect_uri`  | Yes      | Redirect URL associated with the authorization request. It must match the redirect URI used for the authorization request. | `{{redirect_uri}}`       |
</Accordion>

<Accordion title="Sample request" icon="fa-code">
  ```bash
  curl --location '{{accounts_base_url}}/oauth/token' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode 'client_id={{client_id}}' \
    --data-urlencode 'client_secret={{client_secret}}' \
    --data-urlencode 'grant_type=authorization_code' \
    --data-urlencode 'code={{authorization_code}}' \
    --data-urlencode 'redirect_uri={{redirect_uri}}'
  ```
</Accordion>

<Accordion title="Sample response" icon="far fa-reply">
  ```json
  {
    "access_token": "{{access_token}}",
    "token_type": "Bearer",
    "expires_in": {{expires_in}},
    "refresh_token": "{{refresh_token}}",
    "scope": "{{scope}}",
    "created_at": {{created_at}},
    "user_uuid": "{{user_uuid}}"
  }
  ```
</Accordion>

Send the access token as a bearer token when calling Partner Integration APIs.

<br />

## Step 2: Initiate UPI TPV Payment

### Step 2.1: Prepare Request Parameters

**Endpoint URLs:**

| Environment | URL                                                              |
| ----------- | ---------------------------------------------------------------- |
| Test        | `https://test-partnerapilayer.payu.in/apilayer/partner/payments` |
| Production  | `https://api.payu.in/partner/payments`                           |

**HTTP Method:** `POST`

**Headers:**

Use the `access_token` from Step 1 for this step as bearer token:

```
Authorization: Bearer <your_access_token>
Content-Type: application/json
```

<Accordion title="Request Parameters" icon="fa-info-circle">
  **Mandatory Parameters**

  <table>
    <thead>
      <tr>
        <th>Parameter</th>
        <th>Type & Description</th>
        <th>Example</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>txnid</td>
        <td><strong>string</strong> - Unique transaction ID generated by the partner.</td>
        <td>TPVUPI20240315001</td>
      </tr>
      <tr>
        <td>amount</td>
        <td><strong>string</strong> - Transaction amount in decimal format.</td>
        <td>518.02</td>
      </tr>
      <tr>
        <td>productinfo</td>
        <td><strong>string</strong> - Product or service description.</td>
        <td>Loan EMI Payment</td>
      </tr>
      <tr>
        <td>phone</td>
        <td><strong>string</strong> - Customer phone number with country code (10 digits).</td>
        <td>919876543210</td>
      </tr>
      <tr>
        <td>merchant_id</td>
        <td><strong>integer</strong> - PayU merchant ID.</td>
        <td>8739528</td>
      </tr>
      <tr>
        <td>reseller_id</td>
        <td><strong>string</strong> - Partner/reseller UUID.</td>
        <td>11ee-0e7e-5403fde2-9523-0a696b110fde</td>
      </tr>
      <tr>
        <td>txn_s2s_flow</td>
        <td><strong>string</strong> - Server-to-server flow identifier. Must be <code>4</code> for UPI TPV.</td>
        <td>4</td>
      </tr>
      <tr>
        <td>s2s_client_ip</td>
        <td><strong>string</strong> - Customer's IP address.</td>
        <td>157.240.22.9</td>
      </tr>
      <tr>
        <td>s2s_device_info</td>
        <td><strong>string</strong> - Customer's device user-agent string.</td>
        <td>Mozilla/5.0 (iPhone) AppleWebKit/602.4.6</td>
      </tr>
      <tr>
        <td>beneficiarydetail</td>
        <td><strong>string (JSON)</strong> - Beneficiary account details for TPV validation. Must contain: <code>ifscCode</code>, <code>accountNumber</code>, <code>accountHolderName</code></td>
        <td>{"ifscCode":"ICIC0001234","accountNumber":"123456789012","accountHolderName":"Test User"}</td>
      </tr>
      <tr>
        <td>hash</td>
        <td><strong>string</strong> - SHA-512 hash for request authentication, encoded as a lowercase hex string. <strong>Note:</strong> beneficiarydetail is NOT included in hash calculation.</td>
        <td>a3f7c92e1b...</td>
      </tr>
    </tbody>
  </table>

  **Optional Parameters**

  | Parameter | Type & Description                                                                    | Example                                                                      |
  | --------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
  | firstname | <strong>string</strong> - Customer's first name.                                      | Amit                                                                         |
  | email     | <strong>string</strong> - Customer's email address.                                   | [amit.kumar@example.com](mailto:amit.kumar@example.com)                      |
  | udf1      | <strong>string</strong> - User-defined field 1 for custom data.                       | loan_account_123                                                             |
  | udf2      | <strong>string</strong> - User-defined field 2 for custom data.                       | emi_month_06                                                                 |
  | udf3      | <strong>string</strong> - User-defined field 3 for custom data.                       | tpv_reference_001                                                            |
  | udf4      | <strong>string</strong> - User-defined field 4 for custom data.                       | borrower_id_456                                                              |
  | udf5      | <strong>string</strong> - User-defined field 5, often used for partner or channel ID. | partner_tpv_channel                                                          |
  | surl      | <strong>string</strong> - Success callback URL (optional for S2S flow).               | [https://yoursite.com/payment/success](https://yoursite.com/payment/success) |
  | furl      | <strong>string</strong> - Failure callback URL (optional for S2S flow).               | [https://yoursite.com/payment/failure](https://yoursite.com/payment/failure) |
  | curl      | <strong>string</strong> - Cancel callback URL (optional for S2S flow).                | [https://yoursite.com/payment/cancel](https://yoursite.com/payment/cancel)   |

  <Warning>
  **UPI TPV-Specific Notes:**
  - `txn_s2s_flow` MUST be set to `"4"` — This activates the UPI S2S TPV flow
  - `beneficiarydetail` is **mandatory** — Contains IFSC, account number, and account holder name in JSON format
  - `beneficiarydetail` is **NOT included in hash calculation** — Use the same hash formula as UPI Intent
  - When `beneficiarydetail` + `txn_s2s_flow=4` are present, PayU automatically sets:
    - `bankcode = INTTPV`
    - `api_version = 6`
  - `s2s_client_ip` and `s2s_device_info` are **mandatory** when txn_s2s_flow=4
  - Do NOT send `beneficiarydetail` in the hash string
  </Warning>

  **Beneficiarydetail Structure:**

  ```json
  {
    "ifscCode": "ICIC0001234",
    "accountNumber": "123456789012",
    "accountHolderName": "Test User"
  }
  ```

  Send this as a **JSON string** (not an object) in the `beneficiarydetail` parameter.
</Accordion>

### Step 2.2: Generate Payment Request Hash

The payment request hash authenticates your API call using SHA-512. **Important:** The `beneficiarydetail` parameter is NOT included in the hash calculation.

**Hash Formula:**

```
merchant_id|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5||||||client_secret
```

<Warning>
**Critical Hash Rules:**
- There are **six consecutive pipes** (`||||||`) between `udf5` and `client_secret`
- Use your OAuth **client_secret** (NOT merchant salt)
- Use empty strings for any missing optional fields (results in consecutive pipes)
- **DO NOT include `beneficiarydetail` in the hash** — Use the same formula as UPI Intent
- Compute SHA-512 and output as **lowercase hexadecimal**
- Do NOT add a trailing pipe after `client_secret`
</Warning>

<Accordion title="Sample Hash Generation Code" icon="fa-code">
  ```python
  import hashlib

  def generate_payment_hash(merchant_id, txnid, amount, productinfo, firstname, email, udf1, udf2, udf3, udf4, udf5, client_secret):
      hash_string = f"{merchant_id}|{txnid}|{amount}|{productinfo}|{firstname}|{email}|{udf1}|{udf2}|{udf3}|{udf4}|{udf5}||||||{client_secret}"
      return hashlib.sha512(hash_string.encode('utf-8')).hexdigest()

  # Example usage
  payment_hash = generate_payment_hash(
      merchant_id=8739528,
      txnid="PPHOST20240315001",
      amount="1500.00",
      productinfo="Premium Subscription - Monthly",
      firstname="Priya",
      email="priya.sharma@example.com",
      udf1="subscription_plan_premium",
      udf2="monthly_billing",
      udf3="",
      udf4="",
      udf5="partner_web_checkout",
      client_secret="your_client_secret_here"
  )

  print(f"Payment Hash: {payment_hash}")
  ```
  ```java
  import java.security.MessageDigest;
  import java.security.NoSuchAlgorithmException;

  public class HostedCheckoutHashGenerator {
      public static String generateHash(
          int merchantId, String txnid, String amount, String productinfo,
          String firstname, String email, String udf1, String udf2, 
          String udf3, String udf4, String udf5, String clientSecret
      ) throws NoSuchAlgorithmException {
          
          String hashString = merchantId + "|" + txnid + "|" + amount + "|" + 
                            productinfo + "|" + firstname + "|" + email + "|" +
                            udf1 + "|" + udf2 + "|" + udf3 + "|" + udf4 + "|" + 
                            udf5 + "||||||" + clientSecret;
          
          MessageDigest md = MessageDigest.getInstance("SHA-512");
          byte[] hashBytes = md.digest(hashString.getBytes());
          
          StringBuilder hexString = new StringBuilder();
          for (byte b : hashBytes) {
              String hex = Integer.toHexString(0xff & b);
              if (hex.length() == 1) hexString.append('0');
              hexString.append(hex);
          }
          
          return hexString.toString();
      }
  }
  ```
  ```php
  <?php
  function generateHostedCheckoutHash($merchantId, $txnid, $amount, $productinfo, 
                                      $firstname, $email, $udf1, $udf2, $udf3, 
                                      $udf4, $udf5, $clientSecret) {
      
      $hashString = $merchantId . "|" . $txnid . "|" . $amount . "|" . 
                    $productinfo . "|" . $firstname . "|" . $email . "|" .
                    $udf1 . "|" . $udf2 . "|" . $udf3 . "|" . $udf4 . "|" . 
                    $udf5 . "||||||" . $clientSecret;
      
      return hash('sha512', $hashString);
  }

  // Example
  $hash = generateHostedCheckoutHash(
      8739528,
      "PPHOST20240315001",
      "1500.00",
      "Premium Subscription - Monthly",
      "Priya",
      "priya.sharma@example.com",
      "subscription_plan_premium",
      "monthly_billing",
      "",
      "",
      "partner_web_checkout",
      "your_client_secret_here"
  );

  echo "Payment Hash: " . $hash;
  ?>
  ```
</Accordion>

### Step 2.3: Post the request

```curl
curl --location 'https://test-partnerapilayer.payu.in/apilayer/partner/payments' \
--header 'Authorization: Bearer your_access_token_here' \
--header 'Content-Type: application/json' \
--data '{
  "txnid": "28471834809170982",
  "amount": "518.02",
  "productinfo": "28471834809170982",
  "firstname": "",
  "lastname": "",
  "email": "",
  "phone": "919820988398",
  "merchant_id": 8739528,
  "reseller_id": "11ee-0e7e-5403fde2-9523-0a696b110fde",
  "udf1": "",
  "udf2": "1370625260",
  "udf3": "r-hway-TPV-REFERENCE",
  "udf4": "",
  "udf5": "whatsapp",
  "surl": "https://merchant.example.com/success",
  "furl": "https://merchant.example.com/failure",
  "curl": "https://merchant.example.com/cancel",
  "txn_s2s_flow": "4",
  "s2s_client_ip": "157.240.22.9",
  "s2s_device_info": "Mozilla/5.0 (iPhone) AppleWebKit/602.4.6",
  "beneficiarydetail": "{\"ifscCode\":\"ICIC0001234\",\"accountNumber\":\"123456789012\",\"accountHolderName\":\"Test User\"}",
  "hash": "<PAYMENT_REQUEST_HASH>"
}'
```
```python
import requests
import json

url = "https://test-partnerapilayer.payu.in/apilayer/partner/payments"

headers = {
    "Authorization": "Bearer your_access_token_here",
    "Content-Type": "application/json"
}

payload = {
    "txnid": "28471834809170982",
    "amount": "518.02",
    "productinfo": "28471834809170982",
    "firstname": "",
    "lastname": "",
    "email": "",
    "phone": "919820988398",
    "merchant_id": 8739528,
    "reseller_id": "11ee-0e7e-5403fde2-9523-0a696b110fde",
    "udf1": "",
    "udf2": "1370625260",
    "udf3": "r-hway-TPV-REFERENCE",
    "udf4": "",
    "udf5": "whatsapp",
    "surl": "https://merchant.example.com/success",
    "furl": "https://merchant.example.com/failure",
    "curl": "https://merchant.example.com/cancel",
    "txn_s2s_flow": "4",
    "s2s_client_ip": "157.240.22.9",
    "s2s_device_info": "Mozilla/5.0 (iPhone) AppleWebKit/602.4.6",
    "beneficiarydetail": "{\"ifscCode\":\"ICIC0001234\",\"accountNumber\":\"123456789012\",\"accountHolderName\":\"Test User\"}",
    "hash": "<PAYMENT_REQUEST_HASH>"
}

try:
    response = requests.post(url, headers=headers, json=payload)
    print(f"Status Code: {response.status_code}")
    print(f"Response: {response.text}")
except requests.exceptions.RequestException as e:
    print(f"Error: {e}")
```
```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        try
        {
            string url = "https://test-partnerapilayer.payu.in/apilayer/partner/payments";

            var payload = new
            {
                txnid = "28471834809170982",
                amount = "518.02",
                productinfo = "28471834809170982",
                firstname = "",
                lastname = "",
                email = "",
                phone = "919820988398",
                merchant_id = 8739528,
                reseller_id = "11ee-0e7e-5403fde2-9523-0a696b110fde",
                udf1 = "",
                udf2 = "1370625260",
                udf3 = "r-hway-TPV-REFERENCE",
                udf4 = "",
                udf5 = "whatsapp",
                surl = "https://merchant.example.com/success",
                furl = "https://merchant.example.com/failure",
                curl = "https://merchant.example.com/cancel",
                txn_s2s_flow = "4",
                s2s_client_ip = "157.240.22.9",
                s2s_device_info = "Mozilla/5.0 (iPhone) AppleWebKit/602.4.6",
                beneficiarydetail = "{\"ifscCode\":\"ICIC0001234\",\"accountNumber\":\"123456789012\",\"accountHolderName\":\"Test User\"}",
                hash = "<PAYMENT_REQUEST_HASH>"
            };

            string jsonPayload = JsonSerializer.Serialize(payload);
            var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer your_access_token_here");

            HttpResponseMessage response = await client.PostAsync(url, content);
            string responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"Status Code: {response.StatusCode}");
            Console.WriteLine($"Response: {responseContent}");
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
    }
}
```
```javascript
async function initiatePayment() {
    const url = "https://test-partnerapilayer.payu.in/apilayer/partner/payments";

    const payload = {
        txnid: "28471834809170982",
        amount: "518.02",
        productinfo: "28471834809170982",
        firstname: "",
        lastname: "",
        email: "",
        phone: "919820988398",
        merchant_id: 8739528,
        reseller_id: "11ee-0e7e-5403fde2-9523-0a696b110fde",
        udf1: "",
        udf2: "1370625260",
        udf3: "r-hway-TPV-REFERENCE",
        udf4: "",
        udf5: "whatsapp",
        surl: "https://merchant.example.com/success",
        furl: "https://merchant.example.com/failure",
        curl: "https://merchant.example.com/cancel",
        txn_s2s_flow: "4",
        s2s_client_ip: "157.240.22.9",
        s2s_device_info: "Mozilla/5.0 (iPhone) AppleWebKit/602.4.6",
        beneficiarydetail: "{\"ifscCode\":\"ICIC0001234\",\"accountNumber\":\"123456789012\",\"accountHolderName\":\"Test User\"}",
        hash: "<PAYMENT_REQUEST_HASH>"
    };

    const requestOptions = {
        method: "POST",
        headers: {
            "Authorization": "Bearer your_access_token_here",
            "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
    };

    try {
        const response = await fetch(url, requestOptions);
        const responseText = await response.text();
        console.log(`Status: ${response.status}`);
        console.log(`Response: ${responseText}`);
        return { status: response.status, data: responseText };
    } catch (error) {
        console.error("Error:", error);
        throw error;
    }
}

// Usage
initiatePayment()
    .then(result => console.log("Success:", result))
    .catch(error => console.error("Failed:", error));
```
```java
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class PayUPartnerPayment {
    public static void main(String[] args) {
        try {
            initiatePayment();
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    public static void initiatePayment() throws IOException {
        String url = "https://test-partnerapilayer.payu.in/apilayer/partner/payments";

        String jsonPayload = "{"
                + "\"txnid\": \"28471834809170982\"" + ","
                + "\"amount\": \"518.02\"" + ","
                + "\"productinfo\": \"28471834809170982\"" + ","
                + "\"firstname\": \"\"" + ","
                + "\"lastname\": \"\"" + ","
                + "\"email\": \"\"" + ","
                + "\"phone\": \"919820988398\"" + ","
                + "\"merchant_id\": 8739528" + ","
                + "\"reseller_id\": \"11ee-0e7e-5403fde2-9523-0a696b110fde\"" + ","
                + "\"udf1\": \"\"" + ","
                + "\"udf2\": \"1370625260\"" + ","
                + "\"udf3\": \"r-hway-TPV-REFERENCE\"" + ","
                + "\"udf4\": \"\"" + ","
                + "\"udf5\": \"whatsapp\"" + ","
                + "\"surl\": \"https://merchant.example.com/success\"" + ","
                + "\"furl\": \"https://merchant.example.com/failure\"" + ","
                + "\"curl\": \"https://merchant.example.com/cancel\"" + ","
                + "\"txn_s2s_flow\": \"4\"" + ","
                + "\"s2s_client_ip\": \"157.240.22.9\"" + ","
                + "\"s2s_device_info\": \"Mozilla/5.0 (iPhone) AppleWebKit/602.4.6\"" + ","
                + "\"beneficiarydetail\": \"{\\\"ifscCode\\\":\\\"ICIC0001234\\\",\\\"accountNumber\\\":\\\"123456789012\\\",\\\"accountHolderName\\\":\\\"Test User\\\"}\"" + ","
                + "\"hash\": \"<PAYMENT_REQUEST_HASH>\""
                + "}";

        URL urlObj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer your_access_token_here");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Status Code: " + responseCode);

        try (BufferedReader br = new BufferedReader(new InputStreamReader(
                responseCode >= 200 && responseCode < 300
                        ? connection.getInputStream()
                        : connection.getErrorStream(),
                StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            System.out.println("Response: " + response.toString());
        }

        connection.disconnect();
    }
}
```
```php
<?php

$url = "https://test-partnerapilayer.payu.in/apilayer/partner/payments";

$payload = [
    "txnid"            => "28471834809170982",
    "amount"           => "518.02",
    "productinfo"      => "28471834809170982",
    "firstname"        => "",
    "lastname"         => "",
    "email"            => "",
    "phone"            => "919820988398",
    "merchant_id"      => 8739528,
    "reseller_id"      => "11ee-0e7e-5403fde2-9523-0a696b110fde",
    "udf1"             => "",
    "udf2"             => "1370625260",
    "udf3"             => "r-hway-TPV-REFERENCE",
    "udf4"             => "",
    "udf5"             => "whatsapp",
    "surl"             => "https://merchant.example.com/success",
    "furl"             => "https://merchant.example.com/failure",
    "curl"             => "https://merchant.example.com/cancel",
    "txn_s2s_flow"     => "4",
    "s2s_client_ip"    => "157.240.22.9",
    "s2s_device_info"  => "Mozilla/5.0 (iPhone) AppleWebKit/602.4.6",
    "beneficiarydetail"=> '{"ifscCode":"ICIC0001234","accountNumber":"123456789012","accountHolderName":"Test User"}',
    "hash"             => "<PAYMENT_REQUEST_HASH>"
];

$jsonPayload = json_encode($payload);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer your_access_token_here",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo "Error: " . curl_error($ch);
} else {
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    echo "Status Code: " . $httpCode . "\n";
    echo "Response: " . $response . "\n";
}

curl_close($ch);
?>
```

<Callout icon="📘" theme="info">
  ``**Note:** The `Authorization` header value `your_access_token_here` is carried over from the earlier sample request. Replace it with your actual Bearer token before making the call.``
</Callout>

### Step 2.4: Handle Payment Response

**Success Response:**

```json
{
  "metaData": {
    "message": null,
    "referenceId": "7a3060b7462bd2ce6d025c9997220e01",
    "statusCode": null,
    "txnId": "TPVUPI20240315001",
    "txnStatus": "pending",
    "unmappedStatus": "pending"
  },
  "result": {
    "paymentId": "30478359671",
    "merchantName": "YourMerchantName",
    "merchantVpa": "merchant.payu@indus",
    "amount": "518.02",
    "intentURIData": "pa=merchant.payu@indus&pn=YOUR MERCHANT NAME&tr=30478359671&tid=TPVUPI20240315001&am=518.02&cu=INR&tn=UPIIntent",
    "acsTemplate": null,
    "otpPostUrl": null
  }
}
```

**Key Response Fields:**

| Field                  | Description                                            |
| ---------------------- | ------------------------------------------------------ |
| `metaData.txnStatus`   | Initial status (typically `"pending"` for UPI TPV)     |
| `result.paymentId`     | PayU's internal payment ID (mihpayid)                  |
| `result.merchantVpa`   | Merchant's UPI VPA for this transaction                |
| `result.intentURIData` | **Critical** — UPI deep link string to invoke UPI apps |

<Info>
**TPV Processing:**
- PayU internally sets `bankcode=INTTPV` and `api_version=6`
- The `intentURIData` is used to invoke the customer's UPI app
- During payment, PayU validates the customer's UPI account against the `beneficiarydetail` you provided
- Payment succeeds only if the account details match
</Info>

<Warning>
**⚠️ Info Gap: UPI App Invocation Code**

The PDF does not include platform-specific code for invoking UPI apps. Refer to the Partner Payment UPI Intent documentation or request official samples from PayU for:
- Android Intent URI invocation
- iOS URL scheme handling
- Mobile web fallback mechanisms
</Warning>

***

## Step 3: Receive Payment Notification

### Step 3.1: Partner Webhook

After the customer completes payment (or if account validation fails), PayU sends a webhook notification to your configured partner webhook URL.

**Sample Success Webhook Payload (UPI TPV):**

```json
{
  "key": "JPM7Fg",
  "txnid": "TPVUPI20240315001",
  "mihpayid": "30478359671",
  "status": "success",
  "unmappedstatus": "captured",
  "mode": "UPI",
  "bankcode": "INTTPV",
  "amount": "518.02",
  "productinfo": "Loan EMI Payment",
  "firstname": "Amit",
  "email": "amit.kumar@example.com",
  "phone": "919876543210",
  "udf1": "loan_account_123",
  "udf2": "emi_month_06",
  "udf3": "tpv_reference_001",
  "udf4": "",
  "udf5": "partner_tpv_channel",
  "merchant_id": "8739528",
  "error": "No Error",
  "error_Message": "No Error",
  "hash": "webhook_hash_from_payu"
}
```

**UPI TPV-Specific Fields:**

| Field            | Value for UPI TPV                                                |
| ---------------- | ---------------------------------------------------------------- |
| `mode`           | `"UPI"`                                                          |
| `bankcode`       | `"INTTPV"` (automatically set by PayU)                           |
| `unmappedstatus` | `"captured"` (success) or `"failed"` (failure/validation failed) |

### Step 3.2: Verify Webhook Hash

**Reverse Hash Formula:**

```
client_secret|status|||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|merchant_id
```

<Warning>
**Critical Verification Rules:**
- There are **five consecutive pipes** (`|||||`) between `status` and `udf5`
- Use OAuth **client_secret** (NOT merchant salt)
- Do NOT add a trailing pipe after `merchant_id`
- Compute SHA-512 and compare as **case-insensitive**
- **Reject webhook if hash doesn't match**
</Warning>

<Accordion title="Sample Verification Payload" icon="fa-code">
  ```python
  import hashlib

  def verify_webhook_hash(webhook_payload, client_secret):
      status = webhook_payload.get('status', '')
      udf5 = webhook_payload.get('udf5', '')
      udf4 = webhook_payload.get('udf4', '')
      udf3 = webhook_payload.get('udf3', '')
      udf2 = webhook_payload.get('udf2', '')
      udf1 = webhook_payload.get('udf1', '')
      email = webhook_payload.get('email', '')
      firstname = webhook_payload.get('firstname', '')
      productinfo = webhook_payload.get('productinfo', '')
      amount = webhook_payload.get('amount', '')
      txnid = webhook_payload.get('txnid', '')
      merchant_id = webhook_payload.get('merchant_id', '')
      received_hash = webhook_payload.get('hash', '')
      
      hash_string = f"{client_secret}|{status}|||||{udf5}|{udf4}|{udf3}|{udf2}|{udf1}|{email}|{firstname}|{productinfo}|{amount}|{txnid}|{merchant_id}"
      
      computed_hash = hashlib.sha512(hash_string.encode('utf-8')).hexdigest()
      
      return computed_hash.lower() == received_hash.lower()

  # Example
  is_valid = verify_webhook_hash(webhook_data, "your_client_secret")

  if is_valid:
      print("✅ Webhook verified — safe to process")
  else:
      print("❌ Invalid webhook hash — reject")
  ```
  ```java
  import java.security.MessageDigest;
  import java.security.NoSuchAlgorithmException;

  public class WebhookVerifier {
      public static boolean verifyHash(
          String status, String udf5, String udf4, String udf3, String udf2, String udf1,
          String email, String firstname, String productinfo, String amount,
          String txnid, String merchantId, String receivedHash, String clientSecret
      ) throws NoSuchAlgorithmException {
          
          String hashString = clientSecret + "|" + status + "|||||" + 
                            udf5 + "|" + udf4 + "|" + udf3 + "|" + udf2 + "|" + udf1 + "|" +
                            email + "|" + firstname + "|" + productinfo + "|" + 
                            amount + "|" + txnid + "|" + merchantId;
          
          MessageDigest md = MessageDigest.getInstance("SHA-512");
          byte[] hashBytes = md.digest(hashString.getBytes());
          
          StringBuilder hexString = new StringBuilder();
          for (byte b : hashBytes) {
              String hex = Integer.toHexString(0xff & b);
              if (hex.length() == 1) hexString.append('0');
              hexString.append(hex);
          }
          
          return hexString.toString().equalsIgnoreCase(receivedHash);
      }
  }
  ```
</Accordion>

### Step 3.3: Process Webhook

**Python Flask Webhook Handler:**

```python
from flask import Flask, request, jsonify
import hashlib

app = Flask(__name__)

@app.route('/partner/webhook/success', methods=['POST'])
def handle_upi_tpv_webhook():
    webhook_data = request.json
    
    # Verify hash
    if not verify_upi_tpv_webhook_hash(webhook_data, "your_client_secret"):
        return jsonify({"error": "Invalid hash"}), 400
    
    # Extract details
    txnid = webhook_data.get('txnid')
    mihpayid = webhook_data.get('mihpayid')
    status = webhook_data.get('status')
    bankcode = webhook_data.get('bankcode')
    amount = webhook_data.get('amount')
    
    # Verify it's a TPV transaction
    if bankcode == "INTTPV":
        print(f"✅ UPI TPV Payment: {status} | {txnid} | PayU ID: {mihpayid} | Amount: ₹{amount}")
        print(f"   Account validation successful - payment from verified beneficiary account")
    
    # Update database
    # db.update_payment_status(txnid=txnid, mihpayid=mihpayid, status=status, bankcode=bankcode)
    
    # Respond with 200 OK
    return jsonify({"message": "Webhook received"}), 200

if __name__ == '__main__':
    app.run(port=5000)
```

***

## Step 4: Verify Payment

<Accordion title="Verify Payment for Partner Integration" icon="fa-info-circle">
  ### Generate Hash for Verify Payment

  Generate the hash using the following logic and then use it Verify Payment for Partners API:

  **Hash Formula:**

  ```
  merchant_id|verify_payment|txnid|client_secret
  ```

  **Sample Python:**

  ```python
  import hashlib

  def generate_verify_hash(merchant_id, txnid, client_secret):
      hash_string = f"{merchant_id}|verify_payment|{txnid}|{client_secret}"
      return hashlib.sha512(hash_string.encode('utf-8')).hexdigest()

  verify_hash = generate_verify_hash(8739528, "PPHOST20240315001", "your_client_secret")
  ```

  ### Call the Verify Payment API

  #### **Endpoint**

  | Environment | URL                                                                   |
  | ----------- | --------------------------------------------------------------------- |
  | Test        | `https://test-partnerapilayer.payu.in/apilayer/partner/verifyPayment` |
  | Production  | `https://api.payu.in/partner/verifyPayment`                           |

  #### **Request Parmeters**

  **Mandatory Parameters**

  | Parameter   | Description                                              | Example                   |
  | :---------- | :------------------------------------------------------- | :------------------------ |
  | txnid       | The unique transaction ID of the payment to be verified. | PPHOST20240315001         |
  | merchant_id | The unique numeric ID of the merchant.                   | 8739528                   |
  | hash        | The SHA-512 hash computed as: sha512(key\|txnid\|salt)   | computed_verify_hash_here |

  **Optional Parameters**

  | Parameter   | Description                                                      | Example                              |
  | :---------- | :--------------------------------------------------------------- | :----------------------------------- |
  | reseller_id | The unique UUID of the reseller associated with the transaction. | 11ee-0e7e-5403fde2-9523-0a696b110fde |

  #### **Sample Request**

  ```bash
  curl --location 'https://test-partnerapilayer.payu.in/apilayer/partner/verifyPayment' \
  --header 'Authorization: Bearer your_access_token_here' \
  --header 'Content-Type: application/json' \
  --data '{
    "txnid": "PPHOST20240315001",
    "merchant_id": 8739528,
    "reseller_id": "11ee-0e7e-5403fde2-9523-0a696b110fde",
    "hash": "computed_verify_hash_here"
  }'
  ```

  #### **Sample Response**

  ```json
  {
    "status": "success",
    "unmappedstatus": "captured",
    "mihpayid": "403993715521899234",
    "txnid": "PPHOST20240315001",
    "amount": "1500.00",
    "mode": "CC",
    "bankcode": "VISA",
    "productinfo": "Premium Subscription - Monthly",
    "firstname": "Priya",
    "email": "priya.sharma@example.com",
    "phone": "919876543210"
  }
  ```
</Accordion>

<br />

### Process Verification Response

**Reconciliation Checklist:**

✅ `mihpayid` matches<br />✅ `txnid` matches<br />✅ `amount` matches<br />✅ `status` is `"success"`<br />✅ `unmappedstatus` is `"captured"`<br />✅ `mode` is `"UPI"`<br />✅ `bankcode` is `"INTTPV"` (confirms TPV transaction)

If all match, the beneficiary account validation was successful and payment is confirmed.

***

## Error Handling

| Error                                         | Cause                                                    | Resolution                                                                                                              |
| --------------------------------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| <code>s2s\_client\_ip is mandatory</code>     | Missing customer IP when txn\_s2s\_flow=4                | Capture real customer IP from request headers (check <code>X-Forwarded-For</code> if behind proxy)                      |
| <code>s2s\_device\_info is mandatory</code>   | Missing device user-agent when txn\_s2s\_flow=4          | Capture device user-agent from HTTP <code>User-Agent</code> header                                                      |
| <code>beneficiarydetail is mandatory</code>   | Missing beneficiary account details for TPV              | Include <code>beneficiarydetail</code> JSON string with ifscCode, accountNumber, accountHolderName                      |
| <code>Invalid beneficiarydetail format</code> | beneficiarydetail JSON is malformed                      | Ensure JSON is properly formatted and contains all three required fields. Send as JSON string, not object               |
| <code>Account validation failed</code>        | Customer's UPI account doesn't match beneficiary details | Payment rejected by PayU. Customer must use the registered account. Inform customer of the required account             |
| <code>Invalid hash</code>                     | Hash computation mismatch                                | Verify NOT including beneficiarydetail in hash. Use client\_secret, check 6-pipe sequence, ensure SHA-512 lowercase hex |
| <code>Invalid access token</code>             | OAuth token expired                                      | Refresh OAuth token. Implement auto-refresh logic                                                                       |
| <code>HMAC validation failure</code>          | Webhook hash verification failed                         | Check reverse hash formula (5 pipes after status). Use case-insensitive comparison                                      |

***

## Testing

### Test Environment

**API Base URL:** `https://test-partnerapilayer.payu.in/apilayer/partner`

**OAuth URLs:**

* Auth Code: `https://uat-partner.payu.in/api/v1/merchants/auth_code`
* Access Token: `https://uat-accounts.payu.in/oauth/token`

<Warning>
**⚠️ Info Gap: Test Beneficiary Details**

The PDF does not provide test beneficiary account details for sandbox testing. Request test IFSC codes, account numbers, and account holder names from PayU integration team for UAT testing.
</Warning>

### Test Workflow

1. Generate OAuth access token
2. Create UPI TPV payment with test beneficiary details
3. Verify `intentURIData` is returned
4. Test UPI app invocation (on mobile device)
5. Complete payment using test UPI account matching beneficiary details
6. Verify webhook received with `bankcode=INTTPV`
7. Call Verify Payment API
8. Reconcile all data points

### Validation Checklist

✅ OAuth token generation succeeds<br />✅ Payment API returns `intentURIData`<br />✅ `beneficiarydetail` sent correctly (not in hash)<br />✅ UPI app opens with pre-filled details<br />✅ Account validation succeeds<br />✅ Test payment succeeds<br />✅ Webhook received with `bankcode=INTTPV`<br />✅ Webhook hash verified<br />✅ Verify Payment API confirms TPV status<br />✅ Reconciliation successful

***

## Best Practices

### Beneficiary Data Management

* ✅ Validate IFSC code format before sending (11 characters, alphanumeric)
* ✅ Validate account number (typically 9-18 digits)
* ✅ Match account holder name exactly as per bank records
* ✅ Store beneficiary details securely (encrypted database)
* ✅ Implement beneficiary verification during account linking

### Security

* ✅ Never include `beneficiarydetail` in hash calculation
* ✅ Always verify webhook hash before processing
* ✅ Store `client_secret` securely
* ✅ Use HTTPS for all webhook endpoints
* ✅ Encrypt beneficiary account details in database

### Reliability

* ✅ Implement idempotency using `txnid`
* ✅ Use unique `txnid` per transaction
* ✅ Handle account validation failures gracefully
* ✅ Provide clear error messages to customers
* ✅ Implement retry logic for Verify Payment API

### Customer Experience

* ✅ Clearly communicate which account should be used for payment
* ✅ Show beneficiary account details (last 4 digits) before payment
* ✅ Provide helpful error messages if account doesn't match
* ✅ Explain why TPV is required (compliance/security)
* ✅ Allow customers to update registered account if needed

### Compliance

* ✅ Maintain audit trail of all TPV transactions
* ✅ Store account validation results securely
* ✅ Implement data retention policies per regulations
* ✅ Ensure GDPR/data privacy compliance for beneficiary data

***

## Next Steps

* [Partner Payments Hosted Checkout](#) — Multi-method payment gateway integration
* [Partner Payment UPI Intent Integration](#) — Standard UPI S2S without TPV
* [Verify Payment API Reference](#) — Complete verification documentation
* [Partner Webhook Guide](#) — Advanced webhook patterns

<Success>
**Integration Complete!** You can now accept UPI TPV payments with beneficiary account validation using the Partner Payments API.
</Success>