PayU Hosted Checkout Integration

This section describes step-by-step procedure to integrate Apple Pay as a payment method using PayU Hosted Checkout integration.

📘

Before you begin: Ensure that you have completed the prerequisites before you start the integration. For more information, refer to Prerequisites and Set up for Apple Pay Integration.


Step 1: Initiate the payment to PayU

To initiate an Apple Pay payment, post the payment parameters to PayU's transaction endpoint.

EnvironmentURL
Testhttps://test.payu.in/_payment
Productionhttps://secure.payu.in/_payment
Request parameters
ParameterDescriptionExample
key
mandatory
String - This parameter contains the merchant key provided by PayU during onboarding.JP***g
txnid
mandatory
String - This parameter contains a unique transaction ID. You can generate this ID or use the PayU API to generate it. The maximum length of this parameter is 25 characters.txn_applepay_001
amount
mandatory
String - This parameter contains the payment amount.100.00
productinfo
mandatory
String - This parameter contains a brief description of the product or service.iPhone Case
firstname
mandatory
String - This parameter contains the first name of the customer.John
email
mandatory
String - This parameter contains the email address of the customer.[email protected]
phone
mandatory
String - This parameter contains the phone number of the customer.9876543210
surl
mandatory
String - This parameter contains the Success URL. PayU will redirect the customer to this URL after a successful payment.https://yoursite.com/success
furl
mandatory
String - This parameter contains the Failure URL. PayU will redirect the customer to this URL after a failed payment.https://yoursite.com/failure
hash
mandatory
String - This parameter contains the hash value calculated using SHA-512 algorithm. Hash logic ensures the integrity of the transaction data.Refer to Hashing sample code
udf1
optional
String - This parameter contains any additional information you want to pass. Maximum length is 255 characters.
udf2
optional
String - This parameter contains any additional information you want to pass. Maximum length is 255 characters.
udf3
optional
String - This parameter contains any additional information you want to pass. Maximum length is 255 characters.
udf4
optional
String - This parameter contains any additional information you want to pass. Maximum length is 255 characters.
udf5
optional
String - This parameter contains any additional information you want to pass. Maximum length is 255 characters.

Understanding Hashing and sample code

Hashing

You must hash the request parameters using the following hash logic:

sha512(key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5||||||SALT)

For more information, refer to Generate Hash.

Hashing Sample Code

<?php
function generateHash($params, $salt) {
    // Extract parameters or use empty string if not provided
    $key = $params['key'];
    $txnid = $params['txnid'];
    $amount = $params['amount'];
    $productinfo = $params['productinfo'];
    $firstname = $params['firstname'];
    $email = $params['email'];
    $udf1 = isset($params['udf1']) ? $params['udf1'] : '';
    $udf2 = isset($params['udf2']) ? $params['udf2'] : '';
    $udf3 = isset($params['udf3']) ? $params['udf3'] : '';
    $udf4 = isset($params['udf4']) ? $params['udf4'] : '';
    $udf5 = isset($params['udf5']) ? $params['udf5'] : '';
    
    // Construct hash string with exact parameter sequence
    $hashString = $key . '|' . $txnid . '|' . $amount . '|' . $productinfo . '|' . 
                  $firstname . '|' . $email . '|' . $udf1 . '|' . $udf2 . '|' . 
                  $udf3 . '|' . $udf4 . '|' . $udf5 . '||||||' . $salt;
    
    // Generate hash and convert to lowercase
    return strtolower(hash('sha512', $hashString));
}

// Example usage
$params = [
    'key' => 'yourKey',
    'txnid' => 'yourTxnId',
    'amount' => 'yourAmount',
    'productinfo' => 'yourProductInfo',
    'firstname' => 'yourFirstName',
    'email' => 'yourEmail',
    'udf1' => 'optional_value1'
    // udf2, udf3, udf4, udf5 not provided - will be empty strings
];
$salt = 'yourSalt';

