WeixinBaseController.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. System.out.println("getOpenidByCode:"+result);
  41. JSONObject json = new JSONObject(result);
  42. if (json.has("openid")) {
  43. return json.get("openid").toString();
  44. } else {
  45. return null;
  46. }
  47. } catch (Exception e) {
  48. error(e);
  49. }
  50. return null;
  51. }
  52. /**
  53. * 通过code获取判断openid
  54. *
  55. * @param code
  56. * @return
  57. */
  58. public String getOpenid(String code) {
  59. try {
  60. String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
  61. String params = "appid=" + SystemConf.getInstance().getAppId() + "&secret=" + SystemConf.getInstance().getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
  62. String result = HttpUtil.sendGet(token_url, params);
  63. JSONObject json = new JSONObject(result);
  64. Map<Object, Object> map = new HashMap<Object, Object>();
  65. if (json.has("openid")) {
  66. String openid = json.get("openid").toString();
  67. map.put("openid", openid);
  68. return write(200, "获取成功", "data", map);
  69. } else {
  70. return error(Integer.parseInt(json.get("errcode").toString()), "操作失败:" + json.get("errmsg").toString());
  71. }
  72. } catch (Exception e) {
  73. error(e);
  74. return invalidUserException(e, -1, "操作失败!");
  75. }
  76. }
  77. /**
  78. * 拼接地址?后的参数
  79. *
  80. * @param data
  81. * @param type
  82. * @return
  83. */
  84. public String getParamUrl(String data, int type) {
  85. try {
  86. JSONObject jsonData = new JSONObject(data);
  87. String id = jsonData.get("id").toString();
  88. String uid = jsonData.get("uid").toString();
  89. String name = jsonData.get("name").toString();
  90. String openid = jsonData.get("openid").toString();
  91. String photo = jsonData.get("photo").toString();
  92. String token = jsonData.get("token").toString();
  93. String paramUrl = "?type=" + type + "&id=" + id + "&uid=" + uid + "&name=" + name + "&openid=" + openid + "&photo=" + photo + "&token=" + token;
  94. return paramUrl;
  95. } catch (Exception e) {
  96. error(e);
  97. return "";
  98. }
  99. }
  100. /**
  101. * 获取微信的access_token
  102. *
  103. * @return
  104. */
  105. public String getAccessToken() {
  106. try {
  107. Iterable<AccessToken> accessTokens = accessTokenService.findAccessToken();
  108. if (accessTokens != null) {
  109. for (AccessToken accessToken : accessTokens) {
  110. if ((System.currentTimeMillis() - accessToken.getAdd_timestamp()) < (accessToken.getExpires_in() * 1000)) {
  111. return accessToken.getAccess_token();
  112. } else {
  113. accessTokenService.delAccessToken(accessToken);
  114. break;
  115. }
  116. }
  117. }
  118. String token_url = "https://api.weixin.qq.com/cgi-bin/token";
  119. String params = "grant_type=client_credential&appid=" + SystemConf.getInstance().getAppId() + "&secret=" + SystemConf.getInstance().getAppSecret();
  120. String result = HttpUtil.sendGet(token_url, params);
  121. JSONObject json = new JSONObject(result);
  122. if (json.has("access_token")) {
  123. String token = json.get("access_token").toString();
  124. String expires_in = json.get("expires_in").toString();
  125. AccessToken newaccessToken = new AccessToken();
  126. newaccessToken.setAccess_token(token);
  127. newaccessToken.setExpires_in(Long.parseLong(expires_in));
  128. accessTokenService.addAccessToken(newaccessToken);
  129. return token;
  130. } else {
  131. return null;
  132. }
  133. } catch (Exception e) {
  134. error(e);
  135. return null;
  136. }
  137. }
  138. /**
  139. * 获取微信的jsapi_ticket
  140. *
  141. * @return
  142. */
  143. public String getJsapi_ticketByToken() {
  144. try {
  145. Iterable<JsApiTicket> jsapiTickets = accessTokenService.findJsapiTicket();
  146. if (jsapiTickets != null) {
  147. for (JsApiTicket jsApiTicket : jsapiTickets) {
  148. if ((System.currentTimeMillis() - jsApiTicket.getAdd_timestamp()) < (jsApiTicket.getExpires_in() * 1000)) {
  149. return jsApiTicket.getJsapi_ticket();
  150. } else {
  151. accessTokenService.delJsapiTicket(jsApiTicket);
  152. break;
  153. }
  154. }
  155. }
  156. String token = getAccessToken();
  157. if (token != null) {
  158. String token_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
  159. String params = "access_token=" + token + "&type=jsapi";
  160. String result = HttpUtil.sendGet(token_url, params);
  161. JSONObject json = new JSONObject(result);
  162. if (json.has("ticket")) {
  163. String ticket = json.get("ticket").toString();
  164. String expires_in = json.get("expires_in").toString();
  165. JsApiTicket newJsApiTicket = new JsApiTicket();
  166. newJsApiTicket.setJsapi_ticket(ticket);
  167. newJsApiTicket.setExpires_in(Long.parseLong(expires_in));
  168. accessTokenService.addJsapiTicket(newJsApiTicket);
  169. return ticket;
  170. } else {
  171. return null;
  172. }
  173. } else {
  174. return null;
  175. }
  176. } catch (Exception e) {
  177. error(e);
  178. return null;
  179. }
  180. }
  181. /**
  182. * @description: SHA、SHA1加密 @parameter: str:待加密字符串 @return: 加密串
  183. **/
  184. public String SHA1(String str) {
  185. try {
  186. MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); // 如果是SHA加密只需要将"SHA-1"改成"SHA"即可
  187. digest.update(str.getBytes());
  188. byte messageDigest[] = digest.digest();
  189. // Create Hex String
  190. StringBuffer hexStr = new StringBuffer();
  191. // 字节数组转换为 十六进制 数
  192. for (int i = 0; i < messageDigest.length; i++) {
  193. String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
  194. if (shaHex.length() < 2) {
  195. hexStr.append(0);
  196. }
  197. hexStr.append(shaHex);
  198. }
  199. return hexStr.toString();
  200. } catch (Exception e) {
  201. error(e);
  202. }
  203. return null;
  204. }
  205. /**
  206. * 获取微信服务器图片
  207. *
  208. * @return
  209. */
  210. public String Images() {
  211. String photos = "";
  212. try {
  213. String images = request.getParameter("mediaIds");
  214. if (StringUtils.isEmpty(images)) {
  215. return photos;
  216. }
  217. String[] mediaIds = images.split(",");
  218. for (String mediaId : mediaIds) {
  219. if (StringUtils.isEmpty(mediaId)) {
  220. continue;
  221. }
  222. String temp = saveImageToDisk(mediaId);
  223. if (StringUtils.isNotEmpty(temp)) {
  224. if (photos.length() == 0) {
  225. photos = temp;
  226. } else {
  227. photos += "," + temp;
  228. }
  229. }
  230. }
  231. } catch (Exception e) {
  232. error(e);
  233. }
  234. return photos;
  235. }
  236. /**
  237. * 获取下载图片信息(jpg)
  238. *
  239. * @param mediaId 文件的id
  240. * @throws Exception
  241. */
  242. public String saveImageToDisk(String mediaId) throws Exception {
  243. // 文件保存的临时路径
  244. String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
  245. // 拼接年月日路径
  246. String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
  247. // 重命名文件
  248. String newFileName = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000) + ".png";
  249. // 保存路径
  250. File uploadFile = new File(tempPath + datePath + newFileName);
  251. InputStream inputStream = null;
  252. FileOutputStream fileOutputStream = null;
  253. try {
  254. if (!uploadFile.getParentFile().exists()) {
  255. uploadFile.getParentFile().mkdirs();
  256. }
  257. inputStream = getInputStream(mediaId);
  258. byte[] data = new byte[1024];
  259. int len = 0;
  260. fileOutputStream = new FileOutputStream(uploadFile);
  261. while ((len = inputStream.read(data)) != -1) {
  262. fileOutputStream.write(data, 0, len);
  263. }
  264. // 生成缩略图
  265. ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
  266. // 返回保存路径
  267. return datePath + newFileName;
  268. } catch (IOException e) {
  269. e.printStackTrace();
  270. } finally {
  271. if (inputStream != null) {
  272. try {
  273. inputStream.close();
  274. } catch (IOException e) {
  275. e.printStackTrace();
  276. }
  277. }
  278. if (fileOutputStream != null) {
  279. try {
  280. fileOutputStream.close();
  281. } catch (IOException e) {
  282. e.printStackTrace();
  283. }
  284. }
  285. }
  286. return null;
  287. }
  288. public String saveImageToDiskNoImageCompress(String mediaId) throws Exception {
  289. // 文件保存的临时路径
  290. String tempPath = SystemConf.getInstance().getImagePath() + File.separator;
  291. // 拼接年月日路径
  292. String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
  293. // 重命名文件
  294. String newFileName = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000) + ".png";
  295. // 保存路径
  296. File uploadFile = new File(tempPath + datePath + newFileName);
  297. InputStream inputStream = null;
  298. FileOutputStream fileOutputStream = null;
  299. try {
  300. if (!uploadFile.getParentFile().exists()) {
  301. uploadFile.getParentFile().mkdirs();
  302. }
  303. inputStream = getInputStream(mediaId);//下载微信图片
  304. byte[] data = new byte[1024];
  305. int len = 0;
  306. fileOutputStream = new FileOutputStream(uploadFile);
  307. while ((len = inputStream.read(data)) != -1) {
  308. fileOutputStream.write(data, 0, len);
  309. }
  310. return datePath + newFileName;
  311. } catch (IOException e) {
  312. e.printStackTrace();
  313. } finally {
  314. if (inputStream != null) {
  315. try {
  316. inputStream.close();
  317. } catch (IOException e) {
  318. e.printStackTrace();
  319. }
  320. }
  321. if (fileOutputStream != null) {
  322. try {
  323. fileOutputStream.close();
  324. } catch (IOException e) {
  325. e.printStackTrace();
  326. }
  327. }
  328. }
  329. return null;
  330. }
  331. /**
  332. * 获取微信服务器图片
  333. *
  334. * @return
  335. */
  336. public String fetchWxImages() {
  337. String photos = "";
  338. try {
  339. String images = request.getParameter("mediaIds");
  340. if (StringUtils.isEmpty(images)) {
  341. return photos;
  342. }
  343. String[] mediaIds = images.split(",");
  344. for (String mediaId : mediaIds) {
  345. if (StringUtils.isEmpty(mediaId)) {
  346. continue;
  347. }
  348. String temp = saveImageToDisk(mediaId);
  349. if (StringUtils.isNotEmpty(temp)) {
  350. if (photos.length() == 0) {
  351. photos = temp;
  352. } else {
  353. photos += "," + temp;
  354. }
  355. }
  356. }
  357. } catch (Exception e) {
  358. error(e);
  359. }
  360. return photos;
  361. }
  362. /**
  363. * 获取微信服务器语音
  364. *
  365. * @return
  366. */
  367. public String fetchWxVoices() {
  368. String voiceIds = "";
  369. try {
  370. String voices = request.getParameter("voices");
  371. if (StringUtils.isEmpty(voices)) {
  372. return voices;
  373. }
  374. String[] mediaIds = voices.split(",");
  375. for (String mediaId : mediaIds) {
  376. if (StringUtils.isEmpty(mediaId)) {
  377. continue;
  378. }
  379. String temp = saveVoiceToDisk(mediaId);
  380. if (StringUtils.isNotEmpty(temp)) {
  381. if (voiceIds.length() == 0) {
  382. voiceIds = temp;
  383. } else {
  384. voiceIds += "," + temp;
  385. }
  386. }
  387. }
  388. } catch (Exception e) {
  389. error(e);
  390. }
  391. return voiceIds;
  392. }
  393. /**
  394. * 获取下载语音信息(jpg)
  395. *
  396. * @param mediaId 文件的id
  397. * @throws Exception
  398. */
  399. public String saveVoiceToDisk(String mediaId) throws Exception {
  400. // 文件保存的临时路径
  401. String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
  402. // 拼接年月日路径
  403. String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
  404. // 重命名文件
  405. String fileBase = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000);
  406. String newFileName = fileBase+ ".amr";
  407. String mp3FileName = fileBase + ".mp3";
  408. // 保存路径
  409. File uploadFile = new File(tempPath + datePath + newFileName);
  410. InputStream inputStream = null;
  411. FileOutputStream fileOutputStream = null;
  412. try {
  413. if (!uploadFile.getParentFile().exists()) {
  414. uploadFile.getParentFile().mkdirs();
  415. }
  416. inputStream = getInputStream(mediaId);
  417. byte[] data = new byte[1024];
  418. int len = 0;
  419. fileOutputStream = new FileOutputStream(uploadFile);
  420. while ((len = inputStream.read(data)) != -1) {
  421. fileOutputStream.write(data, 0, len);
  422. }
  423. String amrFilePath = tempPath+datePath+newFileName;
  424. String Mp3FilePath = tempPath+datePath+mp3FileName;
  425. CommonUtil.changeToMp3(amrFilePath,Mp3FilePath);
  426. // 返回保存路径
  427. return Mp3FilePath;
  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. /**
  475. * 获取Open
  476. * @param code
  477. * @return
  478. * @throws Exception
  479. */
  480. public String getOpenId(String code) throws Exception {
  481. String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
  482. String params = "appid=" + SystemConf.getInstance().getAppId() + "&secret=" + SystemConf.getInstance().getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
  483. String result = HttpUtil.sendGet(token_url, params);
  484. JSONObject json = new JSONObject(result);
  485. if (json.has("openid")) {
  486. return json.get("openid").toString();
  487. } else {
  488. return null;
  489. }
  490. }
  491. /**
  492. * 获取subscribe
  493. * @param openid
  494. * @return
  495. * @throws Exception
  496. */
  497. public String getIsSus(String openid) throws Exception{
  498. String userInfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + getAccessToken() + "&openid=" + openid + "&lang=zh_CN";
  499. String params = "";
  500. String result = HttpUtil.sendGet(userInfo_url, params);
  501. JSONObject json = new JSONObject(result);
  502. if (json.has("subscribe")) {
  503. return json.get("subscribe").toString();
  504. } else {
  505. return null;
  506. }
  507. }
  508. /**
  509. * 获取Subscribe
  510. * @param code
  511. * @return
  512. * @throws Exception
  513. */
  514. public String getSubscribeByCode(String code)throws Exception{
  515. return getIsSus(getOpenid(code));
  516. }
  517. }