业务需求
微信小程序中支持分享给朋友,但是无法直接分享至朋友圈,所以只能通过分享一个小程序码出去,其他人通过扫码进入到指定的页面。
前端实现步骤
-
前端调用服务端的接口,把生成小程序码需要的参数传递过去。(因为前端无法直接调用该接口)。
-
前端把服务端返回的base64图片转换为binary格式存储在本地临时文件中,返回图片的本地路径。(因为canvasdrawer不支持绘制base64的图片)
-
通过调用canvasdrawer的api把小程序码图片和想要添加的元素绘制到画布上。
后端实现步骤
- 服务端通过appid和secret调用微信提供的api获取全局唯一接口调用凭据access_token。
- 服务端通过access_token调用微信提供的api获取小程序码。
- 返回的图片默认为buffer格式,将buffer转为base64格式,返回给客户端。
前端代码
<view class="container">
<image src="{
{shareImage}}" class="share-image"></image>
<canvasdrawer painting="{
{painting}}" class="canvasdrawer" bind:getImage="eventGetImage" />
<view class="btn-wrap">
<button class="btn" bindtap="eventSave">保存到本地</button>
</view>
</view>
// pages/share/index.js
Page({
data: {
painting: {
},
shareImage: "",
goodsUrl: "",
goods: {
},
},
// 获取小程序码
getQrcode: function (id) {
let that = this;
wx
.request(
'http://localhost:8360/api/qrcode/getBase64',
{
goodsId: id,
},
"POST"
)
.then(function (res) {
if (res.errno === 0) {
that.getQrcodeJpg(res.data);
}
});
},
// 小程序码存储本地文件
getQrcodeJpg(code) {
let that = this;
let num = Math.floor(Math.random() * 50);
let promise = new Promise((resolve, reject) => {
// wx.env.USER_DATA_PATH 为 http://usr
const filePath = wx.env.USER_DATA_PATH + "/temp_image"