Appearance
🔗 Collection Link – Tạo liên kết thanh toán
🧠 Khái niệm
Collection Link là API dùng để khởi tạo đơn hàng từ website của merchant đến hệ thống Pay2S.
🔄 Luồng xử lý
- Khách hàng thực hiện mua hàng trên Website hoặc ứng dụng của merchant và lựa chọn thanh toán trực tuyến Napas 247 cho đơn hàng.
- Website hoặc ứng dụng của merchant tiến hành gọi tạo link thanh toán, Pay2S sẽ kiểm tra dữ liệu và trả về kết quả chứa link thanh toán. Khi hệ thống của merchant nhận kết quả link thanh toán cần chuyển hướng khách hàng của bạn đến trang checkout của Pay2S bằng cách mở link thanh toán từ kết quả.
- Khách hàng sử dụng ứng dụng ngân hàng để quét mã VietQR từ link thanh toán.
- Giao dịch ghi nhận thành công tại ngân hàng, Pay2S sẽ trả kết quả thành công về redirectUrl gồm: trạng thái, mã đơn hàng, mã link thanh toán, ... Từ kết quả nhận được trên redirectUrl Website hoặc ứng dụng của merchant hiển thị giao diện thành công.
- Sau khi có kết quả ở giao diện, đồng thời Pay2S sẽ gửi một kết quả với đầy đủ thông tin thanh toán tới ipnUrl của cửa hàng, sau đó merchant cập nhật trạng thái đơn hàng phù hợp.
⚙️ Cấu hình API
🔸 HTTP Request
- URL:
https://payment.pay2s.vn/v1/gateway/api/create
- Method:
POST
- Content-Type:
application/json; charset=UTF-8
Request Parameters
Key | Type | Required | Description |
---|---|---|---|
partnerCode | String | ✓ | Định danh duy nhất cho mỗi yêu cầu. |
partnerName | String | Tên đối tác. | |
requestId | String(50) | ✓ | Định danh duy nhất cho mỗi yêu cầu. |
amount | Long | ✓ | Số tiền cần thanh toán (VND). |
bankAccounts | String | ✓ | Mảng chứa các số tài khoản và Bank Code. |
orderId | String | ✓ | Mã đơn hàng của đối tác. |
orderInfo | String | ✓ | Thông tin đơn hàng. Lưu ý: Giới hạn 10-32 ký tự, chỉ chấp nhậ ký tự chữ + số, không dấu gạch ngang hoặc đặc biêt. |
redirectUrl | String | ✓ | URL chuyển hướng sau khi thanh toán. |
ipnUrl | String | ✓ | API nhận kết quả thanh toán của đối tác. |
requestType | String | ✓ | Định danh kiểu của request. |
signature | String | ✓ | Chữ ký xác nhận giao dịch. Sử dụng thuật toán Hmac_SHA256 với data theo định dạng: 1 chuỗi String được sort theo thứ tự: accessKey=$accessKey&amount=$amount&bankAccounts=Array&ipnUrl=$ipnUrl&orderId=$orderId&orderInfo=$orderInfo&partnerCode=$partnerCode&redirectUrl=$redirectUrl&requestId=$requestId&requestType=$requestType |
📦 Sample Request
json
{
"accessKey": "66e862c89d4d4d1f34063dc1967fbd64dece4da3cba90af65167fbb8503b2eb3",
"partnerCode": "PAY2S7EPF0SB1ZP27W71",
"partnerName": "Test Payment Woocommerce",
"requestId": "1751916562",
"amount": 2000,
"orderId": "1173",
"orderInfo": "TT1173",
"orderType": "pay2s",
"bankAccounts": [
{
"account_number": "99999999",
"bank_id": "ACB"
}
],
"redirectUrl": "https://demo-payment.pay2s.vn/wp/thanh-toan/order-received/1173/?key=wc_order_qrJlIwVAwIEfl",
"ipnUrl": "https://demo-payment.pay2s.vn/wp/wc-api/WC_Gateway_Pay2S/",
"requestType": "pay2s",
"signature": "40cb7802b7d16bd08b1fc8d2a9f08d9df5efd785c7e7a6e817d8c7c4f71f165e"
}
💻 Code mẫu
php
function execPostRequest($url, $data)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$result = curl_exec($ch);
curl_close($ch);
echo($result);
$jsonResult = json_decode($result, true);
// Điều hướng đến URL thanh toán nếu có
if (isset($jsonResult['payUrl'])) {
header('Location: ' . $jsonResult['payUrl']);
}
return $result;
}
$endpoint = 'https://payment.pay2s.vn/v1/gateway/api/create';
$merchantName = "TEST";
$accessKey = '';
$secretKey = '';
$orderInfo = 'pay with Pay2S';
$order_desc = 'DH{{orderid}}';
$partnerCode = 'PAY2S72MLKFJFURCGPEM';
$redirectUrl = 'https://webhook.site/dd3de633-0a13-40e8-996d-ccd195d7237b';
$ipnUrl = 'https://webhook.site/dd3de633-0a13-40e8-996d-ccd195d7237b';
$amount = '50000';
$bank_accounts = "9877644888|vcb";
$orderId = time()."";
$requestId = time()."";
$extraData = '';
$requestType = 'pay2s';
$partnerName = 'Pay2S Payment';
$lang = 'vi';
if (!empty($_POST)) {
$accessKey = $_POST["accessKey"];
$secretKey = $_POST["secretKey"];
$orderInfo = $_POST["orderInfo"];
$partnerCode = $_POST["partnerCode"];
$redirectUrl = $_POST["redirectUrl"];
$amount = $_POST["amount"];
$orderId = $_POST["orderId"];
$order_desc = $_POST['order_desc'];
$orderInfo = str_replace('{{orderid}}', $orderId, $_POST['order_desc']);
$bank_accounts = $_POST['bank_accounts'];
$lines = explode("\n", $bank_accounts);
$bankList = [];
foreach ($lines as $line) {
// Tách từng dòng thành account_number và bank_id
list($accountNumber, $bankId) = explode('|', trim($line));
// Đưa các giá trị này vào mảng kết quả
$bankList[] = [
'account_number' => trim($accountNumber),
'bank_id' => trim($bankId)
];
}
$requestId = time() . '';
$extraData = "";
// Tạo chữ ký HMAC SHA256
$rawHash = "accessKey=" . $accessKey . "&amount=" . $amount . "&bankAccounts=Array&ipnUrl=" . $ipnUrl . "&orderId=" . $orderId . "&orderInfo=" . $orderInfo . "&partnerCode=" . $partnerCode . "&redirectUrl=" . $redirectUrl . "&requestId=" . $requestId . "&requestType=" . $requestType;
$signature = hash_hmac("sha256", $rawHash, $secretKey);
$data = array(
'accessKey' => $accessKey,
'partnerCode' => $partnerCode,
'partnerName' => $merchantName,
'requestId' => $requestId,
'amount' => $amount,
'orderId' => $orderId,
'orderInfo' => $orderInfo,
'orderType' => $requestType,
'bankAccounts' => $bankList,
'redirectUrl' => $redirectUrl,
'ipnUrl' => $ipnUrl,
'requestType' => $requestType,
'signature' => $signature,
);
$result = execPostRequest($endpoint, json_encode($data));
$jsonResult = json_decode($result, true); // decode json
}
?>
js
const axios = require('axios');
const crypto = require('crypto');
// Các giá trị mặc định
let endpoint = 'https://payment.pay2s.vn/v1/gateway/api/create';
let merchantName = "TEST";
let accessKey = '';
let secretKey = '';
let orderInfo = 'pay with Pay2S';
let order_desc = 'DH{{orderid}}';
let partnerCode = 'PAY2S72MLKFJFURCGPEM';
let redirectUrl = 'https://webhook.site/dd3de633-0a13-40e8-996d-ccd195d7237b';
let ipnUrl = 'https://webhook.site/dd3de633-0a13-40e8-996d-ccd195d7237b';
let amount = '50000';
let bank_accounts = "9877644888|vcb";
let orderId = Date.now() + '';
let requestId = Date.now() + '';
let extraData = '';
let requestType = 'pay2s';
let partnerName = 'Pay2S Payment';
let lang = 'vi';
// Dữ liệu POST
accessKey = 'yourAccessKey'; // Thay thế bằng giá trị từ form POST
secretKey = 'yourSecretKey'; // Thay thế bằng giá trị từ form POST
orderInfo = 'pay with Pay2S';
partnerCode = 'yourPartnerCode'; // Thay thế bằng giá trị từ form POST
redirectUrl = 'https://your-redirect-url.com';
amount = '50000'; // Thay thế bằng giá trị từ form POST
orderId = Date.now() + '';
order_desc = order_desc.replace('{{orderid}}', orderId);
bank_accounts = '9877644888|vcb'; // Thay thế bằng giá trị từ form POST
// Chuyển đổi danh sách tài khoản ngân hàng
const lines = bank_accounts.split('\n');
const bankList = lines.map(line => {
const [accountNumber, bankId] = line.trim().split('|');
return {
account_number: accountNumber.trim(),
bank_id: bankId.trim(),
};
});
// Tạo chữ ký HMAC SHA256
const rawHash = `accessKey=${accessKey}&amount=${amount}&bankAccounts=Array&ipnUrl=${ipnUrl}&orderId=${orderId}&orderInfo=${orderInfo}&partnerCode=${partnerCode}&redirectUrl=${redirectUrl}&requestId=${requestId}&requestType=${requestType}`;
const signature = crypto.createHmac('sha256', secretKey).update(rawHash).digest('hex');
// Dữ liệu gửi đi
const data = {
accessKey: accessKey,
partnerCode: partnerCode,
partnerName: merchantName,
requestId: requestId,
amount: amount,
orderId: orderId,
orderInfo: orderInfo,
orderType: requestType,
bankAccounts: bankList,
redirectUrl: redirectUrl,
ipnUrl: ipnUrl,
requestType: requestType,
signature: signature,
};
// Hàm thực hiện POST request
async function execPostRequest(url, data) {
try {
const response = await axios.post(url, data, {
headers: {
'Content-Type': 'application/json',
},
});
return response.data;
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
}
}
// Gửi yêu cầu tới API
execPostRequest(endpoint, data).then(result => {
console.log('Result:', result);
});
js
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace Pay2SExample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class Pay2SController : ControllerBase
{
private readonly HttpClient _httpClient;
public Pay2SController(HttpClient httpClient)
{
_httpClient = httpClient;
}
[HttpPost("create-payment")]
public async Task<IActionResult> CreatePayment()
{
string endpoint = "https://payment.pay2s.vn/v1/gateway/api/create";
string merchantName = "TEST";
string accessKey = "yourAccessKey";
string secretKey = "yourSecretKey";
string orderInfo = "pay with Pay2S";
string orderDesc = "DH{{orderid}}";
string partnerCode = "PAY2S72MLKFJFURCGPEM";
string redirectUrl = "https://your-redirect-url.com";
string ipnUrl = "https://your-ipn-url.com";
string amount = "50000";
string bankAccounts = "9877644888|vcb";
string orderId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
string requestId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
string requestType = "pay2s";
string partnerName = "Pay2S Payment";
// Tạo danh sách tài khoản ngân hàng
var bankList = bankAccounts.Split("\n")
.Select(line =>
{
var parts = line.Split('|');
return new
{
account_number = parts[0].Trim(),
bank_id = parts[1].Trim()
};
}).ToList();
// Tạo chuỗi chữ ký (rawHash)
string rawHash = $"accessKey={accessKey}&amount={amount}&bankAccounts=Array&ipnUrl={ipnUrl}&orderId={orderId}&orderInfo={orderInfo}&partnerCode={partnerCode}&redirectUrl={redirectUrl}&requestId={requestId}&requestType={requestType}";
// Tạo chữ ký HMAC SHA256
string signature = CreateSignature(rawHash, secretKey);
// Chuẩn bị dữ liệu POST
var requestData = new
{
accessKey,
partnerCode,
partnerName = merchantName,
requestId,
amount,
orderId,
orderInfo,
orderType = requestType,
bankAccounts = bankList,
redirectUrl,
ipnUrl,
requestType,
signature
};
// Gửi yêu cầu POST tới API
var response = await _httpClient.PostAsync(endpoint, new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json"));
// Xử lý phản hồi
string result = await response.Content.ReadAsStringAsync();
return Ok(JsonConvert.DeserializeObject(result));
}
// Hàm tạo chữ ký HMAC SHA256
private string CreateSignature(string rawData, string secretKey)
{
var key = Encoding.UTF8.GetBytes(secretKey);
using (var hmac = new HMACSHA256(key))
{
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(rawData));
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
}
}