微信公众号授权(java后端)

一.授权开发的流程(详情的东西请以官网为准,在此就不多说了):具体而言,网页授权流程分为四步:
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

二.(1)公用网络请求工具类:

public class WXAuthUtil {
    public static final String APPID = "****";
    public static final String APPSECRET = "*****";
    private static final String TOKEN = "itxzz";

    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
        JSONObject jsonObject = null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response =client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //把返回的结果转换为JSON对象
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSON.parseObject(result);
        }

        return jsonObject;
    }

}

(2).微信登录的实现类(里面包含引导action和确认登录后的回调函数):

@RestController
public class WXLoginController {
    private static final Logger logger = Logger.getLogger(WXLoginController.class);

    /**
     * 公众号微信登录授权
     *
     * @param request
     * @param response
     * @return
     * @throws ParseException
     * @parameter  
     */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    public String wxLogin(HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {
        //这个url的域名必须要进行再公众号中进行注册验证,这个地址是成功后的回调地址
        String backUrl = "http://itxzz.51vip.biz:12845/callBack";
        // 第一步:用户同意授权,获取code
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WXAuthUtil.APPID
                + "&redirect_uri=" + URLEncoder.encode(backUrl)
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";
        //logger.info("forward重定向地址{" + url + "}");
        response.sendRedirect(url);
        return  "redirect:"+url;//必须重定向,否则不能成功
    }
    /**
     * 公众号微信登录授权回调函数
     * @param modelMap
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/callBack", method = RequestMethod.GET)
    public ModelAndView callBack(ModelMap modelMap, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  /*
   * start 获取微信用户基本信息
   */
        String code = req.getParameter("code");
        //第二步:通过code换取网页授权access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXAuthUtil.APPID
                + "&secret=" + WXAuthUtil.APPSECRET
                + "&code=" + code
                + "&grant_type=authorization_code";
        JSONObject jsonObject = WXAuthUtil.doGetJson(url);
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        String refresh_token = jsonObject.getString("refresh_token");
        //第五步验证access_token是否失效;展示都不需要
        String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
        JSONObject chickuserInfo = WXAuthUtil.doGetJson(chickUrl);
        System.out.println("chickuserInfo"+chickuserInfo);
        if (!"0".equals(chickuserInfo.getString("errcode"))) {
            // 第三步:刷新access_token(如果需要)-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki,
            String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + openid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            JSONObject refreshInfo = WXAuthUtil.doGetJson(chickUrl);
            access_token = refreshInfo.getString("access_token");
        }

        // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
                + "&openid=" + openid
                + "&lang=zh_CN";
        JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
        System.out.println("JSON-----" + userInfo.toString());
        System.out.println("名字-----" + userInfo.getString("nickname"));
        System.out.println("头像-----" + userInfo.getString("headimgurl"));
      /*
       * end 获取微信用户基本信息
       */
            //获取到用户信息后就可以进行重定向,走自己的业务逻辑了。。。。。。
            //接来的逻辑就是你系统逻辑了,请自由发挥
        ModelAndView modelAndView = new ModelAndView("index.html");
        return modelAndView;
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值