微信号第三方登录(java版)

1、进入微信开放平台得到appid、appSecret。

2、示例类:

package com.xx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xx.common.util.IdGen;
import com.xx.model.User;
import com.xx.service.UserService;
import com.xx.shiro.SubjectUtils;
import com.xx.shiro.UsernamePasswordToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 描述:第三方授权登录
 *
 * @author ssl
 * @create 2018/04/22 10:03
 */
@Controller
@RequestMapping("auth")
public class AuthLogin extends BasicController {
    @Value("${project.url}")
    private String projectUrl;
    @Value("${wechat.qrconnect.appid}")
    private String weChatAppid;
    @Value("${wechat.qrconnect.appSecret}")
    private String weChatAppSecret;
    @Value("${wechat.qrconnect.url}")
    private String weChatQrconnectUrl;
    @Value("${wechat.auth.url}")
    private String wechatAuthUrl;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserService userService;

    /**
     * 微信登录页面
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "wechat")
    public String weChatLogin(HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:/homepage";
        }
        String weChatState = IdGen.uuid();
        SubjectUtils.getSession().setAttribute("weChatState", weChatState);
        String callBackUrl = projectUrl + "/auth/wechat/callback";
        String url = weChatQrconnectUrl + "?appid=" + weChatAppid + "&redirect_uri=" + URLEncoder.encode(callBackUrl,
                "UTF-8") +
                "&response_type=code&scope=snsapi_login&state=" + weChatState + "#wechat_redirect";
        // response.sendRedirect(url);
        return "redirect:" + url;
    }

    @RequestMapping(value = "wechat/callback")
    public String callBackUrl(HttpServletRequest request, RedirectAttributes redirectAttributes, HttpServletResponse
            response) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:/homepage";
        }
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String openid = "";
        if (state.equals(SubjectUtils.getSession().getAttribute("weChatState"))) {
            if (StringUtils.isNotBlank(code)) {
                /** 通过code获取access_token和openid */
                String url = wechatAuthUrl + "?appid=" + weChatAppid + "&secret=" + weChatAppSecret + "&code=" + code
                        + "&grant_type=authorization_code";
                String responseStr = restTemplate.getForObject(url, String.class);
                if (StringUtils.isNotBlank(responseStr)) {
                    JSONObject json = JSON.parseObject(responseStr);
                    if (json.containsKey("openid")) {
                        openid = json.getString("openid");
                    }
                }
            }
        }
        /** 根据openid */
        if (StringUtils.isNotBlank(openid)) {
            User user = userService.getByOpenId(openid);
            if (null == user) {
                return "redirect:/register/wechatBinding/index?openId="+openid;
            }
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getAccount(), "", false,
                    request.getRemoteHost(), "wechat", "");
            SecurityUtils.getSubject().login(usernamePasswordToken);
            return "redirect:/login";
        }
        addMessage(redirectAttributes, "连接失败,请重试");
        return "redirect:/login";
    }
}
3、配置信息:
#微信开放平台
wechat.qrconnect.appid=xxx
wechat.qrconnect.appSecret=xxxxx
wechat.qrconnect.url=https://open.weixin.qq.com/connect/qrconnect
wechat.auth.url=https://api.weixin.qq.com/sns/oauth2/access_token

你可能感兴趣的:(java后台开发)