package com.hx.mp.util; import com.hx.util.OSSUtil; import com.hx.util.SimpleTool; import com.hx.util.StringUtils; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Component; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Date; /** * 微信获取权限基本工具类 * @author ChenJiaHe * @Date 2020-07-14 */ @Component public class MPWeixinBaseUtil { // 类型 private static final String GRANT_TYPE = "client_credential"; /**获取access_token链接*/ private static final String GETACCESS_TOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type="; /**通过code获取小程序信息链接*/ private static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?"; /**发送订阅消息通知链接*/ private static final String SEND_SUBSCRIBE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="; //生成小程序二维码地址(方形) public static final String MAKE_TWOCODE_SQUARE_URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="; //生成小程序二维码地址(圆形) public static final String MAKE_TWOCODE_ROUND_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token={0}"; //生成无限二维码 public static final String URL_UNLIMIT_SQUARE = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}"; ////////////////////////////////////////////////// /** (小程序)通过code换取网页授权access_token/如果是snsapi_base模式的授权,这里就可以拿到openId了 ***/ public static JSONObject getJscode2session(String appid,String secret,String code) { return HttpURLUtil(JSCODE2SESSION_URL+"appid="+appid+"&secret="+secret +"&grant_type=authorization_code&js_code=" + code,null); } /**发送订阅消息通知**/ public static JSONObject sendSubscribeMessage(String data,String accessToken){ return HttpURLUtil(SEND_SUBSCRIBE_MESSAGE+accessToken,data); } /** 获取access_token */ public static JSONObject getAccessToken(String appid,String secret) throws Exception { String access_token; // 通过WX接口获取access_token JSONObject obj = getApplication_Access_tokenForUrl(appid,secret); return obj; } /** 从weixin接口获取Access_token **/ public static JSONObject getApplication_Access_tokenForUrl(String appid,String secret) { return HttpURLUtil(GETACCESS_TOKENURL+GRANT_TYPE +"&appid="+appid +"&secret="+secret,null); } /**生成无限二维码,并上传到OSS*/ public static String createUnlimitQrCode(String at, String scene, String page, int width, boolean autoColor, JSONObject lineColor, boolean isHyaline, String fileName, String keyId, String keySecret, String endPoint, String bucket) { String imgUrl = null; InputStream in = null; HttpURLConnection conn = null; try { //生成发送数据 JSONObject obj = new JSONObject(); obj.put("scene", scene); obj.put("width", width); obj.put("page", page); obj.put("auto_color", autoColor); obj.put("line_color", lineColor); obj.put("is_hyaline", isHyaline); // 创建url资源 URL url = new URL(StringUtils.format(URL_UNLIMIT_SQUARE, at)); // 建立http连接 conn = (HttpURLConnection) url.openConnection(); // 设置允许输出 conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); // 设置传递方式 conn.setRequestMethod("POST"); // 设置维持长连接 conn.setRequestProperty("Connection", "Keep-Alive"); // 设置文件字符集: conn.setRequestProperty("Charset", "UTF-8"); // 设置文件类型: conn.setRequestProperty("contentType", "application/json"); // 开始连接请求 conn.connect(); OutputStream out = conn.getOutputStream(); // 写入请求的字符串 out.write((obj.toString()).getBytes()); out.flush(); out.close(); // 请求返回的状态 if (conn.getResponseCode() == 200) { // 请求返回的数据 in = conn.getInputStream(); imgUrl = OSSUtil.uploadImg(fileName, in, keyId, keySecret, endPoint, bucket); conn.disconnect(); conn = null; } if (in != null) { in.close(); in = null; } if (conn != null) { conn.disconnect(); conn = null; } }catch (Exception e) { e.printStackTrace(); if (in != null) { try { in.close(); }catch (Exception ep) { ep.printStackTrace(); } in = null; } if (conn != null) { conn.disconnect(); conn = null; } } return imgUrl; } /**生成有限二维码,返回临时文 * @param at 微信token * @param page 跳转链接 * @param width 宽度 * @param autoColor 默认false * @param lineColor 默认null * @param isHyaline 默认false * @return */ public static File createLimitedQrCode(String at, String page, int width, boolean autoColor, JSONObject lineColor, boolean isHyaline) { String imgUrl = null; InputStream in = null; HttpURLConnection conn = null; //创建临时文件 File file = null; try { file = File.createTempFile("temp", ".jpg"); //生成发送数据 JSONObject obj = new JSONObject(); obj.put("width", width); obj.put("path", page); obj.put("auto_color", autoColor); obj.put("line_color", lineColor); obj.put("is_hyaline", isHyaline); // 创建url资源 URL url = new URL(StringUtils.format(MAKE_TWOCODE_ROUND_URL, at)); // 建立http连接 conn = (HttpURLConnection) url.openConnection(); // 设置允许输出 conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); // 设置传递方式 conn.setRequestMethod("POST"); // 设置维持长连接 conn.setRequestProperty("Connection", "Keep-Alive"); // 设置文件字符集: conn.setRequestProperty("Charset", "UTF-8"); // 设置文件类型: conn.setRequestProperty("contentType", "application/json"); // 开始连接请求 conn.connect(); OutputStream out = conn.getOutputStream(); // 写入请求的字符串 out.write((obj.toString()).getBytes()); out.flush(); out.close(); // 请求返回的状态 if (conn.getResponseCode() == 200) { // 请求返回的数据 in = conn.getInputStream(); //输入到临时文件 /*OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = in.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); }*/ FileUtils.copyInputStreamToFile(in, file); conn.disconnect(); conn = null; } if (in != null) { in.close(); in = null; } if (conn != null) { conn.disconnect(); conn = null; } }catch (Exception e) { e.printStackTrace(); if (in != null) { try { in.close(); }catch (Exception ep) { ep.printStackTrace(); } in = null; } if (conn != null) { conn.disconnect(); conn = null; } }finally { if(file != null){ file.deleteOnExit(); } } return file; } /**生成无限二维码,返回临时文 * @param at 微信token * @param scene 参数,只能32位,最好不要中文 * @param page 跳转链接 * @param width 宽度 * @param autoColor 默认false * @param lineColor 默认null * @param isHyaline 默认false * @return */ public static File createUnlimitQrCode(String at, String scene, String page, int width, boolean autoColor, JSONObject lineColor, boolean isHyaline) throws IOException { String imgUrl = null; InputStream in = null; HttpURLConnection conn = null; //创建临时文件 File file = File.createTempFile("temp", ".jpg"); try { //生成发送数据 JSONObject obj = new JSONObject(); obj.put("scene", scene); obj.put("width", width); obj.put("page", page); obj.put("auto_color", autoColor); obj.put("line_color", lineColor); obj.put("is_hyaline", isHyaline); // 创建url资源 URL url = new URL(StringUtils.format(URL_UNLIMIT_SQUARE, at)); // 建立http连接 conn = (HttpURLConnection) url.openConnection(); // 设置允许输出 conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); // 设置传递方式 conn.setRequestMethod("POST"); // 设置维持长连接 conn.setRequestProperty("Connection", "Keep-Alive"); // 设置文件字符集: conn.setRequestProperty("Charset", "UTF-8"); // 设置文件类型: conn.setRequestProperty("contentType", "application/json"); // 开始连接请求 conn.connect(); OutputStream out = conn.getOutputStream(); // 写入请求的字符串 out.write((obj.toString()).getBytes()); out.flush(); out.close(); // 请求返回的状态 if (conn.getResponseCode() == 200) { // 请求返回的数据 in = conn.getInputStream(); //输入到临时文件 /*OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = in.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); }*/ FileUtils.copyInputStreamToFile(in, file); conn.disconnect(); conn = null; } if (in != null) { in.close(); in = null; } if (conn != null) { conn.disconnect(); conn = null; } }catch (Exception e) { e.printStackTrace(); if (in != null) { try { in.close(); }catch (Exception ep) { ep.printStackTrace(); } in = null; } if (conn != null) { conn.disconnect(); conn = null; } }finally { file.deleteOnExit(); } return file; } /**生成小程序二维码工具(方形) * path 二维码跳转链接 * width 二维码宽度,默认是430 * saveUrl 保存图片的全路径 * seeUrl 显示图片路径 * appid 小程序配置 * secret 小程序配置 * return 二维码显示图片链接 * @throws Exception * */ public static String twoCodeImgSquare(String at, String path,Integer width,String saveUrl, String seeUrl,String appid,String secret) throws Exception { if(!SimpleTool.checkNotNull(width)) { width = 430; } //生成发送数据 JSONObject obj = new JSONObject(); obj.put("path", path); obj.put("width", width); //二维码图片路径 String codeUrl = ""; codeUrl = HttpURLUtilMakeCodeImg(MAKE_TWOCODE_SQUARE_URL+at,obj,saveUrl,seeUrl); if(SimpleTool.checkNotNull(codeUrl)){ if(!codeUrl.startsWith("/")){ codeUrl = "/"+codeUrl; } } return codeUrl; } public static String twoCodeImgSquare(String at, String path,Integer width, String fileName, String keyId, String keySecret, String endPoint, String bucket) throws Exception { if(!SimpleTool.checkNotNull(width)) { width = 430; } //生成发送数据 JSONObject obj = new JSONObject(); obj.put("path", path); obj.put("width", width); String imgUrl = null; InputStream in = null; HttpURLConnection conn = null; try { // 创建url资源 URL url = new URL(MAKE_TWOCODE_SQUARE_URL + at); // 建立http连接 conn = (HttpURLConnection) url.openConnection(); // 设置允许输出 conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); // 设置传递方式 conn.setRequestMethod("POST"); // 设置维持长连接 conn.setRequestProperty("Connection", "Keep-Alive"); // 设置文件字符集: conn.setRequestProperty("Charset", "UTF-8"); // 设置文件类型: conn.setRequestProperty("contentType", "application/json"); // 开始连接请求 conn.connect(); OutputStream out = conn.getOutputStream(); // 写入请求的字符串 out.write((obj.toString()).getBytes()); out.flush(); out.close(); // 请求返回的状态 if (conn.getResponseCode() == 200) { // 请求返回的数据 in = conn.getInputStream(); imgUrl = OSSUtil.uploadImg(fileName, in, keyId, keySecret, endPoint, bucket); conn.disconnect(); conn = null; } if (in != null) { in.close(); in = null; } if (conn != null) { conn.disconnect(); conn = null; } }catch (Exception e) { e.printStackTrace(); if (in != null) { try { in.close(); }catch (Exception ep) { ep.printStackTrace(); } in = null; } if (conn != null) { conn.disconnect(); conn = null; } } return imgUrl; } /** 生成二维码的图片 返回图片路径 * urlx 执行链接 * objx 数据 * saveUrl 保存图片路径 * seeUrl 显示图片路径 * * **/ public static String HttpURLUtilMakeCodeImg(String urlx,JSONObject objx,String saveUrl,String seeUrl) throws IOException { String realpath = null; // 创建url资源 URL url = new URL(urlx); // 建立http连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置允许输出 conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); // 设置传递方式 conn.setRequestMethod("POST"); // 设置维持长连接 conn.setRequestProperty("Connection", "Keep-Alive"); // 设置文件字符集: conn.setRequestProperty("Charset", "UTF-8"); // 转换为字节数组 // byte[] data = (objx.toString()).getBytes(); // 设置文件长度 // conn.setRequestProperty("Content-Length",String.valueOf(data.length)); // 设置文件类型: conn.setRequestProperty("contentType", "application/json"); // 开始连接请求 conn.connect(); OutputStream out = conn.getOutputStream(); // 写入请求的字符串 out.write((objx.toString()).getBytes()); out.flush(); out.close(); // 请求返回的状态 if (conn.getResponseCode() == 200) { System.out.println("连接成功"); // 请求返回的数据 InputStream in = conn.getInputStream(); ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] temp = new byte[1024]; int rc = 0; while ((rc = in.read(temp, 0, 100)) > 0) { swapStream.write(temp, 0, rc); } byte[] buffer2 = swapStream.toByteArray(); String base64 = Base64.encodeBase64String(buffer2); //生成名称 java.util.Random r=new java.util.Random(); StringBuilder str=new StringBuilder();//定义变长字符串 for(int i=0;i<8;i++){ str.append(r.nextInt(10)); } Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss"); String imgName = sf.format(date); imgName = imgName+str.toString(); //文件保存位置 File saveDir = new File(saveUrl); if(!saveDir.exists()){ saveDir.mkdir(); } File file = new File(saveDir+"/"+imgName+".png"); FileOutputStream fos = new FileOutputStream(file); fos.write(buffer2); if(fos!=null){ fos.close(); } if(in!=null){ in.close(); } realpath = seeUrl+"/"+imgName+".png"; } else { System.out.println("no++"); } return realpath; } /** 请求http协议 获取信息工具 **/ private static JSONObject HttpURLUtil(String url,String data) { HttpURLConnection con = null; URL u; String wxMsgXml; JSONObject obj; try { u = new URL(url); con = (HttpURLConnection) u.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setReadTimeout(5000); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (data != null) { OutputStream os = con.getOutputStream(); os.write(data.getBytes("utf-8")); } if (con.getResponseCode() != 200) throw new RuntimeException("请求url失败"); // 读取返回内容 wxMsgXml = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8); // 判断返回参数是否正确/成功 obj = JSONObject.fromObject(wxMsgXml); // System.out.println("HttpURLUtil:"+wxMsgXml); } catch (Exception e) { e.printStackTrace(); obj = new JSONObject(); try { obj.put("status", 1); obj.put("errMsg", e.getMessage()); } catch (JSONException e1) { e1.printStackTrace(); } } finally { if (con != null) { con.disconnect(); } } return obj; } }