其他分享
首页 > 其他分享> > 微信授权登录(H5为例)

微信授权登录(H5为例)

作者:互联网

/**
* 微信H5授权登录
*
* @author liulu
* 2018/8/13 下午 03:04
*/
@GetMapping(“wxlogin_userinfo”)
public String wxLoginUserInfo(String returnUrl, @RequestHeader(“User-Agent”) String userAgent) {
if (StringUtil.isBlank(returnUrl)) {
returnUrl = loginConfig.getWebApplicationUrl();
}

    if (userAgent.contains("MicroMessenger")) {
        return getOauthUrl(returnUrl, "snsapi_userinfo");
    }

    return "redirect:" + returnWithToken(returnUrl, new User());
}

private String getOauthUrl(String returnUrl, String scope) {
String oauth2Url = String.format(
“%s/login/oauth_response?fromUrl=%s”,
loginConfig.getApiApplicationUrl(),
encodeUrl(returnUrl)
);

    return String.format(
            "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s#wechat_redirect",
            loginConfig.getMpAppid(),
            encodeUrl(oauth2Url),
            scope
    );
}

/**
* @author liulu
* 2018/8/13 下午 03:08
*/
@GetMapping(“oauth_response”)
public String oauthResponse(String code, String fromUrl) {
JSONObject json = getAccessToken(code);
if (!json.containsKey(“openid”)) {
logger.error(“授权获取access_token出错:” + json);
return toLoginFail();
}

    User user;
    if ("snsapi_userinfo".equals(json.getString("scope"))) {
        json = getInfo(json.getString("access_token"), json.getString("openid"));
        if (!json.containsKey("openid")) {
            logger.error("弹窗授权获取用户信息出错:" + json);
            return toLoginFail();
        }

        user = new User();
        user.setUnionid(json.getString("unionid"));
        user.setSex(json.getIntValue("sex"));
        user.setProvince(json.getString("province"));
        user.setNickname(json.getString("nickname"));
        user.setHeadImgUrl(json.getString("headimgurl"));
        user.setCountry(json.getString("country"));
        user.setCity(json.getString("city"));
        user.setMpOpenid(json.getString("openid"));
        user = userService.login(user);
    } else {
        user = new User();
        user.setMpOpenid(json.getString("openid"));
        user = userService.login(user);
    }

    return "redirect:" + returnWithToken(fromUrl, user);
}

private JSONObject getAccessToken(String code) {
    String result = RestClient.getForObject(
            String.format(
                    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                    loginConfig.getMpAppid(),
                    loginConfig.getMpAppSecret(),
                    code
            ),
            String.class
    );
    return JSONObject.parseObject(result);
}

private JSONObject getInfo(String accessToken, String openid) {
    String result = RestClient.getForObject(
            String.format(
                    "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",
                    accessToken,
                    openid
            ),
            String.class
    );
    return JSONObject.parseObject(result);
}

private String encodeUrl(String url) {
try {
return URLEncoder.encode(url, “UTF-8”);
} catch (UnsupportedEncodingException e) {
}
return null;
}

private String returnWithToken(String returnUrl, User user) {
StringBuilder url = new StringBuilder(returnUrl);
if (returnUrl.contains("?")) {
url.append("&access_token=");
} else {
url.append("?access_token=");
}
url.append(userService.createJWTToken(user));
url.append("&token_type=");
url.append(user.getNickname() != null ? Constants.TOKEN_TYPE_AUTHC : Constants.TOKEN_TYPE_ANON);
url.append("&share_id=").append(user.getUuid());
return url.toString();
}

####################登录代码:
package com.beagledata.gaea.securitydoc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.beagledata.gaea.securitydoc.common.SessionHolder;
import com.beagledata.gaea.securitydoc.config.LoginConfigs;
import com.beagledata.gaea.securitydoc.entity.User;
import com.beagledata.gaea.securitydoc.exception.WxQrcodeLoginTimeoutException;
import com.beagledata.gaea.securitydoc.mapper.UserMapper;
import com.beagledata.gaea.securitydoc.service.UserService;
import com.beagledata.gaea.securitydoc.utils.JWTUtils;
import com.beagledata.gaea.securitydoc.utils.WXBizDataCrypt;
import com.beagledata.utils.EncodeUtil;
import com.beagledata.utils.IdUtil;
import com.beagledata.utils.RestClient;
import com.beagledata.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**

####################工具类:
package com.beagledata.gaea.securitydoc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.beagledata.gaea.securitydoc.common.SessionHolder;
import com.beagledata.gaea.securitydoc.config.LoginConfigs;
import com.beagledata.gaea.securitydoc.entity.User;
import com.beagledata.gaea.securitydoc.exception.WxQrcodeLoginTimeoutException;
import com.beagledata.gaea.securitydoc.mapper.UserMapper;
import com.beagledata.gaea.securitydoc.service.UserService;
import com.beagledata.gaea.securitydoc.utils.JWTUtils;
import com.beagledata.gaea.securitydoc.utils.WXBizDataCrypt;
import com.beagledata.utils.EncodeUtil;
import com.beagledata.utils.IdUtil;
import com.beagledata.utils.RestClient;
import com.beagledata.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**

package com.beagledata.gaea.securitydoc.utils;

import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**

package com.beagledata.gaea.securitydoc.common;

import com.beagledata.commons.ThreadHolder;
import com.beagledata.gaea.securitydoc.entity.User;

