Cards Integration
PayU supports the following debit cards and credit cards:
- American Express (AMEX)
- Visa
- Mastercard
- Diners
- Rupay
Note:
PayU accepts domestic and international transactions, but international transactions need to be enabled by writing to PayU Integration Team ([email protected]).
If you are storing or transmitting cardholder data, you must fill the “Self-Assessment Questionnaire A-EP and Attestation of Compliance” form. For more information on Save Cards API integration, refer to PayU Save Cards API Integration docs.
Steps to Integrate
Before you begin:
Register for an account with PayU before you start integration. For more information, refer to Register for a Merchant Account.
Step 1: Validate the card type
When customers use debit cards or credit cards on your website, you can validate the card type with the first six digits. Use the check_isDomestic API (known as BIN API) to validate the type of card. For more information, refer to BIN APIs.
After the customer enters the card number, you can validate the first six digits with the check_isDomestic API. For more information, refer to Check is Domestic API.
Step 2: Initiate the payment to PayU
Post Request Syntax & Composition
Post Request Syntax & Composition for Cards
<body>
<form action='https://test.payu.in/_payment' method='post'>
<input type="hidden" name="key" value="JP***g" />
<input type="hidden" name="txnid" value="t6svtqtjRdl34W" />
<input type="hidden" name="productinfo" value="iPhone" />
<input type="hidden" name="amount" value="10" />
<input type="hidden" name="email" value="[email protected]" />
<input type="hidden" name="firstname" value="Ashish" />
<input type="hidden" name="lastname" value="Kumar" />
<input type="hidden" name="pg" value="CC" />
<input type="hidden" name="bankcode" value="MAST" />
<input type="hidden" name="ccnum" value="5123456789012346" />
<input type="hidden" name="ccname" value="Ashish Kumar" />
<input type="hidden" name="ccvv" value="123" />
<input type="hidden" name="ccexpmon" value="12" />
<input type="hidden" name="ccexpyr" value="2021" />
<input type="hidden" name="surl" value="your own success url" />
<input type="hidden" name="furl" value="your own failure url" />
<input type="hidden" name="phone" value="9988776655" />
<input type="hidden" name="hash" value="eabec285da28fd0e3054d41a4d24fe9f7599c9d0b66646f7a9984303fd6124044b6206daf831e9a8bda28a6200d318293a13d6c193109b60bd4b4f8b09c90972" />
<input type="submit" value="submit"> </form>
</body>
</html>
Note:
The above code block is for Merchant Checkout integration on the credit card call for the test environment.
Request Parameters
Post the following parameters for the card payment to PayU using the Merchant Hosted integration.
Environment
Test Environment | <https://test.payu.in/_payment> |
Production Environment | <https://secure.payu.in/_payment> |
Reference:
For the Try It experience and response, refer to Collect Payment API - Merchant Hosted Checkout under API Reference.
Parameter | Description | Example |
---|---|---|
key
|
|
|
txnid |
|
|
amount |
|
|
productinfo |
|
|
firstname |
| Ashish |
email |
|
|
phone |
|
|
pg |
| CC |
bankcode |
| AMEX |
ccnum |
| 5123456789012346 |
ccname |
| Ashish Kumar |
ccvv |
| 123 |
ccexpmon |
| 10 |
ccexpyr |
| 2021 |
furl |
| |
surl |
| |
hash |
| |
address1 |
| |
address2 |
| |
city |
| |
state |
| |
country |
| |
zipcode |
| |
udf1 |
| |
udf2 |
| |
udf3 |
| |
udf4 |
| |
udf5 |
|
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.
Sample request
# IMPORTANT: This is a server-side call, never execute this client-side
# Replace placeholders with actual values
# In production: Use environment variables for sensitive values
curl -X POST "https://test.payu.in/_payment" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "key=YOUR_MERCHANT_KEY" \
-d "txnid=TXN_12345" \
-d "amount=1000.00" \
-d "productinfo=Product+Description" \
-d "firstname=Customer+Name" \
-d "[email protected]" \
-d "phone=9988776655" \
-d "pg=CC" \
-d "bankcode=CC" \
-d "ccnum=CARD_NUMBER" \
-d "ccexpmon=MM" \
-d "ccexpyr=YY" \
-d "ccvv=CVV" \
-d "ccname=NAME_ON_CARD" \
-d "surl=https://yourwebsite.com/success" \
-d "furl=https://yourwebsite.com/failure" \
-d "hash=HASH_GENERATED_ON_SERVER"
import urllib.request
import urllib.parse
import json
import os
from typing import Dict, Any
def process_payment(payment_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Process payment using PayU's Merchant Hosted Checkout
IMPORTANT: This is a server-side function. Never expose card details to client-side code.
This handles sensitive card data and requires PCI DSS compliance.
Args:
payment_data: Dictionary containing payment information
Returns:
Dictionary with response from PayU API
"""
# API endpoint - Use different URLs for test/production environments
url = "https://test.payu.in/_payment" # Test URL
# url = "https://secure.payu.in/_payment" # Production URL
# Prepare the form data with proper URL encoding
# In production: Get merchant_key and hash from secure environment variables
payload = {
"key": "YOUR_MERCHANT_KEY", # Replace with actual merchant key
"txnid": "TXN_12345", # Generate unique transaction ID
"amount": "1000.00", # Amount to be charged
"productinfo": "Product Description", # Description of product/service
"firstname": "Customer Name", # Customer's first name
"email": "[email protected]", # Customer's email
"phone": "9988776655", # Customer's phone number
"pg": "CC", # Payment gateway (CC for credit card)
"bankcode": "CC", # Bank code (CC for credit card)
# SENSITIVE DATA - Handle with care according to PCI DSS requirements
"ccnum": "CARD_NUMBER", # Credit card number
"ccexpmon": "MM", # Expiry month (2 digits)
"ccexpyr": "YY", # Expiry year (2 digits)
"ccvv": "CVV", # Card verification value
"ccname": "NAME_ON_CARD", # Name on the card
# Success and failure URLs
"surl": "https://yourwebsite.com/success", # Success callback URL
"furl": "https://yourwebsite.com/failure", # Failure callback URL
# Hash is generated on server using specific algorithm provided by PayU
# See PayU documentation for the exact hash generation logic
"hash": "HASH_GENERATED_ON_SERVER", # Security hash
}
# Convert dictionary to URL-encoded form data
data = urllib.parse.urlencode(payload).encode('utf-8')
# Set headers
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
# Create a request object
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
# Send the request and get the response
with urllib.request.urlopen(req) as response:
response_data = response.read().decode('utf-8')
# In production, implement proper response handling and logging
# (but never log full card details)
return {
"status_code": response.getcode(),
"response": response_data
}
except urllib.error.HTTPError as e:
# Handle HTTP errors
error_data = e.read().decode('utf-8')
return {
"status_code": e.code,
"error": e.reason,
"response": error_data
}
except Exception as e:
# Handle other exceptions
return {
"status_code": 500,
"error": str(e),
"response": "An error occurred during the payment process"
}
# Example usage:
# payment_result = process_payment(payment_data)
# print(f"Status: {payment_result['status_code']}")
# Process the response appropriately
<?php
/**
* Process payment using PayU's Merchant Hosted Checkout
*
* IMPORTANT: This is a server-side function. Never expose card details to client-side code.
* This handles sensitive card data and requires PCI DSS compliance.
*
* @param array $paymentData Payment information
* @return array Response from PayU API
*/
function processPayment($paymentData = []) {
// API endpoint - Use different URLs for test/production environments
$url = "https://test.payu.in/_payment"; // Test URL
// $url = "https://secure.payu.in/_payment"; // Production URL
// Prepare the form data
// In production: Get merchant_key and hash from secure environment variables
$payload = [
"key" => "YOUR_MERCHANT_KEY", // Replace with actual merchant key
"txnid" => "TXN_12345", // Generate unique transaction ID
"amount" => "1000.00", // Amount to be charged
"productinfo" => "Product Description", // Description of product/service
"firstname" => "Customer Name", // Customer's first name
"email" => "[email protected]", // Customer's email
"phone" => "9988776655", // Customer's phone number
"pg" => "CC", // Payment gateway (CC for credit card)
"bankcode" => "CC", // Bank code (CC for credit card)
// SENSITIVE DATA - Handle with care according to PCI DSS requirements
"ccnum" => "CARD_NUMBER", // Credit card number
"ccexpmon" => "MM", // Expiry month (2 digits)
"ccexpyr" => "YY", // Expiry year (2 digits)
"ccvv" => "CVV", // Card verification value
"ccname" => "NAME_ON_CARD", // Name on the card
// Success and failure URLs
"surl" => "https://yourwebsite.com/success", // Success callback URL
"furl" => "https://yourwebsite.com/failure", // Failure callback URL
// Hash is generated on server using specific algorithm provided by PayU
// See PayU documentation for the exact hash generation logic
"hash" => "HASH_GENERATED_ON_SERVER", // Security hash
];
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/x-www-form-urlencoded"
]);
// For additional security in production
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// Execute the request
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$errno = curl_errno($ch);
// Close cURL session
curl_close($ch);
// Handle response
if ($errno) {
return [
"status_code" => 500,
"error" => $error,
"response" => "cURL Error: " . $error
];
}
// In production, implement proper response handling and logging
// (but never log full card details)
return [
"status_code" => $status_code,
"response" => $response
];
}
// Example usage:
// $paymentResult = processPayment($paymentData);
// echo "Status: " . $paymentResult["status_code"];
// Process the response appropriately
?>
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
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;
/**
* PayU Payment Processor for Merchant Hosted Checkout
*
* IMPORTANT: This is a server-side implementation. Never expose card details to client-side code.
* This handles sensitive card data and requires PCI DSS compliance.
*/
public class PayUPaymentProcessor {
// API endpoints - Use different URLs for test/production environments
private static final String TEST_URL = "https://test.payu.in/_payment";
private static final String PROD_URL = "https://secure.payu.in/_payment";
/**
* Process payment using PayU Merchant Hosted Checkout
*
* @return PaymentResponse containing status and response data
*/
public PaymentResponse processPayment() {
try {
// Use test URL (change to PROD_URL in production)
URL url = new URL(TEST_URL);
// Prepare form parameters
// In production: Get merchant_key and hash from secure environment variables
Map<String, String> params = new HashMap<>();
params.put("key", "YOUR_MERCHANT_KEY"); // Replace with actual merchant key
params.put("txnid", "TXN_12345"); // Generate unique transaction ID
params.put("amount", "1000.00"); // Amount to be charged
params.put("productinfo", "Product Description"); // Description of product/service
params.put("firstname", "Customer Name"); // Customer's first name
params.put("email", "[email protected]"); // Customer's email
params.put("phone", "9988776655"); // Customer's phone number
params.put("pg", "CC"); // Payment gateway (CC for credit card)
params.put("bankcode", "CC"); // Bank code (CC for credit card)
// SENSITIVE DATA - Handle with care according to PCI DSS requirements
params.put("ccnum", "CARD_NUMBER"); // Credit card number
params.put("ccexpmon", "MM"); // Expiry month (2 digits)
params.put("ccexpyr", "YY"); // Expiry year (2 digits)
params.put("ccvv", "CVV"); // Card verification value
params.put("ccname", "NAME_ON_CARD"); // Name on the card
// Success and failure URLs
params.put("surl", "https://yourwebsite.com/success"); // Success callback URL
params.put("furl", "https://yourwebsite.com/failure"); // Failure callback URL
// Hash is generated on server using specific algorithm provided by PayU
// See PayU documentation for the exact hash generation logic
params.put("hash", "HASH_GENERATED_ON_SERVER"); // Security hash
// Convert parameters to URL-encoded form data
StringJoiner formData = new StringJoiner("&");
for (Map.Entry<String, String> entry : params.entrySet()) {
formData.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" +
URLEncoder.encode(entry.getValue(), "UTF-8"));
}
byte[] postData = formData.toString().getBytes(StandardCharsets.UTF_8);
// Configure connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postData.length));
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(15000);
// Send request
try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) {
dos.write(postData);
dos.flush();
}
// Get response
int responseCode = conn.getResponseCode();
// Read response data
StringBuilder response = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
responseCode >= 400 ? conn.getErrorStream() : conn.getInputStream(),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
}
// In production, implement proper response handling and logging
// (but never log full card details)
return new PaymentResponse(responseCode, response.toString(), null);
} catch (IOException e) {
// Handle exception
return new PaymentResponse(500, null, "Error: " + e.getMessage());
}
}
/**
* Payment response wrapper class
*/
public static class PaymentResponse {
private final int statusCode;
private final String response;
private final String error;
public PaymentResponse(int statusCode, String response, String error) {
this.statusCode = statusCode;
this.response = response;
this.error = error;
}
public int getStatusCode() {
return statusCode;
}
public String getResponse() {
return response;
}
public String getError() {
return error;
}
public boolean isSuccess() {
return statusCode >= 200 && statusCode < 300;
}
}
// Example usage:
public static void main(String[] args) {
PayUPaymentProcessor processor = new PayUPaymentProcessor();
PaymentResponse result = processor.processPayment();
System.out.println("Status Code: " + result.getStatusCode());
if (result.isSuccess()) {
System.out.println("Response: " + result.getResponse());
} else {
System.out.println("Error: " + result.getError());
}
}
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
namespace PayUIntegration
{
/// <summary>
/// PayU Payment Processor for Merchant Hosted Checkout
///
/// IMPORTANT: This is a server-side implementation. Never expose card details to client-side code.
/// This handles sensitive card data and requires PCI DSS compliance.
/// </summary>
public class PayUPaymentProcessor
{
// API endpoints - Use different URLs for test/production environments
private const string TestUrl = "https://test.payu.in/_payment";
private const string ProdUrl = "https://secure.payu.in/_payment";
/// <summary>
/// Process payment using PayU Merchant Hosted Checkout
/// </summary>
/// <returns>PaymentResponse containing status and response data</returns>
public async Task<PaymentResponse> ProcessPaymentAsync()
{
try
{
// Use test URL (change to ProdUrl in production)
string url = TestUrl;
// Prepare form parameters
// In production: Get merchant_key and hash from secure environment variables
var formData = new Dictionary<string, string>
{
{ "key", "YOUR_MERCHANT_KEY" }, // Replace with actual merchant key
{ "txnid", "TXN_12345" }, // Generate unique transaction ID
{ "amount", "1000.00" }, // Amount to be charged
{ "productinfo", "Product Description" }, // Description of product/service
{ "firstname", "Customer Name" }, // Customer's first name
{ "email", "[email protected]" }, // Customer's email
{ "phone", "9988776655" }, // Customer's phone number
{ "pg", "CC" }, // Payment gateway (CC for credit card)
{ "bankcode", "CC" }, // Bank code (CC for credit card)
// SENSITIVE DATA - Handle with care according to PCI DSS requirements
{ "ccnum", "CARD_NUMBER" }, // Credit card number
{ "ccexpmon", "MM" }, // Expiry month (2 digits)
{ "ccexpyr", "YY" }, // Expiry year (2 digits)
{ "ccvv", "CVV" }, // Card verification value
{ "ccname", "NAME_ON_CARD" }, // Name on the card
// Success and failure URLs
{ "surl", "https://yourwebsite.com/success" }, // Success callback URL
{ "furl", "https://yourwebsite.com/failure" }, // Failure callback URL
// Hash is generated on server using specific algorithm provided by PayU
// See PayU documentation for the exact hash generation logic
{ "hash", "HASH_GENERATED_ON_SERVER" } // Security hash
};
// Create HttpClient with timeout
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromSeconds(30);
// Convert form data to content
var content = new FormUrlEncodedContent(formData);
// Send POST request
var response = await httpClient.PostAsync(url, content);
// Get response content
var responseContent = await response.Content.ReadAsStringAsync();
// In production, implement proper response handling and logging
// (but never log full card details)
return new PaymentResponse(
(int)response.StatusCode,
responseContent,
null
);
}
}
catch (Exception ex)
{
// Handle exception
return new PaymentResponse(
500,
null,
$"Error: {ex.Message}"
);
}
}
/// <summary>
/// Payment response wrapper class
/// </summary>
public class PaymentResponse
{
public int StatusCode { get; }
public string Response { get; }
public string Error { get; }
public PaymentResponse(int statusCode, string response, string error)
{
StatusCode = statusCode;
Response = response;
Error = error;
}
public bool IsSuccess => StatusCode >= 200 && StatusCode < 300;
}
}
// Example usage:
public class Program
{
public static async Task Main(string[] args)
{
var processor = new PayUPaymentProcessor();
var result = await processor.ProcessPaymentAsync();
Console.WriteLine($"Status Code: {result.StatusCode}");
if (result.IsSuccess)
{
Console.WriteLine($"Response: {result.Response}");
}
else
{
Console.WriteLine($"Error: {result.Error}");
}
}
}
}
Step 3: 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 tampered within the response.
The order of the parameters is similar to the following code block:
sha512(SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key)
Sample response (parsed)
- Success scenario
Array
(
[mihpayid] => 403993715524069222
[mode] => CC
[status] => success
[unmappedstatus] => captured
[key] => JF***g
[txnid] => EaE4ZO3vU4iPsp
[amount] => 10.00
[cardCategory] => domestic
[discount] => 0.00
[net_amount_debit] => 10
[addedon] => 2021-09-08 19:37:19
[productinfo] => iPhone
[firstname] => Ashish
[lastname] =>
[address1] =>
[address2] =>
[city] =>
[state] =>
[country] =>
[zipcode] =>
[email] => [email protected]
[phone] => 9876543210
[udf1] =>
[udf2] =>
[udf3] =>
[udf4] =>
[udf5] =>
[udf6] =>
[udf7] =>
[udf8] =>
[udf9] =>
[udf10] =>
[hash] => ed99957adb08fea56c907b88e8d158a79c3562c67f96c298461509826f77a7ae9e88b2a176b3234c25f50bcd451271728719656f3bb59c13a52bebabc468615a
[field1] => 0608273386032718000015
[field2] => 986987
[field3] => 10.00
[field4] => 403993715524069222
[field5] => 100
[field6] => 02
[field7] => AUTHPOSITIVE
[field8] =>
[field9] => Transaction is Successful
[payment_source] => payu
[PG_TYPE] => CC-PG
[bank_ref_num] => 0608273386032718000015
[bankcode] => CC
[error] => E000
[error_Message] => No Error
[name_on_card] => payu
[cardnum] => 512345XXXXXX2346
)
- Failure scenario
Array
(
[mihpayid] => 20869277619
[mode] => CC
[status] => failure
[unmappedstatus] => failed
[key] => L43t1c
[txnid] => 26ba7cd6a67b0a010542
[amount] => 1.00
[cardCategory] => domestic
[discount] => 0.00
[net_amount_debit] => 0.00
[addedon] => 2024-09-05 17:46:10
[productinfo] => Product Info
[firstname] => Payu-Admin
[lastname] =>
[address1] =>
[address2] =>
[city] =>
[state] =>
[country] =>
[zipcode] =>
[email] => [email protected]
[phone] => 1234567890
[udf1] =>
[udf2] =>
[udf3] =>
[udf4] =>
[udf5] =>
[udf6] =>
[udf7] =>
[udf8] =>
[udf9] =>
[udf10] =>
[hash] => ac7720e4bc33e5494bec6d37302e522171175a987f9d47286bfd29e8a7fc794f56433fcacf0bc120db781c4dc1d05a4857d71e83f00f6ed6aa9c97a1938b9467
[field1] =>
[field2] =>
[field3] =>
[field4] =>
[field5] => 05
[field6] =>
[field7] => AUTHNEGATIVE
[field8] =>
[field9] => Authorization failed at Bank
[payment_source] => payu
[pa_name] => PayU
[PG_TYPE] => CC-PG
[bank_ref_num] => 2409052690
[bankcode] => AMEX
[error] => E1903
[error_Message] => Authorization failed at Bank
[cardnum] => XXXXXXXXXXXX2003
[cardhash] => This field is no longer supported in postback params.
)
Step 4: Verify the Payment
Verify the transaction details using the Verification APIs. For API reference, refer to Verify Payment API under API Reference.
Note:
The transaction ID that you posted in Step 1 with PayU must be used here.
Recommended Integrations for Cards
- Save Cards: Save cards and expedite the next payment from your customers with a better success rate. For more information, refer to Save Cards.
- Recurring Payments: Enable recurring payments or subscriptions for cards. For more information, refer to Recurring Payments.
- Offers: Configure offers for cards on Dashboard and then collect payments with offers. For more information, refer to Offers Dashboard or Offers Integration APIs.
Updated 18 days ago