文章目录
1、乘客登录
1.1、需求说明
乘客端只要登录,没有注册,登录方式为微信小程序登录,乘客登录我们根据微信接口拿到微信OpenId(全局唯一),到客户表(客户即乘客)查询OpenId是否存在,如果不存在即为注册,添加一天乘客记录;存在则根据用户信息生成token返回。
1.2、微信授权登录
官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系。
登录流程时序
说明:
- 调用 wx.login() 获取 临时登录凭证code ,并回传到开发者服务器。
- 调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 、 用户在微信开放平台账号下的唯一标识UnionID(若当前小程序已绑定到微信开放平台账号) 和 会话密钥 session_key。
之后开发者服务器可以根据用户标识来生成自定义登录态,用于后续业务逻辑中前后端交互时识别用户身份。
2、乘客登录功能
2.1、乘客登录微服务模块service-customer
service-customer模块导入依赖
文档:https://gitee.com/binary/weixin-java-tools
微信Java
开发工具包,支持包括微信支付、开放平台、公众号、企业微信/企业号、小程序等微信功能模块的后端开发。
微信小程序:weixin-java-miniapp
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.5.5.B</version>
</dependency>
说明:在父工程已经对改依赖进行了版本管理,这里直接引入即可
common-account.yaml
wx:
miniapp:
#小程序授权登录
appId: your_appid # 小程序微信公众平台appId
secret: your_secret # 小程序微信公众平台api秘钥
WxMaProperties
@Data
@Component
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxMaProperties {
private String appId;
private String secret;
}
WxMaConfig
配置WxMaService,通过WxMaService可以快速获取微信OpenId
@Component
public class WxMaConfig {
@Autowired
private WxMaProperties wxMaProperties;
@Bean
public WxMaService wxMaService() {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(wxMaProperties.getAppId());
config.setSecret(wxMaProperties.getSecret());
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
return service;
}
}
CustomerInfoController
@Operation(summary = "小程序授权登录")
@GetMapping("/login/{code}")
public Result<Long> login(@PathVariable String code) {
return Result.ok(customerInfoService.login(code));
}
CustomerInfoService
Long login(String code);
CustomerInfoServiceImpl
@Autowired
private WxMaService wxMaService;
@Autowired
private CustomerLoginLogMapper customerLoginLogMapper;
/**
* 条件:
* 1、前端开发者appid与服务器端appid一致
* 2、前端开发者必须加入开发者
* @param code
* @return
*/
@Transactional(rollbackFor = {Exception.class})
@Override
public Long login(String code) {
String openId = null;
try {
//获取openId
WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
openId = sessionInfo.getOpenid();
log.info("【小程序授权】openId={}", openId);
} catch (Exception e) {
e.printStackTrace();
throw new GuiguException(ResultCodeEnum.WX_CODE_ERROR);
}
CustomerInfo customerInfo = this.getOne(new LambdaQueryWrapper<CustomerInfo>().eq(CustomerInfo::getWxOpenId, openId));
if(null == customerInfo) {
customerInfo = new CustomerInfo();
customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
customerInfo.setWxOpenId(openId);
this.save(customerInfo);
}
//登录日志
CustomerLoginLog customerLoginLog = new CustomerLoginLog();
customerLoginLog.setCustomerId(customerInfo.getId());
customerLoginLog.setMsg("小程序登录");
customerLoginLogMapper.insert(customerLoginLog);
return customerInfo.getId();
}
2.2、Feign接口
CustomerInfoFeignClient
/**
* 小程序授权登录
* @param code
* @return
*/
@GetMapping("/customer/info/login/{code}")
Result<Long> login(@PathVariable String code);
2.3、乘客端Web模块web-customer
CustomerController
@Slf4j
@Tag(name = "客户API接口管理")
@RestController
@RequestMapping("/customer")
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerController {
@Autowired
private CustomerService customerInfoService;
@Operation(summary = "小程序授权登录")
@GetMapping("/login/{code}")
public Result<String> wxLogin(@PathVariable String code) {
return Result.ok(customerInfoService.login(code));
}
}
CustomerService
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {
//注入远程调用接口
@Autowired
private CustomerInfoFeignClient client;
@Autowired
private RedisTemplate redisTemplate;
@Override
public String login(String code) {
//1 拿着code进行远程调用,返回用户id
Result<Long> loginResult = client.login(code);
//2 判断如果返回失败了,返回错误提示
Integer codeResult = loginResult.getCode();
if(codeResult != 200) {
throw new GuiguException(ResultCodeEnum.DATA_ERROR);
}
//3 获取远程调用返回用户id
Long customerId = loginResult.getData();
//4 判断返回用户id是否为空,如果为空,返回错误提示
if(customerId == null) {
throw new GuiguException(ResultCodeEnum.DATA_ERROR);
}
//5 生成token字符串
String token = UUID.randomUUID().toString().replaceAll("-","");
//6 把用户id放到Redis,设置过期时间
// key:token value:customerId
//redisTemplate.opsForValue().set(token,customerId.toString(),30, TimeUnit.MINUTES);
redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+token,
customerId.toString(),
RedisConstant.USER_LOGIN_KEY_TIMEOUT,
TimeUnit.SECONDS);
//7 返回token
return token;
}
}
3、获取登录用户信息接口
3.1、乘客登录微服务模块service-customer
controller
@Operation(summary = "获取客户登录信息")
@GetMapping("/getCustomerLoginInfo/{customerId}")
public Result<CustomerLoginVo> getCustomerLoginInfo(@PathVariable Long customerId) {
CustomerLoginVo customerLoginVo = customerInfoService.getCustomerInfo(customerId);
return Result.ok(customerLoginVo);
}
service
//获取客户登录信息
@Override
public CustomerLoginVo getCustomerInfo(Long customerId) {
//1 根据用户id查询用户信息
CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
//2 封装到CustomerLoginVo
CustomerLoginVo customerLoginVo = new CustomerLoginVo();
//customerLoginVo.setNickname(customerInfo.getNickname());
BeanUtils.copyProperties(customerInfo,customerLoginVo);
//@Schema(description = "是否绑定手机号码")
// private Boolean isBindPhone;
String phone = customerInfo.getPhone();
boolean isBindPhone = StringUtils.hasText(phone);
customerLoginVo.setIsBindPhone(isBindPhone);
//3 CustomerLoginVo返回
return customerLoginVo;
}
3.2、Feign接口
//获取登录用户信息
@GetMapping("/customer/info/getCustomerLoginInfo/{customerId}")
public Result<CustomerLoginVo> getCustomerInfo(@PathVariable Long customerId);
3.3、乘客端Web模块web-customer
controller
@Operation(summary = "获取客户登录信息")
@GetMapping("/getCustomerLoginInfo")
public Result<CustomerLoginVo>
getCustomerLoginInfo(@RequestHeader(value = "token") String token) {
//1 从请求头获取token字符串
// HttpServletRequest request
// String token = request.getHeader("token");
//调用service
CustomerLoginVo customerLoginVo = customerInfoService.getCustomerLoginInfo(token);
return Result.ok(customerLoginVo);
}
service
@Override
public CustomerLoginVo getCustomerLoginInfo(String token) {
//2 根据token查询redis
//3 查询token在redis里面对应用户id
String customerId =
(String)redisTemplate.opsForValue()
.get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
if(StringUtils.isEmpty(customerId)) {
throw new GuiguException(ResultCodeEnum.DATA_ERROR);
}
// if(!StringUtils.hasText(customerId)) {
// throw new GuiguException(ResultCodeEnum.DATA_ERROR);
// }
//4 根据用户id进行远程调用 得到用户信息
Result<CustomerLoginVo> customerLoginVoResult =
customerInfoFeignClient.getCustomerLoginInfo(Long.parseLong(customerId));
Integer code = customerLoginVoResult.getCode();
if(code != 200) {
throw new GuiguException(ResultCodeEnum.DATA_ERROR);
}
CustomerLoginVo customerLoginVo = customerLoginVoResult.getData();
if(customerLoginVo == null) {
throw new GuiguException(ResultCodeEnum.DATA_ERROR);
}
//5 返回用户信息
return customerLoginVo;
}
4、登录校验
- 如何判断是否登录状态?
– 判断请求头里面是否包含token字符串
– 根据token查询redis
- 如何实现?
– 原始方式:在需要判断登录的controller进行上面判断(token和redis)
– 如果使用原始方式,功能肯定可以实现的,但是造成有大量重复代码
– 对这样方式进行优化
- 如何优化?
– 使用自定义注解 + aop 进行优化
- aop基础知识
- aop实现流程
4.1、创建注解
//登录判断
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GuiguLogin {
}
4.2、创建切面类
@Component
@Aspect //切面类
public class GuiguLoginAspect {
@Autowired
private RedisTemplate redisTemplate;
//环绕通知,登录判断
//切入点表达式:指定对哪些规则的方法进行增强
@Around("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(guiguLogin)")
public Object login(ProceedingJoinPoint proceedingJoinPoint,GuiguLogin guiguLogin) throws Throwable {
//1 获取request对象
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes)attributes;
HttpServletRequest request = sra.getRequest();
//2 从请求头获取token
String token = request.getHeader("token");
//3 判断token是否为空,如果为空,返回登录提示
if(!StringUtils.hasText(token)) {
throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
}
//4 token不为空,查询redis
String customerId = (String)redisTemplate.opsForValue()
.get(RedisConstant.USER_LOGIN_KEY_PREFIX+token);
//5 查询redis对应用户id,把用户id放到ThreadLocal里面
if(StringUtils.hasText(customerId)) {
AuthContextHolder.setUserId(Long.parseLong(customerId));
}
//6 执行业务方法
return proceedingJoinPoint.proceed();
}
}
5、获取微信手机号
5.1、乘客登录微服务模块service-customer
controller
@Operation(summary = "更新客户微信手机号码")
@PostMapping("/updateWxPhoneNumber")
public Result<Boolean> updateWxPhoneNumber(@RequestBody UpdateWxPhoneForm updateWxPhoneForm) {
return Result.ok(customerInfoService.updateWxPhoneNumber(updateWxPhoneForm));
}
service
更新客户微信手机号码
@Override
public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
//1 根据code值获取微信绑定手机号码
try {
WxMaPhoneNumberInfo phoneNoInfo =
wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
String phoneNumber = phoneNoInfo.getPhoneNumber();
//更新用户信息
Long customerId = updateWxPhoneForm.getCustomerId();
CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
customerInfo.setPhone(phoneNumber);
customerInfoMapper.updateById(customerInfo);
return true;
} catch (WxErrorException e) {
throw new GuiguException(ResultCodeEnum.DATA_ERROR);
}
}
5.2、Feign接口
@PostMapping("/customer/info/updateWxPhoneNumber")
Result<Boolean> updateWxPhoneNumber(@RequestBody UpdateWxPhoneForm updateWxPhoneForm);
5.3、乘客端Web模块web-customer
controller
@Operation(summary = "更新用户微信手机号")
@GuiguLogin
@PostMapping("/updateWxPhone")
public Result updateWxPhone(@RequestBody UpdateWxPhoneForm updateWxPhoneForm) {
updateWxPhoneForm.setCustomerId(AuthContextHolder.getUserId());
return Result.ok(customerInfoService.updateWxPhoneNumber(updateWxPhoneForm));
}
service
//更新用户微信手机号
@Override
public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
Result<Boolean> booleanResult = customerInfoFeignClient.updateWxPhoneNumber(updateWxPhoneForm);
return true;
}