可以自行查询文档-
微信开放平台
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=b76e865cfb65ebc5f7fda8da68755abe4427731a&lang=zh_CN
微信pc端二维码登录(电脑只能是扫码登录)
第一步:请求CODE(注意-微信文档规定回调地址必须外网可以访问)
/**
* pc二维码微信授权
* @param request
* @param response
*/
@RequestMapping(value = "/wx_login1", method = RequestMethod.GET)
public void wxU_login1(HttpServletRequest request, HttpServletResponse response){
try {
String state = StringUtilsEx.RandomString(32);
request.getSession().setAttribute("wechat_login", state);
redisService.set("wechat_login", state, 300);
String scope = "snsapi_login";//静默授权 只能获取access_token和openID,流程走完即终止,snsapi_userinfo可以获取更详细的用户资料,比如头像、昵称、性别等
//String url = URLEncoder.encode(CALLBACKDOMAIN+"wechat_charge.do?cardnum=" + cardnum + "&userid=" + userid + "&agentid=" + agentid, "utf-8");
String url = URLEncoder.encode("http://api.hestia.me/m/validate/M5V5VI9D0EE/"+"v1/user/callback.do" , "utf-8");//CALLBACK_DOMAIN为授权回调页面域名
//获取code
String code_url = "https://open.weixin.qq.com/connect/qrconnect?appid=" +APPIDPC
+ "&redirect_uri=" + url + "&response_type=code&scope=" + scope + "&state="+state+"#wechat_redirect";
response.sendRedirect(code_url);//可以获取code 信息并且转发到redirect_uri的地址里
} catch (Exception e) {
e.printStackTrace();
}
}
第二步:通过code获取access_token
/**
* pc二维码微信授权回调
* @param request
* @param response
*/
@RequestMapping(value = "/callback", method = RequestMethod.GET)
public void callback(HttpServletRequest request, HttpServletResponse response){
String code_url=null;
try {
String back_state = request.getParameter("state");
String state =redisService.get("wechat_login")
redisService.del("wechat_login");
String code = request.getParameter("code");//授权时候,微信会吧参数传到这里
if(!StringUtils.equalsIgnoreCase(back_state, state)){
throw new ServiceException("请求无效!");
}
String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token"+"?appid=" + APPIDPC+ "&secret=" + AppSecretPC + "&code=" + code + "&grant_type=authorization_code";
String access_token_str;
/* RestTemplate restTemplate=new RestTemplate();
String access_token_str1= restTemplate.getForObject(access_token_url, String.class);
logger.info(access_token_str1);
*/
access_token_str = httpAPIService.doGet(access_token_url);
logger.info("----------->> access_token_str:"+access_token_str);
if(StringUtils.isBlank(access_token_str)){throw new ServiceException("微信授权访问通讯异常!");}
Map tokenmap = JSONUtilsEx.deserialize(access_token_str, Map.class);
if(tokenmap.get("errcode") != null){
throw new ServiceException("获取token失败:"+ObjectUtils.defaultIfNull(tokenmap.get("errmsg"), ""));
}
String openid = String.valueOf(tokenmap.get("openid"));
String token = String.valueOf(tokenmap.get("access_token"));
Map
info.put("openid", openid);
info.put("token", token);
String key = "wechat_login_user"+openid;
redisService.set(key, JSONUtilsEx.serialize(info), 300);
// code_url = infourl.replaceAll("\\{openid\\}", openid);
code_url = "http://192.168.1.79:8090/mywx.shtml?openid="+openid; //转发地址-mywx.shtml页面是一个空页面只是为了接受参数转发接口
response.sendRedirect(code_url);
} catch (Exception e) {
e.printStackTrace();
}
}
第三步-页面mywx.shtml
页面获取上面方法传过来的参数openid页面ajax请求接口名为toLogin
/**
* 回调之后获取oppenid返回到的页面
* @param request
* @param response
*/
@RequestMapping(value = "/toLogin", method = RequestMethod.GET)
public ResponseEntity
JsonResult r = null;
//
try {
String openidS=request.getParameter("openid");
if(openidS==null){
throw new ServiceException("openid错误");
}
String key="wechat_login_user"+openidS;
String info =redisService.get(key);
JSONObject jsonObj = new JSONObject(info);
String openid=String.valueOf(jsonObj.get("openid"));
String token=String.valueOf(jsonObj.get("token"));
Map
info1.put("openid", openid);
info1.put("token", token);
r= new JsonResult("0","ok", info1);
} catch (Exception e) {
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
}
页面获取到openid和token在使用ajax请求发送给登录接口
/**
* 登录验证
* @param user
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity
JsonResult r = null;
User v_user = null;
try {
//请求验证
String ver_str = VerifyUtilsEx.verifyData(user, new String[] {"account", "pwd","appid","utype"});
if(StringUtils.isNotBlank(ver_str)){
throw new ServiceException(ver_str);
}
String ip = CommonUtilsEx.getIpAddr(request);
//校验是否三方账号登录
String utype = user.containsKey("utype") ? user.get("utype") : "";
if(StringUtils.isBlank(utype) || !"U_WX".equals(utype)){
v_user = userService.login(user.get("account"), user.get("pwd"), user.get("appid"),utype, ip);
}else{
v_user = userService.authLogin(user.get("account"), user.get("pwd"), user.get("appid"), utype, ip);//根据自己业务 在这个里面根据openid和token获取用户信息
}
TokenModel token = tokenManager.createToken(String.valueOf(v_user.getId()));
r= new JsonResult("0", "", token);
} catch(ServiceException se){
r= new JsonResult("-1", se.getMessage());
} catch (Exception e) {
r= new JsonResult("-2", "系统错误");
logger.error(e.getMessage());
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
用到的工具类
public class HttpUtilEx {
private static Logger logger = LoggerFactory.getLogger(HttpUtilEx.class);
/**
* get请求
* @return
*/
public static String doGet(String url) {
try {
CloseableHttpClient client = HttpClients.createDefault();
//发送get请求
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class JSONUtilsEx {
/**
* JSON字符串反序列化成对象
* @param jsonStr
* @param clazz
* @return
* @throws ServiceException
*/
public static
if (StringUtils.isEmpty(jsonStr)) {
return null;
}
try {
return mapper.readValue(jsonStr.replace("\n", ""), clazz);
} catch (Exception e) {
throw new ServiceException("JSON反序列化结果异常:" + e.getMessage());
}
}
}
时间有点赶,有什么问题可以给我留言!我会及时给你回复!
后续会更新手机端的授权
微信公众号的支付,前后端的整个流程,会写的更详细