微信小程序支付前端源码
1 //index.js 2 Page({ 3 data: { 4 5 }, 6 //点击支付按钮进行支付 7 payclick: function () { 8 var t = this; 9 wx.login({ 10 //获取code换取openID 11 success: function (res) { 12 //code = res.code //返回code 13 console.log("获取code"); 14 console.log(res.code); 15 var opid = t.getOpenId(res.code); 16 } 17 }) 18 }, 19 //获取openID 20 getOpenId: function (code) { 21 var that = this; 22 wx.request({ 23 url: "https://api.weixin.qq.com/sns/jscode2session?appid=你的appid&secret=AppSecret(小程序密钥)&js_code=" + code + "&grant_type=authorization_code", 24 data: {}, 25 method: 'GET', 26 success: function (res) { 27 console.log("获取openid") 28 console.log(res) 29 that.setData({ 30 openid: res.data.openid, 31 session_key: res.data.session_key 32 }) 33 that.generateOrder(res.data.openid) 34 }, 35 fail: function () { 36 // fail 37 }, 38 complete: function () { 39 // complete 40 } 41 }) 42 }, 43 //生成商户订单 44 generateOrder: function (openid) { 45 var that = this 46 wx.request({ 47 url: 'http://localhost:25492/wx/getda',//后台请求地址 48 method: 'GET', 49 data: { 50 gfee: '商品价钱', 51 gname: '商品名称', 52 openId: openid 53 //(商品价钱和商品名称根据自身需要是否传值, openid为必传) 54 }, 55 success: function (res) { 56 console.log("后台获取数据成功"); 57 console.log(res); 58 var param = { "timeStamp": res.data.timeStamp, "package": res.data.package, "paySign": res.data.paySign, "signType": "MD5", "nonceStr": res.data.nonceStr }; 59 //发起支付 60 that.pay(param); 61 }, 62 fail: function (res) { 63 console.log("向后台发送数据失败") 64 } 65 }) 66 }, 67 //支付 68 pay: function (param) { 69 var that = this; 70 console.log("发起支付") 71 console.log(param) 72 wx.requestPayment({ 73 timeStamp: param.timeStamp, 74 nonceStr: param.nonceStr, 75 package: param.package, 76 signType: param.signType, 77 paySign: param.paySign, 78 success: function (res) { 79 console.log("success"); 80 console.log(res); 81 }, 82 fail: function (res) { 83 console.log("fail") 84 console.log(res); 85 }, 86 complete: function (res) { 87 console.log("complete"); 88 console.log(res) 89 } 90 }) 91 } 92 })
本地调试如过出现请求失败请将 微信开发者工具 > 详情(右上角) > 不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书 勾上即可