Search in sources :

Example 6 with WeixinHttpCallback

use of com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback 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);
    }
}
Also used : AccessToken(com.guhanjie.weixin.model.AccessToken) WeixinHttpCallback(com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Example 7 with WeixinHttpCallback

use of com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback in project weixin-boot by guhanjie.

the class UserKit method getUserInfoByOauth2.

public static UserInfo getUserInfoByOauth2(final String openid, final String accsstoken) {
    LOGGER.info("Starting to get user[{}] info by oauth2.0...", openid);
    final UserInfo user = new UserInfo();
    try {
        String url = WeixinConstants.OAUTH2_GET_USER_INFO;
        url = url.replaceAll("OPENID", openid);
        url = url.replaceAll("ACCESS_TOKEN", accsstoken);
        WeixinHttpUtil.sendGet(url, new WeixinHttpCallback() {

            @Override
            public void process(String json) {
                UserInfo ui = JSONObject.parseObject(json, UserInfo.class);
                if (ui != null && ui.getOpenid() != null) {
                    try {
                        PropertyUtils.copyProperties(user, ui);
                        LOGGER.info("Success to get user info:[{}] by oauth2.0.", json);
                    } catch (Exception e) {
                        LOGGER.error("error in coping user properties");
                    }
                } else {
                    LOGGER.error("Failed to get user[{}] info by oauth2.0.", openid);
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error("Failed to get user[{}] info by oauth2.0.", openid);
    }
    return user;
}
Also used : UserInfo(com.guhanjie.weixin.model.UserInfo) WeixinHttpCallback(com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback)

Example 8 with WeixinHttpCallback

use of com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback in project weixin-boot by guhanjie.

the class UserKit method getUserInfo.

public static UserInfo getUserInfo(final String openid) {
    LOGGER.info("Starting to get user[{}] info...", openid);
    final UserInfo user = new UserInfo();
    try {
        String url = WeixinConstants.API_USER_INFO;
        url = url.replaceAll("OPENID", openid);
        WeixinHttpUtil.sendGet(url, new WeixinHttpCallback() {

            @Override
            public void process(String json) {
                UserInfo ui = JSONObject.parseObject(json, UserInfo.class);
                if (ui != null && ui.getOpenid() != null) {
                    try {
                        PropertyUtils.copyProperties(user, ui);
                        LOGGER.info("Success to get user info:[{}].", json);
                    } catch (Exception e) {
                        LOGGER.error("error in coping user properties");
                    }
                } else {
                    LOGGER.error("Failed to get user[{}] info.", openid);
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error("Failed to get user[{}] info.", openid);
    }
    return user;
}
Also used : UserInfo(com.guhanjie.weixin.model.UserInfo) WeixinHttpCallback(com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback)

Example 9 with WeixinHttpCallback

use of com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback 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);
            }
        }
    });
}
Also used : User(com.guhanjie.model.User) HttpSession(javax.servlet.http.HttpSession) AccessToken(com.guhanjie.weixin.model.AccessToken) HttpServletResponse(javax.servlet.http.HttpServletResponse) UserInfo(com.guhanjie.weixin.model.UserInfo) Date(java.util.Date) IOException(java.io.IOException) WeixinHttpCallback(com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

WeixinHttpCallback (com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback)9 HttpEntity (org.apache.http.HttpEntity)5 StringEntity (org.apache.http.entity.StringEntity)4 UserInfo (com.guhanjie.weixin.model.UserInfo)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Random (java.util.Random)3 AccessToken (com.guhanjie.weixin.model.AccessToken)2 IOException (java.io.IOException)2 Date (java.util.Date)2 User (com.guhanjie.model.User)1 ErrorEntity (com.guhanjie.weixin.model.ErrorEntity)1 WeixinMedia (com.guhanjie.weixin.model.WeixinMedia)1 File (java.io.File)1 SimpleDateFormat (java.text.SimpleDateFormat)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpSession (javax.servlet.http.HttpSession)1 FileBody (org.apache.http.entity.mime.content.FileBody)1 Scheduled (org.springframework.scheduling.annotation.Scheduled)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1