原生微信小程序获取生成小程序码并渲染页面上
应用场景:分享朋友/朋友圈时生成海报
- 效果图:
第一步,data中定义一个接收图片路径的空数据
/**
* 页面的初始数据
*/
data: {
//二维码图片
qrCodeImg: null,
},
第二步,选择一个官方接口生成base64
- 老规矩,传送门:微信文档中生成小程序码接口
- 获取小程序码的话,如果数量不多,就用get那个;如果多的话,就用getUnlimited;看下面详细获取方法
- 文档中获取小程序码前,需要先获取到access_token,接口调用凭证
- 先获取到access_token,拼接到路径上,才能调用上面图片生成小程序码的接口
- 找到appid和secret(密钥):微信公众平台->设置->开发设置中
-拿到之后填到请求路径里,是固定的,不用担心
//提前定义
let access_token = null;
wx.request({
url:
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=..............&secret=...........",
method: "GET",
success: function (res) {
//这里写拿到access_token后的操作
access_token = res.data.access_token;
}
})
- 拿到access_token后,就可以请求小程序码的base64,请求地址:
POST https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN
- 只有上面框住的参数是必填的,其他可选填,下面代码详情
wx.request({
url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${access_token}`,
method: "POST",
data: {
"path":"pages/index/index",
"width":430
},
//响应的数据类型,ArrayBuffer 对象
responseType: 'arraybuffer',
success: function (res) {
_this.setData({
//给data中赋值
qrCodeImg:wx.arrayBufferToBase64(res.data)
})
if(_this.data.qrCodeImg !=null){
//用于加载函数
wx.hideLoading()
}
},
});
最后放上完整的代码
JS
/**
* 页面的初始数据
*/
data: {
//二维码图片
qrCodeImg: null,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.showLoading({
title: '加载中',
})
let access_token = null;
let _this = this;
wx.request({
url:
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=..............&secret=...........",
method: "GET",
success: function (res) {
access_token = res.data.access_token;
wx.request({
url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${access_token}`,
method: "POST",
data: {
"path":"pages/index/index",
"width":430
},
responseType: 'arraybuffer',
success: function (res) {
_this.setData({
qrCodeImg:wx.arrayBufferToBase64(res.data)
})
if(_this.data.qrCodeImg !=null){
wx.hideLoading()
}
},
});
},
});
},
WXML:
注意:要在src前加data:image/png;base64,
,代表用base64
<image
wx:if="{{qrCodeImg!= null}}"
src="data:image/png;base64,{{qrCodeImg}}"
mode='widthFix'
/>
到这就可以用了哦,学到的小伙伴感谢三连~
更多推荐:wantLG的《原生微信小程序解析富文本编辑器(TinyMCE)html代码》
- 作者:wantLG
- 本文源自:wantLG的《普歌-码上鸿鹄:原生微信小程序获取生成小程序码并渲染页面上》
- 本文版权归作者和CSDN共有,欢迎转载,且在文章页面明显位置给出原文链接,未经作者同意必须保留此段声明,否则保留追究法律责任的权利。