PHP/Node.jsによるパキスタン決済インターフェースのドッキング
パキスタン決済インターフェースマッチングガイド(PHP/Node.js)
一般的なパキスタン決済ゲートウェイ
パキスタンの主な決済ゲートウェイ
- ジャズキャッシュ
- イージーパイサ
- HBLペイ
- UBLオムニ
- MCBライト
以下では、JazzCashを例にして、PHPとNode.jsとのインターフェースの実装方法を紹介します。
JazzCash API ドッキング (PHP 実装)
1.設定パラメータ
$merchant_id = "YOUR_MERCHANT_ID";
$password = "YOUR_PASSWORD";
$integrity_salt = "YOUR_INTEGRITY_SALT";
$return_url = "https://yourwebsite.com/return.php";
2.リクエスト機能の作成
関数 createJazzCashRequest($amount, $orderId) { $amount, $orderId
global $merchant_id、$password、$integrity_salt、$return_url;
date_default_timezone_set('Asia/Karachi').
$dateTime = new DateTime();
$pp_TxnDateTime = $dateTime->format('YmdHis');
// 取引の有効期限 (時間単位) (オプション)
$expiryHours = '24';
// ハッシュ生成用のデータ配列を準備する
$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' => ''、
// ...その他の必須フィールド
);
return json_encode(array(
...
));
}
Node.jsの実装例
必要な依存関係をインストールする
npm install axios crypto-js uuid moment express body-parser dotenv cors helmet morgan winston express-validator http-status-codes bcryptjsjsonwebtoken mongoose joi pm2 compression rate-limit-redis redis connect-redis session-file-store express-session cookie-parser csurf node-キャッシュ request-promise tough-cookie cheerio puppeteer sharp multer aws-sdk nodemailer socket.io passport-local passport-jwt @hapi/[email protected] ヘルメット xss-clean hpp express-mongo-sanitize toobusy-js node-fetch form-data xml2js fast-xml-parser soap q libphonenumber-js country-listcountries-list currency-formatter accounting money decimal.js big-money numeral numbro accounting-js d3-format intl-messageformat react-intlformat-number-with-string pretty-bytes filesize bytes humanize-duration moment-timezone luxon date-fns timeago.js chrono-node later node-スケジュール agenda bull kue bee-queue rabbitmq amqplib ioredis pg mysql mysql2 sqlite3 tedious mssql oracledb knex bookshelf sequelize typeorm mongoosemongodb 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 実装)
1.必要な依存関係のインストール
npm install axios crypto moment uuid qs
2.設定パラメータ(作成 環境
ドキュメント)
JAZZCASH_MERCHANT_ID=your_merchant_id
JAZZCASH_PASSWORD=あなたのパスワード
JAZZCASH_INTEGRITY_SALT=your_salt
jazzcash_return_url=https://yourdomain.com/payment/callback
3.Node.jsコア実装コード
const crypto = require('crypto');
const moment = require('moment');
const axios = require('axios');
require('dotenv').config();
クラス JazzCashPayment {
コンストラクタ() {
this.config = {
merchantId: process.env.JAZZCASH_MERCHANT_ID、
パスワード: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'
};
}
// JazzCash が必要とする安全なハッシュを生成する。
generateSecureHash(データ) {。
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(メッセージ)
.digest('hex')
.toUpperCase();
}
// 決済リクエストのペイロードを作成する
async createPaymentRequest(orderData) {.
const dateTimeString = moment().format('YYYYMMDDHHmmss');
ペイロード = {
pp_Version:「1.1」、
pp_TxnType:「MWALLET」、
pp_Language:"EN"。
// ...その他の必須フィールド
pp_Amount : orderData.amount.toString()、
pp_BillReference : orderData.orderId、
// ...その他のフィールド ...
};
payload.pp_SecureHash = this.generateSecureHash(payload);
を試す。
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コールバック処理例
支払いが完了すると、JazzCash は 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;
// ハッシュが一致するか確認する。
if(strtoupper(hash("sha256",$message))==$received_hash){。
//成功したことを確認し、注文ロジックを処理する。
} else{
header("HTTP/1.0 Invalid Request"); exit();
}
?>
Node.jsコールバック処理の例
router.post('/payment/callback',async(req,res)=>{。
トライ
const receivedHash=req.body.pp_Secure_Hash;
req.body.pp.Secure.Hashを削除する;
// メッセージ文字列の並べ替えと構築...
const calculatedhash=crypto.createHah(...);
if(calculatedhash==receivedhash.toUpperCase()){。
await Order.updateOne()
{orderid}.
{$set:{ステータス: "paid"}}。
);
res.sendStatus(200);
}else{
res.status(400).send("無効なコールバック");
}
}catch(err){。
console.error(err);
res.sendStatus(500);}。
});
セキュリティに関する推奨事項
実施時には必ず注意を払うこと:
✅ HTTPS -すべての通信がSSL/TLS暗号化を使用してデータを送信することを確認する。
✅ 入力検証 -入力されるすべてのパラメータと量の値を厳密にチェックする。
✅ ロギング -監査とトラブルシューティングのための、トランザクションのリクエストとレスポンスの詳細なロギング。
✅ エラー処理 -例外をエレガントにキャッチして処理し、機密情報の漏洩を防ぐ。
これらのコードスニペットがPakistani支払いシステムをスムーズに統合するのに役立つことを願っています!より詳細なドキュメントや特定の問題が発生した場合は、さらに議論することができます。