package hry.project.cdwjs.wxLogin.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import hry.bean.JsonResult;
import hry.business.cu.model.CuCustomer;
import hry.business.cu.service.CuCustomerService;
import hry.project.cdwjs.wxLogin.WxDecryptUtills;
import hry.project.cdwjs.wxLogin.WxLoginService;
import hry.project.cdwjs.wxLogin.WxLoginVo;
import hry.redis.RedisService;
import hry.security.jwt.JWTToken;
import hry.security.jwt.JWTUtil;
import hry.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
/**
* @author qyb
* @version 1.0
* @date 2023/3/9-17:38
*/
@Service
@Slf4j
public class WxLoginServiceImpl implements WxLoginService {
@Value("${wxLogin.appId}")
private String appId;
@Value("${wxLogin.appSecret}")
private String appSecret;
@Autowired
private CuCustomerService cuCustomerService;
@Autowired
private RedisService redisService;
/**
* 获取accesstoken
*
* @return
*/
private String getAccessToken() {
String accessToken = "";
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
try {
String resultString = HttpUtils.get(url);
log.info("获取微信accessToken:{}", resultString);
if (StringUtils.isNotEmpty(resultString)) {
JSONObject jsonObject = JSON.parseObject(resultString);
accessToken = jsonObject.get("access_token").toString();
} else {
log.error("返回值为空,请检查请求报文或者请求地址是否正确");
}
} catch (Exception e) {
e.printStackTrace();
}
return accessToken;
}
/**
* 获取手机号
*/
private String getPhoneNumber(String code) {
String phoneNumber = "";
String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken();
HashMap<String, String> params = new HashMap<>();
params.put("code", code);
try {
String resultString = HttpUtils.postByQuery(url, params, null);
log.info("获取微信手机号码:{}", resultString);
if (StringUtils.isNotEmpty(resultString)) {
JSONObject jsonObject = JSON.parseObject(resultString);
JSONObject phone_info = jsonObject.getJSONObject("phone_info");
phoneNumber = phone_info.getString("phoneNumber");
} else {
log.error("返回值为空,请检查请求报文或者请求地址是否正确");
}
} catch (Exception e) {
e.printStackTrace();
}
return phoneNumber;
}
/**
* 获取openId
*/
private String getOpenId(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
try {
String resultString = HttpUtils.get(url);
log.info("获取微信openId:{}", resultString);
if (StringUtils.isNotEmpty(resultString)) {
return resultString;
} else {
log.error("返回值为空,请检查请求报文或者请求地址是否正确");
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@Override
public JsonResult loginByWx(WxLoginVo wxLoginVo) {
String res = this.getOpenId(wxLoginVo.getUserInfoCode());
JSONObject jsonObject = JSONObject.parseObject(res);
String openId = jsonObject.getString("openid");
String sessionKey = jsonObject.getString("session_key");
if (StringUtils.isEmpty(openId)) {
return new JsonResult().setMsg("未获取到openId,登录失败");
}
String data = WxDecryptUtills.decrypt(wxLoginVo.getEncryptData(), sessionKey, wxLoginVo.getIv());
JSONObject jsonObject1 = JSONObject.parseObject(data);
String phoneNumber =jsonObject1.getString("phoneNumber");
if (StringUtils.isEmpty(phoneNumber)) {
return new JsonResult().setMsg("未获取到手机号,登录失败");
}
CuCustomer cuCustomer = cuCustomerService.checkMobile(phoneNumber);
if (cuCustomer == null) {
// 注册
cuCustomer = cuCustomerService.regist3(openId, phoneNumber, wxLoginVo.getNickname(), wxLoginVo.getAvatar());
} else {
// 写入微信openid
if (StringUtils.isEmpty(cuCustomer.getWxOpenId())) {
cuCustomer.setWxOpenId(openId);
}
cuCustomer.setWxAvatar(wxLoginVo.getAvatar());
cuCustomerService.update(cuCustomer);
}
// 登录
String token = JWTUtil.sign(phoneNumber, JWTToken.SOURCE_PC, JWTToken.TYPE_CUSTOMER, cuCustomer.getPassword());
redisService.save(JWTUtil.getCustomerRefreshTimeKey(token), JSON.toJSONString(cuCustomer), JWTUtil.REFRESH_TIME);
redisService.save(JWTUtil.getCustomerUserKey(token), JSON.toJSONString(cuCustomer), JWTUtil.EXPIRE_TIME);
//防止用户多端登录,产生多个token
String oldTokenStr = redisService.get("LOGINCUCUSTOMER:" + cuCustomer.getId());
if (StringUtils.isNotEmpty(oldTokenStr)) {
JWTToken oldToken = new JWTToken(oldTokenStr);
redisService.delete("JWT:token:" + oldToken.getSource() + ":" + oldToken.getType() + ":refreshTime:" + oldToken.getSignId());
redisService.delete("JWT:token:" + oldToken.getSource() + ":" + oldToken.getType() + ":user:" + oldToken.getSignId());
}
redisService.save("LOGINCUCUSTOMER:" + cuCustomer.getId(), token);
HashMap<String, Object> map = new HashMap<>();
map.put("token", token);
return new JsonResult().setSuccess(true).setObj(map);
}
}
暂时没有评论,来抢沙发吧~