前言

需求:用户通过扫描小程序码,直接跳转到小程序的登陆页,并自动填充推荐码


一、自测版本

用于前端自己测试如何生成小程序码

页面示例

  1. <!-- 以图片的形式展示 -->
  2. <image :src="maskData"></image>
  1. onLoad(options) {
  2. console.log('需要推荐码',options)//打印出来是 {scene: "code%3D2QQ"}
  3. const scene = options.scene ? decodeURIComponent(options.scene) : ''
  4. console.log('编译出来的scene',scene) //打印出来是 code=3D2QQ
  5. this.code = scene.split('=')[1]//打印出来是 3D2QQ
  6. console.log('编译出来的推荐码',this.code)
  7. },

方法示例

  1. getData(e) {
  2. //获取accessToken
  3. let that = this;
  4. const APP_ID = 'xxx'; // 小程序appid
  5. const APP_SECRET = 'xxxxx'; // 小程序app_secret
  6. let access_token = '';
  7. uni.request({
  8. url: "https://api.weixin.qq.com/cgi-bin/token", //固定链接,不用改
  9. data: {
  10. grant_type: 'client_credential',
  11. appid: APP_ID,
  12. secret: APP_SECRET
  13. },
  14. success: function(res) {
  15. console.log('获取accessToken', res)
  16. access_token = res.data.access_token;
  17. // 接口B:适用于需要的码数量极多的业务场景 生成的是小程序码
  18. that.getQrCode(access_token);
  19. }
  20. })
  21. },
  22. //获取二维码
  23. getQrCode(access_token) {
  24. var that = this;
  25. uni.request({
  26. url: "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + access_token,//固定链接,不用改
  27. method: 'POST',
  28. responseType: 'arraybuffer', //设置响应类型
  29. data: {
  30. path: 'pages/public/login?code=' + that.code, // 必须是已经发布的小程序存在的页面(否则报错)
  31. width: 298,
  32. auto_color: false, // 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调
  33. line_color: {
  34. "r": "0",
  35. "g": "0",
  36. "b": "0"
  37. } // auto_color 为 false 时生效,使用 rgb 设置颜色
  38. },
  39. success: function(res) {
  40. console.log('获取二维码', res)
  41. that.maskData = "data:image/PNG;BASE64," + uni.arrayBufferToBase64(res.data);//以图片的形式展示
  42. }
  43. })
  44. }

二、线上版本

原来以为很难的,压力都在前端,等做完了,测试体验版的时候,发现api.weixin.qq.com域名没加进去,结果官方跟我说,不能加这个域名,原因是前端不能直接用上面的方法自己去生成小程序码,必须要通过后台服务器转一下
小程序生成小程序码 - 图1

  1. // 给了个token,后端自己去实现自测版本中的操作-生成小程序码,返回图片地址,前端直接展示图片就好了,666
  2. getData(e) {
  3. this.$api
  4. .qrcode({
  5. token: this.token
  6. })
  7. .then(res => {
  8. console.log('我的推荐码', res)
  9. this.maskData = res
  10. })
  11. .catch(err => {
  12. this.$api.msg(err)
  13. });

三、测试

截取生成小程序码的图片,用微信开发者工具的“通过二维码编译”扫码测试能不能拿到参数,并填充

小程序生成小程序码 - 图2


总结

事情其实很简单,没必要想的太复杂