微信小程序生成二维码方式
生而为人 谁不付出 谁不努力
最近在小程序生成海报的时候 需要生成一个二维码放在海报上,让用户直接分享
第一种方式:前端直接生成base64的一个二维码图片
qrcode_img:function(){
let that = this;
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/token',
data: {
grant_type: 'client_credential',
appid: '你的小程序APPID', //不能缺少
secret: '你的小程序秘钥' //不能缺少
},
success: function (res) {
wx.request({
url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + res.data.access_token,
data: {
"path": "pages/index/index", //默认跳转到主页:pages/index/index,可指定
"width": 200,
"scene": "type=0&evaId=" + that.data.id,
},
responseType: 'arraybuffer', // 这行很重要,转为二进制数组
header: {
'content-type': 'application/json;charset=utf-8'
},
method: 'POST',
success(res) {
//转为base64
let bin64 = wx.arrayBufferToBase64(res.data);
that.setData({ //base 64设置到页面上
qrcode_image: "data:image/png;base64," + bin64
});
}
})
}
})
}
第二种方式:后台生成二维码图片
public static Map doWXPost(String urls, JSONObject jsonParam) {
String msg ="";
Map<String,Object> map = new HashMap<String,Object>();
try
{
URL url = new URL(urls);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
printWriter.write(jsonParam.toString());
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
String path =Globals.IMAGE_URL+"/wechat/qrcoe/"; //图片存放地址
File imgPath = new File(path);
if(!imgPath.exists()){
imgPath.mkdirs();
}
String fileName = DateUtils.dateToString(new Date(), "yyyyMMddHHmmss")+".png"; //图片名称
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
OutputStream os = new FileOutputStream(new File(Globals.IMAGE_URL+"/wechat/qrcoe/"+fileName));
int len;
byte[] arr = new byte[1024];
while ((len = bis.read(arr)) != -1)
{
os.write(arr, 0, len);
os.flush();
}
os.close();
msg = Globals.IMAGE_HOST+"/wechat/qrcoe/"+fileName;
map.put("imageUrl",msg);
}
catch (Exception e){
e.printStackTrace();
}
return map;
}