@Controller("wechatCodeController")
@RequestMapping({ "/wechatCode" })
public class WechatCodeController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(IndexController.class);
private static final String CACHE_NAME = "accessToken";
private static final String CACHE_CODE = "code";
/**
* 菜单关联
*/
@RequestMapping(value = { "/index" })
public String index(String code, String openid, ModelMap model,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
// 1. 点击个人中心菜单,获取openid
String sessionId = request.getSession().getId();
AccessToken accessToken = getCacheToken(sessionId);
// 判断缓存内token是否存在OpenId
if (accessToken == null || StringUtils.isBlank(accessToken.getOpenid())) {
// 不存在
// 判断code值是否已经使用过
if (!code.equals(getCacheCode(code))) {
// 在缓存 中设置code值
setCacheCode(code);
// 不存在,则说明code未使用过,则用来获取openid值
openid = oid(code, sessionId);
}
// 存在,不作任何操作
} else {
// 存在,直接从缓存中获取OpenId
openid = accessToken.getOpenid();
}
// 判断openid是否为空
if (StringUtils.isBlank(openid)) {
// 为空,则重新跳转到授权页面
// return "/shop/wechatCode/refresh";
return "redirect:refresh.jhtml";
} else {// 不为空
model.addAttribute("openid", openid);
request.getSession().setAttribute("openid", openid);
logger.warn("openid==" + openid);
//根据openid查经纪人
Pageable pageable = new Pageable();
pageable.addFilter("openid", Operator.eq, openid);
List<WecharMember> wecharMember = this.wecharMemberService.findList(pageable, "WecharMember");
if(wecharMember.size() > 0){
// 如果用户已经绑定账号,则跳到个人中心页面
return "redirect:person.jhtml";
}else{
// 则跳转到绑定页面
return "redirect:login.jhtml";
}
}
}
/**
- 进入超时重试页面
- @param model
- @return
*/
@RequestMapping(value = { "/refresh" }, method = { RequestMethod.GET })
public String refresh(ModelMap model) {
Setting setting = SettingUtils.get();
String url = setting.getSiteUrl() + "/wechatCode/index.jhtml";
try {
URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
model.addAttribute(
"oauthUrl",
"https://open.weixin.qq.com/connect/oauth2/authorize?appid="- WxConstants.APP_ID
- "&redirect_uri="
- url
- "&response_type=code&scope=snsapi_userinfo&state=pkb#wechat_redirect");
return "/shop/wechatCode/refresh";
}
/**
- 点击“个人中心“
- 先进入绑定页面
- success进入“个人中心”页面
- fail重绑
*/
@RequestMapping(value={"/login"},method={RequestMethod.GET})
public String login(ModelMap model, String openid, String error, HttpServletRequest req){
//进入绑定页面
if(openid == null){
if(req.getSession().getAttribute("openid") != null && !"".equals(req.getSession().getAttribute("openid"))){
openid = req.getSession().getAttribute("openid").toString();
}
}
model.addAttribute("openid", openid);
model.addAttribute("error", error);
System.out.println("openid---"+openid);
return "/shop/wechatCode/bind";
}
/** -
绑定
*/
@RequestMapping(value = { "/bind" }, method = {RequestMethod.GET })
public String bind(String username, String password,String openid,
ModelMap model,HttpServletResponse response, HttpServletRequest req, RedirectAttributes redirectAttributes) throws IOException {
Member member = null;
if(StringUtils.isNumeric(username)) {
//是否是手机号码登录
List<Member> members = this.memberService.findListByMobile(username);
if(members!=null && members.size()>0){
member = members.get(0);
}
} else {
member = this.memberService.findByUsername(username);
}
if(req.getSession().getAttribute("openid") != null && !"".equals(req.getSession().getAttribute("openid"))){
openid = req.getSession().getAttribute("openid").toString();
}
model.addAttribute("openid", openid);
model.addAttribute("member", member);
req.getSession().setAttribute("openid", openid);
req.getSession().setAttribute("username", username);
req.getSession().setAttribute("member", member);//进行绑定 if (member == null || !member.getPassword().equals(DigestUtils.md5Hex(password))) { model.addAttribute("username", username); model.addAttribute("error", "用户名或密码不正确!"); return "/shop/wechatCode/bind"; } else if (this.wecharMemberService.exists(new Filter("member", Filter.Operator.eq, member))) { // 判断该用户是否已经被绑定 //根据openid获取member信息 Pageable pageable = new Pageable(); pageable.addFilter("openid", Operator.eq, openid); pageable.addFilter("member", Operator.eq, member); List<WecharMember> mlist = this.wecharMemberService.findList(pageable, "WecharMember"); if(mlist.size() > 0){ //成功进入“个人中心”页面---表示openid与member一一对应 return "redirect:person.jhtml"; }else{ //表示此人的账号被别人尝试登录 model.addAttribute("error", "您的账号已在别处进行登录,请退出后再试!"); return "/shop/wechatCode/bind"; } } else if(this.wecharMemberService.exists(new Filter("openid", Operator.eq,openid))){ //提示用户,并跳转到相应的界面 model.addAttribute("error", "您的微信已经绑定了盘客宝账号,请退出再进入"); return "/shop/wechatCode/bind"; }else { WecharMember wecharMember = null; // 将用户与微信关联保存起来 wecharMember = new WecharMember(); wecharMember.setOpenid(openid); wecharMember.setMember(member); this.wecharMemberService.save(wecharMember); //成功进入“个人中心”页面 return "redirect:person.jhtml"; }
}
/** -
个人中心页面
*/
@SuppressWarnings("unused")
@RequestMapping(value={"/person"},method = { RequestMethod.GET })
public String person(ModelMap model,HttpServletRequest request,String error){// 获取错误信息 if (error != null) { // 若不为空 model.addAttribute("error", error); } if(request.getSession().getAttribute("openid") == null){ return "redirect:login.jhtml"; } String openid = request.getSession().getAttribute("openid").toString(); Member member = this.wecharMemberService.findByOpenid(openid).getMember(); request.getSession().setAttribute("member", member); Setting setting = SettingUtils.get(); if(member != null && !"".equals(member)){ if(member.getMemberParent() != null){ //进入新经纪人页面 model.addAttribute("parentId", member.getMemberParent()); model.addAttribute("member", member); if(!"".equals(member.getImage()) && member.getImage() != null){ model.addAttribute("image", member.getImage().replace("${siteUrl}", setting.getSiteUrl())); } }else{ //进入老经纪人页面--有二维码可邀请注册 model.addAttribute("parentId", ""); model.addAttribute("member", member); if(!"".equals(member.getImage()) && member.getImage() != null){ model.addAttribute("image", member.getImage().replace("${siteUrl}", setting.getSiteUrl())); } //生成个人二维码 if (member == null) { model.addAttribute("content", "经纪人信息异常"); } else { File imgDir = new File(this.fileService.getAbsPath() + "/upload/wechatCode/auto/"); if (!imgDir.exists()) { // 创建存储目录 imgDir.mkdirs(); } File regFile = new File(this.fileService.getAbsPath() + "/upload/wechatCode/auto/" + member.getId() + ".png"); String url = setting.getSiteUrl() + "/wechatCode/auto/" + member.getId() + ".jhtml"; model.addAttribute("url", url); qRCodeEncoder.encoderQRCode(url, regFile.getAbsolutePath()); if (regFile.exists()) { model.addAttribute("qrcode", setting.getSiteUrl() + "/upload/wechatCode/auto/" + member.getId() + ".png"); } } } } return "/shop/wechatCode/person";
}
/**
- https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=
- SECRET&code=CODE&grant_type=authorization_code
- 获取授权access_token
- @param code
- @param sessionId 会话ID
-
@return
*/
// @RequestMapping(value = { "/access_token" }, method = { RequestMethod.GET })
@ResponseBody
public AccessToken getAccessToken(String code,String sessionId) {String tokenUrl = SettingUtils.get().getAccessTokenUrl() + "?appid=" + WxConstants.APP_ID + "&secret=" + WxConstants.APP_SECRET + "&code=" + code + "&grant_type=authorization_code"; //logger.info("====tokenUrl===="+tokenUrl); if (logger.isDebugEnabled()) { logger.debug("tokenUrl:" + tokenUrl); } AccessToken token = null; // 发起GET请求获取凭证 JSONObject jsonObject = JSONObject.fromObject(WxCommonUtils .httpsRequest(tokenUrl, "POST", null)); //logger.info("====jsonObject===="+jsonObject.toString()); if (null != jsonObject) { logger.debug(jsonObject.toString()); try { token = new AccessToken(); token.setOpenid(jsonObject.getString("openid")); token.setRefresh_token(jsonObject.getString("refresh_token")); token.setAccess_token(jsonObject.getString("access_token")); token.setExpires_in(jsonObject.getInt("expires_in")); } catch (JSONException e) { e.printStackTrace(); token = null; // 获取token失败 logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } if (token != null) { //logger.debug("==token openid ==" + token.getOpenid()); setCacheToken(token,sessionId); } return token;
}
/** - 将code值保存至缓存中
- @param code
*/
private void setCacheCode(String code){
Element element = new Element(code, code);
cacheManager.getCache(CACHE_CODE).put(element);
}
/** - 从缓存中获取code值
- @param code
-
@return
*/
private String getCacheCode(String code){
Element element = cacheManager.getCache(CACHE_CODE).get(code);
return null == element ? null : (String) element.getObjectValue();
}private void setCacheToken(AccessToken token,String sessionId) {
Element element = new Element(sessionId, token);
getTokenCache().put(element);
}
private Cache getTokenCache() {
return cacheManager.getCache(CACHE_NAME);
}
/** - 获取缓存中的token值
- @param sessionId 会话ID
- @return
*/
private AccessToken getCacheToken(String sessionId) {
Element element = getTokenCache().get(sessionId);
return null == element ? null : (AccessToken) element.getObjectValue();
}
/** - 获取用户授权
- @param code
- @param type
- @return
*/
// @RequestMapping(value = { "/oid" }, method = { RequestMethod.GET })
@ResponseBody
public String oid(String code,String sessionId) {
String openid = null;
//logger.info("======code=======" + code);
AccessToken token = getAccessToken(code,sessionId);
if(token != null){
openid = token.getOpenid();
}
return openid;
}
/** -
微信js接入
*/
@RequestMapping(value = { "/sign" }, method = { RequestMethod.GET })
@ResponseBody
public JSONPObject sign(String timestamp, String url, String jsoncallback) {
if (StringUtils.isBlank(timestamp) || StringUtils.isBlank(url)) {
return null;
}
logger.debug("======timestamp=======" + timestamp);
logger.debug("======url=======" + url);
String jsApiTicket = TokenProxy.jsApiTicket();
String nonceStr = WxPaymentUtils.createNoncestr();
String signature = null;
try {
signature = WxJsSignUtils.signature(jsApiTicket, timestamp,
nonceStr, URLDecoder.decode(url, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//logger.debug("======signature=======" + signature);
JSONObject result = new JSONObject();
result.put("appId", WxConstants.APP_ID);
result.put("noncestr", nonceStr);
result.put("sign", signature);return new JSONPObject(jsoncallback, result);
}
@JsonIgnoreProperties(ignoreUnknown = true)
private static class SignupRequest extends SessionRequest{private String username; private String mobile; private String memberId; private String checkcode; private String gatewayId; private String name;
}
}