参考文档
H5项目运行环境判断
function inWechat() {
let ua = navigator.userAgent.toLowerCase();
let inWechat = ua.indexOf('micromessenger') != -1;
if (inWechat) {
console.log('在微信中打开')
return true;
}else{
console.log('在手机浏览器中打开')
return false;
}
}
1.1 JSAPI 支付/公众号支付
JSAPI支付是用户在微信内打开商户的H5页面,商户在H5页面通过调用微信支付提供的JSAPI接口调起微信支付模块完成支付。
应用场景有:
◆ 用户在微信公众账号内进入商家公众号,打开某个主页面,完成支付
◆ 用户的好友在朋友圈、聊天窗口等分享商家页面连接,用户点击链接打开商家页面,完成支付
◆ 将商户页面转换成二维码,用户扫描二维码后在微信浏览器中打开页面后完成支付
window.wx.config({
debug: isProduction() ? false : true,
appId: appId, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr: nonce, // 必填,生成签名的随机串
signature: signature,// 必填,签名
jsApiList: jsApiList // 必填,需要使用的JS接口列表
})
wx.chooseWXPay({
timestamp: timestamp,
nonceStr: nonce,
package: packageName,
signType: signType,
paySign: signature,
success: function (res) {
const targetHref = window.location.origin + '/wxactivity/#/info';
location.replace(targetHref)
},
error: function (res) {
Toast('支付失败')
},
cancel: function (res) {
console.log('支付cancel', res)
},
complete: function (res) {
console.log('支付complete', res)
},
});
1.2 H5 支付
商户在微信客外的移动端网页展示商品或服务, 用户在前述页面确认使用微信支付时, 商户发起本服务呼起微信客户端进行支付。
主要用于触屏版的手机浏览器请求微信支付的场景。 可以方便的从外部浏览器唤起微信支付。
流程
1.前端请求创建订单接口,后端统一下单获取 orderId 并返回
2.前端带着 orderId 请求支付接口,获得 mweb_url,
然后跳转 mweb_url 会跳转微信自动调用微信支付
- 正常流程用户支付完成后会返回至发起支付的页面,如需返回至指定页面,则可以在MWEB_URL后拼接上redirect_url参数,来指定回调页面。
3.支付后返回原页面,判断是否支付成功(需发送请求后端查询)
- redirect_url带上确认弹窗标志
- 设置确认按钮,让用户点击触发查单。
async wechatPay() {
let params = {};
const res = await fetch("url", "put", params);
const { data, msg, result } = res.data;
if (result === 0) {
const { origin, hash } = window.location;
let add = hash ;
if (hash.includes("?")) {
// 链接原本带参了
if (!hash.includes("userConfirm")) {
// 若未做处理,当用户多次放弃支付,拼接上多个userConfirm
add = hash + "&userConfirm=yes";
}
} else {
add = hash + "?userConfirm=yes";
}
window.location.replace(
data.url +
"&redirect_url=" +
encodeURIComponent(origin + "/wxactivity/" + add)
);
}
}
1.3 小程序支付
在小程序中支付
wx.requestPayment({
timeStamp: timestamp,
nonceStr: nonce,
package: packageName,
signType: 'MD5',
paySign: signature,
success: (res) => {
uni.redirectTo({
url: '/pages/volvo/purchaseSuccess/purchaseSuccess?orderid=' + volvooversealid
+ '×tamp=' + timestamp
+ '&bookedCount=' + this.bookedCount
+ '&isBindVin=' + this.isBindVin
+ '&payLink=' + this.payLink,
})
},
fail: (res) => {
Toast('支付失败');
}
})