<!-- 微信开放平台二维码js-->
<script th:src="@{http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js}">
<!-- js 请求二维码 建议ajax获取公众平台的各种参数-->
var obj = new WxLogin({
id:"login_container",
appid: "appid",//开放平台appid
scope: "snsapi_login",
redirect_uri: "redirect_uri",//请求回调的url 这需要全路径带域名的 例
如: https://xxx.net/getWeChatCallback
state: "请求校验值",//自定的的值,后台存缓存或者存redis中 防止csrf攻击
style: "black",//这个是二维码样式
href: ""//二维码样式引用链接 也需要带域名
});
<!-- 显示二维码的div-->
<div id="login_container">
</div>
后台代码
openWeChatLogin 是直接请求跳转扫码的方法
getWeChatCallback 请求成功回调方法 用于上面JS内容部分 的redirect_uri 例如: https://xxx.net/getWeChatCallback
//微信开放平台请求二维码方法
@RequestMapping("/openWeChatLogin")
public String openWeChatLogin(HttpServletRequest request,HttpServletRequest
httpServletRequest) {
// 防止csrf攻击(跨站请求伪造攻击)
String state = UUID.randomUUID().toString().replaceAll("-", "");
CacheUtils.put("state", state);
// https://open.weixin.qq.com/connect/oauth2/authorize?
String url = "https://open.weixin.qq.com/connect/qrconnect?" +
"appid=" +
env.getProperty("wechat.open.appid").trim() +
"&redirect_uri=" +
env.getProperty("application.url") +
env.getProperty("wechat.open.redirect_uri").trim() +
"&response_type=code" +
"&scope=snsapi_login" +
"&state=" +
state + // 由后台自动生成
"#wechat_redirect";
return "redirect:" + url;
}
//微信开发平台回调方法
@RequestMapping("/getWeChatCallback")
public String getWeChatCallback(HttpServletRequest request,HttpServletRequest httpServletRequest) {
String code = httpServletRequest.getParameter("code");
String state = httpServletRequest.getParameter("state");
// 判断state是否合法
String stateStr = (String) CacheUtils.get("state");//缓存取值
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(stateStr) || !state.equals(stateStr)) {
return "illegalityRequest"; //不合法跳转提示页面
}
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" +
env.getProperty("wechat.open.appid").trim() +
"&secret=" +
env.getProperty("wechat.open.appsecret").trim() +
"&code=" +
code +
"&grant_type=authorization_code";
try {
// 调用请求方法
String json = urlToJson(url);
JSONObject json1 = JSONObject.parseObject(json.toString());
String unionid = json1.get("unionid").toString();
if(StringUtils.isNotEmpty(unionid) ) {
TSBaseUser baseUser = tSBaseUserService.selectTSBaseUserByOpenId(unionid);
if(baseUser != null) {
CustomizedToken token = new CustomizedToken(baseUser.getUsername(), baseUser.getPassword() ,LoginType.APP.toString());
Subject subject = SecurityUtils.getSubject();
try
{
subject.login(token);
return "index";
}
catch (AuthenticationException e){
String msg = "登录失败";
}
}else {
//跳转绑定页面 用户再次登录绑定微信openid
request.setAttribute("openid",unionid);
return "weChatBinding";
}
}else {
//获取openid 失败
}
} catch (JsonParseException e) {
System.out.println("json解析失败:");
} catch (Exception e) {
System.out.println("http获取openId请求失败:");
}
return "login";
}
/**
* 对url发送请求并获取返回的数据
*
* @param url
* @return
*/
public String urlToJson(String url) {
StringBuffer json1 = new StringBuffer();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "utf-8"));
String inputLine = null;
// StringBuffer json1 = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
json1.append(inputLine);
}
} catch (Exception e) {
System.out.println(e);
}
return json1.toString();
}
//微信公众平台请求二维码方法
@RequestMapping("/openWeChatLogin")
public String openWeChatLogin(HttpServletRequest request,HttpServletRequest
httpServletRequest) {
// 防止csrf攻击(跨站请求伪造攻击)
String state = UUID.randomUUID().toString().replaceAll("-", "");
CacheUtils.put("state", state);
// https://open.weixin.qq.com/connect/oauth2/authorize?
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" +
env.getProperty("wechat.open.appid").trim() +
"&redirect_uri=" +
env.getProperty("application.url") +
env.getProperty("wechat.open.redirect_uri").trim() +
"&response_type=code" +
"&scope=snsapi_userinfo" +
"&state=" +
state + // 由后台自动生成
"#wechat_redirect";
return "redirect:" + url;
}
//微信公众平台回调方法
@RequestMapping("/getWeChatCallback")
public String getWeChatCallback(HttpServletRequest request,HttpServletRequest httpServletRequest) {
String code = httpServletRequest.getParameter("code");
String state = httpServletRequest.getParameter("state");
String url = null;
// 判断state是否合法
String stateStr = (String) CacheUtils.get("state");//缓存取值
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(stateStr) || !state.equals(stateStr)) {
return "illegalityRequest";
}
url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" +
env.getProperty("wechat.open.appid").trim() +
"&secret=" +
env.getProperty("wechat.open.appsecret").trim() +
"&code=" +
code +
"&grant_type=authorization_code";
try {
// 调用请求方法
String json = urlToJson(url);
JSONObject json1 = JSONObject.parseObject(json.toString());
String unionid = json1.get("unionid").toString();
if(StringUtils.isNotEmpty(unionid) ) {
TSBaseUser baseUser = tSBaseUserService.selectTSBaseUserByOpenId(unionid);
if(baseUser != null) {
CustomizedToken token = new CustomizedToken(baseUser.getUsername(), baseUser.getPassword() ,LoginType.APP.toString());
Subject subject = SecurityUtils.getSubject();
try
{
subject.login(token);
return "index";
}
catch (AuthenticationException e){
String msg = "登录失败";
}
}else {
//跳转绑定页面 用户再次登录绑定微信openid
request.setAttribute("openid",unionid);
return "weChatBinding";
}
}else {
//获取openid 失败
}
} catch (JsonParseException e) {
System.out.println("json解析失败:");
} catch (Exception e) {
System.out.println("http获取openId请求失败:");
}
return "login";
}
/**
* 对url发送请求并获取返回的数据
*
* @param url
* @return
*/
public String urlToJson(String url) {
StringBuffer json1 = new StringBuffer();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "utf-8"));
String inputLine = null;
// StringBuffer json1 = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
json1.append(inputLine);
}
} catch (Exception e) {
System.out.println(e);
}
return json1.toString();
}