@ApiOperation(value = "微信授权登录")
@RequestMapping("doLoginByWechat")
@ResponseBody
public Object doLoginByWechat(HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
String code = request.getParameter("code");
if (StringUtils.isEmpty(code) ) {
map.put("code", Result.ERROR);
map.put("msg", "请先进行授权!");
return map;
}
String result = null;
try {
//获取access_token
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
String replaceUrl = url.replace("{0}", appid).replace("{1}", secret);
String res = HttpUtil.get(replaceUrl);
JSONObject json_token = JSON.parseObject(res);
String access_token = json_token.getString("access_token");
//获取手机号
String urlTwo = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={0}";
String replaceUrlTwo = urlTwo.replace("{0}",access_token);
HashMap<String, Object> requestParam = new HashMap<>();
// 手机号调用凭证
requestParam.put("code", code);
String jsonStr = JSON.toJSONString(requestParam);
HttpResponse response = HttpRequest.post(replaceUrlTwo)
.header(Header.CONTENT_ENCODING, "UTF-8")
// 发送json数据需要设置contentType
.header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(jsonStr)
.execute();
if (response.getStatus() == HttpStatus.HTTP_OK) {
result = response.body();
}
Object phone_info=JSONObject.parseObject(result).get("phone_info");
String purePhoneNumber=JSONObject.parseObject(phone_info.toString()).get("purePhoneNumber").toString();
if(StringUtils.isBlank(purePhoneNumber)){
map.put("code", Result.ERROR);
map.put("msg", "当前用户没有绑定手机号!");
return map;
}else{
CurriculumVitae curriculumVitae=new CurriculumVitae();
curriculumVitae.setPhone(purePhoneNumber);
//根据loginIphone查询
List<CurriculumVitae> CurriculumVitaes = trialService.selectByIphone(curriculumVitae);
if(CurriculumVitaes.size()==1) {
//修改对应信息
trialService.updateByWechat("1");
}else{
map.put("code", Result.ERROR);
map.put("msg", "手机号有误!");
return map;
}
}
//生成token
String token = JwtUtil.createToken(purePhoneNumber);
map.put("code", Result.SUCCESS);
map.put("msg", "登录成功");
map.put("token", token);
log.info(purePhoneNumber+"在"+new Date()+"登录后台成功");
} catch (Exception e) {
map.put("code", Result.WARN);
map.put("msg", "获取失败!");
return map;
}
return JSONObject.parseObject(result).get("phone_info");
}
yml添加
#微信小程序
weixin:
appid: wx836f5035d64898a5
secret: eb96a3b31d3cc2aa16691b1d38ad7faa