$hash = generateHash($params, $salt);
echo 'Generated Hash: ' . $hash;
?>
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class ImprovedHashGenerator {

    public static String generateHash(Map<String, String> params, String salt) {
        // Extract parameters or use empty string if not provided
        String key = params.get("key");
        String txnid = params.get("txnid");
        String amount = params.get("amount");
        String productinfo = params.get("productinfo");
        String firstname = params.get("firstname");
        String email = params.get("email");
        String udf1 = params.getOrDefault("udf1", "");
        String udf2 = params.getOrDefault("udf2", "");
        String udf3 = params.getOrDefault("udf3", "");
        String udf4 = params.getOrDefault("udf4", "");
        String udf5 = params.getOrDefault("udf5", "");
        
        // Construct hash string with exact parameter sequence
        String hashString = key + "|" + txnid + "|" + amount + "|" + productinfo + "|" + 
                         firstname + "|" + email + "|" + udf1 + "|" + udf2 + "|" + 
                         udf3 + "|" + udf4 + "|" + udf5 + "||||||" + salt;
        
        return sha512(hashString);
    }

    private static String sha512(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // Example usage with parameters map
        Map<String, String> params = new HashMap<>();
        params.put("key", "yourKey");
        params.put("txnid", "yourTxnId");
        params.put("amount", "yourAmount");
        params.put("productinfo", "yourProductInfo");
        params.put("firstname", "yourFirstName");
        params.put("email", "yourEmail");
        params.put("udf1", "optional_value1");
        // udf2, udf3, udf4, udf5 not provided - will be empty strings
        
        String salt = "yourSalt";

        String hash = generateHash(params, salt);
        System.out.println("Generated Hash: " + hash);
    }
}
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

public class ImprovedHashGenerator
{
    public static string GenerateHash(Dictionary<string, string> parameters, string salt)
    {
        // Extract parameters or use empty string if not provided
        string key = parameters["key"];
        string txnid = parameters["txnid"];
        string amount = parameters["amount"];
        string productinfo = parameters["productinfo"];
        string firstname = parameters["firstname"];
        string email = parameters["email"];
        
        // Get UDF values if present, otherwise use empty string
        string udf1 = parameters.ContainsKey("udf1") ? parameters["udf1"] : "";
        string udf2 = parameters.ContainsKey("udf2") ? parameters["udf2"] : "";
        string udf3 = parameters.ContainsKey("udf3") ? parameters["udf3"] : "";
        string udf4 = parameters.ContainsKey("udf4") ? parameters["udf4"] : "";
        string udf5 = parameters.ContainsKey("udf5") ? parameters["udf5"] : "";
        
        // Construct hash string with exact parameter sequence
        string hashString = $"{key}|{txnid}|{amount}|{productinfo}|{firstname}|{email}|{udf1}|{udf2}|{udf3}|{udf4}|{udf5}||||||{salt}";
        
        return Sha512(hashString);
    }

    private static string Sha512(string input)
    {
        using (SHA512 sha512 = SHA512.Create())
        {
            byte[] bytes = sha512.ComputeHash(Encoding.UTF8.GetBytes(input));
            StringBuilder sb = new StringBuilder();
            foreach (byte b in bytes)
            {
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString().ToLower();
        }
    }

    public static void Main(string[] args)
    {
        // Example usage with parameters dictionary
        Dictionary<string, string> parameters = new Dictionary<string, string>
        {
            ["key"] = "yourKey",
            ["txnid"] = "yourTxnId",
            ["amount"] = "yourAmount",
            ["productinfo"] = "yourProductInfo",
            ["firstname"] = "yourFirstName",
            ["email"] = "yourEmail",
            ["udf1"] = "optional_value1"
            // udf2, udf3, udf4, udf5 not provided - will be empty strings
        };
        
        string salt = "yourSalt";

        string hash = GenerateHash(parameters, salt);
        Console.WriteLine("Generated Hash: " + hash);
    }
}
import hashlib

def generate_hash(params, salt):
    # Extract parameters or use empty string if not provided
    key = params['key']
    txnid = params['txnid']
    amount = params['amount']
    productinfo = params['productinfo']
    firstname = params['firstname']
    email = params['email']
    udf1 = params.get('udf1', '')
    udf2 = params.get('udf2', '')
    udf3 = params.get('udf3', '')
    udf4 = params.get('udf4', '')
    udf5 = params.get('udf5', '')
    
