最新推荐:《Vue3.0抢先学》系列学习教程
扫码已经成为一种常见又方便的进入移动应用的途径,可以把线上线下的用户流量带入你的移动应用中来。微信小程序也提供了扫码进入的功能,可以通过扫描二维码或者微信小程序专有的小程序码,进入到相应的小程序页面。
微信官方提供了3个不同的REST API用于生成带参数的小程序码或者二维码,可在扫码后进入指定的小程序页面,其中接口A和C能生成的图片总数量有限制(10万张),对于那种需要生成大量二维码的使用场景(比如为每个订单生成一个二维码、餐厅的每张餐桌生成一个二维码等)是远远不能满足需求的。而接口B可以解决这个问题,我们这次主要来看一下如何使用这个接口。
总体的思路是:在我们的后端开发一个API,在其中调用微信的二维码接口,调用成功后会得到二维码图片的二进制流,最后将这个二进制流输出到前台。
以下步骤中的后端代码是基于Node.js进行编写,并使用了Koa 2框架。代码仅供参考。
步骤1:获取重要参数access_token
调用获取小程序二维码的REST API需要一个很重要的参数:access_token
,这是用于获取微信公众平台API访问权限的重要参数,做过微信公众号HTML5开发的朋友对其肯定非常熟悉。没接触过的话,可以看一下微信公众平台的文档。
调用微信公众平台的API,已经有很多成熟的开源SDK可以使用,从Github上可以搜到很多不同语言实现的SDK。由于我用的是Node.js开发,所以使用了co-wechat-api。
以下是使用co-wechat-api
来获取access_token
的基本用法:
const WechatAPI = require('co-wechat-api')const wxAppAPI = new WechatAPI('小程序的app id', '小程序的app secret')const token = await wxAppAPI.ensureAccessToken()console.log(token.accessToken)
步骤2:拼接url,发送请求获取二维码图片
const fs = require('fs')const axios = require('axios')// 拼接urlconst url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${token.accessToken}`// 发送POST请求const response = await axios.post(url, { page: '小程序中Page的路径', scene: '自定义参数,格式你自己决定'}, { responseType: 'stream' })// 将请求结果中的二进制流写入到本地文件qrcode.pngresponse.data.pipe(fs.createWriteStream('qrcode.png'))
在上面的代码中,我们将access_token
作为query string参数拼接到url上,然后向这个url发送POST
请求,传递的参数主要是page
和scene
,其中page
参数是扫码后进入的小程序页面路径(比如pages/index/index,并且不能携带参数),而scene
则传入的是我们的自定义参数。
其实经过这一步,你就已经可以在你的磁盘上找到这张小程序码的图片了,用微信扫一下这张图片,就能进入你的小程序页面。
步骤3:将二维码图片输出
虽然我们已经获取到了小程序码图片,但是现在它还只是躺在我们的服务器端。而通常实际情况是,我们需要在小程序页面上去显示这张图片,让用户去保存和分享它。因此,我们需要把这张图片通过我们的API进行输出。以下是基于koa 2的示例代码:
const fs = require('fs')const Router = require('koa-router')const router = new Router()router.get('/wx/common/qrcode', async (ctx) => { const stream = fs.createReadStream(‘qrcode.png’) ctx.body = stream})
步骤4:在小程序中显示
在小程序中显示该图片就非常简单了,直接使用<image>
组件来进行展示:
<image src="https://your-domain.com/wx/common/qrcode" style="width:200px;height:200px"></image>
附录:稍微完备一些的服务端代码
上面4个步骤中给出的示例代码只是为了配合说明各个步骤,代码比较简陋,下面是经过稍微的组织过的代码,供参考:
- 路由部分的代码:
const Router = require('koa-router')const PassThrough = require('stream').PassThrough;const wxapi = require('../services/wxapi')const router = new Router()router.get('/wx/common/qrcode', async (ctx) => { const stream = await wxapi.getWxaCodeUnlimit({ page: 'pages/profile/profile', scene: 'abc123' }) ctx.body = stream.pipe(PassThrough())})
- Service部分的代码:
const fs = require('fs')const path = require('path')const crypto = require('crypto')const bluebird = require('bluebird')const axios = require('axios')const WechatAPI = require('co-wechat-api')const wxAppAPI = new WechatAPI('小程序的app id', '小程序的app secret')function sha1(message) { return crypto.createHash('sha1').update(message, 'utf8').digest('hex')}module.exports = { async getWxaCodeUnlimit({ page, scene }) { // 图片文件名使用page和scene等数据生成Hash // 以避免重复生成内容相同的小程序码 const fileName = sha1(page + scene) const filePath = path.join(__dirname, `../../qrcode/${fileName}.png`) let readable try { // 检测该名字的小程序码图片文件是否已存在 await bluebird.promisify(fs.access)(filePath, fs.constants.R_OK); readable = fs.createReadStream(filePath) } catch (e) { // 小程序码不存在,则创建一张新的 const token = await wxAppAPI.ensureAccessToken() const response = await axios({ method: 'post', url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit', responseType: 'stream', params: { access_token: token.accessToken }, data: { page, scene } }) readable = response.data readable.pipe(fs.createWriteStream(filePath)) } // 返回该小程序码图片的文件流 return readable }}
祝大家开发出更好的小程序!
原著是一个有趣的人,若有侵权,请通知删除
还没有人抢沙发呢~