微信小程序---生成带参数的小程序码
我们的业务需要,根据不同的业务区域,设置不同的小程序码,用户扫进去展示的内容是不一样的。
微信获取不限制的小程序码:
https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
微信小程序接受参数:
Page({ onLoad (query) { // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene const scene = decodeURIComponent(query.scene) } })
1、调用接口
POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
参数:
scene 必传 // 这个就是你需要通过页面传的参数 page 非必传 // 默认就是主页 例如 pages/index/index,
2、获取access_token
文档:
https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
接口:
GET https://api.weixin.qq.com/cgi-bin/token
请求示例:
GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
成功返回:
{ "access_token":"ACCESS_TOKEN", "expires_in":7200 }
具体代码示例:
// 获取 access_token getAccessToken(){ uni.request({ method: "GET", url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`, success:(result) =>{ let access_token = result.data.access_token // 获取到 access_token 后 获取二维码 this.getQrCode(access_token) } }) } // 获取二维码 getQrCode(token){ // 注意 access_token 参数是必须放在url后面 其余参数 要在data里面 let path = 'pages/index/index' uni.request({ method: "POST", responseType: 'arraybuffer', // 注意一定要加 不然返回的Buffer流会乱码 导致无法转base64 url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${token}`, data: { page: path, // 需要打开的页面路径 scene: this.userid // 这个是需要传递的参数 }, success:(result) =>{ // 拿到buffer流 通过wx.arrayBufferToBase64 转成base64 在页面展示 // 如果不加请求时 responseType: 'arraybuffer' 则会转码失败 this.bufferImg = "data:image/png;base64," + wx.arrayBufferToBase64(result.data); }, }) } // template 部分 <image :src="bufferImg" style="width: 200px;height: 200px"></image>
3、后端实现代码示例
/** * code */ public function code($id) { $accesstoken = $this->getMiniAccessToken(); $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$accesstoken; $data = [ 'scene'=> "communityid={$id}", 'env_version' => 'release' // 'page'=>'pages/index/index', // 'check_path'=>false ]; // 获取小程序码 $result = http_post($url,$data); $path = '/uploads/qrcode/' . date("YmdHis") . md5($result['content']) . '.jpg'; file_put_contents('.' . $path,$result['content']); $this->edit(['id' => $id,'wxcode' => $path]); return $path; }
4、如何接受参数
我使用的uniapp开发小程序
var decode_link = decodeURIComponent(options.scene)
参考文档:
https://blog.csdn.net/double_Fly_/article/details/132453002
https://blog.csdn.net/qq_42934208/article/details/128668988
打完收工!

浙公网安备 33010602011771号