- 项目中,得先绑定微信
- 安装 微信JS-SDK npm install jweixin-module --save 官网 搜索jweixin
- 绑定微信后才能调起微信支付
项目中绑定微信
目前是在 登录成功后,自动绑定微信,首次 登录会有弹窗确定出现,往后是静默绑定,只能在线上测试
onShow() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/micromessenger/i) == 'micromessenger') {
this.getweixinCode();
} else {
console.log('不在微信环境中')
}
},
=======================分界线,以下的是在 methods: {} 方法里调用
// 获取code
getweixinCode() {
this.code = ''
var local = window.location.href // 获取页面url
var appid = 'wx45c457658667234421djh021fa44e644'
this.code = this.getUrlCode().code // 截取code
if (this.code == null || this.code === '') { // 如果没有code,则去请求
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
}
},
getUrlCode() {
// 截取url中的code方法
var url = location.search
var theRequest = new Object()
if (url.indexOf("?") != -1) {
var str = url.substr(1)
var strs = str.split("&")
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
}
}
return theRequest
},
// 绑定微信
bindingXH5() {
let that = this;
//判断是否在微信中
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/micromessenger/i) == 'micromessenger') {
if(!that.code){
that.getweixinCode();
}
// 调用 绑定微信 的接口 start ======== 根据自身项目情况而定
that.post(that.apis.bangdingweixin, {
data: {
userId:uni.getStorageSync('id'),
code: that.code
}
}).then(res => {
console.log(res, '绑定微信');
if (res.code == 0) {
} else {
uni.showToast({
title: res.msg,
icon: 'none'
})
}
});
// 调用 绑定微信 的接口 end==========
} else {
uni.reLaunch({
url:'/pages/index/index'
});
}
},
页面中调起微信支付
//h5 绑定微信公众号 微信支付 res 是后端返回的 数据,里面包含需要的信息
// appId: '', // 必填,公众号的唯一标识
// timestamp: , // 必填,生成签名的时间戳
// nonceStr: '', // 必填,生成签名的随机串
// signature: '',// 必填,签名
wxH5Pay(res){
let that = this;
var data = res;
//判断是否在微信中
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/micromessenger/i) == 'micromessenger') {
// console.log('是在微信客户端')
// 绑定微信
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId": data.appId, //公众号名称,由商户传入
"timeStamp": data.timeStamp, //时间戳,自1970年以来的秒数
"nonceStr":data.nonceStr, //随机串
"package": data.package,
"signType": data.signType, //微信签名方式:
"paySign": data.paySign,
},
res=> {
// 支付成功
if (res.err_msg == "get_brand_wcpay_request:ok") {
uni.showToast({
title:'支付成功',
icon:'success'
});
that.showPay = false;
that.isCreateOrder = false;
that.isPayOrder = false;
}
// 支付过程中用户取消
if (res.err_msg == "get_brand_wcpay_request:cancel") {
uni.showToast({
title:'支付已取消',
icon:'none'
});
}
// 支付失败
if (res.err_msg == "get_brand_wcpay_request:fail") {
uni.showToast({
title:'支付失败',
icon:'none'
});
}
/**
* 其它
* 1、请检查预支付会话标识prepay_id是否已失效
* 2、请求的appid与下单接口的appid是否一致
* */
if (res.err_msg == "调用支付JSAPI缺少参数:total_fee") {
uni.showToast({
title:'支付失败',
icon:'none'
});
}
});
} else {
// console.log('不是微信客户端')
uni.showToast({
title:'请在微信浏览器中打开',
icon:'none'
});
return;
}
},