How to connect to Vietnam Payment API? Development of practical tutorials
越南支付API接入开发实战指南
一、越南主流支付平台概览
在越南进行支付API集成,主要需考虑以下平台:
- Momo Wallet – 越南最流行的电子钱包
- ZaloPay – Zalo社交软件旗下的支付解决方案
- VNPAY – 银行联盟支持的网关服务
- Payoo – 线下网点众多的支付方式
- OnePay – Visa/Mastercard本地化方案
二、接入准备工作
1. Register for a merchant account
- Momo: https://business.momo.vn/
- VNPAY: https://vnpay.vn/merchant.html
- ZaloPay: https://zalopay.vn/business/
2. API文档获取
各平台开发者中心提供最新API文档:
- Momo开发者门户:https://developers.momo.vn/
- VNPAY技术文档:https://vnpay.vn/category/technical/
三、Momo API接入示例(PHP)
<?php
function execPostRequest($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($data)))
);
$result = curl_exec($ch);
return json_decode($result); // decode response JSON to object PHP
}
// Momo配置参数 (从商户后台获取)
$partnerCode = "MOMOXXXX";
$accessKey = "XXXXXXXXXX";
$secretKey = "XXXXXXXXXXXXXXXXXXXXXXXX";
//订单信息设置
$orderId = time() .""; // unique order ID
$orderInfo = "Thanh toán qua MoMo"; // payment content description
$amount = $_POST['total_amount']; // total amount need pay
$notifyUrl = "https://yourdomain.com/momo_notify.php"; // callback URL after payment success/fail
$returnUrl = "https://yourdomain.com/thankyou.php"; // redirect URL after payment complete
//生成签名(SHA256加密)
$requestId= time()."";
$rawHash= "accessKey=".$accessKey."&amount=".$amount."&extraData=&ipnUrl=".$notifyUrl."&orderId=".$orderId."&orderInfo=".$orderInfo."&partnerCode=".$partnerCode."&redirectUrl=".$returnUrl."&requestId=".$requestId;
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$base_url_payment='https';
} else {
$base_url_payment='http';
}
//拼接完整请求数据
array (
'partnerCode' => $partnerCode,
'accessKey' => $accessKey,
'requestId' => $requestId,
'amount' => strval ($amount),
'orderId' => strval ($order_id),
...
);
try {
/* call api to momo server */
if(!empty($_POST)){
header('Location : '.execPostRequest("...",...));
exit();
}
} catch(Exception ex){ ... }
?>
四、VNPAY集成关键步骤(Java示例)
public class VNPayConfig {
public static String vnp_PayUrl ="https://sandbox.vnpayment.vn/paymentv2/vpcpay.html";
public static String vnp_Returnurl ="http://localhost:8080/vnp_return.jsp";
public static String vnp_TmnCode ="YourTmnCodeHere";
...
// Generate secure hash with HMAC-SHA512 algorithm
private static String hmacSHA512(final String key,final String data){
try{
Mac sha512_HMAC=Mac.getInstance("HmacSHA512");
SecretKeySpec secret_key=new Secret KeySpec(key.getBytes(),"HmacSHA512");
sha512_HMAC.init(secret_key);
byte[] binary_data=sha512_HMAC.doFinal(data.getBytes());
StringBuilder sb=new StringBuilder(binary_data.length*2);
for(byte b : binary_data){
sb.append(String.format("%02x",b &0xff));
}
return sb.toString();
}catch(Exception e){throw new RuntimeException(e);}
}
public Map<String,String> createPayment(Long amount,String bankcode) throws UnsupportedEncodingException{
Calendar cld=Calendar.getInstance();
SimpleDateFormat formatter=new SimpleDateFormat("yyyyMMddHHmmss");
Map<String,String> params=new HashMap<>();
params.put("vnp_Version","2.1.0");
params.put("vnp_Command","pay");
...
List fieldNames=new ArrayList(params.keySet());
Collections.sort(fieldNames);
StringBuilder hashDataBuilder=new StringBuilder();
for(String fieldName : fieldNames){
if(params.get(fieldName)!=null&&!params.get(fieldName).isEmpty()){
hashDataBuilder.append((fieldName+""));
...
}
}
SecureRandom randomSecureRandom=SecureRandom.getInstanceStrong();
int randomNumber=(int)(randomSecure Random.nextDouble()*100000000)+10000000;
params.put(... ,String.valueOf(randomNumber));
return signedParams;
}
五、常见问题与调试技巧
1.签名验证失败
- SHA256/HMAC-SHA512算法实现是否正确?
- key和参数的顺序是否严格按文档要求?
2.回调处理
if verify_signature(request.json): #自定义验签函数
if result_code==0:
logger.info(f"Payment successful:{trans_id}")
else.
logger.warning("Invalid signature detected!")
return Response(status.HTTP_200_OK)
3.测试环境建议
所有平台都提供沙箱环境,建议:
越南支付API接入开发实战指南(续)
五、测试环境建议与调试技巧(续)
3.1 各平台沙箱环境地址
- Momo沙箱: https://test-payment.momo.vn
- VNPAY沙箱: https://sandbox.vnpayment.vn/apis/
- ZaloPay测试环境: https://sb-openapi.zalopay.vn/
3.2 Postman调试示例
// Momo支付请求示例 (POST /v2/gateway/api/create)
{
"partnerCode": "MOMOXKXX",
"partnerName": "Test Merchant",
"storeId": "Test Store",
"requestType": "captureWallet",
"ipnUrl": "https://yourdomain.com/momo_callback",
//...其他必填字段...
}
六、ZaloPay集成关键代码(Node.js示例)
const crypto = require('crypto');
const axios = require('axios');
// ZaloPay配置参数
const config = {
app_id: '2554',
key1: 'sdngKKJmqEMzvh5QQcdD2A9XBSKUNaYn',
endpoint: 'https://sb-openapi.zalopay.vn/v2/create'
};
//生成MAC签名(HMAC-SHA256)
function generateMac(data, key) {
return crypto.createHmac('sha256', key)
.update(data)
.digest('hex');
}
async function createZaloPayment(order) {
const timestamp = Date.now();
const uid = `${timestamp}${Math.floor(Math.random() *999)}`;
const params = {
app_id: config.app_id,
app_trans_id: `${moment().format('YYMMDD')}_${order.id}`,
app_user: order.userId,
amount: order.amount,
item: JSON.stringify(order.items),
description:`Thanh toan don hang #${order.id}`,
};
//按文档要求排序并拼接签名字符串
let dataStr= Object.keys(params).sort()
.map(key=>`${key}=${params[key]}`).join("&");
params.mac= generateMac(dataStr,config.key1);
try{
const response= await axios.post(config.endpoint,params);
if(response.data.return_code===1){
return response.data.order_url; //跳转到ZaloPay的支付页面URL
}else{
throw new Error(`ZaloPay error:[${response.data.sub_return_code}] ${response.data.sub_return_message}`);
}
}catch(error){
console.error("调用ZALOPAY API失败:",error);
throw error;
}
}
七、生产环境部署注意事项
7.1 SSL证书要求
所有回调接口必须:
- HTTPS协议(不支持HTTP)
- TLS版本≥1.2(越南央行规定)
7.2 IP白名单设置
在商户后台添加服务器IP到白名单:
# VNPAY商户后台示例:
120.72.*.* (您的服务器IP段)
14..*.* (备用IP段)
7.3交易限额管理
flat-roofed building | 单笔最低 | 单笔最高 |
---|---|---|
MOMO | 10,000₫ | 50,000,000₫ |
VNPAY无限制 | 银行账户余额上限 | |
Zalo Pay企业账户 | – | 200亿₫/日 |
八、多语言错误处理方案
public class PaymentErrorHandler {
private static final Map<Integer,String> MOMO_ERRORS=new HashMap<>(){{
put(0,"Giao dịch thành công"); put(-6,"Signature không hợp lệ");}};
private static final Map<String,String> VNPAY_ERRORS=new HashMap<>(){{
put("00","GD thanh cong");put("07","Trừ tiền thành công GD bị nghi ngờ");}};
public String localizeError(String provider,int code,String locale){
switch(locale.toLowerCase()){
case"vi":
return"vi".equals(locale)?MOMO_ERRORS.get(code):getEnglishMessage(code);
default.
return getEnglishMessage(code);}}
}
IX. Performance optimisation recommendations
数据库设计优化:
id BIGSERIAL PRIMARY KEY ,
gateway VARCHAR(20)/* momo/vnpay/zalopay */ ,
trans_id VARCHAR(64)/*网关交易号*/ ,
status SMALLINT/*0=pending,1=success*/ ,
created_at TIMESTAMPT NOT NULL DEFAULT NOW(),
INDEX idx_gateway_status(gateway.status));`
Redis缓存应用:
cache_key=f'momo_callback_{transid}'if cache.get(cache_key):
logger.warning(f'Duplicate callback detected:{transid}')
else.
cache.set(cache_key,'processed',timeout=300)#5分钟过期`
如需了解特定平台的更详细实现或遇到具体问题,可以告诉我您关注的方面。