本文只是某项目的一个记录。
需求:

官方给出的流程如下:

我们先按这个图中流程实现。
第一步:获取open_id,首先得获取一个code,根据code进一步查询open_id。
wx.login({
success: res => {
//获取code
resolve(res.code)
}
})
我们把这个方法封装为getcode()
ps:wx.login(Object object) | 微信开放文档
第二步:在微信小程序首页的onload中,调用getWechatInfo方法,把code传到后台服务,进一步查询open_id:

async getWeChatInfo() {
//获取code
const code = await getCode()
let that=this;
//将code发给后端请求token
await uni.request({
url: loginRequest.baseURL + "getWeChat",
method: 'POST',
data: {
code
},
success: res => {
if (res.data.code === 200) {
this._openId = res.data.data.openId;
//自定义登录状态存入缓存
wx.setStorageSync('token', res.data.data.token);
//后面2个最好不要存在缓存中 xj
wx.setStorageSync('openId', res.data.data.openId);
wx.setStorageSync('loginFlag', res.data.data.loginFlag);
that.getUserInfoByOpenId();
//this.getUserInfoByOpenId();
} else {
this._openId = "-1";
uni.showToast({
title: res.data.msg,
icon: 'error',
duration: 2000
})
return;
}
}
})
},
第三步:服务端进行登录凭证校验接口appid+appsect+code:
我们通过集成第三方 WxMaService 在服务端进行登录凭证校验(参数:appid+appsect+code),从而获取session_key及openid。
服务端具体代码如下:
public JSONObject getWeChat(WeChatDTO weChatDTO) {
String code = weChatDTO.getCode();
log.info("code: {}", code);
if (StrUtil.isBlank(code)) {
throw new BizException("非法的授权码信息!");
}
WxMaProperties.Config config = wxMaProperties.getConfigs().stream().findFirst().get();
if (!wxMaService.switchover(config.getAppid())) {
throw new BizException(String.format("未找到对应appid=[%s]的配置,请核实!", config.getAppid()));
}
try {
WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
String sessionKey = session.getSessionKey();
String openid = session.getOpenid();
String unionid = session.getUnionid();
if (!StrUtil.isAllNotBlank(sessionKey, openid)) {

最低0.47元/天 解锁文章
6万+

被折叠的 条评论
为什么被折叠?



