微信号第三方登录(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值