    # Construct hash string with exact parameter sequence
    hash_string = f"{key}|{txnid}|{amount}|{productinfo}|{firstname}|{email}|{udf1}|{udf2}|{udf3}|{udf4}|{udf5}||||||{salt}"
    
    # Generate SHA-512 hash
    return hashlib.sha512(hash_string.encode('utf-8')).hexdigest()

# Example usage
params = {
    'key': 'yourKey',
    'txnid': 'yourTxnId',
    'amount': 'yourAmount',
    'productinfo': 'yourProductInfo',
    'firstname': 'yourFirstName',
    'email': 'yourEmail',
    'udf1': 'optional_value1'
    # udf2, udf3, udf4, udf5 not provided - will default to empty strings
}
salt = 'yourSalt'

hash_value = generate_hash(params, salt)
print("Generated Hash:", hash_value)
const crypto = require('crypto');

function generateHash(params, salt) {
    // Extract parameters or use empty string if not provided
    const key = params.key;
    const txnid = params.txnid;
    const amount = params.amount;
    const productinfo = params.productinfo;
    const firstname = params.firstname;
    const email = params.email;
    const udf1 = params.udf1 || '';
    const udf2 = params.udf2 || '';
    const udf3 = params.udf3 || '';
    const udf4 = params.udf4 || '';
    const udf5 = params.udf5 || '';
    
    // Construct hash string with exact parameter sequence
    const hashString = `${key}|${txnid}|${amount}|${productinfo}|${firstname}|${email}|${udf1}|${udf2}|${udf3}|${udf4}|${udf5}||||||${salt}`;
    
    // Generate SHA-512 hash
    return crypto.createHash('sha512').update(hashString).digest('hex');
}

// Example usage
const params = {
    key: 'yourKey',
    txnid: 'yourTxnId',
    amount: 'yourAmount',
    productinfo: 'yourProductInfo',
    firstname: 'yourFirstName',
    email: 'yourEmail',
    udf1: 'optional_value1'
    // udf2, udf3, udf4, udf5 not provided - will default to empty strings
};
const salt = 'yourSalt';

const hash = generateHash(params, salt);
console.log("Generated Hash:", hash);
Sample request
curl -X POST \
  'https://test.payu.in/_payment' \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'key=JP***g' \
  -d 'txnid=txn_applepay_001' \
  -d 'amount=100.00' \
  -d 'firstname=John' \
  -d '[email protected]' \
  -d 'phone=9876543210' \
  -d 'productinfo=iPhone Case' \
  -d 'pg=APPLEPAY' \
  -d 'bankcode=APPLEPAY' \
  -d 'surl=https://yoursite.com/success' \
  -d 'furl=https://yoursite.com/failure' \
  -d 'hash=<generated_hash>'
import requests

url = "https://test.payu.in/_payment"

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
}

data = {
    'key': 'JP***g',
    'txnid': 'txn_applepay_001',
    'amount': '100.00',
    'firstname': 'John',
    'email': '[email protected]',
    'phone': '9876543210',
    'productinfo': 'iPhone Case',
    'pg': 'APPLEPAY',
    'bankcode': 'APPLEPAY',
    'surl': 'https://yoursite.com/success',
    'furl': 'https://yoursite.com/failure',
    'hash': '<generated_hash>'
}

try:
    response = requests.post(url, headers=headers, data=data)
    print(f"Status Code: {response.status_code}")
    print(f"Response: {response.text}")
except requests.exceptions.RequestException as e:
    print(f"Error: {e}")
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

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

    static async Task Main(string[] args)
    {
        try
        {
            string url = "https://test.payu.in/_payment";
            
            var formParams = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("key", "JP***g"),
                new KeyValuePair<string, string>("txnid", "txn_applepay_001"),
                new KeyValuePair<string, string>("amount", "100.00"),
                new KeyValuePair<string, string>("firstname", "John"),
                new KeyValuePair<string, string>("email", "[email protected]"),
                new KeyValuePair<string, string>("phone", "9876543210"),
                new KeyValuePair<string, string>("productinfo", "iPhone Case"),
                new KeyValuePair<string, string>("pg", "APPLEPAY"),
                new KeyValuePair<string, string>("bankcode", "APPLEPAY"),
                new KeyValuePair<string, string>("surl", "https://yoursite.com/success"),
                new KeyValuePair<string, string>("furl", "https://yoursite.com/failure"),
                new KeyValuePair<string, string>("hash", "<generated_hash>")
            };

            var formContent = new FormUrlEncodedContent(formParams);
            client.DefaultRequestHeaders.Add("Accept", "application/json");

            HttpResponseMessage response = await client.PostAsync(url, formContent);
            string responseContent = await response.Content.ReadAsStringAsync();
            
            Console.WriteLine($"Status Code: {response.StatusCode}");
            Console.WriteLine($"Response: {responseContent}");
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
    }
}
async function initiateApplePayPayment() {
    const url = 'https://test.payu.in/_payment';
    
    const formData = new URLSearchParams();
    formData.append('key', 'JP***g');
    formData.append('txnid', 'txn_applepay_001');
    formData.append('amount', '100.00');
    formData.append('firstname', 'John');
    formData.append('email', '[email protected]');
    formData.append('phone', '9876543210');
    formData.append('productinfo', 'iPhone Case');
    formData.append('pg', 'APPLEPAY');
    formData.append('bankcode', 'APPLEPAY');
    formData.append('surl', 'https://yoursite.com/success');
    formData.append('furl', 'https://yoursite.com/failure');
    formData.append('hash', '<generated_hash>');
    
    const requestOptions = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData
    };
    
    try {
        const response = await fetch(url, requestOptions);
        const responseText = await response.text();
        
        console.log(`Status: ${response.status}`);
        console.log(`Response: ${responseText}`);
        
        return responseText;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
}

initiateApplePayPayment()
    .then(result => console.log('Payment initiated'))
    .catch(error => console.error('Failed:', error));
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

public class InitiateApplePayPayment {

    public static void main(String[] args) {
        try {
            String url = "https://test.payu.in/_payment";

            Map<String, String> params = new HashMap<>();
            params.put("key", "JP***g");
            params.put("txnid", "txn_applepay_001");
            params.put("amount", "100.00");
            params.put("firstname", "John");
            params.put("email", "[email protected]");
            params.put("phone", "9876543210");
            params.put("productinfo", "iPhone Case");
            params.put("pg", "APPLEPAY");
            params.put("bankcode", "APPLEPAY");
            params.put("surl", "https://yoursite.com/success");
            params.put("furl", "https://yoursite.com/failure");
            params.put("hash", "<generated_hash>");

            StringJoiner sj = new StringJoiner("&");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                     + URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            byte[] postData = sj.toString().getBytes(StandardCharsets.UTF_8);

            URL apiUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postData.length));
            conn.setDoOutput(true);

            try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) {
                dos.write(postData);
            }

            int responseCode = conn.getResponseCode();
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }

                System.out.println("Status Code: " + responseCode);
                System.out.println("Response: " + response.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
<?php

$url = 'https://test.payu.in/_payment';

$postData = array(
    'key' => 'JP***g',
    'txnid' => 'txn_applepay_001',
    'amount' => '100.00',
    'firstname' => 'John',
    'email' => '[email protected]',
    'phone' => '9876543210',
    'productinfo' => 'iPhone Case',
    'pg' => 'APPLEPAY',
    'bankcode' => 'APPLEPAY',
    'surl' => 'https://yoursite.com/success',
    'furl' => 'https://yoursite.com/failure',
    'hash' => '<generated_hash>'
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json',
    'Content-Type: application/x-www-form-urlencoded'
));

$response = curl_exec($ch);

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

curl_close($ch);

$responseData = json_decode($response, true);
if ($responseData !== null) {
    echo "Parsed Response:\n";
    print_r($responseData);
}
?>

Step 2: Check response from PayU

Hash validation logic for payment response (Reverse Hashing)

While sending the response, PayU takes the exact same parameters that were sent in the request (in reverse order) to calculate the hash and returns it to you. You must verify the hash and then mark a transaction as a success or failure. This is to make sure the transaction has not been tampered with in the response.

The order of the parameters is similar to the following:

