参考小程序官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/qrcode.html
From文档:
提供了三个接口,开发者可挑选适合自己的接口。
首先需要获取access_token
(这里作为测试,直接写在onload函数中):
onLoad: function (options) {
let that = this;
const APP_ID = 'yourAppid';// 小程序appid
const APP_SECRET = 'yourApp_secret';// 小程序app_secret
let access_token = '';
wx.request({
url:"https://api.weixin.qq.com/cgi-bin/token",
data: {
grant_type: 'client_credential',
appid: APP_ID,
secret: APP_SECRET
},
success:function(res){
access_token = res.data.access_token;
console.log(res);
console.log(access_token);
}
})
},
然后用得到的access_token 请求所需要的小程序二维码获取接口,
以下是测试用的全部代码:
// pages/getQrCode/getQrCode.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let that = this;
const APP_ID = 'yourAppid';// 小程序appid
const APP_SECRET = 'yourApp_secret';// 小程序app_secret
let access_token = '';
wx.request({
url:"https://api.weixin.qq.com/cgi-bin/token",
data: {
grant_type: 'client_credential',
appid: APP_ID,
secret: APP_SECRET
},
success:function(res){
access_token = res.data.access_token;
console.log(res);
console.log(access_token);
// 接口A:适用于需要的码数量较少的业务场景 生成的是小程序码
that.getQrCode_A(access_token);
// 接口B:适用于需要的码数量极多的业务场景 生成的是小程序码
that.getQrCode_B(access_token);
// 接口C:适用于需要的码数量较少的业务场景 生成的是小程序二维码
that.getQrCode_C(access_token);
}
})
},
/**
* 接口A:适用于需要的码数量较少的业务场景
* @param access_token
*/
getQrCode_A: function (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,
auto_color: false,// 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调
line_color: {"r":"0","g":"0","b":"0"} // auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
},
success:function(res){
console.log(res);
}
})
},
/**
* 接口B:适用于需要的码数量极多的业务场景
* @param access_token
*/
getQrCode_B: function (access_token) {
wx.request({
url:"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token,
method: 'POST',
data: {
scene: '200',
page: 'pages/index/index', // 必须是已经发布的小程序存在的页面(否则报错)
width: 430,
auto_color: false,// 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调
line_color: {"r":"0","g":"0","b":"0"} // auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
},
success:function(res){
console.log(res);
}
})
},
/**
* 接口C:适用于需要的码数量较少的业务场景 生成小程序二维码
* @param access_token
*/
getQrCode_C: function (access_token) {
wx.request({
url:"https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + access_token,
method: 'POST',
data: {
path: 'pages/index/index',
width: 430,
},
success:function(res){
console.log(res);
}
})
}
});
返回的是二进制(我眼前是一堆乱码如下),需要传到后台转化为图片(这个等研究了后台处理再补充=_=):
需要注意的是: