目录
一.编码前准备工作
二.源码
1.WXConstants
2.HttpRequestUtils
3.WXLogin
1.打开微信开放平台https://open.weixin.qq.com/,注册并认证账号,必须通过企业注册
2.登录微信开放平台并在管理中心创建网站应用提交审核,审核通知之口通过查看详情可获得AppID和AppSecret
3.进行编码
public class WXConstants {
// 微信开放平台创建的网站应用的appsecret
public static final String APPSECRET = "1b97ce0a29cc41e2abb66096";
// 微信开放平台创建的网站应用的appid
public static final String APPID = "wxf060e68596d5";
public static final String SCOPE = "snsapi_login";
// 微信开放平台创建的网站 设置的授权回调域
public static final String DOMAIN_NAME = "http://196.29.119.38";
}
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class HttpRequestUtils {
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager connectionManager
= new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(100);
connectionManager.setDefaultMaxPerRoute(20);
connectionManager.setDefaultMaxPerRoute(50);
httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
}
public static String get(String url) {
CloseableHttpResponse response = null;
BufferedReader in = null;
String result = "";
try {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)
.setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpGet.setConfig(requestConfig);
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
httpGet.setHeader("Accept", "application/json");
response = httpClient.execute(httpGet);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String post(String url, String jsonString) {
CloseableHttpResponse response = null;
BufferedReader in = null;
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)
.setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpPost.setConfig(requestConfig);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSON;
import com.hongedu.ttms.ttms.commons.constant.EntityTrainingSystemConstants;
import com.hongedu.ttms.ttms.entity.User;
import com.hongedu.ttms.ttms.service.UserService;
import com.hongedu.ttms.ttms.web.front.index.FrontLoginController;
import com.hongedu.ttms.util.shiro.ShiroUser;
/**
*
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
*/
@Controller
@RequestMapping("/front/wxQr")
public class WXLogin extends HttpServlet{
private static final long serialVersionUID = 1L;
private final static Logger logger= LoggerFactory.getLogger(WXLogin.class);
@Autowired
private UserService userService;
/**1.授权*/
@RequestMapping("/wxAuth")
public void wxAuth (HttpServletRequest request,HttpServletResponse response) {
try {
String url = "https://open.weixin.qq.com/connect/qrconnect?"
+ "appid=APPID"
+ "&redirect_uri=REDIRECT_URI"
+ "&response_type=code"
+ "&scope=SCOPE"
+ "&state=STATE#wechat_redirect";
String callBack = WXConstants.DOMAIN_NAME + "/front/wxQr/callBack";
String redirect_uri = URLEncoder.encode(callBack, "UTF-8");
url = url.replace("APPID", WXConstants.APPID)
.replace("REDIRECT_URI", redirect_uri)
.replace("SCOPE", WXConstants.SCOPE);
response.sendRedirect(url);
} catch (Exception e) {
e.printStackTrace();
}
}
/** 2.回调,获取到openId&unionId */
@RequestMapping("/callBack")
public void callBack(HttpServletRequest request,HttpServletResponse response,
String code,String state,User loginUser){
try {
logger.info("进入授权回调,code:{},state:{}",code,state);
//1.通过code获取access_token
JSONObject accessToken = this.getAccessToken(code);
@SuppressWarnings("unused")
//2.通过access_token和openid(unionId)获取用户信息
JSONObject userInfo = this.getUserInfo(accessToken);
//3.通过unionId检测是否绑定微信
this.accountBinding(loginUser,accessToken,request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
/** 获取微信用户信息*/
private JSONObject getUserInfo(JSONObject accessToken) {
String url = "https://api.weixin.qq.com/sns/userinfo?"
+ "access_token=ACCESS_TOKEN&"
+ "openid=OPENID";
url = url.replace("ACCESS_TOKEN",accessToken.getString("access_token"))
.replace("OPENID",accessToken.getString("openid"));
String user = HttpRequestUtils.get(url);
logger.info("userInfo:{}",user);
JSONObject userInfo = new JSONObject(user);
return userInfo;
}
/**获取access_token*/
private JSONObject getAccessToken(String code) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
+ "appid=APPID"
+ "&secret=SECRET"
+ "&code=CODE"
+ "&grant_type=authorization_code";
url = url.replace("APPID",WXConstants.APPID)
.replace("SECRET",WXConstants.APPSECRET)
.replace("CODE",code);
String tokenInfo = HttpRequestUtils.get(url);
JSONObject accessToken = new JSONObject(tokenInfo);
logger.info("accessToken:{}",accessToken);
return accessToken;
}
public void accountBinding(User loginUser, JSONObject accessToken, HttpServletRequest request,
HttpServletResponse response) {
try {
String openId = accessToken.getString("openid");
String unionId = accessToken.getString("unionid");
String url;
PrintWriter out = response.getWriter();
User user = this.checkUserByUnionId(unionId);
if (user != null && StringUtils.isNotEmpty(user.getUnionId())) {
this.saveLoginInfo(user, request);
if (user.getRoleId()==EntityTrainingSystemConstants.EXPERT) {
url = "/expert/index";
out.println("");
}else if (user.getRoleId()==EntityTrainingSystemConstants.TRAINEE) {
url = "/person/projectIndex/index";
out.println("");
}
} else {
url = "/front/wxQr/binding";
User userInfo = new User();
userInfo.setOpenId(openId);
userInfo.setUnionId(unionId);
Cookie userCookie = new Cookie("user", JSON.toJSONString(userInfo));
response.addCookie(userCookie);
logger.info("userCookie:{}",userCookie);
out.println("");
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveLoginInfo(User loginUser, HttpServletRequest request) {
try {
FrontLoginController login = new FrontLoginController();
Subject currentUser = login.Authenticated(loginUser.getUsername(), loginUser.getPassword());
ShiroUser shirouser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
if (EntityTrainingSystemConstants.TRAINEE == loginUser.getRoleId()
|| EntityTrainingSystemConstants.EXPERT == loginUser.getRoleId()) {
login.saveLoginInfo(request, currentUser, shirouser);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private User checkUserByUnionId(String unionId) {
return userService.getUserByUnionId(unionId);
}
@RequestMapping("/binding")
public String binding(String unionId,String openId,Model model) {
model.addAttribute("unionId", unionId)
.addAttribute("openId", openId);
return "/front/wxQr/binding";
}
}