WeixinBaseController.java 14 KB

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