小程序支付功能

场景:做小程序支付功能,正常操作是前端这边调用微信的 wx.requestpayment接口即可。

//比如说,点击付款按钮,然后就会弹出支付的窗口,这里就应该调用wx.requestPayment()
<view bindtap="confirmPay">确定付款</view>

confirmPay(){
let that = this;
let params = {
orderId:'',
orderDetail:'xxx'
};//比如说,这里是后台需要的参数
wx.request({
url:'这里是请求后台的接口',
data:params,
method:'POST',
header:{
'content-type':'application/json'
},
success:function(res){
console.log(res);//这里会返回调用微信支付接口需要的参数
that.pay(res); //到这里应该会弹出一个支付的弹窗了
},
error:function(error){}
})
}
//调用微信支付的接口
pay(temp){
wx.requestPayment({
timeStamp:temp.timeStamp,
nonceStr:temp.nonceStr,
package:temp.package,
signType:'MD5',
paySign:temp.paySign,
success:function(res){
//若执行到这步,则表示支付成功了
},
fail:function(err){}
})
}

//如果让前端做支付的话,其实后端还不是要参与,与其这样还不如上面的操作呐,更简单方便快捷。

//首先 用 wx.login()获取到当前用户的code,因为要拿来换取openid值。
onLoad:function(options){
let that = this;
wx.login({
success:function(res){
console.log(res.code);
that.getOpenid(res.code);
}
})
},
getOpenid(code){ //这个接口是请求微信官方的接口为了获取 openID 值
let that = this;
wx.request({
url:'https://api/weixin.qq.com/sns/jscode2session?appid=小程序APPID&secrest=小程序密钥&js_code=code&grant_type=authorization_code',
data:{},
method:'GET'
success:function(res){
that.getParams(res.data.openid);//这步是把获取到的openID传递给后端
}
})
},
getParams(openid){
let that = this;
wx.request({
url:'请求后端接口',
method:'xxx',
data:{},
success:function(res){
//这里后台会返回请求微信支付接口所需要的参数
that.confirmPay(res);
}
})
},
confirmPay:function(temp){
wx.requestPayment({
timeStamp:temp.timeStamp,
nonceStr:temp.nonceStr,
package:temp.package,
signType:temp.signType,
paySign:temp.paySign,
success:function(res){
//执行到这步就表示 支付成功了
},
fail:function(error){

}
})
}

 

参考链接:https://www.cnblogs.com/yujihaia/p/7459426.html

posted on 2020-03-28 15:53  有匪  阅读(599)  评论(0编辑  收藏  举报

导航