微信官网提供生成小程序码生成方式共有三种,详情链接:https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html
A和C接口不用说了,加起来限制10万条。这里主要说下B接口。文档给出的内容并不详细,笔者也是废了好大功夫才研究成功。
附上java代码和小程序端代码:
private static String WX_B_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN"; //不限次数 scene长度为32个字符 /** * B接口生成小程序码 * @param access_token * @param page * @param scene */ public String createBCode(String access_token,String page,String scene){ String url = WX_B_CODE_URL.replace("ACCESS_TOKEN", access_token); Map<String,Object> param = new HashMap<>(); param.put("page", page); param.put("scene", scene); param.put("width", "100"); param.put("auto_color", false); Map<String,Object> line_color = new HashMap<>(); line_color.put("r", 0); line_color.put("g", 0); line_color.put("b", 0); param.put("line_color", line_color); JSONObject json = JSONObject.fromObject(param); try { String imageUrl = httpPostWithJSON2(url, json.toString(), "xxx.png"); return imageUrl; } catch (Exception e) { e.printStackTrace(); } return null; } //返回图片地址 public String httpPostWithJSON2(String url, String json,String imagePath) throws Exception { String result = null; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); StringEntity se = new StringEntity(json); se.setContentType("application/json"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8")); httpPost.setEntity(se); HttpResponse response = httpClient.execute(httpPost); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { InputStream instreams = resEntity.getContent(); //上传至资源服务器生成url ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bs = new byte[1024];//缓冲数组 int len = -1; while ((len = instreams.read(bs)) != -1) { byteArrayOutputStream.write(bs, 0, len); } byte b[] = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); instreams.close(); //将byte字节数组上传至资源服务器返回图片地址 // ...... } } httpPost.abort(); return result; }
上面代码得到图片地址之后。小程序端也要做处理。
function getOptions(options){
// options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
var scene = decodeURIComponent(options.scene);
// console.log(scene);
var obj = {};
for (
var i =
0; i < scene.split(
'*').length;i++){
var arr = scene.split(
'*')[i].split(
'/');
obj[arr[
0]] = arr[
1];
}
return obj
}
对了,后端入参要这样写:
String page = "pages/service/freight-code/freight-code";
String scene = "id/"+id+"*userIdId/"+userId;
这里自定义了scene的参数格式,以 / 代替 = ,以 * 代替 & 。
因为如果用正常的格式(例如:id=1&userId=2)会导致参数识别一部分,因为小程序在识别二维码页面参数时,拿到的参数列表是这样的scene=id=1&userId=2,这样就会导致只能识别id,id后的等号后面的参数全都无效了。所以这里用特殊字符代替常规字符,然后获取之后再用js去解析,从而拿到参数列表。