目录
一,获取用户昵称和头像
登录过程
二,登录-小程序
三,后台
小程序服器配置
一,获取用户昵称和头像
登录过程
小程序登录
小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系。
二,登录-小程序
-
执行wx.login 登录获取小程序端的code
-
服务端根据code去微信端获取session_key并且缓存;同时生成access_token 保存在小程序端,维持登录状态;
-
小程序端请求服务端用户数据时,先wx.checkSession,有效就通过access_token 确定用户,找到session_key;无效就执行wx.login重新登录重新生成access_token,服务端重新获取session_key;
-
小程序端长时间不使用,服务端的session_key会失效,无法再用session_key去微信端获取数据,需要小程序端重新执行登录操作; 服务端要获取session_key 只能通过小程序端的登录来操作;
wx.checkSession
检查登录态是否过期
wx.login
调用接口获取登录凭证(code)
wx.request
请求自己小程序服器,并且携带了code,userInfo信息
login.js
user.loginByWeixin(res.userInfo).then(res => {
app.globalData.hasLogin = true;
wx.navigateBack({
delta: 1
})
})
user.js
function loginByWeixin(userInfo) {
return new Promise(function(resolve, reject) {
return login().then((res) => {
//登录远程服务器
util.request(api.AuthLoginByWeixin, {
code: res.code,
userInfo: userInfo
}, 'POST').then(res => {
if (res.errno === 0) {
//存储用户信息
wx.setStorageSync('userInfo', res.data.userInfo);
wx.setStorageSync('token', res.data.token);
resolve(res);
} else {
reject(res);
}
})
将userInfo,token数据保存到本地
util.js
function request(url, data = {}, method = "GET") {
return new Promise(function (resolve, reject) {
wx.request({
url: url,
data: data,
method: method,
timeout:6000,
header: {
'Content-Type': 'application/json',
'X-OA-Token': wx.getStorageSync('token')
},
如果使用util.request函数,每次请求都会携带'X-OA-Token': wx.getStorageSync('token');而服器已经保存了所有的token,所以服器通过token区分每个客户端
emoji
mysql的utf8编码的一个字符最多3个字节,但是一个emoji表情为4个字节,所以utf8不支持存储emoji表情。但是utf8的超集utf8mb4一个字符最多能有4字节,所以能支持emoji表情的存储。
Linux系统中MySQL的配置文件为my.cnf。
Winows中的配置文件为my.ini。
[mysql]
# 设置mysql客户端默认字符集
default-character-set=utf8mb4
[mysqld]
#设置3306端口
port = 3306
# 设置mysql的安装目录
basedir=D:\\tools\\mysql-5.7.23-winx64
# 设置mysql数据库的数据的存放目录
datadir=D:\\tools\\mysql-5.7.23-winx64\\data
# 允许最大连接数
max_connections=200
# 服务端使用的字符集默认为8比特编码的latin1字符集
character-set-server=utf8mb4
# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB
三,后台
小程序服器配置
导入微信小程序SDK
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.3.0</version>
</dependency>
application.yml
oa:
wx:
app-id: wxf23b28b5e4ea4d6a
app-secret: 212621faa31cdf0691367ea45b2b6041
msgDataFormat: JSON
WxProperties
封装oa.wx的数据
@Data
@Configuration
@ConfigurationProperties(prefix = "oa.wx")
public class WxProperties {
/**
* 设置微信小程序的appId
*/
private String appId;
/**
* 设置微信小程序的Secret
*/
private String appSecret;
/**
* 消息数据格式
*/
private String msgDataFormat;
}
WxConfig
注册WxMaService
@Configuration
public class WxConfig {
@Autowired
private WxProperties properties;
@Bean
public WxMaConfig wxMaConfig() {
WxMaInMemoryConfig config = new WxMaInMemoryConfig();
config.setAppid(properties.getAppId());
config.setSecret(properties.getAppSecret());
config.setMsgDataFormat(properties.getMsgDataFormat());
return config;
}
@Bean
public WxMaService wxMaService(WxMaConfig maConfig) {
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(maConfig);
return service;
}
}
WxAuthController
@RequestMapping("/wx/auth")
public class WxAuthController {
@Autowired
private WxMaService wxService;
@PostMapping("login_by_weixin")
public Object loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
//客户端需携带code与userInfo信息
String code = wxLoginInfo.getCode();
UserInfo userInfo = wxLoginInfo.getUserInfo();
if (code == null || userInfo == null) {
return ResponseUtil.badArgument();
}
//调用微信sdk获取openId及sessionKey
String sessionKey = null;
String openId = null;
try {
WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
sessionKey = result.getSessionKey();//session id
openId = result.getOpenid();//用户唯一标识 OpenID
} catch (Exception e) {
e.printStackTrace();
}
if (sessionKey == null || openId == null) {
log.error("微信登录,调用官方接口失败:{}", code);
return ResponseUtil.fail();
}else{
log.info("openId={},sessionKey={}",openId,sessionKey);
}
//根据openId查询wx_user表
//如果不存在,初始化wx_user,并保存到数据库中
//如果存在,更新最后登录时间
//....
// token
UserToken userToken = null;
try {
userToken = UserTokenManager.generateToken(user.getId());
} catch (Exception e) {
log.error("微信登录失败,生成token失败:{}", user.getId());
e.printStackTrace();
return ResponseUtil.fail();
}
userToken.setSessionKey(sessionKey);
log.info("SessionKey={}",UserTokenManager.getSessionKey(user.getId()));
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
result.put("userInfo", userInfo);
//....
log.info("【请求结束】微信登录,响应结果:{}", JSONObject.toJSONString(result));
return ResponseUtil.ok(result);
}
响应给客户端数据有:token userInfo
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)