Hướng dẫn tích hợp hệ thống PAY - Cổng thanh toán VNPAY
Giới thiệu
Timeline
Các bước merchant cần xử lý tích hợp code cài đặt
(1)
Cài đặt code build URL thanh toán chuyển hướng.(2)
Cài đặt code vnp_ReturnUrl URL thông báo kết quả thanh toán.(3)
Cài đặt code IPN URL cập nhật kết quả thanh toán. Gửi lại VNPAY URL này khi thiết lập xong.
Mô hình kết nối

- Bước 1: Khách hàng thực hiện mua hàng trên Website - ứng dụng TMĐT và tiến hành thanh toán trực tuyến cho đơn hàng.
- Bước 2: Website - ứng dụng TMĐT thành lập yêu cầu thanh toán dưới dạng URL mang thông tin thanh toán và chuyển hướng khách hàng sang Cổng thanh toán VNPAY bằng URL đó.
Cổng thanh toán VNPAY xử lý yêu cầu thanh toán mà Website - ứng dụng TMĐT gửi sang. Khách hàng tiến hành nhập hoặc xử lý xác thực các thông tin được yêu cầu Thanh toán.
- Bước 3,4: Khách hàng nhập thông tin để xác minh tài khoản Ngân hàng của khách hàng và xác thực giao dịch (Nhập thông tin tài khoản, thẻ hoặc quét mã VNPAY-QR).
- Bước 5: Giao dịch thành công tại Ngân hàng, VNPAY tiến hành:
- Chuyển hướng khách hàng về Website - ứng dụng TMĐT (
vnp_ReturnUrl
)
- Thông báo cho Website - ứng dụng TMĐT kết quả thanh toán của khách hàng thông qua
IPN URL
. Merchant cập nhật kết quả thanh toán VNPAY gửi tại URL này.
- Bước 6: Merchant hiển thị kết quả giao dịch tới khách hàng (
vnp_ReturnUrl
).
Sơ đồ tuần tự
- Bước 1: Khách hàng thực hiện mua hàng trên Website - ứng dụng TMĐT và tiến hành thanh toán trực tuyến cho đơn hàng.
- Bước 2: Website - ứng dụng TMĐT thành lập yêu cầu thanh toán dưới dạng URL mang thông tin thanh toán và chuyển hướng khách hàng sang Cổng thanh toán VNPAY bằng URL đó.
Cổng thanh toán VNPAY xử lý yêu cầu thanh toán mà Website - ứng dụng TMĐT gửi sang. Khách hàng tiến hành nhập hoặc xử lý xác thực các thông tin được yêu cầu Thanh toán. - Bước 3,4: Khách hàng nhập thông tin để xác minh tài khoản Ngân hàng của khách hàng và xác thực giao dịch (Nhập thông tin tài khoản, thẻ hoặc quét mã VNPAY-QR).
- Bước 5: Giao dịch thành công tại Ngân hàng, VNPAY tiến hành:
- Chuyển hướng khách hàng về Website - ứng dụng TMĐT (
vnp_ReturnUrl
) - Thông báo cho Website - ứng dụng TMĐT kết quả thanh toán của khách hàng thông qua
IPN URL
. Merchant cập nhật kết quả thanh toán VNPAY gửi tại URL này.
- Chuyển hướng khách hàng về Website - ứng dụng TMĐT (
- Bước 6: Merchant hiển thị kết quả giao dịch tới khách hàng (
vnp_ReturnUrl
).
Thông tin cấu hình
Các thông tin cần thiết kết nối vào môi trường Sandbox Cổng thanh toán VNPAY:
- Mã TmnCode vnp_TmnCode
là mã định danh kết nối được khai báo tại hệ thống của VNPAY.
Mã định danh tương ứng với tên miền website, ứng dụng, dịch vụ của merchant kết nối vào VNPAY.
Mỗi đơn vị có thể có một hoặc nhiều mã TmnCode kết nối.
- URL thanh toán (Sandbox): https://sandbox.vnpayment.vn/paymentv2/vpcpay.html
- Secret Key vnp_HashSecret
Chuỗi bí mật sử dụng để kiểm tra toàn vẹn dữ liệu khi hai hệ thống trao đổi thông tin (checksum).
- URL truy vấn kết quả giao dịch - hoàn tiền (Sandbox): https://sandbox.vnpayment.vn/merchant_webapi/api/transaction
Nếu chưa có thông tin cấu hình tích hợp, bạn có thể đăng ký ngay tại đây http://sandbox.vnpayment.vn/devreg/ Hệ thống sẽ gửi thông tin kết nối về email bạn đăng ký
Tạo URL Thanh toán
URL thanh toán (Sandbox): https://sandbox.vnpayment.vn/paymentv2/vpcpay.html
Phương thức: GET
URL Thanh toán là địa chỉ URL mang thông tin thanh toán.
Website TMĐT gửi sang Cổng thanh toán VNPAY các thông tin này khi xử lý giao dịch thanh toán trực tuyến cho Khách mua hàng.
URL có dạng:
https://sandbox.vnpayment.vn/paymentv2/vpcpay.html?vnp_Amount=1806000&vnp_Command=pay&vnp_CreateDate=20210801153333&vnp_CurrCode=VND&vnp_IpAddr=127.0.0.1&vnp_Locale=vn&vnp_OrderInfo=Thanh+toan+don+hang+%3A5&vnp_OrderType=other&vnp_ReturnUrl=https%3A%2F%2Fdomainmerchant.vn%2FReturnUrl&vnp_TmnCode=DEMOV210&vnp_TxnRef=5&vnp_Version=2.1.0&vnp_SecureHash=3e0d61a0c0534b2e36680b3f7277743e8784cc4e1d68fa7d276e79c23be7d6318d338b477910a27992f5057bb1582bd44bd82ae8009ffaf6d141219218625c42
Danh sách tham số - Thông tin gửi sang VNPAY (vnp_Command=pay)
Tham số | Kiểu dữ liệu | Bắt buộc/Tùy chọn | Mô tả |
---|---|---|---|
vnp_Version | Alphanumeric[1,8] | Bắt buộc | Phiên bản api mà merchant kết nối. Phiên bản hiện tại là : 2.1.0 |
vnp_Command | Alpha[1,16] | Bắt buộc | Mã API sử dụng, mã cho giao dịch thanh toán là: pay |
vnp_TmnCode | Alphanumeric[8] | Bắt buộc | Mã website của merchant trên hệ thống của VNPAY. Ví dụ: 2QXUI4J4 |
vnp_Amount | Numeric[1,12] | Bắt buộc | Số tiền thanh toán. Số tiền không mang các ký tự phân tách thập phân, phần nghìn, ký tự tiền tệ. Để gửi số tiền thanh toán là 10,000 VND (mười nghìn VNĐ) thì merchant cần nhân thêm 100 lần (khử phần thập phân), sau đó gửi sang VNPAY là: 1000000 |
vnp_BankCode | Alphanumeric[3,20] | Tùy chọn | Mã phương thức thanh toán, mã loại ngân hàng hoặc ví điện tử thanh toán.
Nếu không gửi sang tham số này, chuyển hướng người dùng sang VNPAY chọn phương thức thanh toán.
Lưu ý:
Các mã loại hình thức thanh toán lựa chọn tại website-ứng dụng của merchant
vnp_BankCode=VNPAYQR Thanh toán quét mã QR
vnp_BankCode=VNBANK Thẻ ATM - Tài khoản ngân hàng nội địa
vnp_BankCode=INTCARD Thẻ thanh toán quốc tế
|
vnp_CreateDate | Numeric[14] | Bắt buộc | Là thời gian phát sinh giao dịch định dạng yyyyMMddHHmmss (Time zone GMT+7) Ví dụ: 20220101103111 |
vnp_CurrCode | Alpha[3] | Bắt buộc | Đơn vị tiền tệ sử dụng thanh toán. Hiện tại chỉ hỗ trợ VND |
vnp_IpAddr | Alphanumeric[7,45] | Bắt buộc | Địa chỉ IP của khách hàng thực hiện giao dịch. Ví dụ: 13.160.92.202 |
vnp_Locale | Alpha[2,5] | Bắt buộc | Ngôn ngữ giao diện hiển thị. Hiện tại hỗ trợ Tiếng Việt (vn), Tiếng Anh (en) |
vnp_OrderInfo | Alphanumeric[1,255] | Bắt buộc | Thông tin mô tả nội dung thanh toán quy định dữ liệu gửi sang VNPAY (Tiếng Việt không dấu và không bao gồm các ký tự đặc biệt)
Ví dụ: Nap tien cho thue bao 0123456789. So tien 100,000 VND |
vnp_OrderType | Alpha[1,100] | Bắt buộc | Mã danh mục hàng hóa. Mỗi hàng hóa sẽ thuộc một nhóm danh mục do VNPAY quy định. Xem thêm bảng Danh mục hàng hóa |
vnp_ReturnUrl | Alphanumeric[10,255] | Bắt buộc | URL thông báo kết quả giao dịch khi Khách hàng kết thúc thanh toán. Ví dụ: https://domain.vn/VnPayReturn |
vnp_ExpireDate | Numeric[14] | Bắt buộc | Thời gian hết hạn thanh toán GMT+7, định dạng: yyyyMMddHHmmss |
vnp_TxnRef | Alphanumeric[1,100] | Bắt buộc | Mã tham chiếu của giao dịch tại hệ thống của merchant. Mã này là duy nhất dùng để phân biệt các đơn hàng gửi sang VNPAY. Không được trùng lặp trong ngày. Ví dụ: 23554 |
vnp_SecureHash | Alphanumeric[32,256] | Bắt buộc | Mã kiểm tra (checksum) để đảm bảo dữ liệu của giao dịch không bị thay đổi trong quá trình chuyển từ merchant sang VNPAY. Việc tạo ra mã này phụ thuộc vào cấu hình của merchant và phiên bản api sử dụng. Phiên bản hiện tại hỗ trợ SHA256, HMACSHA512. |
Lưu ý
- Dữ liệu checksum được thành lập dựa trên việc sắp xếp tăng dần của tên tham số (QueryString)
- Số tiền cần thanh toán nhân với 100 để triệt tiêu phần thập phân trước khi gửi sang VNPAY
vnp_BankCode
: Giá trị này tùy chọn.
- Nếu loại bỏ tham số không gửi sang, khách hàng sẽ chọn phương thức thanh toán, ngân hàng thanh toán tại VNPAY.
- Nếu thiết lập giá trị (chọn Ngân hàng thanh toán tại Website-ứng dụng TMĐT), Tham khảo bảng mã trả về tại API:Endpoint:
https://sandbox.vnpayment.vn/qrpayauth/api/merchant/get_bank_listHttp method:
POSTContent-Type:
application/x-www-form-urlencodedkey
tmn_codevalue
Theo mã định danh kết nối (vnp_TmnCode) VNPAY cung cấp- Trong URL thanh toán có tham số
vnp_ReturnUrl
là URL thông báo kết quả giao dịch khi Khách hàng kết thúc thanh toán
Code cài đặt
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
date_default_timezone_set('Asia/Ho_Chi_Minh');
$vnp_Url = "https://sandbox.vnpayment.vn/paymentv2/vpcpay.html";
$vnp_Returnurl = "https://localhost/vnpay_php/vnpay_return.php";
$vnp_TmnCode = "";//Mã website tại VNPAY
$vnp_HashSecret = ""; //Chuỗi bí mật
$vnp_TxnRef = $_POST['order_id']; //Mã đơn hàng. Trong thực tế Merchant cần insert đơn hàng vào DB và gửi mã này
sang VNPAY
$vnp_OrderInfo = $_POST['order_desc'];
$vnp_OrderType = $_POST['order_type'];
$vnp_Amount = $_POST['amount'] * 100;
$vnp_Locale = $_POST['language'];
$vnp_BankCode = $_POST['bank_code'];
$vnp_IpAddr = $_SERVER['REMOTE_ADDR'];
//Add Params of 2.0.1 Version
$vnp_ExpireDate = $_POST['txtexpire'];
//Billing
$vnp_Bill_Mobile = $_POST['txt_billing_mobile'];
$vnp_Bill_Email = $_POST['txt_billing_email'];
$fullName = trim($_POST['txt_billing_fullname']);
if (isset($fullName) && trim($fullName) != '') {
$name = explode(' ', $fullName);
$vnp_Bill_FirstName = array_shift($name);
$vnp_Bill_LastName = array_pop($name);
}
$vnp_Bill_Address=$_POST['txt_inv_addr1'];
$vnp_Bill_City=$_POST['txt_bill_city'];
$vnp_Bill_Country=$_POST['txt_bill_country'];
$vnp_Bill_State=$_POST['txt_bill_state'];
// Invoice
$vnp_Inv_Phone=$_POST['txt_inv_mobile'];
$vnp_Inv_Email=$_POST['txt_inv_email'];
$vnp_Inv_Customer=$_POST['txt_inv_customer'];
$vnp_Inv_Address=$_POST['txt_inv_addr1'];
$vnp_Inv_Company=$_POST['txt_inv_company'];
$vnp_Inv_Taxcode=$_POST['txt_inv_taxcode'];
$vnp_Inv_Type=$_POST['cbo_inv_type'];
$inputData = array(
"vnp_Version" => "2.1.0",
"vnp_TmnCode" => $vnp_TmnCode,
"vnp_Amount" => $vnp_Amount,
"vnp_Command" => "pay",
"vnp_CreateDate" => date('YmdHis'),
"vnp_CurrCode" => "VND",
"vnp_IpAddr" => $vnp_IpAddr,
"vnp_Locale" => $vnp_Locale,
"vnp_OrderInfo" => $vnp_OrderInfo,
"vnp_OrderType" => $vnp_OrderType,
"vnp_ReturnUrl" => $vnp_Returnurl,
"vnp_TxnRef" => $vnp_TxnRef,
"vnp_ExpireDate"=>$vnp_ExpireDate,
"vnp_Bill_Mobile"=>$vnp_Bill_Mobile,
"vnp_Bill_Email"=>$vnp_Bill_Email,
"vnp_Bill_FirstName"=>$vnp_Bill_FirstName,
"vnp_Bill_LastName"=>$vnp_Bill_LastName,
"vnp_Bill_Address"=>$vnp_Bill_Address,
"vnp_Bill_City"=>$vnp_Bill_City,
"vnp_Bill_Country"=>$vnp_Bill_Country,
"vnp_Inv_Phone"=>$vnp_Inv_Phone,
"vnp_Inv_Email"=>$vnp_Inv_Email,
"vnp_Inv_Customer"=>$vnp_Inv_Customer,
"vnp_Inv_Address"=>$vnp_Inv_Address,
"vnp_Inv_Company"=>$vnp_Inv_Company,
"vnp_Inv_Taxcode"=>$vnp_Inv_Taxcode,
"vnp_Inv_Type"=>$vnp_Inv_Type
);
if (isset($vnp_BankCode) && $vnp_BankCode != "") {
$inputData['vnp_BankCode'] = $vnp_BankCode;
}
if (isset($vnp_Bill_State) && $vnp_Bill_State != "") {
$inputData['vnp_Bill_State'] = $vnp_Bill_State;
}
//var_dump($inputData);
ksort($inputData);
$query = "";
$i = 0;
$hashdata = "";
foreach ($inputData as $key => $value) {
if ($i == 1) {
$hashdata .= '&' . urlencode($key) . "=" . urlencode($value);
} else {
$hashdata .= urlencode($key) . "=" . urlencode($value);
$i = 1;
}
$query .= urlencode($key) . "=" . urlencode($value) . '&';
}
$vnp_Url = $vnp_Url . "?" . $query;
if (isset($vnp_HashSecret)) {
$vnpSecureHash = hash_hmac('sha512', $hashdata, $vnp_HashSecret);//
$vnp_Url .= 'vnp_SecureHash=' . $vnpSecureHash;
}
$returnData = array('code' => '00'
, 'message' => 'success'
, 'data' => $vnp_Url);
if (isset($_POST['redirect'])) {
header('Location: ' . $vnp_Url);
die();
} else {
echo json_encode($returnData);
}
// vui lòng tham khảo thêm tại code demo
private static readonly ILog log =
LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtOrderDesc.Text = "Nhap noi dung thanh toan";
txtExpire.Text = DateTime.Now.AddMinutes(15).ToString("yyyyMMddHHmmss");
}
}
protected void btnPay_Click(object sender, EventArgs e)
{
//Get Config Info
string vnp_Returnurl = ConfigurationManager.AppSettings["vnp_Returnurl"]; //URL nhan ket qua tra ve
string vnp_Url = ConfigurationManager.AppSettings["vnp_Url"]; //URL thanh toan cua VNPAY
string vnp_TmnCode = ConfigurationManager.AppSettings["vnp_TmnCode"]; //Ma website
string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat
if (string.IsNullOrEmpty(vnp_TmnCode) || string.IsNullOrEmpty(vnp_HashSecret))
{
lblMessage.Text = "Vui lòng cấu hình các tham số: vnp_TmnCode,vnp_HashSecret trong file web.config";
return;
}
//Get payment input
OrderInfo order = new OrderInfo();
//Save order to db
order.OrderId = DateTime.Now.Ticks; // Giả lập mã giao dịch hệ thống merchant gửi sang VNPAY
order.Amount = 100000; // Giả lập số tiền thanh toán hệ thống merchant gửi sang VNPAY 100,000 VND
order.Status = "0"; //0: Trạng thái thanh toán "chờ thanh toán" hoặc "Pending"
order.OrderDesc = txtOrderDesc.Text;
order.CreatedDate = DateTime.Now;
string locale = cboLanguage.SelectedItem.Value;
//Build URL for VNPAY
VnPayLibrary vnpay = new VnPayLibrary();
vnpay.AddRequestData("vnp_Version", VnPayLibrary.VERSION);
vnpay.AddRequestData("vnp_Command", "pay");
vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
vnpay.AddRequestData("vnp_Amount", (order.Amount * 100).ToString()); //Số tiền thanh toán. Số tiền không
mang các ký tự phân tách thập phân, phần nghìn, ký tự tiền tệ. Để gửi số tiền thanh toán là 100,000 VND
(một trăm nghìn VNĐ) thì merchant cần nhân thêm 100 lần (khử phần thập phân), sau đó gửi sang VNPAY
là: 10000000
if (cboBankCode.SelectedItem != null && !string.IsNullOrEmpty(cboBankCode.SelectedItem.Value))
{
vnpay.AddRequestData("vnp_BankCode", cboBankCode.SelectedItem.Value);
}
vnpay.AddRequestData("vnp_CreateDate", order.CreatedDate.ToString("yyyyMMddHHmmss"));
vnpay.AddRequestData("vnp_CurrCode", "VND");
vnpay.AddRequestData("vnp_IpAddr", Utils.GetIpAddress());
if (!string.IsNullOrEmpty(locale))
{
vnpay.AddRequestData("vnp_Locale", locale);
}
else
{
vnpay.AddRequestData("vnp_Locale", "vn");
}
vnpay.AddRequestData("vnp_OrderInfo", "Thanh toan don hang:" + order.OrderId);
vnpay.AddRequestData("vnp_OrderType", orderCategory.SelectedItem.Value); //default value: other
vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
vnpay.AddRequestData("vnp_TxnRef", order.OrderId.ToString()); // Mã tham chiếu của giao dịch tại hệ
thống của merchant. Mã này là duy nhất dùng để phân biệt các đơn hàng gửi sang VNPAY. Không được
trùng lặp trong ngày
//Add Params of 2.1.0 Version
vnpay.AddRequestData("vnp_ExpireDate",txtExpire.Text);
//Billing
vnpay.AddRequestData("vnp_Bill_Mobile", txt_billing_mobile.Text.Trim());
vnpay.AddRequestData("vnp_Bill_Email", txt_billing_email.Text.Trim());
var fullName = txt_billing_fullname.Text.Trim();
if (!String.IsNullOrEmpty(fullName))
{
var indexof = fullName.IndexOf(' ');
vnpay.AddRequestData("vnp_Bill_FirstName", fullName.Substring(0, indexof));
vnpay.AddRequestData("vnp_Bill_LastName", fullName.Substring(indexof + 1,
fullName.Length - indexof - 1));
}
vnpay.AddRequestData("vnp_Bill_Address", txt_inv_addr1.Text.Trim());
vnpay.AddRequestData("vnp_Bill_City", txt_bill_city.Text.Trim());
vnpay.AddRequestData("vnp_Bill_Country", txt_bill_country.Text.Trim());
vnpay.AddRequestData("vnp_Bill_State", "");
// Invoice
vnpay.AddRequestData("vnp_Inv_Phone", txt_inv_mobile.Text.Trim());
vnpay.AddRequestData("vnp_Inv_Email", txt_inv_email.Text.Trim());
vnpay.AddRequestData("vnp_Inv_Customer", txt_inv_customer.Text.Trim());
vnpay.AddRequestData("vnp_Inv_Address", txt_inv_addr1.Text.Trim());
vnpay.AddRequestData("vnp_Inv_Company", txt_inv_company.Text);
vnpay.AddRequestData("vnp_Inv_Taxcode", txt_inv_taxcode.Text);
vnpay.AddRequestData("vnp_Inv_Type", cbo_inv_type.SelectedItem.Value);
string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);
log.InfoFormat("VNPAY URL: {0}", paymentUrl);
Response.Redirect(paymentUrl);
}
// vui lòng tham khảo thêm tại code demo
def payment(request):
if request.method == 'POST':
# Process input data and build url payment
form = PaymentForm(request.POST)
if form.is_valid():
order_type = form.cleaned_data['order_type']
order_id = form.cleaned_data['order_id']
amount = form.cleaned_data['amount']
order_desc = form.cleaned_data['order_desc']
bank_code = form.cleaned_data['bank_code']
language = form.cleaned_data['language']
ipaddr = get_client_ip(request)
# Build URL Payment
vnp = vnpay()
vnp.requestData['vnp_Version'] = '2.1.0'
vnp.requestData['vnp_Command'] = 'pay'
vnp.requestData['vnp_TmnCode'] = settings.VNPAY_TMN_CODE
vnp.requestData['vnp_Amount'] = amount * 100
vnp.requestData['vnp_CurrCode'] = 'VND'
vnp.requestData['vnp_TxnRef'] = order_id
vnp.requestData['vnp_OrderInfo'] = order_desc
vnp.requestData['vnp_OrderType'] = order_type
# Check language, default: vn
if language and language != '':
vnp.requestData['vnp_Locale'] = language
else:
vnp.requestData['vnp_Locale'] = 'vn'
# Check bank_code, if bank_code is empty, customer will be selected bank on VNPAY
if bank_code and bank_code != "":
vnp.requestData['vnp_BankCode'] = bank_code
vnp.requestData['vnp_CreateDate'] = datetime.now().strftime('%Y%m%d%H%M%S')
vnp.requestData['vnp_IpAddr'] = ipaddr
vnp.requestData['vnp_ReturnUrl'] = settings.VNPAY_RETURN_URL
vnpay_payment_url = vnp.get_payment_url(settings.VNPAY_PAYMENT_URL, settings.VNPAY_HASH_SECRET_KEY)
print(vnpay_payment_url)
# Redirect to VNPAY
return redirect(vnpay_payment_url)
else:
print("Form input not validate")
else:
return render(request, "payment.html", {"title": "Thanh toán"})
// vui lòng tham khảo thêm tại code demo
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String vnp_Version = "2.1.0";
String vnp_Command = "pay";
String vnp_OrderInfo = req.getParameter("vnp_OrderInfo");
String orderType = req.getParameter("ordertype");
String vnp_TxnRef = Config.getRandomNumber(8);
String vnp_IpAddr = Config.getIpAddress(req);
String vnp_TmnCode = Config.vnp_TmnCode;
int amount = Integer.parseInt(req.getParameter("amount")) * 100;
Map vnp_Params = new HashMap<>();
vnp_Params.put("vnp_Version", vnp_Version);
vnp_Params.put("vnp_Command", vnp_Command);
vnp_Params.put("vnp_TmnCode", vnp_TmnCode);
vnp_Params.put("vnp_Amount", String.valueOf(amount));
vnp_Params.put("vnp_CurrCode", "VND");
String bank_code = req.getParameter("bankcode");
if (bank_code != null && !bank_code.isEmpty()) {
vnp_Params.put("vnp_BankCode", bank_code);
}
vnp_Params.put("vnp_TxnRef", vnp_TxnRef);
vnp_Params.put("vnp_OrderInfo", vnp_OrderInfo);
vnp_Params.put("vnp_OrderType", orderType);
String locate = req.getParameter("language");
if (locate != null && !locate.isEmpty()) {
vnp_Params.put("vnp_Locale", locate);
} else {
vnp_Params.put("vnp_Locale", "vn");
}
vnp_Params.put("vnp_ReturnUrl", Config.vnp_Returnurl);
vnp_Params.put("vnp_IpAddr", vnp_IpAddr);
Calendar cld = Calendar.getInstance(TimeZone.getTimeZone("Etc/GMT+7"));
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String vnp_CreateDate = formatter.format(cld.getTime());
vnp_Params.put("vnp_CreateDate", vnp_CreateDate);
cld.add(Calendar.MINUTE, 15);
String vnp_ExpireDate = formatter.format(cld.getTime());
//Add Params of 2.1.0 Version
vnp_Params.put("vnp_ExpireDate", vnp_ExpireDate);
//Billing
vnp_Params.put("vnp_Bill_Mobile", req.getParameter("txt_billing_mobile"));
vnp_Params.put("vnp_Bill_Email", req.getParameter("txt_billing_email"));
String fullName = (req.getParameter("txt_billing_fullname")).trim();
if (fullName != null && !fullName.isEmpty()) {
int idx = fullName.indexOf(' ');
String firstName = fullName.substring(0, idx);
String lastName = fullName.substring(fullName.lastIndexOf(' ') + 1);
vnp_Params.put("vnp_Bill_FirstName", firstName);
vnp_Params.put("vnp_Bill_LastName", lastName);
}
vnp_Params.put("vnp_Bill_Address", req.getParameter("txt_inv_addr1"));
vnp_Params.put("vnp_Bill_City", req.getParameter("txt_bill_city"));
vnp_Params.put("vnp_Bill_Country", req.getParameter("txt_bill_country"));
if (req.getParameter("txt_bill_state") != null && !req.getParameter("txt_bill_state").isEmpty()) {
vnp_Params.put("vnp_Bill_State", req.getParameter("txt_bill_state"));
}
// Invoice
vnp_Params.put("vnp_Inv_Phone", req.getParameter("txt_inv_mobile"));
vnp_Params.put("vnp_Inv_Email", req.getParameter("txt_inv_email"));
vnp_Params.put("vnp_Inv_Customer", req.getParameter("txt_inv_customer"));
vnp_Params.put("vnp_Inv_Address", req.getParameter("txt_inv_addr1"));
vnp_Params.put("vnp_Inv_Company", req.getParameter("txt_inv_company"));
vnp_Params.put("vnp_Inv_Taxcode", req.getParameter("txt_inv_taxcode"));
vnp_Params.put("vnp_Inv_Type", req.getParameter("cbo_inv_type"));
//Build data to hash and querystring
List fieldNames = new ArrayList(vnp_Params.keySet());
Collections.sort(fieldNames);
StringBuilder hashData = new StringBuilder();
StringBuilder query = new StringBuilder();
Iterator itr = fieldNames.iterator();
while (itr.hasNext()) {
String fieldName = (String) itr.next();
String fieldValue = (String) vnp_Params.get(fieldName);
if ((fieldValue != null) && (fieldValue.length() > 0)) {
//Build hash data
hashData.append(fieldName);
hashData.append('=');
hashData.append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII.toString()));
//Build query
query.append(URLEncoder.encode(fieldName, StandardCharsets.US_ASCII.toString()));
query.append('=');
query.append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII.toString()));
if (itr.hasNext()) {
query.append('&');
hashData.append('&');
}
}
}
String queryUrl = query.toString();
String vnp_SecureHash = Config.hmacSHA512(Config.vnp_HashSecret, hashData.toString());
queryUrl += "&vnp_SecureHash=" + vnp_SecureHash;
String paymentUrl = Config.vnp_PayUrl + "?" + queryUrl;
com.google.gson.JsonObject job = new JsonObject();
job.addProperty("code", "00");
job.addProperty("message", "success");
job.addProperty("data", paymentUrl);
Gson gson = new Gson();
resp.getWriter().write(gson.toJson(job));
}
//vui lòng tham khảo thêm tại code demo
router.post('/create_payment_url', function (req, res, next) {
var ipAddr = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
var config = require('config');
var dateFormat = require('dateformat');
var tmnCode = config.get('vnp_TmnCode');
var secretKey = config.get('vnp_HashSecret');
var vnpUrl = config.get('vnp_Url');
var returnUrl = config.get('vnp_ReturnUrl');
var date = new Date();
var createDate = dateFormat(date, 'yyyymmddHHmmss');
var orderId = dateFormat(date, 'HHmmss');
var amount = req.body.amount;
var bankCode = req.body.bankCode;
var orderInfo = req.body.orderDescription;
var orderType = req.body.orderType;
var locale = req.body.language;
if(locale === null || locale === ''){
locale = 'vn';
}
var currCode = 'VND';
var vnp_Params = {};
vnp_Params['vnp_Version'] = '2.1.0';
vnp_Params['vnp_Command'] = 'pay';
vnp_Params['vnp_TmnCode'] = tmnCode;
// vnp_Params['vnp_Merchant'] = ''
vnp_Params['vnp_Locale'] = locale;
vnp_Params['vnp_CurrCode'] = currCode;
vnp_Params['vnp_TxnRef'] = orderId;
vnp_Params['vnp_OrderInfo'] = orderInfo;
vnp_Params['vnp_OrderType'] = orderType;
vnp_Params['vnp_Amount'] = amount * 100;
vnp_Params['vnp_ReturnUrl'] = returnUrl;
vnp_Params['vnp_IpAddr'] = ipAddr;
vnp_Params['vnp_CreateDate'] = createDate;
if(bankCode !== null && bankCode !== ''){
vnp_Params['vnp_BankCode'] = bankCode;
}
vnp_Params = sortObject(vnp_Params);
var querystring = require('qs');
var signData = querystring.stringify(vnp_Params, { encode: false });
var crypto = require("crypto");
var hmac = crypto.createHmac("sha512", secretKey);
var signed = hmac.update(new Buffer(signData, 'utf-8')).digest("hex");
vnp_Params['vnp_SecureHash'] = signed;
vnpUrl += '?' + querystring.stringify(vnp_Params, { encode: false });
res.redirect(vnpUrl)
});
// Vui lòng tham khảo thêm tại code demo
Cài đặt Code IPN URL
- Phương thức: GET
- Yêu cầu:
- IPN URL cần có SSL
- Nhận kết quả phản hồi từ Cổng thanh toán VNPAY, kiểm tra dữ liệu, cập nhật kết quả và phản hồi lại mã lỗi và mô tả mã lỗi (RspCode và Message) cho server VNPAY nhận biết
VNPAY trả về kết quả thanh toán URL có dạng:
https://{domain}/IPN?vnp_Amount=1000000&vnp_BankCode=NCB&vnp_BankTranNo=VNP14226112&vnp_CardType=ATM&vnp_OrderInfo=Thanh+toan+don+hang+thoi+gian%3A+2023-12-07+17%3A00%3A44&vnp_PayDate=20231207170112&vnp_ResponseCode=00&vnp_TmnCode=CTTVNP01&vnp_TransactionNo=14226112&vnp_TransactionStatus=00&vnp_TxnRef=166117&vnp_SecureHash=b6dababca5e07a2d8e32fdd3cf05c29cb426c721ae18e9589f7ad0e2db4b657c6e0e5cc8e271cf745162bcb100fdf2f64520554a6f5275bc4c5b5b3e57dc4b4b
Danh sách tham số - Thông tin nhận về từ VNPAY (vnp_Command=pay)
Tham số | Kiểu dữ liệu | Bắt buộc/Tùy chọn | Mô tả |
---|---|---|---|
vnp_TmnCode | Alphanumeric[8] | Bắt buộc | Mã website của merchant trên hệ thống của VNPAY. Ví dụ: 2QXUI4J4 |
vnp_Amount | Numeric[1,12] | Bắt buộc | Số tiền thanh toán. VNPAY phản hồi số tiền nhân thêm 100 lần. |
vnp_BankCode | Alphanumeric[3,20] | Bắt buộc | Mã Ngân hàng thanh toán. Ví dụ: NCB |
vnp_BankTranNo | Alphanumeric[1,255] | Tùy chọn | Mã giao dịch tại Ngân hàng. Ví dụ: NCB20170829152730 |
vnp_CardType | Alpha[2,20] | Tùy chọn | Loại tài khoản/thẻ khách hàng sử dụng:ATM,QRCODE |
vnp_PayDate | Numeric[14] | Tùy chọn | Thời gian thanh toán. Định dạng: yyyyMMddHHmmss |
vnp_OrderInfo | Alphanumeric[1,255] | Bắt buộc | Thông tin mô tả nội dung thanh toán (Tiếng Việt, không dấu). Ví dụ: **Nap tien cho thue bao 0123456789. So tien 100,000 VND** |
vnp_TransactionNo | Numeric[1,15] | Bắt buộc | Mã giao dịch ghi nhận tại hệ thống VNPAY. Ví dụ: 20170829153052 |
vnp_ResponseCode | Numeric[2] | Bắt buộc | Mã phản hồi kết quả thanh toán. Quy định mã trả lời 00 ứng với kết quả Thành công cho tất cả các API. Tham khảo thêm tại bảng mã lỗi |
vnp_TransactionStatus | Numeric[2] | Bắt buộc | Mã phản hồi kết quả thanh toán. Tình trạng của giao dịch tại Cổng thanh toán VNPAY.
-00: Giao dịch thanh toán được thực hiện thành công tại VNPAY -Khác 00: Giao dịch không thành công tại VNPAY Tham khảo thêm tại bảng mã lỗi |
vnp_TxnRef | Alphanumeric[1,100] | Bắt buộc | Giống mã gửi sang VNPAY khi gửi yêu cầu thanh toán. Ví dụ: 23554 |
vnp_SecureHash | Alphanumeric[32,256] | Bắt buộc | Mã kiểm tra (checksum) để đảm bảo dữ liệu của giao dịch không bị thay đổi trong quá trình chuyển từ VNPAY về Website TMĐT.
Cần kiểm tra đúng checksum khi bắt đầu xử lý yêu cầu (trước khi thực hiện các yêu cầu khác) |
Lưu ý
- Merchant/website TMĐT thực hiện kiểm tra sự toàn vẹn của dữ liệu (checksum) trước khi thực hiện các thao tác khác
- Thao tác cập nhật/xử lý kết quả sau khi thanh toán được thực hiện tại URL này
- Đây là URL server - call - server (Máy chủ VNPAY gọi máy chủ Merchant/website TMĐT)
- Merchant trả dữ liệu lại cho VNPAY bằng mã RspCode và Message định dạng JSON: Trong đó: RspCode là mã lỗi tình trạng cập nhật trạng thái thanh toán của giao dịch tại đầu IPN của merchant. Message là mô tả mã lỗi của RspCode Merchant cần tuân thủ theo các trường hợp kiểm và phản hồi lại RspCode cho VNPAY. Vui lòng tham khảo thêm tại code demo IPN của VNPAY
- Cơ chế retry IPN: Hệ thống VNPAY căn cứ theo RspCode phản hồi từ merchant để kết thúc luồng hay bật cơ chế retry RspCode: 00, 02 là mã lỗi IPN của merchant phản hồi đã cập nhật được tình trạng giao dịch. VNPAY kết thúc luồng RspCode: 01, 04, 97, 99 hoặc IPN timeout là mã lỗi IPN merchant không cập nhật được tình trạng giao dịch. VNPAY bật cơ chế retry IPN Tổng số lần gọi tối đa: 10 lần Khoảng cách giữa các lần gọi lại: 5 phút
Code cài đặt
/* Payment Notify
* IPN URL: Ghi nhận kết quả thanh toán từ VNPAY
* Các bước thực hiện:
* Kiểm tra checksum
* Tìm giao dịch trong database
* Kiểm tra số tiền giữa hai hệ thống
* Kiểm tra tình trạng của giao dịch trước khi cập nhật
* Cập nhật kết quả vào Database
* Trả kết quả ghi nhận lại cho VNPAY
*/
require_once("./config.php");
$inputData = array();
$returnData = array();
foreach ($_GET as $key => $value) {
if (substr($key, 0, 4) == "vnp_") {
$inputData[$key] = $value;
}
}
$vnp_SecureHash = $inputData['vnp_SecureHash'];
unset($inputData['vnp_SecureHash']);
ksort($inputData);
$i = 0;
$hashData = "";
foreach ($inputData as $key => $value) {
if ($i == 1) {
$hashData = $hashData . '&' . urlencode($key) . "=" . urlencode($value);
} else {
$hashData = $hashData . urlencode($key) . "=" . urlencode($value);
$i = 1;
}
}
$secureHash = hash_hmac('sha512', $hashData, $vnp_HashSecret);
$vnpTranId = $inputData['vnp_TransactionNo']; //Mã giao dịch tại VNPAY
$vnp_BankCode = $inputData['vnp_BankCode']; //Ngân hàng thanh toán
$vnp_Amount = $inputData['vnp_Amount']/100; // Số tiền thanh toán VNPAY phản hồi
$Status = 0; // Là trạng thái thanh toán của giao dịch chưa có IPN lưu tại hệ thống của merchant chiều khởi tạo
URL thanh toán.
$orderId = $inputData['vnp_TxnRef'];
try {
//Check Orderid
//Kiểm tra checksum của dữ liệu
if ($secureHash == $vnp_SecureHash) {
//Lấy thông tin đơn hàng lưu trong Database và kiểm tra trạng thái của đơn hàng, mã đơn hàng là: $orderId
//Việc kiểm tra trạng thái của đơn hàng giúp hệ thống không xử lý trùng lặp, xử lý nhiều lần một giao dịch
//Giả sử: $order = mysqli_fetch_assoc($result);
$order = NULL;
if ($order != NULL) {
if($order["Amount"] == $vnp_Amount) //Kiểm tra số tiền thanh toán của giao dịch: giả sử số tiền
kiểm tra là đúng. //$order["Amount"] == $vnp_Amount
{
if ($order["Status"] != NULL && $order["Status"] == 0) {
if ($inputData['vnp_ResponseCode'] == '00' || $inputData['vnp_TransactionStatus'] == '00') {
$Status = 1; // Trạng thái thanh toán thành công
} else {
$Status = 2; // Trạng thái thanh toán thất bại / lỗi
}
//Cài đặt Code cập nhật kết quả thanh toán, tình trạng đơn hàng vào DB
//
//
//
//Trả kết quả về cho VNPAY: Website/APP TMĐT ghi nhận yêu cầu thành công
$returnData['RspCode'] = '00';
$returnData['Message'] = 'Confirm Success';
} else {
$returnData['RspCode'] = '02';
$returnData['Message'] = 'Order already confirmed';
}
}
else {
$returnData['RspCode'] = '04';
$returnData['Message'] = 'invalid amount';
}
} else {
$returnData['RspCode'] = '01';
$returnData['Message'] = 'Order not found';
}
} else {
$returnData['RspCode'] = '97';
$returnData['Message'] = 'Invalid signature';
}
} catch (Exception $e) {
$returnData['RspCode'] = '99';
$returnData['Message'] = 'Unknow error';
}
//Trả lại VNPAY theo định dạng JSON
echo json_encode($returnData);
private static readonly ILog log =
LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected void Page_Load(object sender, EventArgs e)
{
string returnContent = string.Empty;
if (Request.QueryString.Count > 0)
{
string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Secret key
var vnpayData = Request.QueryString;
VnPayLibrary vnpay = new VnPayLibrary();
foreach (string s in vnpayData)
{
//get all querystring data
if (!string.IsNullOrEmpty(s) && s.StartsWith("vnp_"))
{
vnpay.AddResponseData(s, vnpayData[s]);
}
}
//Lay danh sach tham so tra ve tu VNPAY
//vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay
//vnp_TransactionNo: Ma GD tai he thong VNPAY
//vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
//vnp_SecureHash: HmacSHA512 cua du lieu tra ve
long orderId = Convert.ToInt64(vnpay.GetResponseData("vnp_TxnRef"));
long vnp_Amount = Convert.ToInt64(vnpay.GetResponseData("vnp_Amount"))/100;
long vnpayTranId = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
string vnp_TransactionStatus = vnpay.GetResponseData("vnp_TransactionStatus");
String vnp_SecureHash = Request.QueryString["vnp_SecureHash"];
bool checkSignature = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);
if (checkSignature)
{
//Cap nhat ket qua GD
//Yeu cau: Truy van vao CSDL cua Merchant => lay ra duoc OrderInfo
//Giả sử OrderInfo lấy ra được như giả lập bên dưới
OrderInfo order = new OrderInfo();//get from DB
order.OrderId = orderId;
order.Amount = 100000;
order.PaymentTranId = vnpayTranId;
order.Status = "0"; //0: Cho thanh toan,1: da thanh toan,2: GD loi
//Kiem tra tinh trang Order
if (order != null)
{
if (order.Amount == vnp_Amount) {
if (order.Status == "0")
{
if (vnp_ResponseCode == "00" && vnp_TransactionStatus == "00")
{
//Thanh toan thanh cong
log.InfoFormat("Thanh toan thanh cong, OrderId={0}, VNPAY TranId={1}", orderId,
vnpayTranId);
order.Status = "1";
}
else
{
//Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
// displayMsg.InnerText = "Có lỗi xảy ra trong quá trình xử lý.
Mã lỗi: " + vnp_ResponseCode;
log.InfoFormat("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}",
orderId, vnpayTranId, vnp_ResponseCode);
order.Status = "2";
}
//Thêm code Thực hiện cập nhật vào Database
//Update Database
returnContent = "{\"RspCode\":\"00\",\"Message\":\"Confirm Success\"}";
}
else
{
returnContent = "{\"RspCode\":\"02\",\"Message\":\"Order already confirmed\"}";
}
}
else
{
returnContent = "{\"RspCode\":\"04\",\"Message\":\"invalid amount\"}";
}
}
else
{
returnContent = "{\"RspCode\":\"01\",\"Message\":\"Order not found\"}";
}
}
else
{
log.InfoFormat("Invalid signature, InputData={0}", Request.RawUrl);
returnContent = "{\"RspCode\":\"97\",\"Message\":\"Invalid signature\"}";
}
}
else
{
returnContent = "{\"RspCode\":\"99\",\"Message\":\"Input data required\"}";
}
Response.ClearContent();
Response.Write(returnContent);
Response.End();
}
def payment_ipn(request):
inputData = request.GET
if inputData:
vnp = vnpay()
vnp.responseData = inputData.dict()
order_id = inputData['vnp_TxnRef']
amount = inputData['vnp_Amount']
order_desc = inputData['vnp_OrderInfo']
vnp_TransactionNo = inputData['vnp_TransactionNo']
vnp_ResponseCode = inputData['vnp_ResponseCode']
vnp_TmnCode = inputData['vnp_TmnCode']
vnp_PayDate = inputData['vnp_PayDate']
vnp_BankCode = inputData['vnp_BankCode']
vnp_CardType = inputData['vnp_CardType']
if vnp.validate_response(settings.VNPAY_HASH_SECRET_KEY):
# Check & Update Order Status in your Database
# Your code here
firstTimeUpdate = True
totalAmount = True
if totalAmount:
if firstTimeUpdate:
if vnp_ResponseCode == '00':
print('Payment Success. Your code implement here')
else:
print('Payment Error. Your code implement here')
# Return VNPAY: Merchant update success
result = JsonResponse({'RspCode': '00', 'Message': 'Confirm Success'})
else:
# Already Update
result = JsonResponse({'RspCode': '02', 'Message': 'Order Already Update'})
else:
# invalid amount
result = JsonResponse({'RspCode': '04', 'Message': 'invalid amount'})
else:
# Invalid Signature
result = JsonResponse({'RspCode': '97', 'Message': 'Invalid Signature'})
else:
result = JsonResponse({'RspCode': '99', 'Message': 'Invalid request'})
return result
<%
try
{
/* IPN URL: Record payment results from VNPAY
Implementation steps:
Check checksum
Find transactions (vnp_TxnRef) in the database (checkOrderId)
Check the payment status of transactions before updating (checkOrderStatus)
Check the amount (vnp_Amount) of transactions before updating (checkAmount)
Update results to Database
Return recorded results to VNPAY
*/
// ex: PaymnentStatus = 0; pending
// PaymnentStatus = 1; success
// PaymnentStatus = 2; Faile
//Begin process return from VNPAY
Map fields = new HashMap();
for (Enumeration params = request.getParameterNames(); params.hasMoreElements();) {
String fieldName = URLEncoder.encode((String) params.nextElement(), StandardCharsets.US_ASCII.toString());
String fieldValue = URLEncoder.encode(request.getParameter(fieldName), StandardCharsets.US_ASCII.toString());
if ((fieldValue != null) && (fieldValue.length() > 0)) {
fields.put(fieldName, fieldValue);
}
}
String vnp_SecureHash = request.getParameter("vnp_SecureHash");
if (fields.containsKey("vnp_SecureHashType"))
{
fields.remove("vnp_SecureHashType");
}
if (fields.containsKey("vnp_SecureHash"))
{
fields.remove("vnp_SecureHash");
}
// Check checksum
String signValue = Config.hashAllFields(fields);
if (signValue.equals(vnp_SecureHash))
{
boolean checkOrderId = true; // vnp_TxnRef exists in your database
boolean checkAmount = true; // vnp_Amount is valid (Check vnp_Amount VNPAY returns compared to the
amount of the code (vnp_TxnRef) in the Your database).
boolean checkOrderStatus = true; // PaymnentStatus = 0 (pending)
if(checkOrderId)
{
if(checkAmount)
{
if (checkOrderStatus)
{
if ("00".equals(request.getParameter("vnp_ResponseCode")))
{
//Here Code update PaymnentStatus = 1 into your Database
}
else
{
// Here Code update PaymnentStatus = 2 into your Database
}
out.print ("{\"RspCode\":\"00\",\"Message\":\"Confirm Success\"}");
}
else
{
out.print("{\"RspCode\":\"02\",\"Message\":\"Order already confirmed\"}");
}
}
else
{
out.print("{\"RspCode\":\"04\",\"Message\":\"Invalid Amount\"}");
}
}
else
{
out.print("{\"RspCode\":\"01\",\"Message\":\"Order not Found\"}");
}
}
else
{
out.print("{\"RspCode\":\"97\",\"Message\":\"Invalid Checksum\"}");
}
}
catch(Exception e)
{
out.print("{\"RspCode\":\"99\",\"Message\":\"Unknow error\"}");
}
%>
router.get('/vnpay_ipn', function (req, res, next) {
var vnp_Params = req.query;
var secureHash = vnp_Params['vnp_SecureHash'];
delete vnp_Params['vnp_SecureHash'];
delete vnp_Params['vnp_SecureHashType'];
vnp_Params = sortObject(vnp_Params);
var config = require('config');
var secretKey = config.get('vnp_HashSecret');
var querystring = require('qs');
var signData = querystring.stringify(vnp_Params, { encode: false });
var crypto = require("crypto");
var hmac = crypto.createHmac("sha512", secretKey);
var signed = hmac.update(new Buffer(signData, 'utf-8')).digest("hex");
if(secureHash === signed){
var orderId = vnp_Params['vnp_TxnRef'];
var rspCode = vnp_Params['vnp_ResponseCode'];
//Kiem tra du lieu co hop le khong, cap nhat trang thai don hang va gui ket qua cho VNPAY theo dinh dang duoi
res.status(200).json({RspCode: '00', Message: 'success'})
}
else {
res.status(200).json({RspCode: '97', Message: 'Fail checksum'})
}
});
Cài đặt Code Return URL
Dữ liệu VNPAY trả về bằng cách chuyển hướng trình duyệt web của khách hàng theo địa chỉ web mà Merchant cung cấp khi gửi yêu cầu thanh toán. Trên URL này mang thông tin kết quả thanh toán của khách hàng.
VNPAY trả về kết quả thanh toán URL có dạng:
https://{domain}/ReturnUrl?vnp_Amount=1000000&vnp_BankCode=NCB&vnp_BankTranNo=VNP14226112&vnp_CardType=ATM&vnp_OrderInfo=Thanh+toan+don+hang+thoi+gian%3A+2023-12-07+17%3A00%3A44&vnp_PayDate=20231207170112&vnp_ResponseCode=00&vnp_TmnCode=CTTVNP01&vnp_TransactionNo=14226112&vnp_TransactionStatus=00&vnp_TxnRef=166117&vnp_SecureHash=b6dababca5e07a2d8e32fdd3cf05c29cb426c721ae18e9589f7ad0e2db4b657c6e0e5cc8e271cf745162bcb100fdf2f64520554a6f5275bc4c5b5b3e57dc4b4b
Trong đó
https://{domain}/ReturnUrl
là URL nhận kết quả hệ thống gửi sang VNPAY theo URL thanh toán qua tham sốvnp_ReturnUrl
Danh sách tham số
Giống với tham số gửi về địa chỉ IPN URL
Lưu ý
- URL này chỉ kiểm tra toàn vẹn dữ liệu (checksum) và hiển thị thông báo tới khách hàng
- Không cập nhật kết quả giao dịch tại địa chỉ này
Code cài đặt
require_once("./config.php");
$vnp_SecureHash = $_GET['vnp_SecureHash'];
$inputData = array();
foreach ($_GET as $key => $value) {
if (substr($key, 0, 4) == "vnp_") {
$inputData[$key] = $value;
}
}
unset($inputData['vnp_SecureHash']);
ksort($inputData);
$i = 0;
$hashData = "";
foreach ($inputData as $key => $value) {
if ($i == 1) {
$hashData = $hashData . '&' . urlencode($key) . "=" . urlencode($value);
} else {
$hashData = $hashData . urlencode($key) . "=" . urlencode($value);
$i = 1;
}
}
$secureHash = hash_hmac('sha512', $hashData, $vnp_HashSecret);
if ($secureHash == $vnp_SecureHash) {
if ($_GET['vnp_ResponseCode'] == '00') {
echo "GD Thanh cong";
}
else {
echo "GD Khong thanh cong";
}
} else {
echo "Chu ky khong hop le";
}
private static readonly
ILog log =
LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected void Page_Load(object sender, EventArgs e)
{
log.InfoFormat("Begin VNPAY Return, URL={0}", Request.RawUrl);
if (Request.QueryString.Count > 0)
{
string vnp_HashSecret = ConfigurationManager.AppSettings["vnp_HashSecret"]; //Chuoi bi mat
var vnpayData = Request.QueryString;
VnPayLibrary vnpay = new VnPayLibrary();
foreach (string s in vnpayData)
{
//get all querystring data
if (!string.IsNullOrEmpty(s) && s.StartsWith("vnp_"))
{
vnpay.AddResponseData(s, vnpayData[s]);
}
}
//vnp_TxnRef: Ma don hang merchant gui VNPAY tai command=pay
//vnp_TransactionNo: Ma GD tai he thong VNPAY
//vnp_ResponseCode:Response code from VNPAY: 00: Thanh cong, Khac 00: Xem tai lieu
//vnp_SecureHash: HmacSHA512 cua du lieu tra ve
long orderId = Convert.ToInt64(vnpay.GetResponseData("vnp_TxnRef"));
long vnpayTranId = Convert.ToInt64(vnpay.GetResponseData("vnp_TransactionNo"));
string vnp_ResponseCode = vnpay.GetResponseData("vnp_ResponseCode");
string vnp_TransactionStatus = vnpay.GetResponseData("vnp_TransactionStatus");
String vnp_SecureHash = Request.QueryString["vnp_SecureHash"];
String TerminalID = Request.QueryString["vnp_TmnCode"];
long vnp_Amount = Convert.ToInt64(vnpay.GetResponseData("vnp_Amount"))/100;
String bankCode = Request.QueryString["vnp_BankCode"];
bool checkSignature = vnpay.ValidateSignature(vnp_SecureHash, vnp_HashSecret);
if (checkSignature)
{
if (vnp_ResponseCode == "00" && vnp_TransactionStatus == "00")
{
//Thanh toan thanh cong
displayMsg.InnerText = "Giao dịch được thực hiện thành công. Cảm ơn quý khách đã sử
dụng dịch vụ";
log.InfoFormat("Thanh toan thanh cong, OrderId={0}, VNPAY TranId={1}", orderId,
vnpayTranId);
}
else
{
//Thanh toan khong thanh cong. Ma loi: vnp_ResponseCode
displayMsg.InnerText = "Có lỗi xảy ra trong quá trình xử lý.Mã lỗi: " + vnp_ResponseCode;
log.InfoFormat("Thanh toan loi, OrderId={0}, VNPAY TranId={1},ResponseCode={2}", orderId,
vnpayTranId, vnp_ResponseCode);
}
displayTmnCode.InnerText = "Mã Website (Terminal ID):" + TerminalID;
displayTxnRef.InnerText = "Mã giao dịch thanh toán:" + orderId.ToString();
displayVnpayTranNo.InnerText = "Mã giao dịch tại VNPAY:" + vnpayTranId.ToString();
displayAmount.InnerText = "Số tiền thanh toán (VND):" + vnp_Amount.ToString();
displayBankCode.InnerText = "Ngân hàng thanh toán:" + bankCode;
}
else
{
log.InfoFormat("Invalid signature, InputData={0}", Request.RawUrl);
displayMsg.InnerText = "Có lỗi xảy ra trong quá trình xử lý";
}
}
}
def payment_return(request):
inputData = request.GET
if inputData:
vnp = vnpay()
vnp.responseData = inputData.dict()
order_id = inputData['vnp_TxnRef']
amount = int(inputData['vnp_Amount']) / 100
order_desc = inputData['vnp_OrderInfo']
vnp_TransactionNo = inputData['vnp_TransactionNo']
vnp_ResponseCode = inputData['vnp_ResponseCode']
vnp_TmnCode = inputData['vnp_TmnCode']
vnp_PayDate = inputData['vnp_PayDate']
vnp_BankCode = inputData['vnp_BankCode']
vnp_CardType = inputData['vnp_CardType']
if vnp.validate_response(settings.VNPAY_HASH_SECRET_KEY):
if vnp_ResponseCode == "00":
return render(request, "payment_return.html", {"title": "Kết quả thanh toán",
"result": "Thành công", "order_id": order_id,
"amount": amount,
"order_desc": order_desc,
"vnp_TransactionNo": vnp_TransactionNo,
"vnp_ResponseCode": vnp_ResponseCode})
else:
return render(request, "payment_return.html", {"title": "Kết quả thanh toán",
"result": "Lỗi", "order_id": order_id,
"amount": amount,
"order_desc": order_desc,
"vnp_TransactionNo": vnp_TransactionNo,
"vnp_ResponseCode": vnp_ResponseCode})
else:
return render(request, "payment_return.html",
{"title": "Kết quả thanh toán", "result": "Lỗi", "order_id": order_id, "amount": amount,
"order_desc": order_desc, "vnp_TransactionNo": vnp_TransactionNo,
"vnp_ResponseCode": vnp_ResponseCode, "msg": "Sai checksum"})
else:
return render(request, "payment_return.html", {"title": "Kết quả thanh toán", "result": ""})
<%
//Begin process return from VNPAY
Map fields = new HashMap();
for (Enumeration params = request.getParameterNames(); params.hasMoreElements();) {
String fieldName = (String) params.nextElement();
String fieldValue = request.getParameter(fieldName);
if ((fieldValue != null) && (fieldValue.length() > 0)) {
fields.put(fieldName, fieldValue);
}
}
String vnp_SecureHash = request.getParameter("vnp_SecureHash");
if (fields.containsKey("vnp_SecureHashType")) {
fields.remove("vnp_SecureHashType");
}
if (fields.containsKey("vnp_SecureHash")) {
fields.remove("vnp_SecureHash");
}
String signValue = Config.hashAllFields(fields);
%>
<%
if (signValue.equals(vnp_SecureHash)) {
if ("00".equals(request.getParameter("vnp_ResponseCode"))) {
out.print("GD Thanh cong");
} else {
out.print("GD Khong thanh cong");
}
} else {
out.print("Chu ky khong hop le");
}
%>
router.get('/vnpay_return', function (req, res, next) {
var vnp_Params = req.query;
var secureHash = vnp_Params['vnp_SecureHash'];
delete vnp_Params['vnp_SecureHash'];
delete vnp_Params['vnp_SecureHashType'];
vnp_Params = sortObject(vnp_Params);
var config = require('config');
var tmnCode = config.get('vnp_TmnCode');
var secretKey = config.get('vnp_HashSecret');
var querystring = require('qs');
var signData = querystring.stringify(vnp_Params, { encode: false });
var crypto = require("crypto");
var hmac = crypto.createHmac("sha512", secretKey);
var signed = hmac.update(new Buffer(signData, 'utf-8')).digest("hex");
if(secureHash === signed){
//Kiem tra xem du lieu trong db co hop le hay khong va thong bao ket qua
res.render('success', {code: vnp_Params['vnp_ResponseCode']})
} else{
res.render('success', {code: '97'})
}
});
Bảng mã lỗi của hệ thống thanh toán PAY
Mã lỗi | Mô tả |
---|---|
Bảng mã lỗi vnp_TransactionStatus | |
00 | Giao dịch thành công |
01 | Giao dịch chưa hoàn tất |
02 | Giao dịch bị lỗi |
04 | Giao dịch đảo (Khách hàng đã bị trừ tiền tại Ngân hàng nhưng GD chưa thành công ở VNPAY) |
05 | VNPAY đang xử lý giao dịch này (GD hoàn tiền) |
06 | VNPAY đã gửi yêu cầu hoàn tiền sang Ngân hàng (GD hoàn tiền) |
07 | Giao dịch bị nghi ngờ gian lận |
09 | GD Hoàn trả bị từ chối |
Mã lỗi | Mô tả |
---|---|
vnp_ResponseCode VNPAY phản hồi qua IPN và Return URL: | |
00 | Giao dịch thành công |
07 | Trừ tiền thành công. Giao dịch bị nghi ngờ (liên quan tới lừa đảo, giao dịch bất thường). |
09 | Giao dịch không thành công do: Thẻ/Tài khoản của khách hàng chưa đăng ký dịch vụ InternetBanking tại ngân hàng. |
10 | Giao dịch không thành công do: Khách hàng xác thực thông tin thẻ/tài khoản không đúng quá 3 lần |
11 | Giao dịch không thành công do: Đã hết hạn chờ thanh toán. Xin quý khách vui lòng thực hiện lại giao dịch. |
12 | Giao dịch không thành công do: Thẻ/Tài khoản của khách hàng bị khóa. |
13 | Giao dịch không thành công do Quý khách nhập sai mật khẩu xác thực giao dịch (OTP). Xin quý khách vui lòng thực hiện lại giao dịch. |
24 | Giao dịch không thành công do: Khách hàng hủy giao dịch |
51 | Giao dịch không thành công do: Tài khoản của quý khách không đủ số dư để thực hiện giao dịch. |
65 | Giao dịch không thành công do: Tài khoản của Quý khách đã vượt quá hạn mức giao dịch trong ngày. |
75 | Ngân hàng thanh toán đang bảo trì. |
79 | Giao dịch không thành công do: KH nhập sai mật khẩu thanh toán quá số lần quy định. Xin quý khách vui lòng thực hiện lại giao dịch |
99 | Các lỗi khác (lỗi còn lại, không có trong danh sách mã lỗi đã liệt kê) |