ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## uni-app 微信小程序生成二维码带参数 ### 第一步: 获取 access\_token ``` getToken() { uni.showLoading({ title: '加载中', mask: true }) let APPID = '从后台获取' let APPSECRET = '从后台获取' uni.request({ url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`, method: "GET", }).then((res) => { if (res[1].data.expires_in != 7200) { uni.showToast({ title: "分享失败,请重新尝试。", icon: "none", duration: 2000 }) uni.hideLoading(); return } console.log(res) this.shareToken = res[1].data.access_token uni.hideLoading(); }).catch(err => { console.log(err) uni.hideLoading(); }) }, ``` - 这里需要注意的是,现在我们是在前端写的,测试的时候设置成为不校验域名,真是线上版本的时候,是不能这么写的,因为涉及到机密的数据:APPID 和 APPSECRET,微信是强制不让在前端做这个。 - 报错: https://api.weixin.qq.com不在以下 request 合法域名列表中,请参考文档:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/network.html - 所以必须在服务器上获取token 然后再通过后台的服务器返回 token给前端。(没有服务器的也不要担心,云开发可以解决这个难题,写一个云函数来代替服务器返回token) ### 第二步:将要转换的页面和参数转换为小程序码 > 请求微信的接口的时候请求方式为post,要注意设置相应的数据格式为**arraybuffer**,请求完毕后将数值转换为base64。 ~~~ getWxCode() { let that = this let userId = uni.getStorageSync('userId') //这里是我要传递的参数 let scene='t/qrcode01*id/'+ userId; // 这里设置了渠道和分享人的信息 //let scene= 'id=123&name=jack' 也可以是这样子的格式 console.log(scene) uni.showLoading({ title: '加载中', mask: true }) uni.request({ url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${this.shareToken}`, method: "POST", data: { scene: scene, page: 'pages/index/index' }, responseType: 'arraybuffer', success: function(res) { uni.hideLoading(); let src = wx.arrayBufferToBase64(res.data); that.src2 = 'data:image/png;base64,' + src; that.showQrcode = true //控制弹出框,展示二维码 } }) }, ~~~ 注意:**通过微信开发文档将页面转换为带参数的小程序码(一定要保证当前小程序有线上版本)** 最后连贯起来就是: ~~~ createQrCode() { console.log("生成专属二维码") if(this.src2){ this.showQrcode = true } else { this.showQrcode = false this.getToken() } }, ~~~ 页面中如果获取传递的参数呢? ~~~ onLoad: function (options) { let scene = decodeURIComponent(options.scene) console.log(scene) }, ~~~