返回

用云开发实现快速生成小程序码

前端

随着小程序的广泛应用,不少业务场景下都可能会涉及到小程序码的生成,比如:发放购物优惠券、客户引流、商品溯源、活动报名等。

开发者可以使用云开发构建服务,提供生成小程序码的能力,既可以满足低频生成的需求,也可以满足高频生成的需求。

低频生成小程序码

实现步骤

  1. 在云函数中引入二维码生成库
import "github.com/skip2/go-qrcode"
  1. 在云函数中调用二维码库生成二维码图片
func GenerateQrCode(w http.ResponseWriter, r *http.Request) {
    // path 为要生成二维码的小程序路径,如 "/pages/index/index"
    qrcode.WriteFile(path, qrcode.Medium, 256, "static/qrcode.png")
}
  1. 在客户端页面,通过云函数的 URL 获取二维码图片并显示
wx.request({
  url: "https://service-0681-xxxx.ap-shanghai.app.tcloudbase.com/generate-qrcode",
  success: function(res) {
    // 将二维码图片保存到本地
    wx.downloadFile({
      url: res.data.qrcode_url,
      success: function(res) {
        // 将二维码图片路径传递给前端页面
        wx.navigateTo({
          url: "/pages/qrcode/index?qrcode_path=" + res.tempFilePath
        })
      }
    })
  }
})
  1. 在客户端页面,使用图片组件显示二维码图片
<image src="{{qrcode_path}}"></image>

优点

  • 部署简单,成本低
  • 支持自定义小程序码页面路径
  • 无须开通云开发高级版

缺点

  • 无法生成带参数的小程序码
  • 无法生成永久的小程序码

高频生成小程序码

实现步骤

  1. 开通云开发高级版
  2. 在云函数中调用云开发 API 生成小程序码
func GenerateQrCode(w http.ResponseWriter, r *http.Request) {
    var req struct {
        Scene string `json:"scene"`
        Page  string `json:"page"`
    }
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    qrCode, err := wxacode.GetUnlimited(req.Scene, req.Page, 430)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // 将二维码图片保存到临时文件
    tempFile, err := ioutil.TempFile("", "qrcode")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer os.Remove(tempFile.Name())

    if _, err := tempFile.Write(qrCode); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // 将临时文件的路径返回给前端
    json.NewEncoder(w).Encode(struct {
        QrcodeURL string `json:"qrcode_url"`
    }{
        QrcodeURL: tempFile.Name(),
    })
}
  1. 在客户端页面,通过云函数的 URL 获取二维码图片并显示
wx.request({
  url: "https://service-0681-xxxx.ap-shanghai.app.tcloudbase.com/generate-qrcode",
  method: "POST",
  data: {
    scene: "123",
    page: "/pages/index/index"
  },
  success: function(res) {
    // 将二维码图片保存到本地
    wx.downloadFile({
      url: res.data.qrcode_url,
      success: function(res) {
        // 将二维码图片路径传递给前端页面
        wx.navigateTo({
          url: "/pages/qrcode/index?qrcode_path=" + res.tempFilePath
        })
      }
    })
  }
})
  1. 在客户端页面,使用图片组件显示二维码图片
<image src="{{qrcode_path}}"></image>

优点

  • 可以生成带参数的小程序码
  • 可以生成永久的小程序码

缺点

  • 需要开通云开发高级版
  • 部署较为复杂
  • 成本较高

结语

开发者可以根据自己的需求选择低频生成小程序码还是高频生成小程序码。低频生成小程序码适合对小程序码数量要求不高、对成本敏感的场景;高频生成小程序码适合对小程序码数量要求高、需要生成带参数小程序码或永久小程序码的场景。