java微信H5授权登录

微信h5页面的授权登录,首先你要申请一个测试公众号

微信公众平台

在配置里的网页服务-网页账号输入自己的ip地址+端口,如127.0.0.1:8080

第一步:前端拉起授权,用户同意,获取code,前端直接调用下边链接即可拉起授权

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

 

成功之后会回调到你写的redirect_uri地址,注意一点,这里的redirect_uri要和你在测试号里配置的一直,不然会一直报错

第二步:通过 code 换取网页授权access_token

前端通过接口把获取到的token传给后端,后端再调用以下链接,获取access_token和openid

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
  public static JSONObject getAccessTokenOpenId(String code) throws IOException {

        String params = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + WX_APPID +
                "&secret=" + AppSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        GetMethod getMethod = new GetMethod(params);
        HttpClient client = new HttpClient();

        client.executeMethod(getMethod);
       
        if (getMethod.getStatusCode() == 200) {

            String responseBodyAsString = getMethod.getResponseBodyAsString();
            getMethod.releaseConnection();
            return JSONObject.parseObject(responseBodyAsString);
        }

        return null;
    }

这里的HttpClient是org.apache.commons.httpclient包下的方法,微信的接口调用成功后会返回一个json对象,java里解析一下就能拿到

第三步:拉取用户信息

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
 public static JSONObject getUserInfo(String code) throws IOException {
        JSONObject jsonObject = getAccessTokenOpenId(code);
        if (jsonObject == null) return null;

        if (!StringUtils.isEmpty(jsonObject.getString("errcode"))){
            return jsonObject;
        }

        String params = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + jsonObject.getString("access_token") +
                "&openid=" + jsonObject.getString("openid") +
                "&lang=zh_CN";

        GetMethod getMethod = new GetMethod(params);
        HttpClient client = new HttpClient();
        client.executeMethod(getMethod);

        if (getMethod.getStatusCode() == 200) {
            String responseBodyAsString = getMethod.getResponseBodyAsString();

            JSONObject jsonObject2 = JSONObject.parseObject(responseBodyAsString);
            getMethod.releaseConnection();
            return jsonObject2;
        }
        return null;
    }

通过上个方法 获取到openid和access_token再调用userinfo链接 ,获取当前用户的信息。结果如下

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值