package com.hssx.controller; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.util.Date; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.lang.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.estates.filter.EmojiHttpServletRequestWraper; import com.hssx.constant.Constant; import com.hssx.entity.User; import com.hssx.entity.UserExample; import com.hssx.mapper.UserMapper; import com.hssx.mapper.WxParamMapper; import com.hssx.model.WxParam; import com.hssx.model.WxParamExample; import com.hssx.utils.HttpKit; import com.hssx.utils.HttpRespMsg; import com.hssx.utils.JsapiTicketUtil; import com.hssx.utils.Sha1Util; @Controller @RequestMapping("/user") public class UserController { @Autowired UserMapper usermapper; @Autowired WxParamMapper wxParamMapper; public static int WX_TOKEN_EXPIRE = 7200*1000; /** * 微信授权登录 参数: type:授权类型,0-微信,1-微博 code:平台返回的code值 * * @return */ @RequestMapping(value = "weiXinLogin") public void weiXinLogin(@RequestParam String code, @RequestParam Integer type, HttpServletResponse response) throws Exception, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException { HttpRespMsg msg = new HttpRespMsg(); User user = new User(); user.setType(type); UserExample example = new UserExample(); if (type == 0) { String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constant.WECHAT_APPID + "&secret=" + Constant.WECHAT_APPSECRET + "&code=" + code + "&grant_type=authorization_code"; String resp = HttpKit.get(url, true); resp = StringEscapeUtils.unescapeJava(resp); System.out.println(resp); JSONObject json = (JSONObject) JSON.parse(resp); if (!json.containsKey("errcode")) { String openId = json.getString("openid"); String accessToken = json.getString("access_token"); user.setVoucherId(openId); String url1 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN"; // 获取用户基本信息 resp = HttpKit.get(url1, true); resp = StringEscapeUtils.unescapeJava(resp); System.out.println(resp); json = (JSONObject) JSON.parse(resp); if (!json.containsKey("errcode")) { user.setNickName(EmojiHttpServletRequestWraper.filterEmoji(json.getString("nickname"))); user.setHeaderPic(json.getString("headimgurl")); } System.out.println(user + "user"); example.createCriteria().andVoucherIdEqualTo(openId).andTypeEqualTo(type); if (usermapper.countByExample(example) == 0) { usermapper.insert(user); } else { // 列表中已包含当前用户, user = usermapper.selectByExample(example).get(0); if (null == user.getNickName() && null == user.getHeaderPic()) { user.setNickName(json.getString("nickname")); user.setHeaderPic(json.getString("headimgurl")); usermapper.updateByPrimaryKeySelective(user); } } msg.data = user; } else { msg.setError(json.getString("errmsg")); } } else if (type == 1) { // String url2 = // "https://api.weibo.com/oauth2/access_token?client_id=" + // Constant.MICROBLOG_APPKEY // + "&client_secret=" + Constant.MICROBLOG_APPSECRET + // "&grant_type=authoriz"; // HashMap token = new HashMap(); // 本机运行时会报证书错误 /* * ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory(); * Protocol.registerProtocol("https", new Protocol("https", fcty, * 443)); */ PostMethod postMethod = new PostMethod("https://api.weibo.com/oauth2/access_token"); postMethod.addParameter("grant_type", "authorization_code"); postMethod.addParameter("code", code); postMethod.addParameter("redirect_uri", Constant.CALLBACKURL); postMethod.addParameter("client_id", Constant.MICROBLOG_APPKEY); postMethod.addParameter("client_secret", Constant.MICROBLOG_APPSECRET); HttpClient client = new HttpClient(); try { client.executeMethod(postMethod); String responseDate = postMethod.getResponseBodyAsString(); if (!responseDate.equals("") && responseDate.indexOf("access_token") != -1) { System.out.println("responseDate=======>"+responseDate); JSONObject jsonData = JSONObject.parseObject(responseDate); System.out.println("jsonData===>"+jsonData); String uid = jsonData.getString("uid"); user.setVoucherId(uid); String accessToken = jsonData.getString("access_token"); String url = "https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + uid; GetMethod getMethod = new GetMethod(url); client = new HttpClient(); try { client.executeMethod(getMethod); responseDate = getMethod.getResponseBodyAsString(); jsonData = JSONObject.parseObject(responseDate); System.out.println("返回User jsonData===>"+jsonData); user.setNickName(jsonData.getString("name")); user.setHeaderPic(jsonData.getString("profile_image_url")); example.createCriteria().andVoucherIdEqualTo(uid).andTypeEqualTo(type); if (usermapper.countByExample(example) == 0) { usermapper.insert(user); } else { // 列表中已包含当前用户, user = usermapper.selectByExample(example).get(0); if (null == user.getNickName() && null == user.getHeaderPic()) { user.setNickName(jsonData.getString("name")); user.setHeaderPic(jsonData.getString("profile_image_url")); usermapper.updateByPrimaryKeySelective(user); } } System.out.println("微博user----->"+user); msg.data = user; } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().println(msg.toJSONStr()); } /** * 根据userId获取用户信息 id * 参数 :id:用户id * @param response * @throws IOException */ @RequestMapping(value = "getUser") public void getUser(User user,HttpServletResponse response) throws IOException{ HttpRespMsg msg = new HttpRespMsg(); user = usermapper.selectByPrimaryKey(user.getId()); msg.data = user; response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().println(msg.toJSONStr()); } /** * 获取微信JS config参数 * @param url * @param response * @return * @throws Exception */ @RequestMapping(value="getWxConfigParam") public String getWxConfigParam( @RequestParam String url, HttpServletResponse response) throws Exception { HttpRespMsg msg = new HttpRespMsg(); System.out.println("接收到url=="+url); WxParamExample example = new WxParamExample(); Date d = new Date(System.currentTimeMillis() - WX_TOKEN_EXPIRE); example.createCriteria().andIndateGreaterThan(d); example.setOrderByClause("id desc limit 1"); String jsapiTicket = ""; if (wxParamMapper.countByExample(example) == 0) { jsapiTicket = JsapiTicketUtil.getJSApiTicket(); WxParam record = new WxParam(); record.setJsapiTicket(jsapiTicket); wxParamMapper.insertSelective(record); } else { jsapiTicket = wxParamMapper.selectByExample(example).get(0).getJsapiTicket(); } // 随机数 String nonce_str = Sha1Util.getNonceStr(); String timestamp = Sha1Util.getTimeStamp(); // 对以下字段进行签名 SortedMap packageParams = new TreeMap(); packageParams.put("jsapi_ticket", jsapiTicket); packageParams.put("noncestr", nonce_str); packageParams.put("timestamp", ""+timestamp); packageParams.put("url", url); String sign = Sha1Util.createSHA1Sign(packageParams); packageParams.put("sign", sign); packageParams.put("appid", Constant.WECHAT_APPID); msg.data = packageParams; response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().println(msg.toJSONStr()); return null; } }