koa2通过https调用生成小程序码

该博客介绍了如何在Node.js环境中使用https调用微信接口getwxacodeunlimit来生成小程序码,并将生成的图片Buffer写入本地文件,随后通过云存储HTTP API上传至云存储空间。主要涉及的技术包括请求库request、文件系统fs以及小程序码和云存储的API交互。
摘要由CSDN通过智能技术生成

记录一下nodejs下使用https调用生成小程序码的方法

# 主要思路

调用getwxacodeunlimit之后将图片buffer写入本地并调用云存储http api上传至云存储空间

# 主程序代码

server.js

app.use(async (ctx, next) => {
  await next()
  ctx.set('content-type', ctx.mimeType)
  ctx.body = ctx.data
})

// 获取小程序码
router.get('/getWxaCode', async (ctx, next) => {
  let page = ctx.request.query.page || '',
    token = ctx.request.header.token || ''

  // 获取小程序码配置
  const codeOptions = {
    method: 'POST',
    url:
      'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + token,
    body: {
      page: page,
      width: 230,
      scene: 'pc=1',
    },
    json: true,
    encoding: null,
  }

  let imgBuffer = await new Promise(function (resolve, reject) {
    request.post(codeOptions, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        resolve(body)
      }
      reject(error)
    })
  })

  fs.writeFile(page.replace(/\//g, '-') + '.jpg', imgBuffer, function (err) {
    //生成图片(把buffer写入到图片文件)
    if (err) {
      console.log(err)
    }
  })

  //  上传至云存储
  const upOptions = {
    method: 'POST',
    url: 'https://api.weixin.qq.com/tcb/uploadfile?access_token=' + token,
    body: {
      env: env,//小程序云环境的ID
      path: page.replace(/\//g, '-') + '.jpg',
    },
    json: true,
  }
  let res = await new Promise(function (resolve, reject) {
    request(upOptions, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        resolve(body)
      }
      reject(error)
    })
  })

  ctx.data = res
  await next()
})

# 参考文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

薛定喵君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值