java后端实现微信登录获取code,后端获取code、openid以及用户信息数据

业务描述:前端仅访问一下接口,后端java获取code以及用户的数据(重点:进行重定向,response.sendRedirect(url));

网上大部分是前端获取code传给后端进行操作,结合自己的场景,后端直接获取code进行数据的获取
重点提示(注意看这里)如果项目是前后端分离项目,不可以使用重定向,前端会出现跨域问题
解决方式:获取前端的访问地址,向前端返回微信获取code的地址,前端进行访问,获取code,再传到后端,进行业务的操作

 /**
     * description  微信授权登录接口
     * param []
     * return common.enums.ResultVO
     * author 
     * createTime 2021/11/22 16:28
     **/
    @PostMapping("WxLogin")
    public ResultVO WxLogin(HttpServletRequest request, @RequestBody String param) throws Exception {
            String orgCode = request.getHeader("orgCode");
            Organization organization = organizationService.findByOrgCode(orgCode);
            String appid = "";
            String appsecret = "";
            if (StringUtils.isNotBlank(organization.getAppid()) && StringUtils.isNotBlank(organization.getAppsecret())) {
                appid = organization.getAppid();
                appsecret = organization.getAppsecret();
            }
            String url = JSON.parseObject(param).getString("URL");
            return new ResultVO(ResultCode.SUCCESS, WeChatLoginUtil.getUserUathUrl(appid, url));
     

    }

1.搭建微信登录工具类:

package util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 微信登录工具类
 *
 * @description:
 * @projectName:alumni
 * @see:util
 * @author:lgb
 * @createTime:2021/8/27 17:02
 * @version:1.0
 */
public class WeChatLoginUtil {

    final Boolean flag = false;

    /**
     * description 1.获取用户的临时code
     * param [appid, redirectUrl]
     * return java.lang.String
     * authorlgb
     * createTime 2021/8/27 17:30
     **/
    public static String getUserUathUrl(String appid, String redirectUrl) throws UnsupportedEncodingException {
        StringBuffer getcodeUrl = new StringBuffer()
                .append("https://open.weixin.qq.com/connect/oauth2/authorize")
                .append("?appid=" + appid)
                .append("&redirect_uri=" + URLEncoder.encode(redirectUrl, "utf-8"))
                .append("&response_type=code")
                .append("&scope=snsapi_userinfo")
                .append("&state=" + System.currentTimeMillis())
                .append("#wechat_redirect");

        return getcodeUrl.toString();
    }

    /**
     * description  2.获取用户的openid和access_token
     * param [appid, appSecret, code]
     * return java.lang.String
     * author
     * createTime 2021/8/27 17:30
     **/
    public static String getBaseAccessTokenUrl(String appid, String appSecret, String code) throws UnsupportedEncodingException {
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=" + appid)
                .append("&secret=" + appSecret)
                .append("&code=" + code)
                .append("&grant_type=authorization_code");

        return baseAccessTokenUrl.toString();
    }

    /**
     * description  3.根据openid 获取用户的信息
     * param [accessToken, openid]
     * return java.lang.String
     * author 
     * createTime 2021/8/27 17:31
     **/
    public static String getBaseUserInfoUrl(String accessToken, String openid) {
        StringBuffer baseUserInfoUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/userinfo")
                .append("?access_token=" + accessToken)
                .append("&openid=" + openid)
                .append("&lang=zh_CN");
        return baseUserInfoUrl.toString();
    }

    /**
     * description 4检验授权凭证(access_token)是否有效
     * param [openid, accessToken]
     * return java.lang.String
     * author 
     * createTime 2021/11/29 10:16
     **/
    public static String checkAccessToken(String openid, String accessToken) {
        StringBuffer stringBuffer = new StringBuffer().append(" https://api.weixin.qq.com/sns/auth")
                .append("?access_token=" + accessToken)
                .append("&openid=" + openid);
        return stringBuffer.toString();
    }

    /**
     * description 微信小程序登录,通过code获取session_key和openid
     * param [appid, secret, code]
     * return java.lang.String
     * author 
     * createTime 2021/8/30 10:15
     **/
    public static String getCode2Session(String appid, String secret, String code) {
        StringBuffer code2Session = new StringBuffer()
                .append("ttps://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=" + appid)
                .append("&secret=" + secret)
                .append("&js_code=" + code)
                .append("&grant_type=authorization_code");
        return code2Session.toString();
    }


}

2.构建微信配置类

package mobile.config;

import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: 微信相关信息配置
 * @projectName:alumni
 * @see:mobile.config
 * @author:
 * @createTime:2021/8/30 9:31
 * @version:1.0
 */
