> 技术文档 > uniapp 生成小程序码以及获取scene参数_uniapp生成小程序码

uniapp 生成小程序码以及获取scene参数_uniapp生成小程序码

提示:本文章主要目的为开发者提供思路, 实际落地需要后端提供接口, 文章中会有标注。

文章目录

    • 一、获取access_token
    • 二、生成小程序
    • 三、获取scene参数
    • 四、通过开发者工具调试分享页面
    • 参考文档

一、获取access_token

提示:实际开发中需要后端提供接口,根据业务逻辑存储access_token

// 前端代码实现获取access_tokengetToken() {// 小程序唯一凭证,即 AppID,可在「微信公众平台 - 设置 - 开发设置」页中获得。const appid = \'appid\';// 小程序唯一凭证密钥,即 AppSecret,获取方式同 appidconst appSecret = \'appSecret \'uni.request({method: \'GET\', url: \'https://api.weixin.qq.com/cgi-bin/token\', data: { grant_type: \'client_credential\',appid,secret: appSecret }, success: (res) => { this.accessToken = res.data.access_token || \'\' }});},

二、生成小程序码

getUnlimitedQRCode 通过该接口生成的小程序码,永久有效,数量暂无限制。

提示:getUnlimitedQRCode 微信官网虽然没有强调该接口由后端调用,但是前端调用的话发布到线上是不展示小程序码的, 所以前端需要携带data参数请求后端接口, 后端调用wx接口返回小程序码,前端通过uni.arrayBufferToBase64转换为base64展示在页面上

getWxaCode() {// 分享页面需要的参数const scene = \"id=1&type=1\"// 分享页面路由const page = \'pages/share/share\'// 默认是true,检查page 是否存在,为 true 时 page 必须是已经发布的小程序存在的页面(否则报错);为 false 时允许小程序未发布或者 page 不存在const check_path = false// 要打开的小程序版本。正式版为 \"release\",体验版为 \"trial\",开发版为 \"develop\"。默认是正式版。const env_version = \'develop\'uni.request({method: \'POST\', url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${this.accessToken}`, data: {scene,page,check_path,env_version },responseType: \'arraybuffer\', success: (res) => {// 这里的url可以直接在页面显示 let url =\'data:image/png;base64,\'+ uni.arrayBufferToBase64(res.data);this.imgUrl = url }});},

注:uni.request 请求须加上responseType: \'arraybuffer\', 请求后端接口时同样需要带上arraybuffer: true, 否则不能解析二进制图片

三、获取scene参数

methods: {// 将url中的参数转成对象{key:value}的形式urlParams (scene) {// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 sceneconst str = decodeURIComponent(scene).replace(\'?\', \'&\')let strArr = str.split(\'&\')strArr = strArr.filter(item => item)const result = {}strArr.filter(item => {const key = item.split(\'=\')result[key[0]] = key[1]})return result}},onLoad(options) {this.scene = this.urlParams(options.scene)}

四、通过开发者工具调试分享页面

调试分享页面时将生成的小程序码通过“快速二维码编译”,在开发者工具中调试。

uniapp 生成小程序码以及获取scene参数_uniapp生成小程序码

参考文档

获取 Access token
获取不限制的小程序码

留档总结