WeixinBaseController.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. package com.yihu.wlyy.web;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.security.MessageDigest;
  9. import java.util.Date;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. import java.util.Random;
  13. import org.apache.commons.lang3.StringUtils;
  14. import org.json.JSONObject;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import com.yihu.wlyy.entity.security.AccessToken;
  17. import com.yihu.wlyy.entity.security.JsApiTicket;
  18. import com.yihu.wlyy.entity.patient.Patient;
  19. import com.yihu.wlyy.entity.security.Token;
  20. import com.yihu.wlyy.service.common.account.AccessTokenService;
  21. import com.yihu.wlyy.service.common.account.PatientService;
  22. import com.yihu.wlyy.service.common.account.TokenService;
  23. import com.yihu.wlyy.util.DateUtil;
  24. import com.yihu.wlyy.util.HttpUtil;
  25. import com.yihu.wlyy.util.ImageCompress;
  26. import com.yihu.wlyy.util.SystemConf;
  27. import com.yihu.wlyy.util.SystemData;
  28. public class WeixinBaseController extends BaseController {
  29. @Autowired
  30. private PatientService patientService;
  31. @Autowired
  32. private AccessTokenService accessTokenService;
  33. @Autowired
  34. private TokenService tokenService;
  35. /**
  36. * 通过code获取判断openid
  37. *
  38. * @param code
  39. * @return
  40. */
  41. public String getOpenidByCode(String code) {
  42. try {
  43. String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
  44. String params = "appid=" + SystemConf.getInstance().getAppId() + "&secret=" + SystemConf.getInstance().getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
  45. String result = HttpUtil.sendGet(token_url, params);
  46. JSONObject json = new JSONObject(result);
  47. if (json.has("openid")) {
  48. return json.get("openid").toString();
  49. } else {
  50. return null;
  51. }
  52. } catch (Exception e) {
  53. error(e);
  54. }
  55. return null;
  56. }
  57. /**
  58. * 通过code获取判断openid
  59. *
  60. * @param code
  61. * @return
  62. */
  63. public String getOpenid(String code) {
  64. try {
  65. String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
  66. String params = "appid=" + SystemConf.getInstance().getAppId() + "&secret=" + SystemConf.getInstance().getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
  67. String result = HttpUtil.sendGet(token_url, params);
  68. JSONObject json = new JSONObject(result);
  69. Map<Object, Object> map = new HashMap<Object, Object>();
  70. if (json.has("openid")) {
  71. String openid = json.get("openid").toString();
  72. Patient patient = patientService.findByOpenid(openid);
  73. if (patient != null) {
  74. // 返回用户信息
  75. map.put("id", patient.getId());
  76. map.put("uid", patient.getCode());
  77. map.put("name", patient.getName());
  78. map.put("openid", patient.getOpenid());
  79. map.put("photo", patient.getPhoto());
  80. // 查询token
  81. Token token = SystemData.wxPatientTokens.get(patient.getCode());
  82. if (token == null) {
  83. // 从数据库加载
  84. token = tokenService.findWxToken(patient.getCode());
  85. }
  86. if (token == null) {
  87. // 生成新的token
  88. token = tokenService.newTxToken(patient.getCode(), openid);
  89. }
  90. map.put("token", token.getToken());
  91. return write(200, "获取成功", "data", map);
  92. } else {
  93. return error(100, openid);
  94. }
  95. } else {
  96. return error(Integer.parseInt(json.get("errcode").toString()), "操作失败:" + json.get("errmsg").toString());
  97. }
  98. } catch (Exception e) {
  99. error(e);
  100. return invalidUserException(e, -1, "操作失败!");
  101. }
  102. }
  103. /**
  104. * 拼接地址?后的参数
  105. *
  106. * @param data
  107. * @param type
  108. * @return
  109. */
  110. public String getParamUrl(String data, int type) {
  111. try {
  112. JSONObject jsonData = new JSONObject(data);
  113. String id = jsonData.get("id").toString();
  114. String uid = jsonData.get("uid").toString();
  115. String name = jsonData.get("name").toString();
  116. String openid = jsonData.get("openid").toString();
  117. String photo = jsonData.get("photo").toString();
  118. String token = jsonData.get("token").toString();
  119. String paramUrl = "?type=" + type + "&id=" + id + "&uid=" + uid + "&name=" + name + "&openid=" + openid + "&photo=" + photo + "&token=" + token;
  120. return paramUrl;
  121. } catch (Exception e) {
  122. error(e);
  123. return "";
  124. }
  125. }
  126. /**
  127. * 获取微信的access_token
  128. *
  129. * @return
  130. */
  131. public String getAccessToken() {
  132. try {
  133. Iterable<AccessToken> accessTokens = accessTokenService.findAccessToken();
  134. if (accessTokens != null) {
  135. for (AccessToken accessToken : accessTokens) {
  136. if ((System.currentTimeMillis() - accessToken.getAdd_timestamp()) < (accessToken.getExpires_in() * 1000)) {
  137. return accessToken.getAccess_token();
  138. } else {
  139. accessTokenService.delAccessToken(accessToken);
  140. break;
  141. }
  142. }
  143. }
  144. String token_url = "https://api.weixin.qq.com/cgi-bin/token";
  145. String params = "grant_type=client_credential&appid=" + SystemConf.getInstance().getAppId() + "&secret=" + SystemConf.getInstance().getAppSecret();
  146. String result = HttpUtil.sendGet(token_url, params);
  147. JSONObject json = new JSONObject(result);
  148. if (json.has("access_token")) {
  149. String token = json.get("access_token").toString();
  150. String expires_in = json.get("expires_in").toString();
  151. AccessToken newaccessToken = new AccessToken();
  152. newaccessToken.setAccess_token(token);
  153. newaccessToken.setExpires_in(Long.parseLong(expires_in));
  154. accessTokenService.addAccessToken(newaccessToken);
  155. return token;
  156. } else {
  157. return null;
  158. }
  159. } catch (Exception e) {
  160. error(e);
  161. return null;
  162. }
  163. }
  164. /**
  165. * 获取微信的jsapi_ticket
  166. *
  167. * @return
  168. */
  169. public String getJsapi_ticketByToken() {
  170. try {
  171. Iterable<JsApiTicket> jsapiTickets = accessTokenService.findJsapiTicket();
  172. if (jsapiTickets != null) {
  173. for (JsApiTicket jsApiTicket : jsapiTickets) {
  174. if ((System.currentTimeMillis() - jsApiTicket.getAdd_timestamp()) < (jsApiTicket.getExpires_in() * 1000)) {
  175. return jsApiTicket.getJsapi_ticket();
  176. } else {
  177. accessTokenService.delJsapiTicket(jsApiTicket);
  178. break;
  179. }
  180. }
  181. }
  182. String token = getAccessToken();
  183. if (token != null) {
  184. String token_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
  185. String params = "access_token=" + token + "&type=jsapi";
  186. String result = HttpUtil.sendGet(token_url, params);
  187. JSONObject json = new JSONObject(result);
  188. if (json.has("ticket")) {
  189. String ticket = json.get("ticket").toString();
  190. String expires_in = json.get("expires_in").toString();
  191. JsApiTicket newJsApiTicket = new JsApiTicket();
  192. newJsApiTicket.setJsapi_ticket(ticket);
  193. newJsApiTicket.setExpires_in(Long.parseLong(expires_in));
  194. accessTokenService.addJsapiTicket(newJsApiTicket);
  195. return ticket;
  196. } else {
  197. return null;
  198. }
  199. } else {
  200. return null;
  201. }
  202. } catch (Exception e) {
  203. error(e);
  204. return null;
  205. }
  206. }
  207. /**
  208. * @description: SHA、SHA1加密 @parameter: str:待加密字符串 @return: 加密串
  209. **/
  210. public String SHA1(String str) {
  211. try {
  212. MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); // 如果是SHA加密只需要将"SHA-1"改成"SHA"即可
  213. digest.update(str.getBytes());
  214. byte messageDigest[] = digest.digest();
  215. // Create Hex String
  216. StringBuffer hexStr = new StringBuffer();
  217. // 字节数组转换为 十六进制 数
  218. for (int i = 0; i < messageDigest.length; i++) {
  219. String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
  220. if (shaHex.length() < 2) {
  221. hexStr.append(0);
  222. }
  223. hexStr.append(shaHex);
  224. }
  225. return hexStr.toString();
  226. } catch (Exception e) {
  227. error(e);
  228. }
  229. return null;
  230. }
  231. /**
  232. * 获取微信服务器图片
  233. *
  234. * @return
  235. */
  236. public String Images() {
  237. String photos = "";
  238. try {
  239. String images = request.getParameter("mediaIds");
  240. if (StringUtils.isEmpty(images)) {
  241. return photos;
  242. }
  243. String[] mediaIds = images.split(",");
  244. for (String mediaId : mediaIds) {
  245. if (StringUtils.isEmpty(mediaId)) {
  246. continue;
  247. }
  248. String temp = saveImageToDisk(mediaId);
  249. if (StringUtils.isNotEmpty(temp)) {
  250. if (photos.length() == 0) {
  251. photos = temp;
  252. } else {
  253. photos += "," + temp;
  254. }
  255. }
  256. }
  257. } catch (Exception e) {
  258. error(e);
  259. }
  260. return photos;
  261. }
  262. /**
  263. * 获取下载图片信息(jpg)
  264. *
  265. * @param mediaId 文件的id
  266. * @throws Exception
  267. */
  268. public String saveImageToDisk(String mediaId) throws Exception {
  269. // 文件保存的临时路径
  270. String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
  271. // 拼接年月日路径
  272. String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
  273. // 重命名文件
  274. String newFileName = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000) + ".png";
  275. // 保存路径
  276. File uploadFile = new File(tempPath + datePath + newFileName);
  277. InputStream inputStream = null;
  278. FileOutputStream fileOutputStream = null;
  279. try {
  280. if (!uploadFile.getParentFile().exists()) {
  281. uploadFile.getParentFile().mkdirs();
  282. }
  283. inputStream = getInputStream(mediaId);
  284. byte[] data = new byte[1024];
  285. int len = 0;
  286. fileOutputStream = new FileOutputStream(uploadFile);
  287. while ((len = inputStream.read(data)) != -1) {
  288. fileOutputStream.write(data, 0, len);
  289. }
  290. // 生成缩略图
  291. ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
  292. // 返回保存路径
  293. return datePath + newFileName;
  294. } catch (IOException e) {
  295. e.printStackTrace();
  296. } finally {
  297. if (inputStream != null) {
  298. try {
  299. inputStream.close();
  300. } catch (IOException e) {
  301. e.printStackTrace();
  302. }
  303. }
  304. if (fileOutputStream != null) {
  305. try {
  306. fileOutputStream.close();
  307. } catch (IOException e) {
  308. e.printStackTrace();
  309. }
  310. }
  311. }
  312. return null;
  313. }
  314. public String saveImageToDiskNoImageCompress(String mediaId) throws Exception {
  315. // 文件保存的临时路径
  316. String tempPath = SystemConf.getInstance().getImagePath() + File.separator;
  317. // 拼接年月日路径
  318. String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
  319. // 重命名文件
  320. String newFileName = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000) + ".png";
  321. // 保存路径
  322. File uploadFile = new File(tempPath + datePath + newFileName);
  323. InputStream inputStream = null;
  324. FileOutputStream fileOutputStream = null;
  325. try {
  326. if (!uploadFile.getParentFile().exists()) {
  327. uploadFile.getParentFile().mkdirs();
  328. }
  329. inputStream = getInputStream(mediaId);//下载微信图片
  330. byte[] data = new byte[1024];
  331. int len = 0;
  332. fileOutputStream = new FileOutputStream(uploadFile);
  333. while ((len = inputStream.read(data)) != -1) {
  334. fileOutputStream.write(data, 0, len);
  335. }
  336. // 生成缩略图
  337. //ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
  338. // 返回保存路径
  339. return datePath + newFileName;
  340. } catch (IOException e) {
  341. e.printStackTrace();
  342. } finally {
  343. if (inputStream != null) {
  344. try {
  345. inputStream.close();
  346. } catch (IOException e) {
  347. e.printStackTrace();
  348. }
  349. }
  350. if (fileOutputStream != null) {
  351. try {
  352. fileOutputStream.close();
  353. } catch (IOException e) {
  354. e.printStackTrace();
  355. }
  356. }
  357. }
  358. return null;
  359. }
  360. /**
  361. * 获取微信服务器图片
  362. *
  363. * @return
  364. */
  365. public String fetchWxImages() {
  366. String photos = "";
  367. try {
  368. String images = request.getParameter("mediaIds");
  369. if (StringUtils.isEmpty(images)) {
  370. return photos;
  371. }
  372. String[] mediaIds = images.split(",");
  373. for (String mediaId : mediaIds) {
  374. if (StringUtils.isEmpty(mediaId)) {
  375. continue;
  376. }
  377. String temp = saveImageToDisk(mediaId);
  378. if (StringUtils.isNotEmpty(temp)) {
  379. if (photos.length() == 0) {
  380. photos = temp;
  381. } else {
  382. photos += "," + temp;
  383. }
  384. }
  385. }
  386. } catch (Exception e) {
  387. error(e);
  388. }
  389. return photos;
  390. }
  391. /**
  392. * 获取微信服务器语音
  393. *
  394. * @return
  395. */
  396. public String fetchWxVoices() {
  397. String voiceIds = "";
  398. try {
  399. String voices = request.getParameter("voices");
  400. if (StringUtils.isEmpty(voices)) {
  401. return voices;
  402. }
  403. String[] mediaIds = voices.split(",");
  404. for (String mediaId : mediaIds) {
  405. if (StringUtils.isEmpty(mediaId)) {
  406. continue;
  407. }
  408. String temp = saveVoiceToDisk(mediaId);
  409. if (StringUtils.isNotEmpty(temp)) {
  410. if (voiceIds.length() == 0) {
  411. voiceIds = temp;
  412. } else {
  413. voiceIds += "," + temp;
  414. }
  415. }
  416. }
  417. } catch (Exception e) {
  418. error(e);
  419. }
  420. return voiceIds;
  421. }
  422. /**
  423. * 获取下载语音信息(jpg)
  424. *
  425. * @param mediaId 文件的id
  426. * @throws Exception
  427. */
  428. public String saveVoiceToDisk(String mediaId) throws Exception {
  429. // 文件保存的临时路径
  430. String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
  431. // 拼接年月日路径
  432. String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
  433. // 重命名文件
  434. String newFileName = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000) + ".amr";
  435. // 保存路径
  436. File uploadFile = new File(tempPath + datePath + newFileName);
  437. InputStream inputStream = null;
  438. FileOutputStream fileOutputStream = null;
  439. try {
  440. if (!uploadFile.getParentFile().exists()) {
  441. uploadFile.getParentFile().mkdirs();
  442. }
  443. inputStream = getInputStream(mediaId);
  444. byte[] data = new byte[1024];
  445. int len = 0;
  446. fileOutputStream = new FileOutputStream(uploadFile);
  447. while ((len = inputStream.read(data)) != -1) {
  448. fileOutputStream.write(data, 0, len);
  449. }
  450. // 返回保存路径
  451. return datePath + newFileName;
  452. } catch (IOException e) {
  453. e.printStackTrace();
  454. } finally {
  455. if (inputStream != null) {
  456. try {
  457. inputStream.close();
  458. } catch (IOException e) {
  459. e.printStackTrace();
  460. }
  461. }
  462. if (fileOutputStream != null) {
  463. try {
  464. fileOutputStream.close();
  465. } catch (IOException e) {
  466. e.printStackTrace();
  467. }
  468. }
  469. }
  470. return null;
  471. }
  472. /**
  473. * 下载多媒体文件(请注意,视频文件不支持下载,调用该接口需http协议)
  474. *
  475. * @return
  476. */
  477. private InputStream getInputStream(String mediaId) {
  478. String accessToken = getAccessToken();
  479. InputStream is = null;
  480. String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
  481. try {
  482. URL urlGet = new URL(url);
  483. HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
  484. http.setRequestMethod("GET"); // 必须是get方式请求
  485. http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  486. http.setDoOutput(true);
  487. http.setDoInput(true);
  488. System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
  489. System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
  490. http.connect();
  491. // 获取文件转化为byte流
  492. is = http.getInputStream();
  493. } catch (Exception e) {
  494. e.printStackTrace();
  495. }
  496. return is;
  497. }
  498. }