chenjiahe
2022-01-28 b1097dce55d857ae1ae63798911c1e7027c00de4
提交 | 用户 | age
5c5945 1 package com.hx.mp.util;
E 2
3 import com.hx.util.StringUtils;
4 import net.sf.json.JSONException;
5 import net.sf.json.JSONObject;
6 import org.apache.commons.codec.binary.Base64;
7 import org.apache.commons.io.IOUtils;
8
9 import java.io.ByteArrayOutputStream;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.net.HttpURLConnection;
13 import java.net.URL;
14 import java.sql.Timestamp;
15 import java.text.MessageFormat;
16 import java.util.Date;
17
18 /**
19  * 微信小程序工具类
20  */
21 public class MpUtil {
22
23     /** 请求access_token */
24     public static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
25     /** 请求服务器IP地址 */
26     public static final String URL_SERVER_ADDR = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=";
27     /** 微信js的code换去sessionKey */
28     public static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&grant_type=authorization_code&js_code=";
29     /** 请求小程序码 **/
30     public static final String URL_WXACODE = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";
31     /** 请求小程序码-无数量限制 **/
32     public static final String URL_WXACODEUNLIMIT = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
33     /** 请求小程序二维码 */
34     public static final String URL_QRCODE = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
35     /** 发模版消息 */
36     public static final String URL_SEND_TEMP_MSG = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=";
37     /** 设置发票授权字段 */
38     public static final String URL_SET_TICKET_FIELD = "https://api.weixin.qq.com/card/invoice/setbizattr?action=set_auth_field&access_token=";
39     /** 获取发票ticket */
40     public static final String URL_GET_TICKET_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token=";
41     /** 获取发票授权页链接 */
42     public static final String URL_GET_TICKET_AUTH_LINK = "https://api.weixin.qq.com/card/invoice/getauthurl?access_token=";
43     /** 查询发票授权字段 */
44     public static final String URL_GET_AUTH_FIELD = "https://api.weixin.qq.com/card/invoice/getauthdata?access_token=";
45     /** 设置 支付后开发票 */
46     public static final String URL_SET_PAY_INVOICE = "https://api.weixin.qq.com/card/invoice/setbizattr?action=set_pay_mch&access_token=";
47     /** 查询支付后开发票 */
48     public static final String URL_GET_PAY_INVOICE = "https://api.weixin.qq.com/card/invoice/setbizattr?action=get_pay_mch&access_token=";
49     /** 发送客服消息 */
50     public static final String URL_SEND_KF_MSG = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
51
52     /*************************************************
53      * 小程序
54      *************************/
55     /** 利用code换取sessionKey */
56     public static JSONObject jsCode2session(String code, String appId, String appSecret) {
57         JSONObject obj = new JSONObject();
58         String url = StringUtils.format(JSCODE2SESSION_URL, appId, appSecret) + code;
59         obj = HttpURLUtil(url, null);
60         return obj;
61     }
62
63     /** 获取小程序二维码图片 */
64     public static String getQrCode(String accessToken, String jsonParam)
65             throws Exception {
66         JSONObject obj = HttpURLUtilJson(URL_QRCODE + accessToken, jsonParam);
67         String qrStr = obj.optString("data");
68         return qrStr;
69     }
70
71     /** 从weixin接口获取Access_token **/
72     public static JSONObject getApplication_Access_tokenForUrl(String appId, String appSecret)
73             throws Exception {
74         String url = MessageFormat.format(URL_ACCESS_TOKEN, appId, appSecret);
75         JSONObject obj = HttpURLUtil(url, null);
76         return obj;
77     }
78
79     /** 请求http协议 获取信息工具 **/
80     public static InputStream HttpURLUtilStream(String url, String data) {
81         HttpURLConnection con = null;
82         URL u = null;
83         try {
84             u = new URL(url);
85             con = (HttpURLConnection) u.openConnection();
86             con.setRequestMethod("POST");
87             con.setDoOutput(true);
88             con.setDoInput(true);
89             con.setUseCaches(false);
90             con.setReadTimeout(200000);
91             con.setRequestProperty("Charset", "UTF-8");
92             con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
93
94             if (data != null) {
95                 OutputStream os = con.getOutputStream();
96                 os.write(data.getBytes("utf-8"));
97             }
98
99             if (con.getResponseCode() != 200)
100                 throw new RuntimeException("请求url失败");
101
102             return con.getInputStream();
103         } catch (Exception e) {
104             e.printStackTrace();
105         } finally {
106             if (con != null) {
107                 con.disconnect();
108             }
109         }
110         return null;
111     }
112
113     /** 获取二维码图片 **/
114     public static JSONObject HttpURLUtilJson(String urlx, String objx) {
115         JSONObject jo = new JSONObject();
116         try {
117             // 创建url资源
118             URL url = new URL(urlx);
119             // 建立http连接
120             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
121             // 设置允许输出
122             conn.setDoOutput(true);
123
124             conn.setDoInput(true);
125
126             // 设置不用缓存
127             conn.setUseCaches(false);
128             // 设置传递方式
129             conn.setRequestMethod("POST");
130             // 设置维持长连接
131             conn.setRequestProperty("Connection", "Keep-Alive");
132             // 设置文件字符集:
133             conn.setRequestProperty("Charset", "UTF-8");
134             // 设置文件类型:
135             conn.setRequestProperty("contentType", "application/json");
136             // 开始连接请求
137             conn.connect();
138             OutputStream out = conn.getOutputStream();
139             // 写入请求的字符串
140             out.write(objx.getBytes());
141             out.flush();
142             out.close();
143
144             // 请求返回的状态
145             if (conn.getResponseCode() == 200) {
146                 // 请求返回的数据
147                 InputStream in = conn.getInputStream();
148                 try {
149                     ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
150                     byte[] temp = new byte[1024];
151                     int rc = 0;
152                     while ((rc = in.read(temp, 0, 100)) > 0) {
153                         swapStream.write(temp, 0, rc);
154                     }
155                     byte[] buffer = swapStream.toByteArray();
156                     String base64 = Base64.encodeBase64String(buffer);
157                     jo.put("data", base64);
158                 } catch (Exception e1) {
159                     e1.printStackTrace();
160                 }
161             } else {
162                 // System.out.println("no++");
163             }
164
165         } catch (Exception e) {
166             e.printStackTrace();
167         }
168         return jo;
169     }
170
171     /** 请求http协议 获取信息工具 **/
172     public static JSONObject HttpURLUtil(String url, String data) {
173         HttpURLConnection con = null;
174         URL u = null;
175         String wxMsgXml = null;
176         JSONObject obj = null;
177         try {
178             u = new URL(url);
179             con = (HttpURLConnection) u.openConnection();
180             con.setRequestMethod("POST");
181             con.setDoOutput(true);
182             con.setDoInput(true);
183             con.setUseCaches(false);
184             con.setReadTimeout(5000);
185             con.setRequestProperty("Charset", "UTF-8");
186             con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
187
188             if (data != null) {
189                 OutputStream os = con.getOutputStream();
190                 os.write(data.getBytes("utf-8"));
191             }
192
193             if (con.getResponseCode() != 200)
194                 throw new RuntimeException("请求url失败");
195             // 读取返回内容
196             wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8");
197             obj = JSONObject.fromObject(wxMsgXml);
198             // //System.out.println("HttpURLUtil:"+wxMsgXml);
199         } catch (Exception e) {
200             e.printStackTrace();
201             obj = new JSONObject();
202             try {
203                 obj.put("status", 1);
204                 obj.put("errMsg", e.getMessage());
205             } catch (JSONException e1) {
206                 e1.printStackTrace();
207             }
208         } finally {
209             if (con != null) {
210                 con.disconnect();
211             }
212         }
213         return obj;
214     }
215
216     /** 发送模版消息 **/
217     public static JSONObject sendTempMsg(String accessToken, String jsonStr) {
218         JSONObject obj = HttpURLUtil(URL_SEND_TEMP_MSG + accessToken, jsonStr);
219         return obj;
220     }
221
222     public static Integer DateToTimestamp(Date time) {
223         Timestamp ts = new Timestamp(time.getTime());
224         return (int) ((ts.getTime()) / 1000);
225     }
226
227     /**
228      * 发送链接客服消息
229      *
230      * @throws JSONException
231      */
232     public static String sendKfLinkMsg(String at, String openId, String title, String description, String url,
233                                        String imgUrl) throws JSONException {
234         String result = "fail";
235
236         JSONObject obj = new JSONObject();
237         obj.put("touser", openId);
238         obj.put("msgtype", "link");
239
240         JSONObject pObj = new JSONObject();
241         pObj.put("title", title);
242         pObj.put("description", description);
243         pObj.put("url", url);
244         pObj.put("thumb_url", imgUrl);
245         obj.put("link", pObj);
246
247         JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + at, obj.toString());
248         // System.out.println("rObj==="+rObj);
249         if (rObj != null) {
250             if (rObj.optInt("errcode", -1) == 0) {
251                 result = "suc";
252             } else {
253                 result = rObj.optString("errmsg");
254             }
255         }
256         rObj = null;
257         obj = null;
258
259         return result;
260     }
261
262     /**
263      * 发送图片客户消息
264      *
265      * @param access_token
266      *            access_token
267      * @param toUser
268      *            用户openid
269      * @param media_id
270      *            素材id
271      * @return
272      */
273     public static String sendKfImageMsg(String access_token, String toUser, String media_id) {
274         String result = "fail";
275
276         try {
277             JSONObject obj = new JSONObject();
278             obj.put("touser", toUser);
279             obj.put("msgtype", "image");
280
281             JSONObject pObj = new JSONObject();
282             pObj.put("media_id", media_id);
283             obj.put("image", pObj);
284
285             JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + access_token, obj.toString());
286             System.out.println("rObj==" + rObj.toString());
287             if (rObj != null) {
288                 if (rObj.optInt("errcode", -1) == 0) {
289                     result = "suc";
290                 } else {
291                     result = rObj.optString("errmsg");
292                 }
293             }
294             rObj = null;
295             obj = null;
296         } catch (Exception e) {
297             e.printStackTrace();
298         }
299
300         return result;
301     }
302
303     /**
304      * 发送文本客户消息
305      *
306      * @param access_token
307      *            access_token
308      * @param toUser
309      *            用户openid
310      * @return
311      */
312     public static String sendKfTextMsg(String access_token, String toUser, String content) {
313         String result = "fail";
314
315         try {
316             JSONObject obj = new JSONObject();
317             obj.put("touser", toUser);
318             obj.put("msgtype", "text");
319
320             JSONObject pObj = new JSONObject();
321             pObj.put("content", content);
322             obj.put("text", pObj);
323
324             JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + access_token, obj.toString());
325             if (rObj != null) {
326                 if (rObj.optInt("errcode", -1) == 0) {
327                     result = "suc";
328                 } else {
329                     result = rObj.optString("errmsg");
330                 }
331             }
332             rObj = null;
333             obj = null;
334         } catch (Exception e) {
335             e.printStackTrace();
336         }
337
338         return result;
339     }
340
341     /** 获取小程序码图片 */
342     public static String getWXACode(String accessToken, String jsonParam, String path)
343             throws Exception {
344         JSONObject obj = HttpURLUtilJson(URL_WXACODE + accessToken, jsonParam);
345         String qrStr = obj.optString("data");
346         return qrStr;
347     }
348
349     /** 获取小程序码图片 */
350     public static String getWXACodeUnlimit(String accessToken, String jsonParam, String path)
351             throws Exception {
352         JSONObject obj = HttpURLUtilJson(URL_WXACODEUNLIMIT + accessToken, jsonParam);
353         String qrStr = obj.optString("data");
354         return qrStr;
355     }
356
357 }