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