美文网首页
Java web微信请求拦截器(微信公众号开发)

Java web微信请求拦截器(微信公众号开发)

作者: 酷酷的小k | 来源:发表于2019-01-24 21:59 被阅读0次

    Java web微信请求拦截器(微信公众号开发),获取微信用户信息。

    package com.mvc.interceptor;
    
    import com.alibaba.fastjson.JSONObject;
    import com.mvc.utils.HttpUtil;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.net.URLEncoder;
    
    /**
     * 微信请求拦截器
     *
     * @author smallk
     * @date 2018/12/3 0:39
     */
    public class WxRequestInterceptor implements HandlerInterceptor {
    
        @Value("${wx.appId}")
        private String appId;
    
        @Value("${wx.appSecret}")
        private String appSecret;
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) throws Exception {
            //
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView e) throws Exception {
            //
        }
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
            String backURL = request.getRequestURL().toString();
            if (request.getQueryString() != null) {
                backURL += "?" + request.getQueryString();
            }
            HttpSession session = request.getSession();
            String userAgent = request.getHeader("User-Agent");
            //判断是否是微信浏览器
            if (userAgent == null || !userAgent.toLowerCase().contains("micromessenger")) {
                return true;
            }
            JSONObject wxUserInfoJson = (JSONObject) session.getAttribute("sessionWxUserInfoJson");
            if (wxUserInfoJson != null) {
                return true;
            }
            String code = request.getParameter("code");
            // 第一次访问
            if (StringUtils.isBlank(code)) {
                response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="
                        + appId
                        + "&redirect_uri="
                        + URLEncoder.encode(backURL, "UTF-8")
                        + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
                return false;
            }
            // 微信认证回来
            JSONObject authJson = this.getOpenId(appId, appSecret, code);
            String openId = authJson.getString("openid");
            if (openId == null) {
                return false;
            }
            String accessToken = authJson.getString("access_token");
            wxUserInfoJson = this.getWxUserInfo(accessToken, openId);
            session.setAttribute("sessionWxUserInfoJson", wxUserInfoJson);
            return true;
        }
    
        private JSONObject getOpenId(String appId, String appSecret, String code) throws Exception {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                    + appId
                    + "&secret="
                    + appSecret
                    + "&code="
                    + code
                    + "&grant_type=authorization_code";
            String res = HttpUtil.getSSL(url, null, 0, 0);
            return JSONObject.parseObject(res);
        }
    
        private JSONObject getWxUserInfo(String accessToken, String openId) throws Exception {
            String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                    + accessToken
                    + "&openid="
                    + openId
                    + "&lang=zh_CN";
            String res = HttpUtil.getSSL(url, null, 0, 0);
            return JSONObject.parseObject(res);
        }
    }
    

    相关文章

      网友评论

          本文标题:Java web微信请求拦截器(微信公众号开发)

          本文链接:https://www.haomeiwen.com/subject/lxfpjqtx.html