微信公众号自动登录

JerryXia 发表于 , 阅读 (0)
除了QQ, 当前最火爆的社交工具无非是微信, 或许连QQ都难以匹敌, 更重要的是其更是一个平台, 一个可持续扩展的平台, 无论是公众号, 微店, 支付等, 都使得微信被运用得更为广, 再而深。之前做了一个关于公众号对接的, 实现用户只需第一次登录即可永久自动登录的功能, 觉得是个比较实用的功能, 分享如下:

要实现该功能, 主要是使用OAuth2实现第三方登录, 看看OAuth2原理:

oauth2.jpg

微信浏览器判断(若是微信浏览器, 其User-Agent将包含"MicroMessenger")

public static Boolean isWxClient(HttpServletRequest request){    String header = request.getHeader("USER-AGENT");    return header != null && header.contains("MicroMessenger");}            

自动登录需要用到的几个URL:

// 微信授权页面private static final String authorizeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";// 获取微信用户openIdprivate static final String getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";// 获取访问tokenprivate static final String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";        

对于实现自动登录功能, 可以在拦截器中实现这样的功能, 逻辑如下:

String requestUri = req.getRequestURI();if (WxConstants.isWxClient(req)    && filterUri(requestUri)){ // 过滤一些业务中不需要拦截的URI, 比如登入登出等(若登入登出拦截了, 用户将无法登入登出)    Object openId = req.getSession().getAttribute(WxConstants.OPEN_ID);    if (openId == null){        String redirectUrl = "http://" + ThreadVars.getHost() + requestUri;        // 未登录        Object code = req.getParameter(WxConstants.CODE);        if (code == null){            // 重定向到微信认证            wxRequestor.toAuthorize(redirectUrl, resp);            return Boolean.FALSE;            } else {                log.info("[weixin]: get code({}) from authorized.", code);                // 获取openId                Map<String, Object> mapResp = wxRequestor.getOpenId(String.valueOf(code));                if (mapResp.get("errcode") != null){                    log.error("[weixin]: failed to get openid by code({}) cause: {}", code, mapResp);                } else {                    String openIdStr = String.valueOf(mapResp.get(WxConstants.OPEN_ID));                    // TODO 这里可以从数据源中通过openIdStr查询对应的系统用户是否存在, 存在则可以让用户自动登录                }