获取微信小程序二维码
参考文档:微信小程序官方文档
1.代码实现如下:
<template>
<view>
<button open-type="text" @click="huoqu">点击生成小程序二维码</button>
<view class="cls" style="width: 500rpx;height: 500rpx;margin:0 auto;">
<image :src="src" mode="" style="width: 100%;
height: 100%;"></image>
</view>
</view>
</template>
<script>
export default {
data() {
return {
src:""
}
},
methods: {
huoqu() {
uni.request({
url: "https://api.weixin.qq.com/cgi-bin/token",
method: "get",
dataType: "json",
data: {
grant_type: "client_credential",
appid: "",//填写自己小程序的appid
secret: "",//填写该appid对应的秘钥
},
success: (res) => {
this.erweim(res.data.access_token)
},
fail: (err) => {
uni.showModal({
content:"获取‘token’凭证错误!"
})
}
})
},
// 生成二维码
erweim(access_token) {
wx.request({
url: "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token+"",
method: "POST",
dataType: "json",
responseType: 'arraybuffer', //设置响应类型
data: {
"scene": "a=1"
},
success: (res) => {
this.src = "data:image/PNG;BASE64," + uni.arrayBufferToBase64(res.data);
},
fail: (err) => {
uni.showModal({
content:"二维码获取错误"
})
}
})
}
}
}
</script>
<style>
</style>
2.结果截图:
3.注意:
(1)在获取二维码成功后得到的是一个编码,
解码过程:
在解码之前要设置请求中的相应类型:responseType: ‘arraybuffer’,不然解码不会成功,设置好之后就将得到的二维码编码解码:
this.src = "data:image/PNG;BASE64," + uni.arrayBufferToBase64(res.data);
//其中res.data是返回的二维码编码
(2)认真读官方文档,有些数据形式与平常写代码的习惯不一样