最近涉及到微信小程序分享到朋友圈,不知道微信為什么不直接接口分享,咱也不敢佛,咱也不敢問,只能百度問度娘,看官方文檔,網上的一些分享五花八門,每一個重點的,所以整理了一下到底怎樣生成二維碼分享圖片才是正確的,做了如下總結
說實話踩了很多坑,最大的坑就是把獲取微信小程序二維碼的事情在前端做了,人家明確說了不要在前端做,可是沒好好看官方文檔。
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, width: 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="width: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="width: 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是真的不好畫,調不對格式呀,歡迎討論,謝謝
轉載請表明出處。