package com.xcd.zc.controller;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xcd.zc.model.entity.TUser;
import com.xcd.zc.service.UserService;
import com.xcd.zc.utils.CommonPropertyUtil;
import com.xcd.zc.utils.HttpClientUtil;
import com.xcd.zc.utils.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.apache.http.client.HttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.poi.util.StringUtil;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xcd.zc.utils.SHA1;
import org.springframework.web.servlet.ModelAndView;
import sun.net.www.http.HttpClient;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.registry.infomodel.User;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping(value = "/wxconfig")
public class WxConfigController {
@Autowired
private UserService userService;
//这个token要与公众平台服务器配置填写的token一致
private final static String token = CommonPropertyUtil.getProperty("wx_token");
private Logger log = Logger.getLogger(WxConfigController.class);
@RequestMapping(value = "/verifyWXConfig", method = RequestMethod.GET)
@ResponseBody
public String verifyWXConfig(@RequestParam(value = "signature", required = false) String signature,
@RequestParam(value = "timestamp", required = false) String timestamp,
@RequestParam(value = "nonce", required = false) String nonce,
@RequestParam(value = "echostr", required = false) String echostr) {
System.out.println(" PARAM VAL: >>>" + signature + "\t" + timestamp + "\t" + nonce + "\t" + echostr);
log.info("开始签名验证:" + " PARAM VAL: >>>" + signature + "\t" + timestamp + "\t" + nonce + "\t" + echostr);
if (StringUtils.isNotEmpty(signature)
&& StringUtils.isNotEmpty(timestamp)
&& StringUtils.isNotEmpty(nonce)
&& StringUtils.isNotEmpty(echostr)) {
String sTempStr = "";
try {
sTempStr = SHA1.getSHA1(timestamp, nonce, token, "");
} catch (Exception e) {
e.printStackTrace();
}
if (StringUtils.isNotEmpty(sTempStr) && signature.equals(sTempStr)) {
log.info("验证成功:-----------:" + sTempStr);
return echostr;
} else {
log.info("验证失败:-----------:00000");
return "-1";
}
} else {
log.info("验证失败:-----------:11111");
return "-1";
}
}
//微信里面填写的就是这个url 用户点击这个url就会跳到授权页面
@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public void redirectToMyPage(HttpServletRequest request, HttpServletResponse response) {
StringBuffer sb = new StringBuffer();
StringBuffer encodeUrl = new StringBuffer(300);
String doname = CommonPropertyUtil.getProperty("wx_doname");//公众号中配置的回调域名(网页授权回调域名)
String root = request.getContextPath();
String appId = CommonPropertyUtil.getProperty("wx_appid");
log.info("doname=" + doname + ", appId = " + appId);
sb.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
sb.append(appId);
String url = "";
try { //对重定向url进行编码,官方文档要求
encodeUrl.append("http://").append(doname).append(root).append("/wxconfig/wxauth.html");
url = URLEncoder.encode(encodeUrl.toString(), "utf-8");
sb.append("&redirect_uri=").append(url); //网页授权的静默授权snsapi_base
sb.append("&response_type=code&scope=snsapi_userinfo&state=ycgj123#wechat_redirect");
response.sendRedirect(sb.toString());
} catch (UnsupportedEncodingException e) {
log.error("重定向url编码失败:>>" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
log.error("response重定向失败:>>" + e.getMessage());
e.printStackTrace();
}
}
/*微信回调这个url 在这里获取code*/
@RequestMapping(value = "/wxauth.html", method = RequestMethod.GET)
public ModelAndView wxauth(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mv = new ModelAndView("redirect:/yicheng/index.html");
String code = request.getParameter("code");//获取重定向携带的code参数值
Map access_tokenMap = getAccess_token(request,response,code);
if (access_tokenMap == null){
mv.setViewName("redirect:/yicheng/error.html"); //要写一个error页面
}else{
String access_token = String.valueOf(access_tokenMap.get("access_token"));
String openid = String.valueOf(access_tokenMap.get("openid"));
log.info("获取的access_token:" + access_token);
log.info("获取的openid:" + openid);
/* * 将openId保存到session中,当其他业务获取access_token时, * 可先从session中获取access_token. */
request.getSession().setAttribute("access_token", access_token);
request.getSession().setAttribute("openid", openid);
String userId = getWechatUserInfo(openid,access_token);
if(userId.equals("")){
mv.setViewName("redirect:/yicheng/error.html"); //要写一个error页面
}else{
Map params = new HashMap();
params.put("userId",userId);
}
}
return mv;
}
/*发送请求,根据code获取getAccess_token*/
public Map getAccess_token(HttpServletRequest request, HttpServletResponse response, String code) {
String content = "";
StringBuffer url = new StringBuffer();
Map map = null;
url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
.append(CommonPropertyUtil.getProperty("wx_appid"))
.append("&secret=")
.append(CommonPropertyUtil.getProperty("wx_appsecret"))
.append("&code=")
.append(code)
.append("&grant_type=authorization_code");
ObjectMapper objectMapper = new ObjectMapper();
try {
HttpClientUtil httpClientUtil = new HttpClientUtil();
HttpResponse httpResponse = httpClientUtil.doGet(url);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
content = EntityUtils.toString(entity, "utf-8");
}
map = objectMapper.readValue(content, Map.class);
} catch (JsonParseException e) {
log.error("json解析失败:", e);
} catch (JsonMappingException e) {
log.error("map转换成json失败:", e);
} catch (Exception e) {
log.error("http获取openId请求失败:", e);
}
return map;
}
public String getWechatUserInfo(String openId, String accessToken) {
//构造获取用户基本信息api
StringBuffer url = new StringBuffer();
url.append("https://api.weixin.qq.com/sns/userinfo?").append("access_token=").append(accessToken).append("&openid=").append(openId).append("&lang=zh_CN");
String content = "";
ObjectMapper objectMapper = new ObjectMapper();
String userid = "";
try {
for (int i = 1; i <= 5; i++) { //content就是json格式的用户信息
HttpClientUtil httpClientUtil = new HttpClientUtil();
HttpEntity httpEntity = httpClientUtil.doGet(url).getEntity();
if (httpEntity != null) {
content = EntityUtils.toString(httpEntity, "utf-8");
}
log.info("获取微信用户请求响应信息:>>" + content);
Map map = objectMapper.readValue(content, Map.class);
Object mopenId = map.get("openid");
Object nickName = map.get("nickname");
log.info("第" + i + "次获取openId=" + openId + "的微信用户昵称:>>" + nickName);
if (openId.equals(mopenId) && nickName != null) {
String sex = String.valueOf(map.get("sex"));
String province = String.valueOf(map.get("province"));
String city = String.valueOf(map.get("city"));
String country = String.valueOf(map.get("country"));
String headimgurl = String.valueOf(map.get("headimgurl"));
String nickname = String.valueOf(nickName);
TUser user = userService.getOpenidUser(openId);
if (user == null){
TUser new_user = new TUser();
new_user.setOpenid(openId);
new_user.setNickname(nickname);
new_user.setProvince(province);
new_user.setCity(city);
new_user.setCountry(country);
new_user.setHeadimgurl(headimgurl);
new_user.setSex(sex);
boolean flag = userService.addWxUser(new_user);
if (flag){
TUser user1 = userService.getOpenidUser(openId);
if (user1 != null){
userid = user1.getId().toString();
}
}
}else{
userService.updateWxUser(nickname,sex,province,city,country,headimgurl,openId);
userid = user.getId().toString();
}
break;
}
log.info("第" + i + "次获取openId=" + openId + "的微信用户信息失败!!");
}
} catch (JsonParseException e) {
log.error("获取微信基本用户信息时,json转换失败:>>", e);
e.printStackTrace();
} catch (Exception e) {
log.error("http请求执行错误:>>", e);
e.printStackTrace();
}
// return user == null ? new Users() : user;
log.error("http请求执行返回的userId = :>>"+userid);
return userid;//返回的是userid
}
}