@Component
@Data
public class WxOpenLoginConfig implements InitializingBean {

    //微信登录的appid,应用唯一标识
    @Value("${wx.open.app_id}")
    private String appId;
    // 微信登录的应用密钥AppSecret
    @Value("${wx.open.app_secret}")
    private String appSecret;

    //重定向地址,使用urlEncode对链接进行处理
    @Value("${wx.open.redirect_url}")
    private String redirectUrl;
    //token
    @Value("${wx.open.token}")
    private String appToken;
    //消息加解密秘钥
    @Value("${wx.open.encodingAESKey}")
    private String encodingAESKey;


    //微信小程序登录录的appid,应用唯一标识
    @Value("${wx.applet.app_id}")
    private String appletAppId;
    // 微信小程序登录的应用密钥AppSecret
    @Value("${wx.applet.app_secret}")
    private String appletAppSecret;


    public static String WX_OPEN_APP_ID;
    public static String WX_OPEN_APP_SECRET;
    public static String WX_OPEN_REDIRECT_URL;//回调地址


    public static String WX_APPLET_APP_ID;
    public static String WX_APPLET_APP_SECRET;


    @Override
    public void afterPropertiesSet() throws Exception {
        WX_OPEN_APP_ID = appId;
        WX_OPEN_APP_SECRET = appSecret;
        WX_OPEN_REDIRECT_URL = redirectUrl;
        WX_APPLET_APP_ID = appletAppId;
        WX_APPLET_APP_SECRET = appletAppSecret;

    }
}


3.重点来啦,代码的实现(非前后端分离项目,前后端分离看最前面的重要提示)

3.1重定向

/**
     * description  微信授权登录接口
     * param []
     * return common.enums.ResultVO
     * author 
     * createTime 2021/11/22 16:28
     **/
    @GetMapping("/WxLogin")
    public ResultVO WxLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.sendRedirect(WeChatLoginUtil.getUserUathUrl(WxOpenLoginConfig.WX_OPEN_APP_ID, WxOpenLoginConfig.WX_OPEN_REDIRECT_URL));//(openid和微信回调地址/WxCallback)进行重定向
  return new ResultVO(ResultCode.SUCCESS, WeChatLoginUtil.getUserUathUrl(WxOpenLoginConfig.WX_OPEN_APP_ID, WxOpenLoginConfig.WX_OPEN_REDIRECT_URL));
        }
        return new ResultVO(ResultCode.ERROR, "请重新尝试");
    }

3.1进行微信的回调

/*
     *
     * description  微信公众号回调地址
     * param [code, state]
     * return javax.annotation.Resource
     * author
     * createTime 2021/8/27 17:42
     *
     */
    @GetMapping("/WxCallback")
    public ResultVO WxCallback(HttpServletRequest request) throws Exception {
        String code = request.getParameter("code");
        String errcode = request.getParameter("errcode");
        String state = request.getParameter("state");
        if (StringUtils.isBlank(code)) {//返回的code为空
            return new ResultVO(ResultCode.VALIDATE_FAILED);
        }
        //获取openid和access_token
        String accesstokenInfo = HttpClientUtil.get(util.WeChatLoginUtil.getBaseAccessTokenUrl(WxOpenLoginConfig.WX_OPEN_APP_ID, WxOpenLoginConfig.WX_OPEN_APP_SECRET, code));
        if (StringUtils.isNotBlank(JSON.parseObject(accesstokenInfo).getString("errcode"))) {
            return new ResultVO(ResultCode.ERROR, "请重新尝试");
        }
        JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        String s = HttpClientUtil.get(WeChatLoginUtil.checkAccessToken(openid, accessToken));//检验授权凭证(access_token)是否有效
        if (JSON.parseObject(s).getString("errcode").equals("0")) {
            // 3根据openid获取该用户的信息
            String resultInfo = HttpClientUtil.get(util.WeChatLoginUtil.getBaseUserInfoUrl(accessToken, openid));
            if (StringUtils.isNotBlank(errcode)) {
                return new ResultVO(ResultCode.FAILED, errcode);
            }
            ResultVO ret = getRet(request, resultInfo);//将用户数据存入到数据库
            return ret;
        }
        return new ResultVO(ResultCode.SERVER_FAILED, "请重新尝试");
    }

3.3之后拿到数据你就可以进行相关业务的操作啦!

参考微信官方文档微信登录官方文档:
参考链接部分实现参考:

你可能感兴趣的:(微信相关,java,微信)