sha512(SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key)
Sample response (parsed)
Array
(
    [mihpayid] => 403993715524045752
    [mode] => APPLEPAY
    [status] => success
    [unmappedstatus] => captured
    [key] => JP***g
    [txnid] => txn_applepay_001
    [amount] => 100.00
    [discount] => 0.00
    [net_amount_debit] => 100
    [addedon] => 2024-01-15 10:30:00
    [productinfo] => iPhone Case
    [firstname] => John
    [lastname] => 
    [address1] => 
    [address2] => 
    [city] => 
    [state] => 
    [country] => 
    [zipcode] => 
    [email] => [email protected]
    [phone] => 9876543210
    [udf1] => 
    [udf2] => 
    [udf3] => 
    [udf4] => 
    [udf5] => 
    [udf6] => 
    [udf7] => 
    [udf8] => 
    [udf9] => 
    [udf10] => 
    [hash] => 1be7e6e97ab1ea9034b9a107e7cf9718308aa9637b4dbbd1a3343c91b0da02b34a40d00ac7267ebe81c20ea1129b931371c555d565bc6e11f470c3d2cf69b5a3
    [field1] => 
    [field2] => 
    [field3] => 
    [field4] => 
    [field5] => 
    [field6] => 
    [field7] => 
    [field8] => 
    [field9] => Transaction Completed Successfully
    [payment_source] => payu
    [PG_TYPE] => APPLEPAY-PG
    [bank_ref_num] => 87d3b2a1-5a60-4169-8692-649f61923b3d
    [bankcode] => APPLEPAY
    [error] => E000
    [error_Message] => No Error
)
Response parameters
ParameterDescriptionExample
mihpayid
mandatory
String - This parameter contains the unique payment ID generated by PayU for this transaction.403993715524045752
mode
mandatory
String - This parameter contains the payment mode used for the transaction. For Apple Pay, this value is APPLEPAY.APPLEPAY
status
mandatory
String - This parameter contains the status of the transaction. Possible values: success, failure, pending.success
unmappedstatus
mandatory
String - This parameter contains the detailed status of the transaction. Possible values: captured, auth, bounced, dropped, etc.captured
key
mandatory
String - This parameter contains the merchant key.JP***g
txnid
mandatory
String - This parameter contains the transaction ID that was sent in the request.txn_applepay_001
amount
mandatory
String - This parameter contains the transaction amount.100.00
discount
optional
String - This parameter contains the discount amount applied to the transaction.0.00
net_amount_debit
mandatory
String - This parameter contains the net amount debited from the customer.100
addedon
mandatory
String - This parameter contains the date and time when the transaction was added.2024-01-15 10:30:00
productinfo
mandatory
String - This parameter contains the product information sent in the request.iPhone Case
firstname
mandatory
String - This parameter contains the first name of the customer.John
email
mandatory
String - This parameter contains the email address of the customer.[email protected]
phone
mandatory
String - This parameter contains the phone number of the customer.9876543210
hash
mandatory
String - This parameter contains the hash value returned by PayU. You must validate this hash to ensure the response integrity.1be7e6e97...
field9
optional
String - This parameter contains additional information or error description returned by the bank or payment gateway.Transaction Completed Successfully
payment_source
mandatory
String - This parameter contains the source of the payment.payu
PG_TYPE
mandatory
String - This parameter contains the type of payment gateway used. For Apple Pay, this value is APPLEPAY-PG.APPLEPAY-PG
bank_ref_num
mandatory
String - This parameter contains the reference number returned by the bank for this transaction.87d3b2a1-5a60...
bankcode
mandatory
String - This parameter contains the bank code used for the transaction. For Apple Pay, this value is APPLEPAY.APPLEPAY
error
mandatory
String - This parameter contains the error code. E000 indicates no error.E000
error_Message
mandatory
String - This parameter contains the description of the error.No Error

Step 3: Verify the payment

Upon receiving the response, PayU recommends you performing a reconciliation step to validate all transaction details.

You can verify your payments using either of the following methods:

Configure the webhooks to monitor the status of payments.
Webhooks enable a server to communicate with another server by sending an HTTP callback or message.
These callbacks are triggered by specific events or instances and operate at the server-to-server (S2S) level.


Know how to manage Webhooks for Payments.



Did this page help you?