use of com.guhanjie.weixin.model.AccessToken in project weixin-boot by guhanjie.
the class TestGetAccessToken method main.
/**
* Method Name: main<br/>
* Description: [description]
* @author guhanjie
* @time 2016年9月3日 下午10:27:28
* @param args
*/
public static void main(String[] args) {
LOGGER.info("Starting to refresh access token...");
HttpGet get = null;
CloseableHttpResponse resp = null;
CloseableHttpClient client = null;
try {
client = HttpClients.createDefault();
String url = WeixinConstants.API_ACCESS_TOKEN;
url = url.replaceAll("APPID", "***");
url = url.replaceAll("APPSECRET", "***");
get = new HttpGet(url);
resp = client.execute(get);
int statusCode = resp.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
HttpEntity entity = resp.getEntity();
String content = EntityUtils.toString(entity);
try {
LOGGER.debug("Got response:[{}]", content);
AccessToken at = JSONObject.parseObject(content, AccessToken.class);
// token = at.getAccess_token();
LOGGER.info("Success to refresh access token:[{}]", at);
} catch (Exception e) {
ErrorEntity err = JSONObject.parseObject(content, ErrorEntity.class);
LOGGER.error("Failed to refresh access token, errcode:[{}], errmsg:[{}].", err.getErrcode(), err.getErrmsg());
// refreshToken();
}
}
} catch (Exception e) {
LOGGER.error("Http error while refreshing access token", e);
} finally {
try {
if (resp != null)
resp.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (client != null)
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
use of com.guhanjie.weixin.model.AccessToken in project weixin-boot by guhanjie.
the class TestWeixinModel method testAccessToken.
@Test
public void testAccessToken() {
// String response = "{\"access_token\":\"ACCESS_TOKEN\",\"expires_in\":7200}";
String response = "{\"errcode\":40013,\"errmsg\":\"invalid appid hint: [.n0.QA0680ken1]\"}";
System.out.println(response);
AccessToken e = JSONObject.parseObject(response, AccessToken.class);
// AccessToken e = JSON.parseObject(response, AccessToken.class);
System.out.println(e.getAccess_token() + "\n" + e.getExpires_in());
assertNotNull(e);
}
use of com.guhanjie.weixin.model.AccessToken in project weixin-boot by guhanjie.
the class AccessTokenKit method refreshToken.
@Scheduled(fixedRate = 6000000)
public synchronized void refreshToken() {
LOGGER.info("Starting to refresh access token...");
try {
String url = WeixinConstants.API_ACCESS_TOKEN;
url = url.replaceAll("APPID", weixinContants.APPID);
url = url.replaceAll("APPSECRET", weixinContants.APPSECRET);
WeixinHttpUtil.sendGet(url, new WeixinHttpCallback() {
@Override
public void process(String json) {
AccessToken at = JSONObject.parseObject(json, AccessToken.class);
if (at != null && at.getAccess_token() != null) {
token = at.getAccess_token();
LOGGER.info("Success to refresh access token:[{}].", token);
} else {
LOGGER.error("Failed to refresh access token.");
}
}
});
} catch (Exception e) {
LOGGER.error("Failed to refresh access token.", e);
}
}
use of com.guhanjie.weixin.model.AccessToken in project weixin-boot by guhanjie.
the class WeixinController method oauth2.
@RequestMapping(value = "oauth2", method = RequestMethod.GET)
public void oauth2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
LOGGER.debug("entering oauth2 return url for weixin...");
final HttpSession session = req.getSession();
final HttpServletResponse response = resp;
String originState = (String) session.getAttribute(AppConstants.SESSION_KEY_OAUTH_STATE);
// 根据state校验是否是刚刚发出的授权申请,防止CSRF跨站伪造攻击
String state = req.getParameter("state");
if (!state.equals(originState)) {
LOGGER.warn("The state[{}] does not match original value[{}]. You may be a victim of CSRF.", state, originState);
resp.getWriter().write("Authentication failed. It may be CSRF attack.");
resp.getWriter().flush();
return;
}
String code = req.getParameter("code");
String url = WeixinConstants.OAUTH2_ACCESS_TOKEN;
url = url.replaceAll("APPID", weixinContants.APPID);
url = url.replaceAll("SECRET", weixinContants.APPSECRET);
url = url.replaceAll("CODE", code);
WeixinHttpUtil.sendGet(url, new WeixinHttpCallback() {
@Override
public void process(String json) {
AccessToken at = JSONObject.parseObject(json, AccessToken.class);
if (at != null && at.getAccess_token() != null && at.getOpenid() != null) {
// 拿到accesstoken,绑定到对应的人
final String token = at.getAccess_token();
final String openid = at.getOpenid();
LOGGER.info("User authentication successful, access token:[{}], openid:[{}].", token, openid);
session.setAttribute(AppConstants.SESSION_KEY_ACCESS_TOKEN, token);
session.setAttribute(AppConstants.SESSION_KEY_OPEN_ID, openid);
User user = userService.getUserByOpenId(openid);
if (user == null) {
user = new User();
user.setOpenId(openid);
UserInfo userInfo = UserKit.getUserInfoByOauth2(openid, token);
user.setUnionid(userInfo.getUnionid());
user.setName(userInfo.getNickname());
user.setNickname(userInfo.getNickname());
user.setSex(userInfo.getSex());
user.setLanguage(userInfo.getLanguage());
user.setCountry(userInfo.getCountry());
user.setProvince(userInfo.getProvince());
user.setCity(userInfo.getCity());
if (StringUtils.isNumeric(userInfo.getSubscribe_time())) {
user.setSubscribeTime(new Date(Long.parseLong(userInfo.getSubscribe_time())));
}
userService.addUser(user);
}
session.setAttribute(AppConstants.SESSION_KEY_USER, user);
try {
String returnURL = (String) session.getAttribute(AppConstants.SESSION_KEY_RETURN_URL);
if (StringUtils.isBlank(returnURL)) {
response.getWriter().write("Welcome, user authentication successful.");
response.getWriter().flush();
} else {
// 跳转回原来地址
LOGGER.debug("redirecting back to last request[{}] for user.", returnURL);
response.sendRedirect(returnURL);
}
} catch (Exception e) {
LOGGER.error("error in user authentication for weixin oauth2.0.", e);
}
} else {
LOGGER.error("User authentication failed in weixin oauth2.0, error response:[{}].", json);
}
}
});
}
Aggregations