微信授权登录(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;
/**
-
Created by mahongfei on 2019/9/3.
*/
@Service
public class UserServiceImpl implements UserService {
private Logger logger = LoggerFactory.getLogger(this.getClass());@Autowired
private UserMapper userMapper;
@Autowired
private LoginConfigs loginConfigs;@Override
public User login(User loginUser) {
if (loginUser.getUnionid() == null) {
User user;
if (loginUser.getMpOpenid() != null) {
user = userMapper.selectByMpOpenid(loginUser.getMpOpenid());
} else {
user = userMapper.selectByLiteOpenid(loginUser.getLiteOpenid());
}
if (user != null) {
loginUser.setId(user.getId());
loginUser.setUuid(user.getUuid());
}
saveUser(loginUser);
} else {
User userOfUnionid = userMapper.selectByUnionid(loginUser.getUnionid());
if (userOfUnionid == null) {
User user;
if (loginUser.getMpOpenid() != null) {
user = userMapper.selectByMpOpenid(loginUser.getMpOpenid());
} else {
user = userMapper.selectByLiteOpenid(loginUser.getLiteOpenid());
}
if (user != null) {
loginUser.setId(user.getId());
loginUser.setUuid(user.getUuid());
}
saveUser(loginUser);
} else {
if ((userOfUnionid.getMpOpenid() != null
&& userOfUnionid.getMpOpenid().equals(loginUser.getMpOpenid()))
|| (userOfUnionid.getLiteOpenid() != null
&& userOfUnionid.getLiteOpenid().equals(loginUser.getLiteOpenid()))) {
loginUser.setId(userOfUnionid.getId());
loginUser.setUuid(userOfUnionid.getUuid());
saveUser(loginUser);
} else {
User user;
if (loginUser.getMpOpenid() != null) {
user = userMapper.selectByMpOpenid(loginUser.getMpOpenid());
} else {
user = userMapper.selectByLiteOpenid(loginUser.getLiteOpenid());
}
if (user == null) {
loginUser.setId(userOfUnionid.getId());
loginUser.setUuid(userOfUnionid.getUuid());
saveUser(loginUser);
} else {
mergeUser(loginUser, user, userOfUnionid);
}
}
}
}return userMapper.selectById(loginUser.getId());
}
private void signature(JSONObject json, String sessionKey) {
String rawData = json.getString(“rawData”);
String signature = json.getString(“signature”);
String signature2 = EncodeUtil.encodeSHA1(rawData + sessionKey);
if (!signature.equals(signature2)) {
throw new IllegalArgumentException(“签名校验失败”);
}
}private JSONObject decrypt(JSONObject json, String sessionKey) throws Exception {
return WXBizDataCrypt.decrypt(
json.getString(“encryptedData”),
json.getString(“iv”),
loginConfigs.getLiteAppid(),
sessionKey
);
}@Override
public String createJWTToken(User user) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, loginConfigs.getTokenExpiresAt());
Date expiresAt = calendar.getTime();Map<String, Object> map = new HashMap<>(1); map.put("id", user.getId()); return JWTUtils.create(expiresAt, Collections.singletonMap("id", user.getId()));
}
private void saveUser(User user) {
if (user.getId() != null) {
userMapper.update(user);
} else {
user.setUuid(IdUtil.UUID());
userMapper.insert(user);
}
}private void mergeUser(User loginUser, User fromUser, User toUser) {
userMapper.updateForMerge(fromUser.getId(), toUser.getId());
userMapper.deleteById(fromUser.getId());
loginUser.setId(toUser.getId());
loginUser.setUuid(toUser.getUuid());
saveUser(loginUser);
}
}
####################工具类:
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;
/**
-
Created by mahongfei on 2019/9/3.
*/
@Service
public class UserServiceImpl implements UserService {
private Logger logger = LoggerFactory.getLogger(this.getClass());@Autowired
private UserMapper userMapper;
@Autowired
private LoginConfigs loginConfigs;@Override
public User login(User loginUser) {
if (loginUser.getUnionid() == null) {
User user;
if (loginUser.getMpOpenid() != null) {
user = userMapper.selectByMpOpenid(loginUser.getMpOpenid());
} else {
user = userMapper.selectByLiteOpenid(loginUser.getLiteOpenid());
}
if (user != null) {
loginUser.setId(user.getId());
loginUser.setUuid(user.getUuid());
}
saveUser(loginUser);
} else {
User userOfUnionid = userMapper.selectByUnionid(loginUser.getUnionid());
if (userOfUnionid == null) {
User user;
if (loginUser.getMpOpenid() != null) {
user = userMapper.selectByMpOpenid(loginUser.getMpOpenid());
} else {
user = userMapper.selectByLiteOpenid(loginUser.getLiteOpenid());
}
if (user != null) {
loginUser.setId(user.getId());
loginUser.setUuid(user.getUuid());
}
saveUser(loginUser);
} else {
if ((userOfUnionid.getMpOpenid() != null
&& userOfUnionid.getMpOpenid().equals(loginUser.getMpOpenid()))
|| (userOfUnionid.getLiteOpenid() != null
&& userOfUnionid.getLiteOpenid().equals(loginUser.getLiteOpenid()))) {
loginUser.setId(userOfUnionid.getId());
loginUser.setUuid(userOfUnionid.getUuid());
saveUser(loginUser);
} else {
User user;
if (loginUser.getMpOpenid() != null) {
user = userMapper.selectByMpOpenid(loginUser.getMpOpenid());
} else {
user = userMapper.selectByLiteOpenid(loginUser.getLiteOpenid());
}
if (user == null) {
loginUser.setId(userOfUnionid.getId());
loginUser.setUuid(userOfUnionid.getUuid());
saveUser(loginUser);
} else {
mergeUser(loginUser, user, userOfUnionid);
}
}
}
}return userMapper.selectById(loginUser.getId());
}
private void signature(JSONObject json, String sessionKey) {
String rawData = json.getString(“rawData”);
String signature = json.getString(“signature”);
String signature2 = EncodeUtil.encodeSHA1(rawData + sessionKey);
if (!signature.equals(signature2)) {
throw new IllegalArgumentException(“签名校验失败”);
}
}private JSONObject decrypt(JSONObject json, String sessionKey) throws Exception {
return WXBizDataCrypt.decrypt(
json.getString(“encryptedData”),
json.getString(“iv”),
loginConfigs.getLiteAppid(),
sessionKey
);
}@Override
public String createJWTToken(User user) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, loginConfigs.getTokenExpiresAt());
Date expiresAt = calendar.getTime();Map<String, Object> map = new HashMap<>(1); map.put("id", user.getId()); return JWTUtils.create(expiresAt, Collections.singletonMap("id", user.getId()));
}
private void saveUser(User user) {
if (user.getId() != null) {
userMapper.update(user);
} else {
user.setUuid(IdUtil.UUID());
userMapper.insert(user);
}
}private void mergeUser(User loginUser, User fromUser, User toUser) {
userMapper.updateForMerge(fromUser.getId(), toUser.getId());
userMapper.deleteById(fromUser.getId());
loginUser.setId(toUser.getId());
loginUser.setUuid(toUser.getUuid());
saveUser(loginUser);
}
}
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;
/**
-
小程序解密工具类
-
-
Created by liulu on 2018/8/17.
*/
public class WXBizDataCrypt {
public static JSONObject decrypt(String encryptedData,
String iv,
String appid,
String sessionKey) throws Exception {
byte[] encryptedByte = Base64.getDecoder().decode(encryptedData);
byte[] sessionKeyByte = Base64.getDecoder().decode(sessionKey);
byte[] ivByte = Base64.getDecoder().decode(iv);SecretKeySpec skeySpec = new SecretKeySpec(sessionKeyByte, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ivParameterSpec = new IvParameterSpec(ivByte); cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec); byte[] decrypted = cipher.doFinal(encryptedByte); JSONObject json = JSONObject.parseObject(new String(decrypted)); if (!json.getJSONObject("watermark").getString("appid").equals(appid)) { throw new Exception("数据水印校验失败"); } return json;
}
}
package com.beagledata.gaea.securitydoc.common;
import com.beagledata.commons.ThreadHolder;
import com.beagledata.gaea.securitydoc.entity.User;
/**
-
Created by liulu on 2018/8/13.
/
public class SessionHolder {
/*- @author liulu
- 2018/8/13 下午 02:28
*/
public static void set(User user) {
ThreadHolder.set(user);
}
/**
- @author liulu
- 2018/8/13 下午 02:28
*/
public static void remove() {
ThreadHolder.remove();
}
/**
-
@author liulu
-
2018/8/13 下午 02:40
*/
public static int currentUserId() {
User user = currentUser();
if (user == null) {
return 0;
}Integer id = currentUser().getId();
return id != null ? id : 0;
}
/**
- @author liulu
- 2018/8/13 下午 02:29
*/
private static User currentUser() {
return (User) ThreadHolder.get();
}
}
package com.beagledata.gaea.securitydoc.common;
/**
- Created by liulu on 2019/8/12.
/
public class Constants {
/*- 默认最小页码
/
public static final int DEFAULT_MIN_PAGE = 1;
/* - 默认最小页码
/
public static final String DEFAULT_MIN_PAGE_STR = “1”;
/* - 默认最小每页记录条数
/
public static final int DEFAULT_MIN_PAGE_NUM = 10;
/* - 默认最小每页记录条数
/
public static final String DEFAULT_MIN_PAGE_NUM_STR = “10”;
/* - 默认最大每页记录条数
/
public static final int DEFAULT_MAX_PAGE_NUM = 20;
/* - source来源是search
/
public static final String SOURCE_TYPE= “search”;
/* - Redis推荐资讯集合key
/
public static final String REDIS_KEY_RECOMMEND_NEWS = “news.recommends”;
/* - Redis热门资讯集合key
/
public static final String REDIS_KEY_HOT_NEWS = “news.hots”;
/* - 请求接口凭证头部
/
public static final String TOKEN_HEADER_NAME = “Authorization”;
/* - 微信access_token刷新频率
/
public static final long WX_ACCESS_TOKEN_REFRESH_RATE = 60 * 60 * 1000;
/* - Redis微信access_token key
/
public static final String REDIS_KEY_WX_ACCESS_TOKEN = “wx.access_token”;
/* - Redis微信jsapi_ticket key
/
public static final String REDIS_KEY_WX_JSAPI_TICKET = “wx.jsapi_ticket”;
/* - token授权类型
/
public static final String TOKEN_TYPE_AUTHC = “authc”;
/* - token匿名类型
*/
public static final String TOKEN_TYPE_ANON = “anon”;
}
- 默认最小页码
package com.beagledata.gaea.securitydoc.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
-
Created by mahongfei on 2019/9/3.
/
@Configuration
@ConfigurationProperties(prefix = “config”)
public class LoginConfigs {
/*- 服务号appid
/
private String mpAppid;
/* - 服务号appsecret
/
private String mpAppSecret;
/* - 小程序appid
/
private String liteAppid;
/* - 小程序appsecret
/
private String liteAppSecret;
/* - html服务地址
/
private String webApplicationUrl;
/* - api服务地址
/
private String apiApplicationUrl;
/* - jwt token过期时间,单位:小时
/
private int tokenExpiresAt;
/* - 推荐资讯列表缓存最大长度
/
private int recommendNewsMaxSize;
/* - 热门资讯列表缓存最大长度
/
private int hotNewsMaxSize;
/* - solr查询接口地址
/
private String solrQueryUrl;
/* - 算相似资讯的种子资讯缓存最大长度
/
private int articleCacheMaxSize;
/* - 天云小QAI资讯计算相似的资讯id
/
private int xiaoqAiNewsId;
/* - 天云小QFintech资讯计算相似的资讯id
/
private int xiaoqFintechNewsId;
/* - 是否刷新微信access_token
/
private boolean refreshWxAccessToken;
/* - 布兜接口地址
/
private String buudooUrl;
/* - 天云小Q2资讯列表缓存最大长度,设置小于1不执行任务
*/
private int xiaoq2NewsMaxSize;
public String getMpAppid() {
return mpAppid;
}public void setMpAppid(String mpAppid) {
this.mpAppid = mpAppid;
}public String getMpAppSecret() {
return mpAppSecret;
}public void setMpAppSecret(String mpAppSecret) {
this.mpAppSecret = mpAppSecret;
}public String getLiteAppid() {
return liteAppid;
}public void setLiteAppid(String liteAppid) {
this.liteAppid = liteAppid;
}public String getLiteAppSecret() {
return liteAppSecret;
}public void setLiteAppSecret(String liteAppSecret) {
this.liteAppSecret = liteAppSecret;
}public String getWebApplicationUrl() {
return webApplicationUrl;
}public void setWebApplicationUrl(String webApplicationUrl) {
this.webApplicationUrl = webApplicationUrl;
}public String getApiApplicationUrl() {
return apiApplicationUrl;
}public void setApiApplicationUrl(String apiApplicationUrl) {
this.apiApplicationUrl = apiApplicationUrl;
}public int getTokenExpiresAt() {
return tokenExpiresAt;
}public void setTokenExpiresAt(int tokenExpiresAt) {
this.tokenExpiresAt = tokenExpiresAt;
}public int getRecommendNewsMaxSize() {
return recommendNewsMaxSize;
}public void setRecommendNewsMaxSize(int recommendNewsMaxSize) {
this.recommendNewsMaxSize = recommendNewsMaxSize;
}public int getHotNewsMaxSize() {
return hotNewsMaxSize;
}public void setHotNewsMaxSize(int hotNewsMaxSize) {
this.hotNewsMaxSize = hotNewsMaxSize;
}public String getSolrQueryUrl() {
return solrQueryUrl;
}public void setSolrQueryUrl(String solrQueryUrl) {
this.solrQueryUrl = solrQueryUrl;
}public int getArticleCacheMaxSize() {
return articleCacheMaxSize;
}public void setArticleCacheMaxSize(int articleCacheMaxSize) {
this.articleCacheMaxSize = articleCacheMaxSize;
}public int getXiaoqAiNewsId() {
return xiaoqAiNewsId;
}public void setXiaoqAiNewsId(int xiaoqAiNewsId) {
this.xiaoqAiNewsId = xiaoqAiNewsId;
}public int getXiaoqFintechNewsId() {
return xiaoqFintechNewsId;
}public void setXiaoqFintechNewsId(int xiaoqFintechNewsId) {
this.xiaoqFintechNewsId = xiaoqFintechNewsId;
}public boolean isRefreshWxAccessToken() {
return refreshWxAccessToken;
}public void setRefreshWxAccessToken(boolean refreshWxAccessToken) {
this.refreshWxAccessToken = refreshWxAccessToken;
}public String getBuudooUrl() {
return buudooUrl;
}public void setBuudooUrl(String buudooUrl) {
this.buudooUrl = buudooUrl;
}public int getXiaoq2NewsMaxSize() {
return xiaoq2NewsMaxSize;
}public void setXiaoq2NewsMaxSize(int xiaoq2NewsMaxSize) {
this.xiaoq2NewsMaxSize = xiaoq2NewsMaxSize;
}@Override
public String toString() {
StringBuilder sb = new StringBuilder(“DefaultConfigs{”);
sb.append(“mpAppid=’”).append(mpAppid).append(’’’);
sb.append(", mpAppSecret=’").append(mpAppSecret).append(’’’);
sb.append(", liteAppid=’").append(liteAppid).append(’’’);
sb.append(", liteAppSecret=’").append(liteAppSecret).append(’’’);
sb.append(", webApplicationUrl=’").append(webApplicationUrl).append(’’’);
sb.append(", apiApplicationUrl=’").append(apiApplicationUrl).append(’’’);
sb.append(", tokenExpiresAt=").append(tokenExpiresAt);
sb.append(", recommendNewsMaxSize=").append(recommendNewsMaxSize);
sb.append(", hotNewsMaxSize=").append(hotNewsMaxSize);
sb.append(", solrQueryUrl=’").append(solrQueryUrl).append(’’’);
sb.append(", articleCacheMaxSize=").append(articleCacheMaxSize);
sb.append(", xiaoqAiNewsId=").append(xiaoqAiNewsId);
sb.append(", xiaoqFintechNewsId=").append(xiaoqFintechNewsId);
sb.append(", refreshWxAccessToken=").append(refreshWxAccessToken);
sb.append(", buudooUrl=’").append(buudooUrl).append(’’’);
sb.append(", xiaoq2NewsMaxSize=").append(xiaoq2NewsMaxSize);
sb.append(’}’);
return sb.toString();
}
}
########################实体类:
package com.beagledata.gaea.securitydoc.entity; - 服务号appid
/**
-
Created by mahongfei on 2019/9/3.
/
public class User extends BaseEntity {
private static final long serialVersionUID = 695194018646397677L;
/*- 微信unionid
/
private String unionid;
/* - 微信公众号openid
/
private String mpOpenid;
/* - 小程序openid
/
private String liteOpenid;
/* - 微信昵称
/
private String nickname;
/* - 微信性别
/
private Integer sex;
/* - 微信城市
/
private String city;
/* - 微信省份
/
private String province;
/* - 微信国家
/
private String country;
/* - 微信头像地址
/
private String headImgUrl;
/* - 用户标签
/
private String tags;
/* - 小程序会话密钥
*/
private String sessionKey;
public User() {
}public User(int id) {
super.setId(id);
}public String getUnionid() {
return unionid;
}public void setUnionid(String unionid) {
this.unionid = unionid;
}public String getMpOpenid() {
return mpOpenid;
}public void setMpOpenid(String mpOpenid) {
this.mpOpenid = mpOpenid;
}public String getLiteOpenid() {
return liteOpenid;
}public void setLiteOpenid(String liteOpenid) {
this.liteOpenid = liteOpenid;
}public String getNickname() {
return nickname;
}public void setNickname(String nickname) {
this.nickname = nickname;
}public Integer getSex() {
return sex;
}public void setSex(Integer sex) {
this.sex = sex;
}public String getCity() {
return city;
}public void setCity(String city) {
this.city = city;
}public String getProvince() {
return province;
}public void setProvince(String province) {
this.province = province;
}public String getCountry() {
return country;
}public void setCountry(String country) {
this.country = country;
}public String getHeadImgUrl() {
return headImgUrl;
}public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl;
}public String getTags() {
return tags;
}public void setTags(String tags) {
this.tags = tags;
}public String getSessionKey() {
return sessionKey;
}public void setSessionKey(String sessionKey) {
this.sessionKey = sessionKey;
}@Override
public String toString() {
StringBuilder sb = new StringBuilder(“User{”);
sb.append(“unionid=’”).append(unionid).append(’’’);
sb.append(", mpOpenid=’").append(mpOpenid).append(’’’);
sb.append(", liteOpenid=’").append(liteOpenid).append(’’’);
sb.append(", nickname=’").append(nickname).append(’’’);
sb.append(", sex=").append(sex);
sb.append(", city=’").append(city).append(’’’);
sb.append(", province=’").append(province).append(’’’);
sb.append(", country=’").append(country).append(’’’);
sb.append(", headImgUrl=’").append(headImgUrl).append(’’’);
sb.append(", tags=’").append(tags).append(’’’);
sb.append(", sessionKey=’").append(sessionKey).append(’’’);
sb.append(’}’);
sb.append(" ").append(super.toString());
return sb.toString();
}
} - 微信unionid
##################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