记录vue微信支付!!!
在vue中调用微信支付(JSAPI支付)
一、首先第一步在支付页面的上一个页面来获取微信授权,也是获取微信code的方法
location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=微信appid&redirect_uri=' + 要跳转页面的地址&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect'
二、第二步就是截取第一步传过来的code(注:微信支付只能从微信开发者工具上进行测试;在浏览器中测试不了),下面这个方法是截取地址栏传过来的字符串方法,方便很多,拿去用就行
getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
},
三、点击支付按钮会调用后台接口生成一个订单ID
btnZhiFuClick(){
let self = this;
let obj = { // obj里 看后台要什么传什么
stuId:self.*****,
token:self.*****,
courseId:self.*****,
unitId:self.*****,
currency:self.*****,
originalPrice:self.***** 9 }
this.$http.post(this.$api.******.******)
.then(res=>{
if(res.status == '200'){
self.orderId = res.data //获取到的订单ID保存到全局变量里
this.weixinCode() //直接调用微信支付
}
})
},
四、取到的code去调用后台接口,换取openID(openid是调用支付的主要凭证)
getOpenIdByCode(){
this.$http.get(this.$api.****.****,{
params:{
code:self.getQueryVariable("code") //直接调用第二步方法 获取code
}
})
.then(res=>{
this.getOpenIdCODE = res.data.data //接收后台传过来的openid,保存到全局变量中,支付时候传
})
},
五、发起支付方法,具体看后台需要什么参数,传过去就完了
weixinCode(){
let self = this
this.$http.get(this.$api.******.******,{
params:{ // params里是后台需要的参数,看你们后台需要什么
description: "123123",
orderId: self.orderId, //orderId 支付时后台返回来的订单ID
orderTotal: uitrmb*100, //微信的支付正常情况下是要乘以100
openId: self.getOpenIdCODE, //这里就是上一步获取到的微信 openid 直接拿过来就行11 }
})
.then(res=>{ //res里保存着后台给返回来的调取微信支付的凭证
function onBridgeReady(){WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId":"*************",//公众号名称,由商户传入==》公众号平台里的appid,直接复制过来
"timeStamp":res.data.timeStamp,//时间戳,自1970年以来的秒数
"nonceStr":res.data.nonceStr, //随机串
"package":res.data.package,
"signType":res.data.signType,//微信签名方式:
"paySign":res.data.paySign //微信签名
},
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok"){
window.location.href = self.$apiList+"paymentSuccessful" //支付成功跳转页面
else if(res.err_msg == "get_brand_wcpay_request:cancel"){
// this.$router.push({path: '/payment'}) //取消支付跳转页面
}else if(res.err_msg == "get_brand_wcpay_request:fail"){
window.location.href = self.$apiList+"paytoFailure" //支付失败跳转页面
}
});
}
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();
}
})
},
最后,调起微信支付只能在手机上实测,微信开发者工具是测不了的

浙公网安备 33010602011771号