H5根据微信code自动获取微信openId【cookie缓存微信openId】

import com.sxapp.gateway.annotation.SxCallback;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@Controller
public class AuthorizeController {
//    wxbaseurl: https://h5.test.com
//    redirecturl: https://api.test.com/h5/
//    basedomain: test.com
//    appid: 123
//    secret: 123
    @Value("${wxbaseurl}")
    String wxBaseUrl;
    @Value("${redirecturl}")
    String redirectUrl;
    @Value("${basedomain}")
    String baseDomain;
    @Value("${appid}")
    String appId;
    @Value("${secret}")
    String secret;

    @RequestMapping("/authorize")
    //白名单、支持异步请求
    @SxCallback
    public String authorize(@RequestParam(value = "code", required = false, defaultValue = "") String code, @RequestParam(value = "referer", required = false, defaultValue = "") String referer, @RequestParam(value = "activityCode", required = false, defaultValue = "") String activityCode, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(code)) {
            return String.format("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", appId, getEncodedRequestUrl(request));
        }
        String openId = this.getOpenIdByCode(appId, secret, code);
        //获取微信用户openid存储在cookie中的信息
        Cookie cookie = new Cookie("activityOpenId", openId);
        cookie.setPath("/");
        cookie.setDomain(baseDomain);
        response.addCookie(cookie);
        if (StringUtils.isBlank(referer)) {
            return String.format("redirect:%s/Intimacy/index.html", wxBaseUrl);
        } else {
            return String.format("redirect:%s", URLDecoder.decode(referer, "UTF-8"));
        }
    }

    /**
     * 获取URL
     *
     * @param request
     * @return
     */
    private String getEncodedRequestUrl(HttpServletRequest request) throws UnsupportedEncodingException {
        String uri = request.getRequestURI();
        uri = uri + "?";
        if (StringUtils.isNotBlank(request.getQueryString())) {
            uri = uri + request.getQueryString();
        }
        if (!uri.endsWith("?")) {
            uri += "&";
        }
        uri += "referer=" + URLEncoder.encode(request.getHeader("Referer"), "UTF-8");
        if (redirectUrl.endsWith("/")) {
            uri = StringUtils.stripStart(uri, "/");
        }
        String url = redirectUrl + uri;
        return URLEncoder.encode(url, "UTF-8");
    }

    /**
     * 微信根据code获取openId
     * HttpClientUtil请求工具类
     */
    private String getOpenIdByCode(String appId, String secret, String code) {
        String userInfo = "";
        //String accessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        String accessUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, secret, code);
        String accessTokenStr = HttpClientUtil.httpGet(accessUrl);
        JSONObject jsonObject = JSON.parseObject(accessTokenStr);
        return jsonObject.getString("openid");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值