WeixinUtil.java 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package com.izouma.awesomeadmin.util;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.InetAddress;
  7. import java.net.MalformedURLException;
  8. import java.net.URL;
  9. import java.net.URLConnection;
  10. import java.security.MessageDigest;
  11. import java.security.NoSuchAlgorithmException;
  12. import java.util.Arrays;
  13. import java.util.Formatter;
  14. import java.util.HashMap;
  15. import java.util.Map;
  16. import java.util.Random;
  17. import java.util.UUID;
  18. import org.apache.http.HttpResponse;
  19. import org.apache.http.ParseException;
  20. import org.apache.http.client.methods.HttpPost;
  21. import org.apache.http.entity.StringEntity;
  22. import org.apache.http.impl.client.DefaultHttpClient;
  23. import org.apache.http.util.EntityUtils;
  24. import org.apache.log4j.Logger;
  25. import org.json.JSONObject;
  26. import org.springframework.stereotype.Service;
  27. import com.izouma.awesomeadmin.dto.wx.TemplateMessage;
  28. import com.google.gson.Gson;
  29. /**
  30. * 微信工具类
  31. * @author
  32. *
  33. */
  34. @Service
  35. public class WeixinUtil {
  36. private final static String SEND_TEMPLAYE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
  37. private static Logger logger = Logger.getLogger(WeixinUtil.class);
  38. public static Map <String, String> sign(String jsapi_ticket, String url) {
  39. Map <String, String> ret = new HashMap <String, String>();
  40. String nonce_str = create_nonce_str();
  41. String timestamp = create_timestamp();
  42. String string1;
  43. String signature = "";
  44. //注意这里参数名必须全部小写,且必须有序
  45. string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
  46. System.out.println(string1);
  47. try {
  48. MessageDigest crypt = MessageDigest.getInstance("SHA-1");
  49. crypt.reset();
  50. crypt.update(string1.getBytes("UTF-8"));
  51. signature = byteToHex(crypt.digest());
  52. } catch (NoSuchAlgorithmException e) {
  53. e.printStackTrace();
  54. } catch (UnsupportedEncodingException e) {
  55. e.printStackTrace();
  56. }
  57. ret.put("url", url);
  58. ret.put("jsapi_ticket", jsapi_ticket);
  59. ret.put("nonceStr", nonce_str);
  60. ret.put("timestamp", timestamp);
  61. ret.put("signature", signature);
  62. return ret;
  63. }
  64. public static JSONObject loadJSON(String url) {
  65. StringBuilder json = new StringBuilder();
  66. try {
  67. URL oracle = new URL(url);
  68. URLConnection yc = oracle.openConnection();
  69. BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
  70. String inputLine = null;
  71. while ((inputLine = in.readLine()) != null) {
  72. json.append(inputLine);
  73. }
  74. in.close();
  75. } catch (MalformedURLException e) {
  76. } catch (IOException e) {
  77. }
  78. return new JSONObject(json.toString());
  79. }
  80. /**
  81. * 用SHA1算法生成安全签名
  82. * @param token 票据
  83. * @param timestamp 时间戳
  84. * @param nonce 随机字符串
  85. * @param encrypt 密文
  86. * @return 安全签名
  87. * @throws NoSuchAlgorithmException
  88. * @throws AesException
  89. */
  90. public String getSHA1(String token, String timestamp, String nonce) throws NoSuchAlgorithmException {
  91. String[] array = new String[] {token, timestamp, nonce};
  92. StringBuffer sb = new StringBuffer();
  93. // 字符串排序
  94. Arrays.sort(array);
  95. for (int i = 0; i < 3; i++) {
  96. sb.append(array[i]);
  97. }
  98. String str = sb.toString();
  99. // SHA1签名生成
  100. MessageDigest md = MessageDigest.getInstance("SHA-1");
  101. md.update(str.getBytes());
  102. byte[] digest = md.digest();
  103. StringBuffer hexstr = new StringBuffer();
  104. String shaHex = "";
  105. for (int i = 0; i < digest.length; i++) {
  106. shaHex = Integer.toHexString(digest[i] & 0xFF);
  107. if (shaHex.length() < 2) {
  108. hexstr.append(0);
  109. }
  110. hexstr.append(shaHex);
  111. }
  112. return hexstr.toString();
  113. }
  114. public static String byteToHex(final byte[] hash) {
  115. Formatter formatter = new Formatter();
  116. for (byte b : hash) {
  117. formatter.format("%02x", b);
  118. }
  119. String result = formatter.toString();
  120. formatter.close();
  121. return result;
  122. }
  123. public static String create_nonce_str() {
  124. return UUID.randomUUID().toString().replace("-", "");
  125. }
  126. public static String create_timestamp() {
  127. return Long.toString(System.currentTimeMillis() / 1000);
  128. }
  129. public static String create_out_trade_no() {
  130. return Long.toString(System.currentTimeMillis() / 1000) + getRandomNum(10);
  131. }
  132. private static String byteArrayToHexString(byte b[]) {
  133. StringBuffer resultSb = new StringBuffer();
  134. for (int i = 0; i < b.length; i++)
  135. resultSb.append(byteToHexString(b[i]));
  136. return resultSb.toString();
  137. }
  138. private static String byteToHexString(byte b) {
  139. int n = b;
  140. if (n < 0)
  141. n += 256;
  142. int d1 = n / 16;
  143. int d2 = n % 16;
  144. return hexDigits[d1] + hexDigits[d2];
  145. }
  146. public static String MD5Encode(String origin, String charsetname) {
  147. String resultString = null;
  148. try {
  149. resultString = new String(origin);
  150. MessageDigest md = MessageDigest.getInstance("MD5");
  151. if (charsetname == null || "".equals(charsetname))
  152. resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
  153. else
  154. resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
  155. } catch (Exception exception) {
  156. }
  157. return resultString;
  158. }
  159. private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
  160. /**
  161. *
  162. * <p>获取ip地址。</p>
  163. *
  164. * @return
  165. */
  166. @SuppressWarnings("static-access")
  167. public static String getHostAdderss() {
  168. InetAddress ia = null;
  169. try {
  170. ia = ia.getLocalHost();
  171. String localname = ia.getHostName();
  172. String localip = ia.getHostAddress();
  173. System.out.println("本机名称是:" + localname);
  174. System.out.println("本机的ip是 :" + localip);
  175. return localip;
  176. } catch (Exception e) {
  177. e.printStackTrace();
  178. }
  179. return null;
  180. }
  181. /**
  182. * 生成特定位数的随机数字
  183. * @param length
  184. * @return
  185. */
  186. public static String getRandomNum(int length) {
  187. String val = "";
  188. Random random = new Random();
  189. for (int i = 0; i < length; i++) {
  190. val += String.valueOf(random.nextInt(10));
  191. }
  192. return val;
  193. }
  194. /**
  195. * POST请求
  196. *
  197. * @param url
  198. * @param outStr
  199. * @return
  200. * @throws ParseException
  201. * @throws IOException
  202. */
  203. public static JSONObject doPostStr(String url, String outStr) throws ParseException, IOException {
  204. DefaultHttpClient client = new DefaultHttpClient();
  205. HttpPost httpost = new HttpPost(url);
  206. JSONObject jsonObject = null;
  207. httpost.setEntity(new StringEntity(outStr, "UTF-8"));
  208. HttpResponse response = client.execute(httpost);
  209. String result = EntityUtils.toString(response.getEntity(), "UTF-8");
  210. jsonObject = new JSONObject(result);
  211. return jsonObject;
  212. }
  213. public static void sendTemplateMessage(String accessToken, TemplateMessage templateMessage) throws ParseException, IOException {
  214. String jsonString = new Gson().toJson(templateMessage).toString();
  215. String requestUrl = SEND_TEMPLAYE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
  216. JSONObject result = WeixinUtil.doPostStr(requestUrl, jsonString);
  217. logger.info("jsonObject=" + result);
  218. if (null != result) {
  219. int errorCode = result.getInt("errcode");
  220. if (0 == errorCode) {
  221. logger.info("模板消息发送成功");
  222. } else {
  223. String errorMsg = result.getString("errmsg");
  224. logger.info("模板消息发送失败,错误是 " + errorCode + ",错误信息是" + errorMsg);
  225. }
  226. }
  227. }
  228. }