WeixinBaseController.java 14 KB

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