/**

package com.beagledata.gaea.securitydoc.common;

/**

package com.beagledata.gaea.securitydoc.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**

/**

##################sql

<?xml version="1.0" encoding="UTF-8" ?>
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO t_user
      (
        uuid, create_time, unionid, mp_openid, lite_openid,
        nickname, sex, city, province, country, head_img_url, session_key
      )
    VALUES
      (
        #{uuid}, NOW(), #{unionid}, #{mpOpenid}, #{liteOpenid},
        #{nickname}, #{sex}, #{city}, #{province}, #{country}, #{headImgUrl}, #{sessionKey}
      )
</insert>

<update id="update">
    UPDATE t_user
    <set>
        update_time = NOW()
        <if test="unionid != null and unionid != ''">
            ,unionid = #{unionid}
        </if>
        <if test="mpOpenid != null and mpOpenid != ''">
            ,mp_openid = #{mpOpenid}
        </if>
        <if test="liteOpenid != null and liteOpenid != ''">
            ,lite_openid = #{liteOpenid}
        </if>
        <if test="nickname != null and nickname != ''">
            ,nickname = #{nickname}
        </if>
        <if test="sex != null">
            ,sex = #{sex}
        </if>
        <if test="city != null and city != ''">
            ,city = #{city}
        </if>
        <if test="province != null and province != ''">
            ,province = #{province}
        </if>
        <if test="country != null and country != ''">
            ,country = #{country}
        </if>
        <if test="headImgUrl != null and headImgUrl != ''">
            ,head_img_url = #{headImgUrl}
        </if>
        <if test="sessionKey != null and sessionKey != ''">
            ,session_key = #{sessionKey}
        </if>
    </set>
    WHERE id = #{id}
</update>

<select id="selectByMpOpenid" resultMap="userResultMap">
    SELECT id, uuid, unionid, mp_openid, lite_openid, nickname
    FROM t_user
    WHERE mp_openid = #{mpOpenid}
</select>

<select id="selectByLiteOpenid" resultMap="userResultMap">
    SELECT id, uuid, unionid, mp_openid, lite_openid, nickname
    FROM t_user
    WHERE lite_openid = #{liteOpenid}
</select>

<select id="selectByUnionid" resultMap="userResultMap">
    SELECT id, uuid, unionid, mp_openid, lite_openid, nickname
    FROM t_user
    WHERE unionid = #{unionid}
</select>

<select id="selectById" resultMap="userResultMap">
    SELECT id, uuid, unionid, mp_openid, lite_openid, nickname, head_img_url, session_key
    FROM t_user
    WHERE id = #{id}
</select>

<select id="selectByUuid" resultMap="userResultMap">
    SELECT id, uuid, nickname, head_img_url, session_key
    FROM t_user
    WHERE uuid = #{uuid}
</select>

<select id="selectFriendsById" resultMap="userResultMap">
    SELECT
        t2.id, IFNULL(t2.mark_name, t1.nickname) AS nickname, t1.head_img_url, t3.tags
    FROM
        t_user t1
            JOIN
        t_friend t2 ON t1.id = t2.friend_id
            JOIN
        t_user_tags t3 ON t2.friend_id = t3.user_id
    WHERE
        t2.user_id = #{id}
    ORDER BY t2.id DESC
</select>

<update id="updateFriendMarkName">
    UPDATE t_friend
    SET mark_name = #{param3}, update_time = NOW()
    WHERE id = #{param1} AND user_id = #{param2}
</update>

<insert id="insertFriend">
    INSERT INTO t_friend (create_time, user_id, friend_id)
    VALUES (NOW(), #{param1}, #{param2})
    ON DUPLICATE KEY UPDATE update_time = NOW()
</insert>

<update id="updateForMerge">
    UPDATE t_friend SET user_id = #{param2} WHERE user_id = #{param1};
    UPDATE t_share SET user_id = #{param2} WHERE user_id = #{param1};
    UPDATE t_browse SET user_id = #{param2} WHERE user_id = #{param1};
    UPDATE t_user_tags SET user_id = #{param2} WHERE user_id = #{param1};
</update>

<delete id="deleteById">
    DELETE FROM t_user WHERE id = #{id}
</delete>

#############配置类:
config:
mp-appid: wxdde334e3184ddc81 # 服务号appid
mp-app-secret: 7f2c5f82b872d09324e6fe09cb1e4393 # 服务号appsecret
lite-appid: wxbe68a1b4256ca4f1 # 小程序appid
lite-app-secret: 9f120ce0dfe5b49c3e970820b768abb2 # 小程序appsecret
web-application-url: http://192.168.100.90:8080/beaglenews # html服务地址
api-application-url: http://192.168.100.90:8080/beaglenews # api服务地址
token-expires-at: 24 # jwt token过期时间,单位:小时
recommend-news-max-size: 0 # 推荐资讯列表缓存最大长度,设置小于1不执行任务
hot-news-max-size: 0 # 热门资讯列表缓存最大长度,设置小于1不执行任务
solr-query-url: http://47.93.193.31/solr/solr/select?q={q}&start={start}&rows={rows}&fl={fl}&wt=json&indent=true # solr查询接口地址
article-cache-max-size: 0 # 计算相似资讯的种子资讯缓存最大长度,设置小于1不执行任务
xiaoq-ai-news-id: 0 # 天云小QAI资讯计算相似的资讯id
xiaoq-fintech-news-id: 0 # 天云小QFintech资讯计算相似的资讯id
refresh-wx-access-token: true # 是否刷新微信access_token
buudoo-url: http://www.buudoo.com # 布兜接口地址
xiaoq2-news-max-size: 100 # 天云小Q2资讯列表缓存最大长度,设置小于1不执行任务
app-home: ${SECURITYDOC_HOME:E:\fagui}

########相关依赖:

com.beagledata
utils
0.0.3


org.springframework.boot
spring-boot-starter-data-redis


com.auth0
java-jwt
3.4.0


com.beagledata
commons
0.0.2

标签:String,为例,微信,H5,user,loginUser,import,public,append
来源: https://blog.csdn.net/weixin_43812065/article/details/100533797