编程那点事编程那点事

专注编程入门及提高
探究程序员职业规划之道!

getUnlimitedQRCode 获取不限制的微信小程序码

微信名片程序完成了,现在需要给每个人生成不同的小程序码以便方便的分发给客户:

看了下,微信官方有api:小程序码与小程序链接 / 小程序码 / 获取不限制的小程序码 (qq.com)

后台POST请求太麻烦了,直接axios post获取吧,代码如下:

getQRCode(id) {
      const accessToken = 'accessToken'; // 这里需要动态获取你的 access_token
      const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`
      const postData = {
        page: 'pages/index/index',
        scene: 'userId='+id,
        check_path: false,
        env_version: 'release'
      };

      try {
        const response = await axios.post(url, postData, {
          headers: {
            "Content-Type":"application/json; charset=utf-8"
          },
          responseType: 'arraybuffer',
        });

        // Convert the buffer to a Base64 string
        const base64Image = `data:image/png;base64,${btoa(
            String.fromCharCode(...new Uint8Array(response.data))
        )}`;

        this.qrcodeVisible = true
        this.$nextTick(() => {
          this.$refs.qrcode.init(base64Image)
        })
      } catch (error) {
        console.error('Error fetching Wxacode:', error);
      }
    }

发现不行,提示跨域了:

Access to XMLHttpRequest at 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=access_token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

一开始以为是 服务器域名 的问题,于是配置了 服务器域名,后来发现问题依旧

于是修改了以下代码,vue.config.js 中新增跨域请求配置:

'/wxapi': {
        target: 'https://api.weixin.qq.com',
        changeOrigin: true,
        pathRewrite: { '^/wxapi': '' }
      }

同时修改,请求小程序码的代码:(注意,我修改了 url的赋值

getQRCode(id) {
  const accessToken = 'accessToken'; // 这里需要动态获取你的 access_token

  const url = `/wxapi/wxa/getwxacodeunlimit?access_token=${accessToken}`

  const postData = {
    page: 'pages/index/index',
    scene: 'userId='+id,
    check_path: false,
    env_version: 'release'
  };

  try {
    const response = await axios.post(url, postData, {
      headers: {
        "Content-Type":"application/json; charset=utf-8"
      },
      responseType: 'arraybuffer',
    });

    // Convert the buffer to a Base64 string
    const base64Image = `data:image/png;base64,${btoa(
        String.fromCharCode(...new Uint8Array(response.data))
    )}`;

    this.qrcodeVisible = true
    this.$nextTick(() => {
      this.$refs.qrcode.init(base64Image)
    })
  } catch (error) {
    console.error('Error fetching Wxacode:', error);
  }
}

 

 

未经允许不得转载: 技术文章 » getUnlimitedQRCode 获取不限制的微信小程序码