應用場景:在小程序內展示小程序二維碼,此二維碼可以進入目標小程序的特定頁面或者攜帶參數
一、獲取access_token
如在小程序A內或B內本身要展示B的二維碼,需要使用小程序B的appid與密鑰,通過微信小城程官方接口換取B小程序的access_token, 換取二維碼的時候會用到;
wxml:
<button bindtap='getqrcode'>獲取二維碼</button>
<image class='qrcode' src='data:image/png;base64,{{imgUrls}}'></image>
此處image需要使用base64格式圖片,接口返回來的數據原本爲圖片,但接收數據顯示爲亂碼,因爲默認接收格式responseType爲text,解析圖片會出現錯誤,需要轉換爲base64碼
js:
getqrcode:function(){
let that = this;
let appid = '想要展示二維碼小程序的appid';
let sec = '想要展示二維碼小程序的密鑰';
wx.request({
//換取access_token 接口
url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid + '&secret=' + sec,
header:{
'content-type':'application/json'
},
success:function(res){
console.log(res);
wx:wx.request({
//獲得二維碼數據接口
url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + res.data.access_token,
data: {
'scene': 111,//必填 scene 攜帶參數,可以在onload頁面裏面query裏面解析出來,詳情百度
'page': 'pages/login/login',//必填 具體的小程序頁面,但不能攜帶參數,參數在scene中攜帶
'line_color': { 'r': 30, 'g': 144, 'b': 255 },//小程序二維碼線條顏色
'is_hyaline':true//圖片底色是否爲透明
},
header: {
'content-type':'application/json'
},
method: 'POST',
// dataType: 'json',
responseType: 'arraybuffer',//將原本按文本解析修改爲arraybuffer
success: function(res) {
that.setData({
imgUrls: wx.arrayBufferToBase64(res.data)
})
}
})
}
})
},