WeixinBaseController.java 14 KB

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