WxMiniUtil.java
19.5 KB
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
package org.theyeasy.weixin.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.theyeasy.weixin.model.WxMiniSessionInfo;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.w1hd.zzhnc.util.CommonUtil;
import com.w1hd.zzhnc.util.RedisUtil;
import com.w1hd.zzhnc.vo.Vo_msg;
import net.sf.json.JSONObject;
/**
* 小程序公共接口类
*
* @author lcc
*
*/
@Component
public class WxMiniUtil {
private final static String _appid = "wxbe75806d33ab8a2e";
final static String _appsecret = "ad525cff47f679ae0f318b38deb2705e";
final static String _token = "theyeasy_zzhnc";
final static String _EncodingAESKey = "eALRfGYXIRpgFmz1UG84t4F3lwooi1T20POx95ZN6TE";
final static String _url_message_custom_send = "https://api.weixin.qq.com/cgi-bin/message/custom/send";
final static String _RedisKey_WxToken = "zzhnc_wxtoken_wx64e56457ec5c6338";
public static String getAccessToken() {
String accessToken = RedisUtil.get(_RedisKey_WxToken);
if (null != accessToken && accessToken.length() > 0) {
return accessToken;
} else {
return refreshAccessToken();
}
}
public static String refreshAccessToken() {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + getAppid()
+ "&secret=" + _appsecret;
String result = CommonUtil.sendPost(url, "");
System.out.print("refreshAccessToken刷新小程序的AccessToken: result=" + result);
JSONObject resultJson = JSONObject.fromObject(result);
String accessToken = resultJson.getString("access_token");
RedisUtil.set(_RedisKey_WxToken, accessToken, 3600);
return accessToken;
}
public synchronized static String refreshToken() {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + _appid + "&secret="
+ _appsecret;
String result = CommonUtil.sendPost(url, "");
System.out.print("refreshAccessToken刷新小程序的AccessToken: result=" + result);
JSONObject resultJson = JSONObject.fromObject(result);
String accessToken = resultJson.getString("access_token");
RedisUtil.set(_RedisKey_WxToken, accessToken, 3600);
return accessToken;
}
/*
* 获取session信息:openid和sessionKey
*/
public static WxMiniSessionInfo jscode2session(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + getAppid() + "&secret=" + _appsecret
+ "&js_code=" + code + "&grant_type=authorization_code";
String result = CommonUtil.sendPost(url, "");
JSONObject resultJson = JSONObject.fromObject(result);
String session_key = resultJson.getString("session_key");
String openid = resultJson.getString("openid");
WxMiniSessionInfo sessionInfo = new WxMiniSessionInfo();
sessionInfo.setCode(code);
sessionInfo.setOpenid(openid);
sessionInfo.setSessionKey(session_key);
sessionInfo.setAppid(getAppid());
return sessionInfo;
}
public static String getAppid() {
return _appid;
}
/*
* 接口A方式生成二维码(数量较少)
*/
public static String getMiniCode1(String path, int width, boolean autoColor, int r, int g, int b) {
String url = "https://api.weixin.qq.com/wxa/getwxacode";
Map<String, Object> param = new HashMap<>();
param.put("path", path);
param.put("width", width);
param.put("auto_color", autoColor);
Map<String, Object> line_color = new HashMap<>();
line_color.put("r", r);
line_color.put("g", g);
line_color.put("b", b);
param.put("line_color", line_color);
String filename = sendWxPostGetImg(url, param);
return filename;
}
/*
* 接口B方式生成二维码(数量多,带场景值)
*/
public static String getMiniCode2(String sceneStr, String page, int width, boolean autoColor, int r, int g, int b) {
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";
Map<String, Object> param = new HashMap<>();
param.put("scene", sceneStr);
param.put("page", page);
param.put("width", width);
param.put("auto_color", autoColor);
Map<String, Object> line_color = new HashMap<>();
line_color.put("r", r + "");
line_color.put("g", g + "");
line_color.put("b", b + "");
param.put("line_color", line_color);
String filename = sendWxPostGetImg(url, param);
return filename;
}
/*
* 接口C方式生成二维码(需要的码极少时用)
*/
public static String getMiniCode3(String path, int width) {
String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode";
Map<String, Object> param = new HashMap<>();
param.put("path", path);
param.put("width", width);
String filename = sendWxPostGetImg(url, param);
return filename;
}
/*
* 校验signature合法性
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { _token, timestamp, nonce };
Arrays.sort(arr);
String content = arr[0] + arr[1] + arr[2];
String temp = new SHA1().getDigestOfString(content.getBytes());
return temp.equalsIgnoreCase(signature);
}
public static int getRandom(int max) {
if(max==0) return 0;
Random random = new Random();
return random.nextInt(max);
}
/* 发送客服消息_文本 */
public static String sendCustomMsgText(String openid, String text) {
if(null==text || text.length()<1) return "";
Map<String, Object> param = new HashMap<>();
param.put("touser", openid);
param.put("msgtype", "text");
Map<String, Object> t = new HashMap<>();
t.put("content", text);
param.put("text", t);
String result = sendWxPost(_url_message_custom_send, param);
return result;
}
/**
* 功能:上传图片的临时素材 filepath:本地的图片路径 返回: vo_msg,成功时vo_msg.code=0;
*/
public static Vo_msg uploadImage(String filepath, boolean isRealPath) {
System.out.println("WxMiniUtil.uploadImage:filepath= " + filepath);
String realPath = null;
if (!isRealPath) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
realPath = request.getSession().getServletContext().getRealPath(filepath);
realPath = realPath.replace("/zzhnc/zzhnc", "/zzhnc/WEB-INF");
} else {
realPath = filepath;
}
System.out.println("WxMiniUtil.uploadImage:realpath= " + realPath);
File file = new File(realPath);
if (!file.exists()) {
System.out.println("WxMiniUtil.uploadImage:图片不存在! " + realPath);
return new Vo_msg(-1, "", "error:图片文件不存在!");
}
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
String uploadurl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + getAccessToken()
+ "&type=image";
PostMethod post = new PostMethod(uploadurl);
post.setRequestHeader("User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0");
post.setRequestHeader("Host", "file.api.weixin.qq.com");
post.setRequestHeader("Connection", "Keep-Alive");
post.setRequestHeader("Cache-Control", "no-cache");
try {
if (file != null && file.exists()) {
int i = filepath.lastIndexOf('.');
String filetype = filepath.substring(i + 1);
FilePart filepart = new FilePart("media", file, "image/" + filetype, "UTF-8");
Part[] parts = new Part[] { filepart };
MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(entity);
int status = client.executeMethod(post);
if (status == HttpStatus.SC_OK) {
String responseContent = post.getResponseBodyAsString();
System.out.println("WxMiniUtil上传图片临时素材:" + responseContent);
JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
if (json.get("errcode") == null)// {"errcode":40004,"errmsg":"invalid media type"}
{ // 上传成功
return new Vo_msg(0, json.get("media_id").getAsString(), "");
} else {
return new Vo_msg(-2, "", json.get("errmsg").getAsString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return new Vo_msg(-3, "", "系统处理失败");
}
/* 发送客服消息_图片 */
public static String sendCustomMsgImg(String openid, String media_id) {
Map<String, Object> param = new HashMap<>();
param.put("touser", openid);
param.put("msgtype", "image");
Map<String, Object> img = new HashMap<>();
img.put("media_id", media_id);
param.put("image", img);
String result = sendWxPost(_url_message_custom_send, param);
return result;
}
/* 发送客服消息_图文消息 */
public static String sendCustomMsgLink(String openid, String title, String description, String url,
String thumb_url) {
Map<String, Object> param = new HashMap<>();
param.put("touser", openid);
param.put("msgtype", "link");
Map<String, Object> link = new HashMap<>();
link.put("title", title);
link.put("description", description);
link.put("url", url);
link.put("thumb_url", thumb_url);
param.put("link", link);
String result = sendWxPost(_url_message_custom_send, param);
return result;
}
public static String sendCustoMiniprogrampage(String openid, String title, String pagePath,String thumb_url,String thumb_media_id) {
Map<String, Object> param = new HashMap<>();
param.put("touser", openid);
param.put("msgtype", "miniprogrampage");
Map<String, Object> miniprogrampage = new HashMap<>();
miniprogrampage.put("title", title);
miniprogrampage.put("pagepath", pagePath);
miniprogrampage.put("thumb_url", thumb_url);
miniprogrampage.put("thumb_media_id", thumb_media_id);
param.put("miniprogrampage", miniprogrampage);
String result = sendWxPost(_url_message_custom_send, param);
return result;
}
/* 上传微信的临时素材 */
/* 向微信服务器发送Post请求 */
private static String sendWxPost(String uri, Map<String, Object> param) {
if (uri.indexOf("access_token=") != -1) {
throw new IllegalArgumentException("WxMiniUtil.sendWxPost:uri参数中不允许有access_token: " + uri);
}
String uriWithAccessToken = uri;
String accessToken = getAccessToken();
uriWithAccessToken += uri.indexOf('?') == -1 ? "?access_token=" + accessToken : "&access_token=" + accessToken;
RestTemplate rest = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<Map<String, Object>>(param, headers);
ResponseEntity<String> entity = rest.exchange(uriWithAccessToken, HttpMethod.POST, requestEntity, String.class);
String result = entity.getBody();
System.out.print("sendWxPost.result=" + result + " param=" + param.toString());
return result;
}
/* 向微信服务器发送Post请求,返回结果保存为本地图片 */
private static String sendWxPostGetImg(String uri, Map<String, Object> param) {
RestTemplate rest = new RestTemplate();
InputStream inputStream = null;
OutputStream outputStream = null;
String filename = "";
try {
if (uri.indexOf("access_token=") != -1) {
throw new IllegalArgumentException("WxMiniUtil.sendWxPost:uri参数中不允许有access_token: " + uri);
}
String uriWithAccessToken = uri;
String accessToken = getAccessToken();
uriWithAccessToken += uri.indexOf('?') == -1 ? "?access_token=" + accessToken
: "&access_token=" + accessToken;
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<Map<String, Object>>(param, headers);
ResponseEntity<byte[]> entity = rest.exchange(uriWithAccessToken, HttpMethod.POST, requestEntity,
byte[].class, new Object[0]);
byte[] result = entity.getBody();
System.out.print("WxMiniUtil.sendWxPostGetImg.url=" + uriWithAccessToken + " result.leng=" + result.length
+ " http.status=" + entity.getStatusCode());
System.out.print(result.toString());
inputStream = new ByteArrayInputStream(result);
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/res/weixin/");
filename = "wx_" + DateTime.now().getMillis() + getRandom(9999) + ".png";
System.out.println("realPath:" + realPath);
File file = new File(realPath);
if (!file.exists()) {
// file.createNewFile();
file.mkdir();
}
outputStream = new FileOutputStream(realPath + filename);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "/res/weixin/" + filename;
}
public static String getQQFace() {
String faces = "/::)|/::~|/::B|/::|/:8-)|/::<|/::$|/::X|/::Z|/::'(|/::-|/::@|/::P|/::D|/::O|/::(|/::+|/:--b|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:|-)|/::!|/::L|/::>|/::,@|/:,@f|/::-S|/:?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-(|/:B-)|/:<@|/:@>|/::-O|/:>-|/:P-(|/::'|/:X-)|/::*|/:@x|/:8*|/:pd|/:<W>|/:beer|/:basketb|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@)|/:jj|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>";
String[] keys = faces.split("\\|");
return keys[getRandom(keys.length - 1)];
}
/**
* 判断是否是QQ表情
*
* @param content
* @return
*/
public static boolean isQqFace(String content) {
boolean result = false;
// 判断QQ表情的正则表达式
String qqfaceRegex = "/::\\)|/::~|/::B|/::\\||/:8-\\)|/::<|/::$|/::X|/::Z|/::'\\(|/::-\\||/::@|/::P|/::D|/::O|/::\\(|/::\\+|/:--b|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:\\|-\\)|/::!|/::L|/::>|/::,@|/:,@f|/::-S|/:\\?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-\\(|/:B-\\)|/:<@|/:@>|/::-O|/:>-\\||/:P-\\(|/::'\\||/:X-\\)|/::\\*|/:@x|/:8\\*|/:pd|/:<W>|/:beer|/:basketb|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@\\)|/:jj|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>";
Pattern p = Pattern.compile(qqfaceRegex);
Matcher m = p.matcher(content);
if (m.matches()) {
result = true;
}
return result;
}
public static String sponseQqFace(String content) {
String qqfaceRegex = "/::\\)|/::~|/::B|/::\\||/:8-\\)|/::<|/::$|/::X|/::Z|/::'\\(|/::-\\||/::@|/::P|/::D|/::O|/::\\(|/::\\+|/:--b|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:\\|-\\)|/::!|/::L|/::>|/::,@|/:,@f|/::-S|/:\\?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-\\(|/:B-\\)|/:<@|/:@>|/::-O|/:>-\\||/:P-\\(|/::'\\||/:X-\\)|/::\\*|/:@x|/:8\\*|/:pd|/:<W>|/:beer|/:basketb|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@\\)|/:jj|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>";
Pattern p = Pattern.compile(qqfaceRegex);
Matcher m = p.matcher(content);
List<String> list = new LinkedList<String>();
int count = 0;
while (m.find()) {
list.add(m.group());
count++;
}
Collections.shuffle(list);
String faces = list.toString();
System.out.println("count=" + count);
if (count < 3 && !m.matches())
return "";
if (count < 3 && m.matches())
return faces.toString();
if (count < 5 && m.matches())
return "我也来," + faces + faces;
if (count < 8)
return faces.toString();
if (count < 12)
return "...";
if (count < 15)
return "/尴尬/尴尬/尴尬...";
if (count >= 15)
return "/晕/晕/晕表情也是要流量的,表情也是要流量的,表情也是要流量的,重要的事情说三遍!";
return faces.toString();
}
public static String getAddress(String lat,String lng)
{
String url = "http://apis.baidu.com/netpopo/geoconvert/coord2addr?lat=" + lat + "&lng=" + lng + "&type=baidu";
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//conn.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("content-type", "application/json");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("apikey", "481cbc41525f86c636e8bb4fc1daa775"); //8893165的apistore.baidu.com的key
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
return result;
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
return "";
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] arg) {
String address = getAddress("22.542600", "114.061501");
System.out.println(address);
}
}