导入Maven:
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>wx-java-miniapp-spring-boot-starter</artifactId>
<version>4.6.1.B</version>
</dependency>
yaml和properties配置文件:
appid查看:
自己的在微信小程序管理后台,设置》基本设置》账号信息。 或 开发》开发管理》开发设置》开发者ID(可重置 AppSecret 小程序密钥
properties:
wx.miniapp.appid=你的小程序appid
wx.miniapp.secret=你的小程序密钥
yaml:
wx:
miniapp:
appid: xxx
secret: xxx
现在能获取的用户信息就只有呢称(nickName)和头像(avatarUrl),根据自己需求看需不要保存用户信息。openid这个建议保存,不要暴露在前端。
{
"nickName": "xxxx",
"gender": 0,
"language": "zh_CN",
"city": "",
"province": "",
"country": "",
"avatarUrl": "头像"
}
/**
*
* @param appid 小程序appid
* @param code 前端wx.login获取的code
* @return
*/
@GetMapping("/login")
public R<Object> login(@PathVariable String appid, String code) {
if (StrUtil.isBlank(code)) {
return R.error(RC112.getCode(), "登录凭证不能为空");
}
if (!wxMaService.switchover(appid)) {
return R.error(RC112.getCode(), String.format("未找到对应appid=[%s]的配置,请核实!", appid));
}
try {
WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
//下面做自己的业务逻辑,大概就是去数据库查询信息存不存在,不存在创建用户信息,保存openid
log.info(session.getSessionKey());
log.info(session.getOpenid());
} catch (WxErrorException e) {
log.error(e.getMessage(), e);
return R.error(200,e.getMessage());
} finally {
WxMaConfigHolder.remove();//清理ThreadLocal
}
return R.error(RC500.getCode(),RC500.getMsg());
}