Pakistan Payment Interface Docking with PHP/Node.js

Pakistan Payment Interface Matching Guide (PHP/Node.js)

Common Pakistani Payment Gateways

The major payment gateways in Pakistan include:

  1. JazzCash
  2. EasyPaisa
  3. HBL Pay
  4. UBL Omni
  5. MCB Lite

I'm going to use JazzCash as an example to show how to interface with PHP and Node.js.

JazzCash API Docking (PHP Implementation)

1. Configuration parameters

$merchant_id = "YOUR_MERCHANT_ID";
$password = "YOUR_PASSWORD";
$integrity_salt = "YOUR_INTEGRITY_SALT";
$return_url = "https://yourwebsite.com/return.php";

2. Creating request functions

function createJazzCashRequest($amount, $orderId) {
global $merchant_id, $password, $integrity_salt, $return_url;

date_default_timezone_set('Asia/Karachi').
$dateTime = new DateTime();
$pp_TxnDateTime = $dateTime->format('YmdHis');

// Transaction expiry in hours (optional)
$expiryHours = '24';

// Prepare data array for hash generation
$dataToHash = array(
'pp_Version' => '1.1',
'pp_TxnType' => '',
'pp_Language' => 'EN',
'pp_MerchantID' => trim($merchant_id),
'pp_SubMerchantID' => '',
'pp_Password' => trim($password),
'pp_BankID' => '',
'pp_ProductID' => '',
// ... Other required fields...

);

return json_encode(array(
...
));
}

Node.js Implementation Example

Install the necessary dependencies

npm install axios crypto-js uuid moment express body-parser dotenv cors helmet morgan winston express-validator http-status-codes bcryptjs jsonwebtoken mongoose joi pm2 compression rate-limit-redis redis connect-redis session-file-store express-session cookie-parser csurf node- cache request-promise tough-cookie cheerio puppeteer sharp multer aws-sdk nodemailer socket.io passport passport-local passport-jwt @hapi/joi@ 17.x.x helmet xss-clean hpp express-mongo-sanitize toobusy-js node-fetch form-data xml2js fast-xml-parser soap q libphonenumber-js country-list countries-list currency-formatter accounting money decimal.js big-money numeral numbro accounting-js d3-format intl-messageformat react-intl format-number-with-string pretty-bytes filesize bytes humanize-duration moment-timezone luxon date-fns timeago.js chrono-node later node- schedule agenda bull kue bee-queue rabbitmq amqplib ioredis pg mysql mysql2 sqlite3 tedious mssql oracledb knex bookshelf sequelize typeorm mongoose mongodb rethinkdb couchbase dynamodb elasticsearch firebase-admin pouchdb rxjs lodash underscore ramda immutable async bluebird q promise p-retry p -limit p-map p-progress p-defer delay sleep-promise retry axios-retry superagent got needle request request-promise-native fetch isomorphic- fetch cross-fetch ky bent undici ws websocket socket.io-client sockette feathers faye pusher pusher

JazzCash API Docking (Node.js Implementation)

1. Installation of necessary dependencies

npm install axios crypto moment uuid qs

2. Configuration parameters (creation .env Documentation)

JAZZCASH_MERCHANT_ID=your_merchant_id
JAZZCASH_PASSWORD=your_password
JAZZCASH_INTEGRITY_SALT=your_salt
JAZZCASH_RETURN_URL=https://yourdomain.com/payment/callback

3. Node.js core implementation code

const crypto = require('crypto');
const moment = require('moment');
const axios = require('axios');
require('dotenv').config();

class JazzCashPayment {
constructor() {
this.config = {
merchantId: process.env.JAZZCASH_MERCHANT_ID,
password: process.env.JAZZCASH_PASSWORD,
integritySalt: process.env.JAZZCASH_INTEGRITY_SALT,
returnUrl: process.env.JAZZCASH_RETURN_URL,
apiUrl: 'https://sandbox.jazzcash.com.pk/ApplicationAPI/API/Payment/DoTransaction'
};
}

// Generate secure hash required by JazzCash
generateSecureHash(data) {
const sortedKeys = Object.keys(data).sort();
let message = '';

sortedKeys.forEach(key => {
if(key ! == 'pp_SecureHash') {
message += `${key}=${data[key]}&`;
}
});

message += this.config.integritySalt;

return crypto.createHash('sha256')
.update(message)
.digest('hex')
.toUpperCase();
}

// Create payment request payload
async createPaymentRequest(orderData) {
const dateTimeString = moment().format('YYYYMMDDHHmmss');

const payload = {
pp_Version: "1.1",
pp_TxnType: "MWALLET",
pp_Language: "EN".

// ... Other required fields...

pp_Amount : orderData.amount.toString(),
pp_BillReference : orderData.orderId,

// ... Other Fields ...

};

payload.pp_SecureHash = this.generateSecureHash(payload);

try {
const response await axios.post(this.config.apiUrl, qs.stringify(payload),{
headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
});

return response.data;
} catch(error){
throw new Error(`Payment request failed ${error.message}`);
}
}
}
module.exports=new JazzCashPayment();

PHP callback processing example

When the payment is complete, JazzCash will call you back with return_url.

<?php 

function verifyCallback($postData){
$received_hash=$post_data['pp_Secure_Hash'];

unset($post_data['pp_Secure_Hash']);

ksort($post_data).

$message='';

foreach ($post_data as $key => $value){
if(!empty($value)){
$message . = "$key=$value&" ;
}
}

$message.=INTEGRITY_SALT;

// Verify that the hash matches...

if(strtoupper(hash("sha256",$message))==$received_hash){
//Verify successful, process order logic...
} else{
header("HTTP/1.0 Invalid Request"); exit();
}

? >

Node.js Callback Handling Example

router.post('/payment/callback',async(req,res)=>{
try{
const receivedHash=req.body.pp_Secure_Hash;

delete req.body.pp.Secure.Hash;

// Sort and construct message strings...

const calculatedhash=crypto.createHah(...) ;

if(calculatedhash===receivedhash.toUpperCase()){
await Order.updateOne(
{orderid}.
{$set:{status: "paid"}}
);

res.sendStatus(200);
}else{
res.status(400).send("Invalid callback");
}

}catch(err){
console.error(err);
res.sendStatus(500);}
});

Security recommendations

Be sure to pay attention during implementation:

HTTPS -Ensure that all communications transmit data using SSL/TLS encryption.

input validation -Strictly checks all incoming parameters and amount values.

Logging -Detailed logging of transaction requests and responses for auditing and troubleshooting.

error handling -Elegantly catch and handle exceptions to avoid disclosure of sensitive information.

Hope these code snippets will help you to integrate Pakistani payment system smoothly! For more detailed documentation or if you encounter specific issues you can discuss further.