小程序里经常会出现分销这个功能。而绑定用户之间的关系一般都是通过分享自己的小程序码,别人扫后,绑定之间的关系。 记录下自己去实现生成小程序的过程。
首先去查看微信的文档,找到对应的接口。
附上链接
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
可以看到这个接口十分满足我们的需求。
看需要传的参数,access_token接口调用凭证。这里可以我是后台自己去请求获取了一下,好像前台传给我们也可以,access_token在获取微信用户信息的时候有个坑,这里就先不讲了。scene参数就是我们要传递的参数,这里可以和前台商量好,传什么格式的,比如json字符串啊,逗号分隔啊,什么的,达到传多个参数的目的。
这里这个接口的返回值是buffer,我是通过先将这个文件保存到本地,然后上传到七牛云,获取到网路访问路径,然后返回给前端。这里感觉我操作有点多余,保存到本地的时候,在上线后可以直接获取一个网路访问路径,完全不用上传到七牛云,不过如果为了节省空间,可以把本地的那张图片删掉。
附上代码
StringBuffer url = new StringBuffer();
url.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=");
url.append(SmallEnum.getAppId(SMALLCODE));// 这里填自己的appid
url.append("&secret=");
url.append(SmallEnum.getSecret(SMALLCODE));
String rs = HttpClientUtil.doGet(url.toString());
JSONObject jsonObject = JSONObject.parseObject(rs);
log.info(jsonObject.get("access_token").toString());
StringBuffer url2 = new StringBuffer();
url2.append("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=");
url2.append(jsonObject.get("access_token").toString());
// 获取access_token
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url2.toString());
Map<String,Object> map = new HashMap<>();
map.put("scene",user.getId()); // 添加传递的参数
// map.put("page","pages/user"); 控制跳转的页面
httpPost.setEntity(new StringEntity(JSONObject.toJSONString(map), ContentType.create("application/json", "utf-8")));
HttpResponse execute = httpClient.execute(httpPost);
HttpEntity entity = execute.getEntity();
InputStream inputStream = entity.getContent();
FileOutputStream outputStream = null;
try{
File file = new File(smallPath+user.getOpenId()+".png");
if(!file.exists()){
file.createNewFile();
}
outputStream = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} catch (Exception e){
log.info("获取二维码异常={0}",e);
} finally {
try{
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
} catch (Exception e){
log.info("流关闭异常={0}",e);
}
}
String filename = UUID.randomUUID().toString().replaceAll("-","") + user.getOpenId()+".png";
File file1 = new File(smallPath+user.getOpenId()+".png");
QiNiuUtil qiNiuUtil = new QiNiuUtil();
Map<String, Object> stringObjectMap = qiNiuUtil.uploadImg(file1,filename); // 这里是自己写的七牛云上传方法
String fileName = (String)stringObjectMap.get("fileName");
user.setGeneralizeCode(fileName);
userMapper.update(user);
return stringObjectMap;