前端对接 H5支付(非微信浏览器)与JSApi(微信浏览器支付)
0.参考文档
微信支付官方文档
1.首先需要来判断所在在环境是微信浏览器,还是除了微信浏览器外的其他浏览器
/**
* 判断是否是微信浏览器
*/
export const isWx = () => {
let uAgent = navigator.userAgent.toLowerCase()
return (/micromessenger/.test(uAgent)) ? true : false;
}
2.如果jsApi支付则需要先获取code值,h5支付不需要code
/**
* 再微信浏览器支付时候获取code
*/
export const getCode = () => {
let appid = "微信公众号所对应的appid"
let redirect_uri = window.location.href //重定向地址,当前重定向为当前页
let redirectUrl = encodeURIComponent(redirect_uri)//重定向的地址在拼接前需要转码
//跳转微信去获取code,当跳回当页时候url中会携带code值
let url_code = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect";
window.location.href = url_code;//打开这个链接,你的url后面就会跟上code的参数
}
onMounted(async () => {
if(isWx()){//当为微信浏览器的时候一进页面先判断url上是否携带code
if(window.location.href.includes('code=')){
state.code = getQueryVariable('code')
state.payres = await onCreatePayMent(state.orderNo,state.code)//调取创建交易接口
wxPay()
})
3.点击确认订单掉起支付的时候判断环境
if(isWx()){
wxPay()//微信浏览器拉起支付
}else{
h5Pay()//非微信浏览器拉起支付
}
const wxPay = async() =>{
if(state.code){//判断是否已经获取到code
openWeXinpay()//调起微信支付
}else{
getCode()
}
const h5Pay = async() =>{
//调起发起交易接口获取到后端返回的mwebUrl地址,跳转到当前地址拉起微信支付
state.payres = await onCreatePayMent(state.orderNo)
window.location.href = state.payres.data.mwebUrl;
}
4.调起微信支付弹框(jsapi方式)
微信支付官方文档
const openWeXinpay = () => {
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
}
} else {
onBridgeReady();
}
}
const onBridgeReady = () => {
/* eslint-disable */
WeixinJSBridge.invoke('getBrandWCPayRequest',
{
appId: state.payres.data.appId, // 公众号ID,由商户传入(
timeStamp: state.payres.data.timeStamp, // 时间戳,自1970年以来的秒数
nonceStr: state.payres.data.nonceStr, // 随机串
package: state.payres.data.package,
signType: state.payres.data.signType, // 微信签名方式:
paySign: state.payres.data.paySign,
},
async function (res) {
if (res.err_msg === 'get_brand_wcpay_request:ok') {
Toast('支付成功')
router.push({ path: "/manage/pay_status", query: { orderNo: state.orderNo } })
}else{
Toast('支付失败')
const res = await cancelWxPayMent(state.code,state.orderNo) //取消交易订单接口
router.push({ path: "/manage/pay_status", query: { orderNo: state.orderNo } })
}
},
)}