微信H5支付是指商户在移动端网页(非微信内置浏览器)提供的支付服务。本文将从商户号申请到接口对接,全方位讲解微信H5支付的开发流程。
什么是微信H5支付?
微信H5支付(也称为 Wap 支付或 MWEB 支付)是微信支付为移动端网页提供的支付能力。与 JSAPI 支付不同,H5 支付可以在手机浏览器(包括微信外部的浏览器)中调用微信支付完成付款。
适用场景:用户在手机浏览器中浏览商户网页,选择商品后通过微信支付完成购买。
前期准备
1. 注册微信商户号
访问微信支付商户平台 pay.weixin.qq.com,提交以下资料:
- 营业执照(个体工商户或企业)
- 法人身份证
- 对公银行账户
- 已备案的网站域名
2. 获取必要参数
申请成功后,你将获得以下关键信息:
appid- 微信公众号或小程序的应用IDmch_id- 商户号api_key- API 密钥cert/key- 证书文件
3. 配置授权域名
在商户平台配置支付授权目录(通常是 H5 网站的域名)。
开发流程
第1步:用户下单
// 前端发起下单请求
async function createOrder(productId) {
const response = await fetch('/api/order/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
productId,
userId: getCurrentUserId()
})
})
const data = await response.json()
return data.orderId
}
第2步:服务端统一下单
服务端调用微信统一下单 API,获取支付跳转链接 mweb_url:
const axios = require('axios')
const crypto = require('crypto')
async function wechatUnifiedOrder(order) {
const params = {
appid: process.env.WECHAT_APPID,
mch_id: process.env.WECHAT_MCH_ID,
nonce_str: crypto.randomBytes(16).toString('hex'),
body: order.productName,
out_trade_no: order.orderNo,
total_fee: order.amount * 100, // 转为分
spbill_create_ip: order.clientIp,
notify_url: 'https://www.example.com/api/pay/notify',
trade_type: 'MWEB',
scene_info: JSON.stringify({
h5_info: {
type: 'Wap',
wap_url: 'https://www.example.com',
wap_name: '智源论坛'
}
})
}
// 生成签名
params.sign = generateSign(params, process.env.WECHAT_API_KEY)
// 转换为 XML 格式
const xmlData = objectToXml(params)
// 调用微信API
const response = await axios.post(
'https://api.mch.weixin.qq.com/pay/unifiedorder',
xmlData,
{ headers: { 'Content-Type': 'application/xml' } }
)
// 解析返回的 XML,提取 mweb_url
const result = parseXml(response.data)
return result.mweb_url
}
第3步:前端跳转支付
// 跳转到微信支付
function gotoWeChatPay(orderId) {
fetch(`/api/pay/wechat?orderId=${orderId}`)
.then(res => res.json())
.then(data => {
if (data.mwebUrl) {
// 跳转到微信支付中间页
window.location.href = data.mwebUrl
} else {
alert('创建支付订单失败')
}
})
}
第4步:处理支付回调
// 异步通知接口
app.post('/api/pay/notify', async (req, res) => {
const xmlData = req.body
const notifyData = parseXml(xmlData)
// 验证签名
if (!verifySign(notifyData)) {
return res.send(xmlResponse('FAIL', '签名验证失败'))
}
// 处理订单逻辑
if (notifyData.return_code === 'SUCCESS') {
await markOrderAsPaid(notifyData.out_trade_no)
}
// 返回成功响应
res.send(xmlResponse('SUCCESS', 'OK'))
})
常见问题
Q1:支付完成后如何跳转回商户网站?
A:H5 支付完成后,用户停留在微信中。商户需要在 mweb_url 后拼接 redirect_url 参数,指定支付完成后的回跳地址。
Q2:测试环境如何使用?
A:微信支付没有官方沙箱环境,建议先在测试商户号(申请沙箱测试权限)中进行开发联调。
Q3:iOS 微信H5支付失败?
A:常见原因:未在商户平台配置正确的授权域名、wap_url 必须与发起支付的页面域名一致。
安全注意事项
⚠️ 重要提醒:
- API 密钥必须保管在服务端,不能泄露给前端
- 所有回调必须验证签名
- 实现幂等性处理,防止重复通知
- 订单金额必须服务端校验,不能信任前端传入的值
总结
微信H5支付是移动端网页支付的重要方案,掌握其开发流程对于构建商业化应用非常重要。本文从前期准备到接口对接,再到回调处理,详细介绍了完整开发过程。
下一步,你可以学习 更详细的微信H5支付技术文档,或了解 支付宝H5支付的对接方法。