小程序生成二维码

1、根据官网文档 微信官方文档

接口规范

小程序接口调用凭证auth.getAccessToken接口规范参考链接

接口请求地址

GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

接口请求参数

appid:小程序 appId
secret:小程序 appSecret
grant_type:授权类型,填写 client_credential

接口响应参数(返回的 JSON 数据包)

access_token:获取到的凭证
expires_in:凭证有效时间,单位:秒。目前是7200秒之内的值。
errcode:错误码(异常情况才会有错误码返回,正常是没有该字段返回的)
errmsg:错误信息

准备工作

需要准备请求接口的2个参数:
appid:小程序 appId,需要小程序注册申请流程获得;
secret:小程序 appSecret,需要在小程序开发配置选项里面经由管理员扫码授权生成;
获取链接:https://mp.weixin.qq.com/](https://mp.weixin.qq.com/

image.png

切记:测试时要使用测试的appId和appSecret 链接:https://developers.weixin.qq.com/sandbox

获取token

getToken() {
     uni.showLoading({
    title: '加载中',
        mask: true
   })
    let APPID = 'wxbxxxxxxxxxx'
    let APPSECRET = 'bxxxxxxxxxxxxxxxx'
    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
        console.log('getToken', this.shareToken, res)
        uni.hideLoading();
    }).catch(err => {
        console.log(err)
        uni.hideLoading();
    })
},

2、生成二维码:

https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + this.shareToken

避坑

  • page是页面地址,例如:'pages/index/index'。pages前面不能有斜杠
  • scene是参数,为字符串。比如要传入id=428,那么scene参数就可以写成"428",多个参数以&分开,如第二个参数是code=0,则是"428&0"。
getQrCode() {    //获取小程序码带参数
    const that = this;
    let scene = 'id=' + that.id + '&spid=' + that.currSpid + '&scode=' + that.scode;
    uni.request({
       url: "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + this.shareToken, // 固定链接,不用改
         method: 'POST',
         responseType: 'arraybuffer', //设置响应类型
         data: {
            path: 'pages/goods_details/index', // 必须是已经发布的小程序存在的页面(否则报错)()
       scene: scene,
           width: 298,
           auto_color: true, // 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调
           line_color: {
               "r": "0",
               "g": "0",
               "b": "0"
               } // auto_color 为 false 时生效,使用 rgb 设置颜色
           },
          success: function(res) {
              console.log('获取二维码111', res) //返回的是ArrayBuffer 对象
              setTimeout(()=>{
                  that.maskData = "data:image/PNG;BASE64," + uni.arrayBufferToBase64(res.data);//以图片的形式展示
                 },50)
             console.log("生成成功2222", that.maskData);
           }
     })
},
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容