zoukankan      html  css  js  c++  java
  • golang-vue实现微信小程序分享到朋友圈

    最近涉及到微信小程序分享到朋友圈,不知道微信为什么不直接接口分享,咱也不敢佛,咱也不敢问,只能百度问度娘,看官方文档,网上的一些分享五花八门,每一个重点的,所以整理了一下到底怎样生成二维码分享图片才是正确的,做了如下总结

    说实话踩了很多坑,最大的坑就是把获取微信小程序二维码的事情在前端做了,人家明确说了不要在前端做,可是没好好看官方文档。

    1,获取带参数二维码

    2.将二维码传到前端

    3 将二维码及其他信息画到canvas上

    4 保存到相册

    5 开开心心分享朋友圈

    一步一步来

    1,获取带参二维码

        微信提供了三个接口

        链接如下:

         https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html

      一定要好好看文档,这个接口是后台调用的,后台,后台,后台,重要的事情说三遍

      上服务器代码(注意:access_token是有过期时间的。获取时要注意哦)

    func getWXcode(id int64, accessToken string) []byte {
        path := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken
        client := &http.Client{}
        params := `{"scene":"calendarId=` + strconv.FormatInt(id, 10) + `", "page": "pages/ClassSchedule"}`
        reqBody := bytes.NewBuffer([]byte(params))
        request, _ := http.NewRequest("POST", path, reqBody)
        request.Header.Set("Content-type", "application/json")
        response, _ := client.Do(request)
        if response.StatusCode == 200 {
            body, err := ioutil.ReadAll(response.Body)
            if err != nil {
                log.Logger.Debug("fail to get QRCode", zap.Error(err))
            }
            return body
        }
        return nil
    }

    注意返回的是图片的字节,利用gin框架返回图片

    2.将二维码传到前端

    func (api *ScheduleAPI) WxCode(c *gin.Context) {
        id, err := api.ValidateInt64Id(c)
        if err != nil {
            api.BadRequest(c)
    
        }
        accessToken, err := RequestToken(AppId, AppSecret)
        if err != nil {
            api.BadRequest(c)
            return
        }
        c.Writer.Header().Set("Content-Type", "image/png")
        _, err = c.Writer.Write(getWXcode(id, accessToken))
    
        if err != nil {
            log.Logger.Debug("fail to write QRCode", zap.Error(err))
        }
    }

    后台基本就是这个样子的了,接下来就是前端如何处理,前端获取图片后会保存到临时目录,这个看文档应该就清楚了

    3 将二维码及其他信息画到canvas上

    shareImage () {
            console.log('that.access_token', this.access_token)
            this.sharePop = false
            var that = this
            wx.showLoading({
              title: '图片生成中...'
            })
            wx.downloadFile({
              url:
                'https://后台获取图片你地址/' + this.calendarId + '/code',
              success: function (res) {
                wx.downloadFile({
                  url: that.user.avatarId,
                  success: function (res3) {
                    const ctx = wx.createCanvasContext('shareCanvas')
                    ctx.setFontSize(50)
                    ctx.drawImage(res3.tempFilePath, 250, 20, 200, 200)
                    ctx.fillText(that.user.nickname, 250, 300, 100)
                    ctx.fillText('分享', 400, 300, 100)
                    ctx.fillText(that.calendar.name, 250, 400, 500)
                    ctx.drawImage(res.tempFilePath, 150, 450, 500, 600)
                    ctx.fillText('长按识别小程序,查看课程详细', 150, 1150, 500)
    
                    ctx.stroke()
                    ctx.draw()
                    // loading
                    setTimeout(function () {
                      wx.canvasToTempFilePath({
                        x: 0,
                        y: 0,
                         800,
                        height: 1200,
                        destWidth: 480,
                        destHeight: 550,
                        canvasId: 'shareCanvas',
                        fileType: 'jpg',
                        success: function (res2) {
                          that.imageurl = res2.tempFilePath
                          wx.hideLoading()
                          that.canvasDialog = true
                        },
                        fail: function (err) {
                          console.log('errr111', err)
                          console.log('生成失败......')
                          wx.hideLoading()
                        }
                      })
                    }, 2000)
                  },
                  fail: function (err) {
                    console.log('1111', err)
                  }
                })
              },
              fail: function (err) {
                console.log(err)
              }
            })
          },

    仔细瞧你会发现有两个wx.downloadFile解释一下,一个是我们生成的二维码,一个是用户信息的头像,这个canvas 画完之后就是要显示一下了,就是个图片显示一下好了

    4 保存到相册

    div.shareimage
          canvas(canvas-id="shareCanvas",style="800px;height:1200px;")
        van-dialog.dialogPop(use-slot='', :show='canvasDialog', show-cancel-button='', @cancel='onClose("canvasDialog")' @confirm='saveImage' cancel-button-text="取消" confirm-button-text="保存到相册" )
          .df-col-ac.py-20p
            image(:src="imageurl" style=" 200px; height: 300px")
        van-toast#van-toast

    本人用的pug格式的html,看不明白的下次讲讲开发效率的问题

    保存代码如下:

          saveImage () {
            // debugger
            var that = this
            that.canvasDialog = false
            wx.saveImageToPhotosAlbum({
              filePath: that.imageurl,
              success (res) {
                wx.showModal({
                  content: '图片已保存到相册',
                  showCancel: false,
                  confirmText: '好的',
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户确定了')
                    }
                  }
                })
              }
            })
          },

    最后一步就去分享吧

    获取sence的传递的值

    onLoad (options) {
      if (options.scene) {
        let scene2 = decodeURIComponent(options.scene)
        //按照传递的值进行拆分。例如
        var str = scene2.split('=')
        shopId = str[1]
      }
    }

    总结:

    canvas是真的不好画,调不对格式呀,欢迎讨论,谢谢

    转载请表明出处。

     

  • 相关阅读:
    BootstrapValidator 解决多属性被同时校验问题《转》
    SSRS 浮动表头设置
    ToString(string format)输出格式简述
    配置AutoMapper映射规则《转》
    IE浏览器上传图片预览兼容(IE 7 8 9 10 11)
    SQL : IN 和 Exists 的区别
    BitArray简单例子
    Rx.net 例子——(1)基础
    C# Pinvoke判断是UEFI模式还是BIOS模式
    wpf Route Event Code Snippet
  • 原文地址:https://www.cnblogs.com/tsxylhs/p/11397470.html
Copyright © 2011-2022 走看看