微信登录授权获取openId和其他用户信息

微信登录授权小结

    最近在公司一直在做微信授权和支付的事,自己也在网上百度了很多,也走了不少的坑.现在整理一下.以下代码也有不少是copy别人的,先对借鉴过的各位大神表示感谢.
	微信授权登录就是通过每一个微信用户在每一个公众号中的openId不同来达到授权登录的目的.
	首先你需要去公众号上配置你的授权域名,登录“微信公众平台-开发-基本配置”提前将服务器IP地址添加到IP白名单中.这样才能拿到access_token才能用access_token去换取其他的信息.
	准备工作做好以后
	直接上代码,代码分为两块,第一块是微信登录的接口,第二块为回调函数,在这里注意:回调函数必须是在微信公众号中配置过的域名,需要是能再公网中访问的域名(已备案).回调函数的接口为/wx/callBack 这个在你的登录接口中配置时加入自己的域名就可以了
/**
  * 公众号微信登录授权
  */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    public String wxLogin(HttpServletRequest request,
            HttpServletResponse response)
            throws ParseException {
       
        //这个url的域名必须要进行再公众号中进行注册验证,这个地址是成功后的回调地址
        String backUrl="https://www.xxxx.com/wx/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;//必须重定向,否则不能成功
    }
/**
  * 公众号微信登录授权回调函数
  */
    @RequestMapping(value = "/callBack", method = RequestMethod.GET)
    public String 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";
        System.out.println("url:"+url);
        JSONObject jsonObject = WXAuthUtil.doGetJson(url);
        /*
         { "access_token":"ACCESS_TOKEN",
            "expires_in":7200,
            "refresh_token":"REFRESH_TOKEN",
            "openid":"OPENID",
            "scope":"SCOPE" 
           }
         */
        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.toString());
        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":"ACCESS_TOKEN",
                "expires_in":7200,
                "refresh_token":"REFRESH_TOKEN",
                "openid":"OPENID",
                "scope":"SCOPE" }
             */
            System.out.println(refreshInfo.toString());
            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";
        System.out.println("infoUrl:"+infoUrl);
        JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
        /*
         {    "openid":" OPENID",
            " nickname": NICKNAME,
            "sex":"1",
            "province":"PROVINCE"
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
            "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
            "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
            }
         */
        System.out.println("JSON-----"+userInfo.toString());
        System.out.println("名字-----"+userInfo.getString("nickname"));
        System.out.println("头像-----"+userInfo.getString("headimgurl"));
        /*
         * end 获取微信用户基本信息
         */
        //开始你自己的业务逻辑
        return null;
    }

工具类:

public class WXAuthUtil {
public static final String APPID="";//你公众号的appid
public static final String APPSECRET ="";//你公众号的appSercert
private static final String TOKEN = "";
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;
    }
}

以上代码中用的一些工具需要导一下包 除此之外这段代码使百分之百好使的亲测
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
最后欢迎大家多多交流,也非常感谢在CSDN上写了微信授权登录的大神们才能让我把这个功能写出来.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值