//获取小程序码
wx.scanCode(Object object) | 微信开放文档
/**
* 获取小程序码
* @param appId 小程序ID
* @param secret 小程序秘钥
* scene = "id/"+id+"*userIdId/"+userId;
* 这里自定义了scene的参数格式,以 / 代替 = ,以 * 代替 & 。
* 因为如果用正常的格式(例如:id=1&userId=2)会导致参数识别一部分,
* 因为小程序在识别二维码页面参数时,拿到的参数列表是这样的scene=id=1&userId=2,
* 这样就会导致只能识别id,id后的等号后面的参数全都无效了。
* 所以这里用特殊字符代替常规字符,然后获取之后再用js去解析,从而拿到参数列表。
* @param path 路径
* @param scene 参数
* @return
*/
public static String gainMiniProgramCode(String appId,String secret,String path,String scene) throws IOException {
//access_token 根据appid和secret去获取
String accessToken = null;
if(StringUtils.isNotBlank(accessToken)){
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
Map<String,Object> data = new HashMap<>();
data.put("scene",scene);
data.put("path",path);
data.put("width",430);
data.put("auto_color",false);
data.put("line_color",null);
data.put("is_hyaline",false);
InputStream inputStream = tempHttpClientUtil(url,data);
if(inputStream != null){
//图片文件名称
String fileName = new SimpleDateFormat("yyyy/MM/dd").format(Calendar.getInstance().getTime()) + UUIDUtil.getUUID().substring(8)+".png";
//图片文件存放地址
String filePath = "D:\";
saveToImgByInputStream(inputStream,filePath,fileName.replaceAll("/", ""));
return fileName.replaceAll("/", "");
}
}
return null;
}
public static InputStream tempHttpClientUtil(String url,Map<String,Object> data){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(data);
StringEntity entity = null;
try {
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
return inputStream;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 保存图片
* @param instreams
* @param imgPath
* @param imgName
* @return
*/
public static int saveToImgByInputStream(InputStream instreams, String imgPath, String imgName){
int stateInt = 1;
if(instreams != null){
try {
File file=new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等
FileOutputStream fos=new FileOutputStream(file);
byte[] b = new byte[1024];
int nRead = 0;
while ((nRead = instreams.read(b)) != -1) {
fos.write(b, 0, nRead);
}
fos.flush();
fos.close();
} catch (Exception e) {
stateInt = 0;
e.printStackTrace();
} finally {
}
}
return stateInt;
}
创作不易,感谢相赠。