在作为前端开发的时候,我们开发的h5页面会设计到在手机浏览器中进行拉起微信支付和在微信内部打开网页是发起的微信本身的支付。 这样我们比如在订单发起支付的时候就会判断网页是在什么情况发起的支付。 我们直接上代码: 1、首先我们会前端会判断在什么浏览器中打开:
const ua = navigator.userAgent.toLowerCase();
const isWeixins = ua.indexOf('micromessenger') != -1;
这个就是判断是否在微信中打开
2、我们先说在微信中打开的情况下: 收下我们要在微信官网配置好了关于支付的一些配置才能进行 developers.weixin.qq.com/doc/offiacc… pay.weixin.qq.com/static/prod… 如果是第一次进入页面我们 我们会去微信的官网去获取授权的code,以便我们进行和后端进行交互: 页面中会跳转到网址:
这就是去获取code网址
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxx&redirect_uri=xxxxxx&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
我们如果获取了我们会从路径中获取参数code: 我们前端可以这样
/**
* @description : 获取页面路径地址的参数
* @date : 20221020
* @function : closePopM
* */
GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]);
return null;
}
我们可以将获取到的参数存起以便和接口进行获取openid
和后端进行交互获取openid
/**
* @description : 初始化获取openid
* @date : 20221115
* @function : getOpenid
* */
getOpenid(codes){
const params = {
code: codes
}
this.http.get(this.api.queryOffiaccountOpenId, params, res => {
if (res.data.code == '200'){
localStorage.setItem('openId', res.data.data.openId);
// this.openId = res.data.data.openId;
}
}, error => {
console.log(error);
});
},
// 微信提交支付
jssubmit(){
const param = {
"openid": '',
"orderid":''
}
this.http.post(this.api.jsSubmitPay, param, result => {
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', this.payss(result), false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', this.payss(result));
document.attachEvent('onWeixinJSBridgeReady', this.payss(result));
}
}else{
this.payss(result);
}
});
}
/**
* @description : 在微信内部发起微信支付,拉起微信支付的弹窗
* @function : payss
* @date : 20221103
* */
payss(result){
var that = this;
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId": result.data.data.appId, //公众号ID,由商户传入
"timeStamp": result.data.data.timeStamp, //时间戳,自1970年以来的秒数
"nonceStr":result.data.data.nonceStr, //随机串
"package": result.data.data.packageStr,
"signType": result.data.data.signType, //微信签名方式:
"paySign": result.data.data.paySign //微信签名
},
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ){
// 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
// 支付成功后就跳转到订单详情页面
window.location.href = "";
}else if(res.err_msg == "get_brand_wcpay_request:fail" ){
window.location.href = '';
}else{
//修改上面生成的预支付订单状态
}
});
},
这就是页面在微信内部支付的完整的前端流程 3、如果我们在微信外部打开页面并发起支付的时候,h5支付比较简单
// 这是在h5中打开发起支付
const param = {
"orderId": '',
"orderType": '1'
}
this.http.post(this.api.h5Submit, param, res => {
const rescode200 = res.data.code === 200;
if (rescode200) {
location.href = res.data.data.h5Url + '&redirect_url=';
}
}, error => {
console.log(error);
});
}
上面就是完整的h5支付的前端代码 总结: 1、在微信内部支付对于前端来说比较复杂需要不断的调试。 2、在微信外部发起支付对于前端来说比较简单只需要联调一下接口,然后跳转到接口返回的链接就完成了。 希望上面的能帮助到前端开发支付的小伙伴。