UserController.java 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package com.hssx.controller;
  2. import java.io.IOException;
  3. import java.security.KeyManagementException;
  4. import java.security.NoSuchAlgorithmException;
  5. import java.security.NoSuchProviderException;
  6. import java.util.Date;
  7. import java.util.SortedMap;
  8. import java.util.TreeMap;
  9. import javax.servlet.http.HttpServletResponse;
  10. import org.apache.commons.httpclient.HttpClient;
  11. import org.apache.commons.httpclient.methods.GetMethod;
  12. import org.apache.commons.httpclient.methods.PostMethod;
  13. import org.apache.commons.lang.StringEscapeUtils;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.stereotype.Controller;
  16. import org.springframework.web.bind.annotation.RequestMapping;
  17. import org.springframework.web.bind.annotation.RequestParam;
  18. import com.alibaba.fastjson.JSON;
  19. import com.alibaba.fastjson.JSONObject;
  20. import com.estates.filter.EmojiHttpServletRequestWraper;
  21. import com.hssx.constant.Constant;
  22. import com.hssx.entity.User;
  23. import com.hssx.entity.UserExample;
  24. import com.hssx.mapper.UserMapper;
  25. import com.hssx.mapper.WxParamMapper;
  26. import com.hssx.model.WxParam;
  27. import com.hssx.model.WxParamExample;
  28. import com.hssx.utils.HttpKit;
  29. import com.hssx.utils.HttpRespMsg;
  30. import com.hssx.utils.JsapiTicketUtil;
  31. import com.hssx.utils.Sha1Util;
  32. @Controller
  33. @RequestMapping("/user")
  34. public class UserController {
  35. @Autowired
  36. UserMapper usermapper;
  37. @Autowired
  38. WxParamMapper wxParamMapper;
  39. public static int WX_TOKEN_EXPIRE = 7200*1000;
  40. /**
  41. * 微信授权登录 参数: type:授权类型,0-微信,1-微博 code:平台返回的code值
  42. *
  43. * @return
  44. */
  45. @RequestMapping(value = "weiXinLogin")
  46. public void weiXinLogin(@RequestParam String code, @RequestParam Integer type, HttpServletResponse response)
  47. throws Exception, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
  48. HttpRespMsg msg = new HttpRespMsg();
  49. User user = new User();
  50. user.setType(type);
  51. UserExample example = new UserExample();
  52. if (type == 0) {
  53. String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constant.WECHAT_APPID + "&secret="
  54. + Constant.WECHAT_APPSECRET + "&code=" + code + "&grant_type=authorization_code";
  55. String resp = HttpKit.get(url, true);
  56. resp = StringEscapeUtils.unescapeJava(resp);
  57. System.out.println(resp);
  58. JSONObject json = (JSONObject) JSON.parse(resp);
  59. if (!json.containsKey("errcode")) {
  60. String openId = json.getString("openid");
  61. String accessToken = json.getString("access_token");
  62. user.setVoucherId(openId);
  63. String url1 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId
  64. + "&lang=zh_CN";
  65. // 获取用户基本信息
  66. resp = HttpKit.get(url1, true);
  67. resp = StringEscapeUtils.unescapeJava(resp);
  68. System.out.println(resp);
  69. json = (JSONObject) JSON.parse(resp);
  70. if (!json.containsKey("errcode")) {
  71. user.setNickName(EmojiHttpServletRequestWraper.filterEmoji(json.getString("nickname")));
  72. user.setHeaderPic(json.getString("headimgurl"));
  73. }
  74. System.out.println(user + "user");
  75. example.createCriteria().andVoucherIdEqualTo(openId).andTypeEqualTo(type);
  76. if (usermapper.countByExample(example) == 0) {
  77. usermapper.insert(user);
  78. } else {
  79. // 列表中已包含当前用户,
  80. user = usermapper.selectByExample(example).get(0);
  81. if (null == user.getNickName() && null == user.getHeaderPic()) {
  82. user.setNickName(json.getString("nickname"));
  83. user.setHeaderPic(json.getString("headimgurl"));
  84. usermapper.updateByPrimaryKeySelective(user);
  85. }
  86. }
  87. msg.data = user;
  88. } else {
  89. msg.setError(json.getString("errmsg"));
  90. }
  91. } else if (type == 1) {
  92. // String url2 =
  93. // "https://api.weibo.com/oauth2/access_token?client_id=" +
  94. // Constant.MICROBLOG_APPKEY
  95. // + "&client_secret=" + Constant.MICROBLOG_APPSECRET +
  96. // "&grant_type=authoriz";
  97. // HashMap<String, String> token = new HashMap<String, String>();
  98. // 本机运行时会报证书错误
  99. /*
  100. * ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
  101. * Protocol.registerProtocol("https", new Protocol("https", fcty,
  102. * 443));
  103. */
  104. PostMethod postMethod = new PostMethod("https://api.weibo.com/oauth2/access_token");
  105. postMethod.addParameter("grant_type", "authorization_code");
  106. postMethod.addParameter("code", code);
  107. postMethod.addParameter("redirect_uri", Constant.CALLBACKURL);
  108. postMethod.addParameter("client_id", Constant.MICROBLOG_APPKEY);
  109. postMethod.addParameter("client_secret", Constant.MICROBLOG_APPSECRET);
  110. HttpClient client = new HttpClient();
  111. try {
  112. client.executeMethod(postMethod);
  113. String responseDate = postMethod.getResponseBodyAsString();
  114. if (!responseDate.equals("") && responseDate.indexOf("access_token") != -1) {
  115. System.out.println("responseDate=======>"+responseDate);
  116. JSONObject jsonData = JSONObject.parseObject(responseDate);
  117. System.out.println("jsonData===>"+jsonData);
  118. String uid = jsonData.getString("uid");
  119. user.setVoucherId(uid);
  120. String accessToken = jsonData.getString("access_token");
  121. String url = "https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + uid;
  122. GetMethod getMethod = new GetMethod(url);
  123. client = new HttpClient();
  124. try {
  125. client.executeMethod(getMethod);
  126. responseDate = getMethod.getResponseBodyAsString();
  127. jsonData = JSONObject.parseObject(responseDate);
  128. System.out.println("返回User jsonData===>"+jsonData);
  129. user.setNickName(jsonData.getString("name"));
  130. user.setHeaderPic(jsonData.getString("profile_image_url"));
  131. example.createCriteria().andVoucherIdEqualTo(uid).andTypeEqualTo(type);
  132. if (usermapper.countByExample(example) == 0) {
  133. usermapper.insert(user);
  134. } else {
  135. // 列表中已包含当前用户,
  136. user = usermapper.selectByExample(example).get(0);
  137. if (null == user.getNickName() && null == user.getHeaderPic()) {
  138. user.setNickName(jsonData.getString("name"));
  139. user.setHeaderPic(jsonData.getString("profile_image_url"));
  140. usermapper.updateByPrimaryKeySelective(user);
  141. }
  142. }
  143. System.out.println("微博user----->"+user);
  144. msg.data = user;
  145. } catch (Exception e) {
  146. e.printStackTrace();
  147. }
  148. }
  149. } catch (Exception e) {
  150. e.printStackTrace();
  151. }
  152. }
  153. response.setContentType("application/json");
  154. response.setCharacterEncoding("UTF-8");
  155. response.getWriter().println(msg.toJSONStr());
  156. }
  157. /**
  158. * 根据userId获取用户信息 id
  159. * 参数 :id:用户id
  160. * @param response
  161. * @throws IOException
  162. */
  163. @RequestMapping(value = "getUser")
  164. public void getUser(User user,HttpServletResponse response) throws IOException{
  165. HttpRespMsg msg = new HttpRespMsg();
  166. user = usermapper.selectByPrimaryKey(user.getId());
  167. msg.data = user;
  168. response.setContentType("application/json");
  169. response.setCharacterEncoding("UTF-8");
  170. response.getWriter().println(msg.toJSONStr());
  171. }
  172. /**
  173. * 获取微信JS config参数
  174. * @param url
  175. * @param response
  176. * @return
  177. * @throws Exception
  178. */
  179. @RequestMapping(value="getWxConfigParam")
  180. public String getWxConfigParam(
  181. @RequestParam String url,
  182. HttpServletResponse response) throws Exception {
  183. HttpRespMsg msg = new HttpRespMsg();
  184. System.out.println("接收到url=="+url);
  185. WxParamExample example = new WxParamExample();
  186. Date d = new Date(System.currentTimeMillis() - WX_TOKEN_EXPIRE);
  187. example.createCriteria().andIndateGreaterThan(d);
  188. example.setOrderByClause("id desc limit 1");
  189. String jsapiTicket = "";
  190. if (wxParamMapper.countByExample(example) == 0) {
  191. jsapiTicket = JsapiTicketUtil.getJSApiTicket();
  192. WxParam record = new WxParam();
  193. record.setJsapiTicket(jsapiTicket);
  194. wxParamMapper.insertSelective(record);
  195. } else {
  196. jsapiTicket = wxParamMapper.selectByExample(example).get(0).getJsapiTicket();
  197. }
  198. // 随机数
  199. String nonce_str = Sha1Util.getNonceStr();
  200. String timestamp = Sha1Util.getTimeStamp();
  201. // 对以下字段进行签名
  202. SortedMap<String, String> packageParams = new TreeMap<String, String>();
  203. packageParams.put("jsapi_ticket", jsapiTicket);
  204. packageParams.put("noncestr", nonce_str);
  205. packageParams.put("timestamp", ""+timestamp);
  206. packageParams.put("url", url);
  207. String sign = Sha1Util.createSHA1Sign(packageParams);
  208. packageParams.put("sign", sign);
  209. packageParams.put("appid", Constant.WECHAT_APPID);
  210. msg.data = packageParams;
  211. response.setContentType("application/json");
  212. response.setCharacterEncoding("UTF-8");
  213. response.getWriter().println(msg.toJSONStr());
  214. return null;
  215. }
  216. }