E1ED922C1E9526DD63272D7EC5C6CB77
2020-09-23 5c59454c8a12b1a19846c23c99cff612db037e4f
提交 | 用户 | age
5c5945 1 package com.hx.mp.util;
E 2
3 import com.hx.util.OSSUtil;
4 import com.hx.util.SimpleTool;
5 import com.hx.util.StringUtils;
6 import net.sf.json.JSONException;
7 import net.sf.json.JSONObject;
8 import org.apache.commons.codec.binary.Base64;
9 import org.apache.commons.io.IOUtils;
10 import org.springframework.stereotype.Component;
11
12 import java.io.*;
13 import java.net.HttpURLConnection;
14 import java.net.URL;
15 import java.nio.charset.StandardCharsets;
16 import java.text.SimpleDateFormat;
17 import java.util.Date;
18
19 /**
20  * 微信获取权限基本工具类
21  * @author ChenJiaHe
22  * @Date 2020-07-14
23  */
24 @Component
25 public class MPWeixinBaseUtil {
26
27     // 类型
28     private static final String GRANT_TYPE = "client_credential";
29
30     /**获取access_token链接*/
31     private static final String GETACCESS_TOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=";
32     /**通过code获取小程序信息链接*/
33     private static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?";
34     /**发送订阅消息通知链接*/
35     private static final String SEND_SUBSCRIBE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";
36     //生成小程序二维码地址(方形)
37     public static final String MAKE_TWOCODE_SQUARE_URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
38     //生成小程序二维码地址(圆形)
39     public static final String MAKE_TWOCODE_ROUND_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";
40     //生成无限二维码
41     public static final String URL_UNLIMIT_SQUARE = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}";
42     //////////////////////////////////////////////////
43
44     /** (小程序)通过code换取网页授权access_token/如果是snsapi_base模式的授权,这里就可以拿到openId了 ***/
45     public static JSONObject getJscode2session(String appid,String secret,String code) {
46
47         return HttpURLUtil(JSCODE2SESSION_URL+"appid="+appid+"&secret="+secret
48                 +"&grant_type=authorization_code&js_code=" + code,null);
49     }
50
51     /**发送订阅消息通知**/
52     public static JSONObject sendSubscribeMessage(String data,String accessToken){
53         return HttpURLUtil(SEND_SUBSCRIBE_MESSAGE+accessToken,data);
54     }
55
56     /** 获取access_token */
57     public static JSONObject getAccessToken(String appid,String secret) throws Exception {
58         String access_token;
59         // 通过WX接口获取access_token
60         JSONObject obj = getApplication_Access_tokenForUrl(appid,secret);
61         return obj;
62     }
63
64     /** 从weixin接口获取Access_token **/
65     public static JSONObject getApplication_Access_tokenForUrl(String appid,String secret) {
66         return HttpURLUtil(GETACCESS_TOKENURL+GRANT_TYPE +"&appid="+appid +"&secret="+secret,null);
67     }
68
69     /**生成无限二维码,并上传到OSS*/
70     public static String createUnlimitQrCode(String at, String scene, String page, int width, boolean autoColor,
71                                              JSONObject lineColor, boolean isHyaline, String fileName, String keyId,
72                                              String keySecret, String endPoint, String bucket)
73     {
74         String imgUrl = null;
75         InputStream in = null;
76         HttpURLConnection conn = null;
77
78         try {
79             //生成发送数据
80             JSONObject obj = new JSONObject();
81             obj.put("scene", scene);
82             obj.put("width", width);
83             obj.put("page", page);
84             obj.put("auto_color", autoColor);
85             obj.put("line_color", lineColor);
86             obj.put("is_hyaline", isHyaline);
87
88             // 创建url资源
89             URL url = new URL(StringUtils.format(URL_UNLIMIT_SQUARE, at));
90             // 建立http连接
91             conn = (HttpURLConnection) url.openConnection();
92             // 设置允许输出
93             conn.setDoOutput(true);
94             conn.setDoInput(true);
95             // 设置不用缓存
96             conn.setUseCaches(false);
97             // 设置传递方式
98             conn.setRequestMethod("POST");
99             // 设置维持长连接
100             conn.setRequestProperty("Connection", "Keep-Alive");
101             // 设置文件字符集:
102             conn.setRequestProperty("Charset", "UTF-8");
103             // 设置文件类型:
104             conn.setRequestProperty("contentType", "application/json");
105             // 开始连接请求
106             conn.connect();
107             OutputStream out = conn.getOutputStream();
108             // 写入请求的字符串
109             out.write((obj.toString()).getBytes());
110             out.flush();
111             out.close();
112
113             // 请求返回的状态
114             if (conn.getResponseCode() == 200) {
115                 // 请求返回的数据
116                 in = conn.getInputStream();
117                 imgUrl = OSSUtil.uploadImg(fileName, in, keyId, keySecret, endPoint, bucket);
118                 conn.disconnect();
119                 conn = null;
120             }
121
122             if (in != null) {
123                 in.close();
124                 in = null;
125             }
126
127             if (conn != null) {
128                 conn.disconnect();
129                 conn = null;
130             }
131         }catch (Exception e)
132         {
133             e.printStackTrace();
134
135             if (in != null) {
136                 try {
137                     in.close();
138                 }catch (Exception ep)
139                 {
140                     ep.printStackTrace();
141                 }
142                 in = null;
143             }
144
145             if (conn != null) {
146                 conn.disconnect();
147                 conn = null;
148             }
149         }
150
151         return imgUrl;
152     }
153
154     /**生成小程序二维码工具(方形)
155      * path 二维码跳转链接
156      * width 二维码宽度,默认是430
157      * saveUrl 保存图片的全路径
158      * seeUrl 显示图片路径
159      * appid 小程序配置
160      * secret 小程序配置
161      * return 二维码显示图片链接
162      * @throws Exception
163      * */
164     public static String twoCodeImgSquare(String at, String path,Integer width,String saveUrl,
165                                           String seeUrl,String appid,String secret) throws Exception {
166
167         if(!SimpleTool.checkNotNull(width)) {
168             width = 430;
169         }
170         //生成发送数据
171         JSONObject obj = new JSONObject();
172         obj.put("path", path);
173         obj.put("width", width);
174
175         //二维码图片路径
176         String codeUrl = "";
177         codeUrl = HttpURLUtilMakeCodeImg(MAKE_TWOCODE_SQUARE_URL+at,obj,saveUrl,seeUrl);
178         if(SimpleTool.checkNotNull(codeUrl)){
179             if(!codeUrl.startsWith("/")){
180                 codeUrl = "/"+codeUrl;
181             }
182         }
183         return codeUrl;
184     }
185
186     public static String twoCodeImgSquare(String at, String path,Integer width, String fileName, String keyId,
187                                           String keySecret, String endPoint, String bucket) throws Exception {
188
189         if(!SimpleTool.checkNotNull(width)) {
190             width = 430;
191         }
192         //生成发送数据
193         JSONObject obj = new JSONObject();
194         obj.put("path", path);
195         obj.put("width", width);
196
197         String imgUrl = null;
198         InputStream in = null;
199         HttpURLConnection conn = null;
200
201         try {
202
203             // 创建url资源
204             URL url = new URL(MAKE_TWOCODE_SQUARE_URL + at);
205             // 建立http连接
206             conn = (HttpURLConnection) url.openConnection();
207             // 设置允许输出
208             conn.setDoOutput(true);
209             conn.setDoInput(true);
210             // 设置不用缓存
211             conn.setUseCaches(false);
212             // 设置传递方式
213             conn.setRequestMethod("POST");
214             // 设置维持长连接
215             conn.setRequestProperty("Connection", "Keep-Alive");
216             // 设置文件字符集:
217             conn.setRequestProperty("Charset", "UTF-8");
218             // 设置文件类型:
219             conn.setRequestProperty("contentType", "application/json");
220             // 开始连接请求
221             conn.connect();
222             OutputStream out = conn.getOutputStream();
223             // 写入请求的字符串
224             out.write((obj.toString()).getBytes());
225             out.flush();
226             out.close();
227
228             // 请求返回的状态
229             if (conn.getResponseCode() == 200) {
230                 // 请求返回的数据
231                 in = conn.getInputStream();
232                 imgUrl = OSSUtil.uploadImg(fileName, in, keyId, keySecret, endPoint, bucket);
233                 conn.disconnect();
234                 conn = null;
235             }
236
237             if (in != null) {
238                 in.close();
239                 in = null;
240             }
241
242             if (conn != null) {
243                 conn.disconnect();
244                 conn = null;
245             }
246         }catch (Exception e)
247         {
248             e.printStackTrace();
249
250             if (in != null) {
251                 try {
252                     in.close();
253                 }catch (Exception ep)
254                 {
255                     ep.printStackTrace();
256                 }
257                 in = null;
258             }
259
260             if (conn != null) {
261                 conn.disconnect();
262                 conn = null;
263             }
264         }
265
266         return imgUrl;
267
268
269     }
270
271     /** 生成二维码的图片 返回图片路径
272      * urlx 执行链接
273      * objx 数据
274      * saveUrl 保存图片路径
275      * seeUrl 显示图片路径
276      *
277      *  **/
278     public static String HttpURLUtilMakeCodeImg(String urlx,JSONObject objx,String saveUrl,String seeUrl) throws IOException {
279         String realpath = null;
280
281         // 创建url资源
282         URL url = new URL(urlx);
283         // 建立http连接
284         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
285         // 设置允许输出
286         conn.setDoOutput(true);
287
288         conn.setDoInput(true);
289
290         // 设置不用缓存
291         conn.setUseCaches(false);
292         // 设置传递方式
293         conn.setRequestMethod("POST");
294         // 设置维持长连接
295         conn.setRequestProperty("Connection", "Keep-Alive");
296         // 设置文件字符集:
297         conn.setRequestProperty("Charset", "UTF-8");
298         // 转换为字节数组
299         // byte[] data = (objx.toString()).getBytes();
300         // 设置文件长度
301         // conn.setRequestProperty("Content-Length",String.valueOf(data.length));
302
303         // 设置文件类型:
304         conn.setRequestProperty("contentType", "application/json");
305         // 开始连接请求
306         conn.connect();
307         OutputStream out = conn.getOutputStream();
308         // 写入请求的字符串
309         out.write((objx.toString()).getBytes());
310         out.flush();
311         out.close();
312
313         // 请求返回的状态
314         if (conn.getResponseCode() == 200) {
315             System.out.println("连接成功");
316             // 请求返回的数据
317             InputStream in = conn.getInputStream();
318             ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
319             byte[] temp = new byte[1024];
320             int rc = 0;
321             while ((rc = in.read(temp, 0, 100)) > 0) {
322                 swapStream.write(temp, 0, rc);
323             }
324             byte[] buffer2 = swapStream.toByteArray();
325             String base64 = Base64.encodeBase64String(buffer2);
326
327             //生成名称
328             java.util.Random r=new java.util.Random();
329             StringBuilder str=new StringBuilder();//定义变长字符串
330             for(int i=0;i<8;i++){
331                 str.append(r.nextInt(10));
332             }
333             Date date = new Date();
334             SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
335             String imgName = sf.format(date);
336             imgName = imgName+str.toString();
337
338             //文件保存位置
339             File saveDir = new File(saveUrl);
340             if(!saveDir.exists()){
341                 saveDir.mkdir();
342             }
343             File file = new File(saveDir+"/"+imgName+".png");
344             FileOutputStream fos = new FileOutputStream(file);
345             fos.write(buffer2);
346             if(fos!=null){
347                 fos.close();
348             }
349             if(in!=null){
350                 in.close();
351             }
352             realpath = seeUrl+"/"+imgName+".png";
353         } else {
354             System.out.println("no++");
355         }
356         return realpath;
357     }
358
359     /** 请求http协议 获取信息工具 **/
360     private static JSONObject HttpURLUtil(String url,String data) {
361         HttpURLConnection con = null;
362         URL u;
363         String wxMsgXml;
364         JSONObject obj;
365         try {
366             u = new URL(url);
367             con = (HttpURLConnection) u.openConnection();
368             con.setRequestMethod("POST");
369             con.setDoOutput(true);
370             con.setDoInput(true);
371             con.setUseCaches(false);
372             con.setReadTimeout(5000);
373             con.setRequestProperty("Charset", "UTF-8");
374             con.setRequestProperty("Content-Type",
375                     "application/x-www-form-urlencoded");
376             if (data != null) {
377                 OutputStream os = con.getOutputStream();
378                 os.write(data.getBytes("utf-8"));
379             }
380             if (con.getResponseCode() != 200)
381                 throw new RuntimeException("请求url失败");
382             // 读取返回内容
383             wxMsgXml = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8);
384             // 判断返回参数是否正确/成功
385             obj = JSONObject.fromObject(wxMsgXml);
386             // System.out.println("HttpURLUtil:"+wxMsgXml);
387         } catch (Exception e) {
388             e.printStackTrace();
389             obj = new JSONObject();
390             try {
391                 obj.put("status", 1);
392                 obj.put("errMsg", e.getMessage());
393             } catch (JSONException e1) {
394                 e1.printStackTrace();
395             }
396         } finally {
397             if (con != null) {
398                 con.disconnect();
399             }
400         }
401         return obj;
402     }
403
404 }