微信小程序前端根据路径生成访问二维码


小程序项目中需要生成访问二维码,借助微信小程序提供的 API 在前端根据小程序后台配置的二维码访问路径生成了对应的二维码;不建议在项目中直接使用,因为会暴露小程序的 appid 和 secret;

1、步骤

1、生成 access_token;
2、调用小程序提供的接口;
3、处理 buffer 类型数据为 base64;

2、总体代码

const { btoa } =  require('./base64')
Component({
  data: {
    image:''
  },
  methods: {
    getToken(){
      let that = this;
      let domain = "https://api.weixin.qq.com/cgi-bin/token";
      let appid = "xxxx";
      let secret = "xxxxxx";
      let params = {
        grant_type:"client_credential",
        appid,
        secret
      }
      wx.request({
        url: domain,
        data:params,
        method:'get',
        success(res){
          that.getQRcode(res.data.access_token);
        }
      })
    },
    //小程序必须发布成功,且page对应路径可以找到才能调通这个接口
    getQRcode(token){
      let params = {
        page:'pages/home/index',
        scene:'xxxx'
      }
      let domain = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token= ${token}`
      let that = this;
      wx.request({
        url: domain,
        data:params,
        responseType: "arraybuffer",
        method:"post",
        success(res){
          console.log(res)
          const str = String.fromCharCode(...new Uint8Array(res.data));
          let img = `data:image/jpeg;base64,${btoa(str)}`;
          that.setData({
            image:img
          })
        }
      })
    }
  }
})

由于拿到的是 buffer 类型的数据,我们需要将他转化为 base64 格式,之前小程序官方提供了一个 api 来转化,目前已经废弃了;所以这里需要自己弄一个方法 base64.js:

var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
  a256 = "",
  r64 = [256],
  r256 = [256],
  i = 0;

var UTF8 = {
  /**
   * Encode multi-byte Unicode string into utf-8 multiple single-byte characters
   * (BMP / basic multilingual plane only)
   *
   * Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
   *
   * @param {String} strUni Unicode string to be encoded as UTF-8
   * @returns {String} encoded string
   */
  encode: function (strUni) {
    // use regular expressions & String.replace callback function for better efficiency
    // than procedural approaches
    var strUtf = strUni
      .replace(
        /[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
        function (c) {
          var cc = c.charCodeAt(0);
          return String.fromCharCode(0xc0 | (cc >> 6), 0x80 | (cc & 0x3f));
        }
      )
      .replace(
        /[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
        function (c) {
          var cc = c.charCodeAt(0);
          return String.fromCharCode(
            0xe0 | (cc >> 12),
            0x80 | ((cc >> 6) & 0x3f),
            0x80 | (cc & 0x3f)
          );
        }
      );
    return strUtf;
  },

  /**
   * Decode utf-8 encoded string back into multi-byte Unicode characters
   *
   * @param {String} strUtf UTF-8 string to be decoded back to Unicode
   * @returns {String} decoded string
   */
  decode: function (strUtf) {
    // note: decode 3-byte chars first as decoded 2-byte strings could appear to be 3-byte char!
    var strUni = strUtf
      .replace(
        /[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars
        function (c) {
          // (note parentheses for precence)
          var cc =
            ((c.charCodeAt(0) & 0x0f) << 12) |
            ((c.charCodeAt(1) & 0x3f) << 6) |
            (c.charCodeAt(2) & 0x3f);
          return String.fromCharCode(cc);
        }
      )
      .replace(
        /[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars
        function (c) {
          // (note parentheses for precence)
          var cc = ((c.charCodeAt(0) & 0x1f) << 6) | (c.charCodeAt(1) & 0x3f);
          return String.fromCharCode(cc);
        }
      );
    return strUni;
  },
};

while (i < 256) {
  var c = String.fromCharCode(i);
  a256 += c;
  r256[i] = i;
  r64[i] = b64.indexOf(c);
  ++i;
}

function code(s, discard, alpha, beta, w1, w2) {
  s = String(s);
  var buffer = 0,
    i = 0,
    length = s.length,
    result = "",
    bitsInBuffer = 0;

  while (i < length) {
    var c = s.charCodeAt(i);
    c = c < 256 ? alpha[c] : -1;

    buffer = (buffer << w1) + c;
    bitsInBuffer += w1;

    while (bitsInBuffer >= w2) {
      bitsInBuffer -= w2;
      var tmp = buffer >> bitsInBuffer;
      result += beta.charAt(tmp);
      buffer ^= tmp << bitsInBuffer;
    }
    ++i;
  }
  if (!discard && bitsInBuffer > 0)
    result += beta.charAt(buffer << (w2 - bitsInBuffer));
  return result;
}

var Plugin = function (dir, input, encode) {
  return input ? Plugin[dir](input, encode) : dir ? null : this;
};

Plugin.btoa = Plugin.encode = function (plain, utf8encode) {
  plain =
    Plugin.raw === false || Plugin.utf8encode || utf8encode
      ? UTF8.encode(plain)
      : plain;
  plain = code(plain, false, r256, b64, 8, 6);
  return plain + "====".slice(plain.length % 4 || 4);
};

Plugin.atob = Plugin.decode = function (coded, utf8decode) {
  coded = coded.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  coded = String(coded).split("=");
  var i = coded.length;
  do {
    --i;
    coded[i] = code(coded[i], true, r64, a256, 6, 8);
  } while (i > 0);
  coded = coded.join("");
  return Plugin.raw === false || Plugin.utf8decode || utf8decode
    ? UTF8.decode(coded)
    : coded;
};
module.exports = {
  btoa: Plugin.btoa,
  atob: Plugin.atob,
};

3、总结

1、使用 getwxacode 这个接口,我们需要传递参数是 path,可以正常生成二维码,但是 path 路径在线上不存在的话会跳到 404 页面;
2、使用 getwxacodeunlimit 这个接口,我们需要使用 scene 传递参数,路径是 page 不可以拼接任何参数;并且这个接口的 page 必须是发布过的代码里存在的路径,否则接口是调不通的;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值