美文网首页
Vue使用微信JS-SDK实现微信支付

Vue使用微信JS-SDK实现微信支付

作者: 前端浅语 | 来源:发表于2020-01-19 17:27 被阅读0次

最近做公众号开发,需要做充值功能调起微信支付,项目是Vue框架写的h5页面,研究了很多微信的官方文档和一些文章。终于开发完成,在此总结一下jssdk-jsapi微信支付的开发流程。
前端开发(vue-cli):

1、项目中下载jsapi文件包
(1)npm install weixin-jsapi
(2)在页面中引入文件 import wx from 'weixin-jsapi'

如果是html文件中可以<script>标签引入

// 只需要引入weixin-1.4.0.js 调试不成功时引入jq 
// <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script> 
<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
2、页面授权

页面授权可以根据项目需求选择静默授权和用户手动授权两种方式

(1)对于已关注公众号的用户,如果用户从公众号的会话或者自定义菜单进入本公众号的网页授权页,即使是scope为snsapi_userinfo,也是静默授权,用户无感知;
(2)对于以snsapi_base为scope的网页授权,就静默授权的,用户无感知。

打开此链接获取到code值
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirec

参数说明.png
3、拿到code传给后端接口,后端返回openid,token等用户信息,主要是为了获取openid
4、【立即充值】点击事件提交充值金额等页面信息,成功后执行以下代码
  wx.config({ 
    debug: true, // 这里一般在测试阶段先用ture,等打包给后台的时候就改回false, 
    appId: this.wx_config.appId, // 必填,公众号的唯一标识 
    timestamp: this.timestamp, // 必填,生成签名的时间戳     
    nonceStr: this.nonceStr, // 必填,生成签名的随机串 
    signature: this.paySign, // 必填,签名 
    jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表 
  }) 
  wx.ready(() => {  
    wx.checkJsApi({     
      jsApiList: ['chooseWXPay'],     
      success:function(res){ 
        console.log("seccess") 
        console.log('hskdjskjk', res) 
      }, 
      fail:function(res){      
        console.log("fail");       
        console.log(res) }   
      })   
    wx.chooseWXPay({     
        timestamp: this.timestamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符     
        nonceStr: this.nonceStr, // 支付签名随机串,不长于 32 位         
        package: this.package, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)     
        signType: this.signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'     
        paySign: this.paySign, // 支付签名     
        success: function (res) {  // 支付成功后的回调函数       
          alert(res.errorMsg)     
        },     
        fail: function (res) {       
          alert("支付失败");       
          alert(res.errMsg);     
        }   
      }) 
  }) 
  wx.error(err => { 
    alert(err) 
  })
5、测试支付功能时需要在微信公众号后台绑定开发者微信号,必须发测试线测试,本地不能测试 屏幕快照 2020-01-17 上午10.15.05.png

原生页面开发参考微信支付开发文档:https://pay.weixin.qq.com/wiki/doc/api/external/jsapi.php?chapter=7_7&index=6

相关文章

网友评论

      本文标题:Vue使用微信JS-SDK实现微信支付

      本文链接:https://www.haomeiwen.com/subject/cpwrzctx.html