WeixinBaseController.java 16 KB

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