获取微信授权,获取微信用户信息

本文介绍如何使用微信OAuth2.0进行授权登录,包括获取临时授权码、通过授权码换取access_token及openid、利用access_token和openid获取用户基本信息等步骤。此过程涉及URL编码、HTTP请求发送及响应处理。
{
   try {
//先判断cookie中是否存在,不存在就执行下面的
      if (code == null) {
         String redirectUrl =URLEncoder.encode(redirect_url, "gb2312");
         String getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect"; // //
         String url = getCodeUrl.replace("APPID", AppID).replace("SCOPE", SCOPE).replace("REDIRECT_URI", redirectUrl);
         log.debug("getCodeUrl="+url);
         return "redirect:" + url;
      }else{
         //获取token & openid
         String getTokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
         String url=getTokenUrl.replace("APPID",AppID).replace("SECRET",AppSecret).replace("CODE",code);//code为第一步请求所获取的
         String  jsonStr=HttpClientUtil.doGet(url);
         JSONObject result = JSONObject.fromObject(jsonStr);
         String openid=(String)     result.get("openid");//获取到openid
         String access_token=(String)result.get("access_token");
         log.debug("openid="+openid);
         if (StringUtils.isNotBlank(openid)){
            //获取用户信息
         
	String userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	userinfo = userinfo .replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
String a = HttpClientUtil.doGet(userinfo );
System.out.println(a);
//存入cookie
}
      }
   } catch (Exception e) {
   e.printStackTrace();

   }
   return "xxxxxxxx";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值