微信小程序微信登录实现和注意事项

微信登录的官方api:小程序登录 / 小程序登录

现在如果使用的是2.17以上的基础库是无法获取用户头像,昵称和手机等信息,需要先获取openid,不过好像2.1以下版本的库也不行,所以还是用openid登录吧

什么是openID?openID是微信用户的唯一标识(跟微信号很像),利用这一点就可以用它来注册或登录。

直接先上前端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 直接处理微信登录
const handleWxLoginDirectly= () => {
uni.login({
provider: 'weixin',
success: (res) => {
console.log(res.code)
uni.request({
url: `${baseUrl}/user/wx-login`,
method: 'POST',
data: res.code,
success: (res) => {
console.log(res)
if(res.data.code === 200){
uni.setStorageSync('sa-token', res.data.data.tokenValue)
uni.showToast({
title: '登录成功',
icon: 'success'
})
setTimeout(() => {
uni.switchTab({
url: '/pages/index/index'
})
}, 1500)
}else{
uni.showToast({
title: res.data.msg || '登录失败',
icon: 'none'
})
}
},
fail: () => {
uni.showToast({
title: '网络错误',
icon: 'none'
})
},
complete: () => {
isLoading.value = false
}
})
}
});


};
  • baseUrl为你的后端地址
  • 具体返回的res需要自己处理
  • uni.setStorageSync为存储token在本地
  • 登录好后会跳转到/pages/index/index

uni.login()官方文档:uni.login(OBJECT) | uni-app官网

后端获取openID的类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class WechatUtil {
// 配置自己的app_id、app_secret
private static final String APP_ID = "";
private static final String APP_SECRET = "";

public static String getOpenId(String loginCode) {
String url = "https://api.weixin.qq.com/sns/jscode2session";
String requestUrl = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("appid", APP_ID)
.queryParam("secret", APP_SECRET)
.queryParam("js_code", loginCode)
.queryParam("grant_type", "authorization_code")
.toUriString();

HttpResponse response = HttpUtil.createGet(requestUrl).execute();

// 获取 session_key 和 openid
JSONObject parseObj = JSONUtil.parseObj(response.body());

String openid = (String) parseObj.get("openid");
return openid;
}
}
  • 先填写自己的APP_ID和APP_SECRET

接收微信登录的接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 微信小程序登录
* @return 登录结果
*/
@PostMapping("/wx-login")
public Result wxLogin(@RequestBody String code) {
String openId = WechatUtil.getOpenId(code);
User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getOpenId, openId));
if (user == null) {
user = new User();
user.setOpenId(openId);
user.setUsername("wx_"+openId.substring(0, 15));
user.setPassword("123456");

user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
user.setCreatedTime(LocalDateTime.now());
userMapper.insert(user);
StpUtil.login(user.getId());
return Result.data(StpUtil.getTokenInfo());
}else {
StpUtil.login(user.getId());
return Result.data(StpUtil.getTokenInfo());
}

主要看前面部分后面就是处理逻辑了,通过前端传过来的code(这个code是什么?登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见小程序登录。)来获取openID,然后判断数据库里有无这个openId来判断是使用注册还是登录。

注意自己的wxappid,微信开发者工具要和Java里设置的一样哦

部分问题

  • 40029

微信小程序返回40029的情况原因有很多,遇到后大概总结了几个已知的

1.小程序里传到后台的code被微信的调用接口使用了两次(只能使用一次)

2.appid、AppSecret的值不对(这个自己复制感觉一般不会错)

3.自己遇到的最难受的原因:创建项目的appid跟你请求url里的appid、AppSecret不是同一组

起因:刚开始学习的时候,自己注册了一个小程序账号,第一个项目用的这个appid。在真正开始做项目的时候,新建小程序用的测试appid,然后请求openid的时候忘了,用了自己申请的appid、AppSecret,结果就是浪费一下午调试。如果要用测试账号的AppSecret,可以在开发工具里 ‘测试号’—‘申请地址里找到’。

  • 41002

{errcode: 41002, errmsg: “appid missing rid: xxxxxxxxxxx”} 错用成post请求

  • 41004

{errcode: 41004, errmsg: “appsecret missing, rid: xxxxxxxxxxx”} 请求时键名错了,应为 secret

  • 41008

{errcode: 41008, errmsg: “missing code, req_id: xxxxxx “} 请求时键名错了,应为 js_code