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