概述
微信小程序通过wx.login
函数登录时,会返回一个code,后端拿到这个code向微信接口服务请求可以拿到openid,后端根据openid在数据库中查询这个登录的用户是否存在,不存在则向数据库新增这个用户的信息然后返回给微信小程序,微信小程序使用wx.setStorageSync
函数保存用户的信息以保持登录状态
实现流程图
代码实现
获取code并传给后端
requestUtil是封装的wx.request方法,详情查看博客:微信小程序封装请求的地址(IP地址以及端口)和方法 | LeDao’s Blog (zoutl.cn)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| if (!wx.getStorageSync('currentCustomer')) { wx.login({ success: (res) => { requestUtil({ url: '/customer/login', method: 'POST', data: { loginCode: res.code }, header: { 'content-type': 'application/x-www-form-urlencoded', } }).then(result => { wx.setStorageSync('currentCustomer', result.data.customer); }) }, }) }
|
请求的后端方法
下面方法主要是请求了微信接口服务返回openid,仅供参考,如要运行和查看完整代码去查看GitHub仓库:a6678696/mall-admin: 微信小程序商城服务端 (github.com)
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
|
@PostMapping("/login") public R login(String loginCode) { Map<String, Object> map = new HashMap<>(16); HashMap<String, Object> paramMap = new HashMap<>(16); String settingFileLocation = "E://data/mall/myConfig.setting"; Setting setting = new Setting(settingFileLocation); paramMap.put("appid", setting.getStr("appid")); paramMap.put("secret", setting.getStr("secret")); paramMap.put("js_code", loginCode); paramMap.put("grant_type", "authorization_code"); String result = HttpUtil.post("https://api.weixin.qq.com/sns/jscode2session", paramMap); String openid = new JsonParser().parse(result).getAsJsonObject().get("openid").getAsString(); Customer customer = customerService.findByLoginCode(openid); if (ObjectUtil.isNull(customer)) { Customer customer2 = new Customer(); customer2.setNickName("默认昵称" + System.currentTimeMillis()); customer2.setOpenid(openid); customer2.setAvatarImageName("default.jpg"); customerService.add(customer2); customer2.setOpenid(""); map.put("customer", customer2); } else { customer.setOpenid(""); map.put("customer", customer); } return R.ok(map); }
|
myConfig.setting的内容如下:(appid和secret填自己的,获取流程查看博客:微信开发者工具创建小程序 | LeDao’s Blog (zoutl.cn))
1 2 3
| [] appid = 12131 secret = 2323
|