Commit c3c49c90 authored by 廖旭伟's avatar 廖旭伟

获取微信openId接口

parent dd888f6a
package com.mortals.xhx.busiz.web;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.SecurityUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.busiz.req.H5Req;
import com.mortals.xhx.common.utils.WeChatUtils;
import com.mortals.xhx.module.company.model.CompanyEntity;
import com.mortals.xhx.module.company.service.CompanyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED_CONTENT;
......@@ -44,7 +55,81 @@ public class H5LoginController extends BaseCRUDJsonBodyMappingController<UserSer
private IAuthTokenService authTokenService;
@Autowired
private CompanyService companyService;
@Autowired
private ICacheService cacheService;
private static String WX_VERIFY_CODE_KEY ="login:wx:verify:";
/**
* 微信appId
*/
@Value("${WeChat.pc.appID:wx3490570828df45c8}")
private static String APP_ID;
/**
* 微信appSecret
*/
@Value("${WeChat.pc.appSecret:8654c409f1a18f7ddffc70ee20d05ef1}")
private static String APP_SECRET;
@RequestMapping(value = {"getLoginSoleCode"},method = {RequestMethod.POST, RequestMethod.GET})
@UnAuth
public Rest<Object> sendSmsVerifyCode(){
Rest<Object> ret = new Rest();
Map<String, Object> model = new HashMap();
String busiDesc = "获取微信登录验证码";
int code=1;
try {
String vCode = RandomUtil.randomNumbers(11);
cacheService.setnx(WX_VERIFY_CODE_KEY+vCode,vCode,90);
model.put("data",vCode);
model.put("message_info", busiDesc + "成功");
} catch (Exception var9) {
code = -1;
this.doException(this.request, busiDesc, model, var9);
}
ret.setCode(code);
ret.setData(model.get("data"));
ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
return ret;
}
@RequestMapping(value = {"bind"},method = {RequestMethod.POST, RequestMethod.GET})
@UnAuth
public String bind(HttpServletRequest request, HttpServletResponse response){
JSONObject ret = new JSONObject();
Map<String, Object> data = new HashMap<>();
try {
// 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;
String loginCode = request.getParameter("code");
//前端扫码登入传来的时间戳
String loginState = request.getParameter("state");
//用户拒绝授权时code为空,微信也不会请求该接口。为了防止非法请求,若code为空则返回
if (StringUtils.isEmpty(loginCode)) {
throw new AppException("登入请求被拒绝");
}
if (StringUtils.isEmpty(loginState)) {
throw new AppException("请求状态异常");
}
String vCode = cacheService.get(WX_VERIFY_CODE_KEY + loginState);
if (StringUtils.isEmpty(vCode)){
throw new AppException("微信登录验证码失效");
}
Map<String,String> accessTokenMap = WeChatUtils.getAccessToken(loginCode,APP_ID,APP_SECRET);
//String access_token = accessTokenMap.get("access_token");//接口调用凭证,登录后右上角展示数据需要该值去获取
String openid = accessTokenMap.get("openid");//授权用户唯一标识
data.put("openId", openid);
ret.put(KEY_RESULT_DATA, data);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
ret.put(KEY_RESULT_MSG, "微信扫码成功!");
return ret.toJSONString();
} catch (Exception e) {
log.error("bind error ", e);
ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
ret.put(KEY_RESULT_MSG, super.convertException(e));
return ret.toJSONString();
}
}
@RequestMapping("login")
@UnAuth
......
package com.mortals.xhx.common.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* description: json工具类 <br>
* version: 1.0 <br>
* @date: 2019/7/20 0019 上午 10:17 <br>
* @author: William <br>
*/
public class JsonUtils {
public static final ObjectMapper MAPPER = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
public static String serialize(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("json序列化出错:" + obj, e);
return null;
}
}
public static <T> T parse(String json, Class<T> tClass) {
try {
return MAPPER.readValue(json, tClass);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <E> List<E> parseList(String json, Class<E> eClass) {
try {
return MAPPER.readValue(json, MAPPER.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <K, V> Map<K, V> parseMap(String json, Class<K> kClass, Class<V> vClass) {
try {
return MAPPER.readValue(json, MAPPER.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <T> T nativeRead(String json, TypeReference<T> type) {
try {
return MAPPER.readValue(json, type);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
}
\ No newline at end of file
package com.mortals.xhx.common.utils;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import java.util.Map;
/**
* description: WeChatUtils 微信获取用户工具类<br>
*
* @date: 2021/8/19 0019 上午 10:05 <br>
* @author: William <br>
* version: 1.0 <br>
*/
public class WeChatUtils {
/**
* 获取微信accessToken路径
*/
private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
/**
* 微信appId
*/
@Value("${WeChat.pc.appID:wx3490570828df45c8}")
private static String APP_ID;
/**
* 微信appSecret
*/
@Value("${WeChat.pc.appSecret:8654c409f1a18f7ddffc70ee20d05ef1}")
private static String APP_SECRET;
/**
* description: getAccessToken 根据code获取accessToken<br>
* version: 1.0 <br>
* @date: 2021/8/19 0019 上午 10:10 <br>
* @author: William <br>
* @param code 微信用户授权code
* @return java.util.Map<java.lang.String,java.lang.String>
*/
public static Map<String,String> getAccessToken(String code){
return getAccessToken(code,APP_ID,APP_SECRET);
}
/**
* description: getAccessToken 根据code获取微信用户信息,返回map如果正确map包含access_token ,如果错误则包含:errcode<br>
* version: 1.0 <br>
* @date: 2021/8/19 0019 上午 10:11 <br>
* @author: William <br>
* @param code 微信授权code
* @param appId 微信appId
* @param appSecret 微信appSecret
* @return java.util.Map<java.lang.String,java.lang.String>
*/
public static Map<String,String> getAccessToken(String code,String appId,String appSecret){
//判断所有字段不能为空
if(isAnyBlank(code,appId,appSecret)){
throw new IllegalArgumentException("参数错误");
}
String requestUrl = GET_ACCESS_TOKEN_URL.replace("APPID",appId)
.replace("SECRET",appSecret).replace("CODE",code);
String result = HttpUtil.get(requestUrl);
return JsonUtils.parseMap(result, String.class, String.class);
}
/**
* description: isAnyBlank 判断是否存在空字符串,Hutool未编写<br>
* version: 1.0 <br>
* @date: 2021/8/19 0019 上午 10:25 <br>
* @author: William <br>
* @param strs 字符串
* @return java.lang.Boolean
*/
public static Boolean isAnyBlank(CharSequence... strs){
//如果为空直接返回true
if (ArrayUtil.isEmpty(strs)) {
return true;
}
for (CharSequence str : strs) {
if (StrUtil.isBlank(str)) {
return true;
}
}
return false;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment