java判断公众是否关注(用户点击被分享的页面判断是否关注)

第一天了解公众号,第二天写有关公众号的代码!有点挑战但不大!如果有更好的解决办法请告知!

一、授权获取code,要用静默的那种(&scope=snsapi_base) 注:此步骤要在前端做操作,要不然会发生错误!

二、通过code获取openid

三、根据appid和secret获取access_token

四、根据openid和access_token获取subscribe。注:subscribe的值1代表已关注、0代表未关注

开始:根据以上步骤完成操作

一、授权获取code,这个步骤我只是在html页面做的,url 是你重定向的地址,比如:我的这个是查询列表的

var code = '${code!}';
    var url = "";
    var urlquanxian = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=&redirect_uri=" + url +
        "&response_type=code" +
        "&scope=snsapi_base" +
        "&state=kcxw#wechat_redirect";
    if (!code) {
        window.location.href = urlquanxian;
    } else {
        mui.ajax("http://。。。/weixin/oauthss/wxcallback", {
            data: {code: code},
            dataType: "json",
            success: function (data) {
                if ("1"==data) {
                    pub();
                } else {
                    
                }
            }
        })
    }

二、2、3、4步骤在同一个方法里执行的,在这个Controller里还有个方法是传url返回json字符串的

 @RequestMapping("/wxcallback")
    @ResponseBody
    public String wxcallback(String code) throws IOException {
        //二、通过code获取openid
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID +
                "&secret=" + APP_SECRET +
                "&code=" + code +
                "&grant_type=authorization_code";

        JSONObject param = doGet(url);
        String openid = param.getString("openid");
        //三、获取access_token
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APP_SECRET;
        JSONObject paramt = doGet(tokenUrl);
        String access_token = paramt.getString("access_token");
        //四、判断是否关注
        String url2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject jsonObject = doGet(url2);
        String subscribe = jsonObject.getString("subscribe");
        System.out.println("是否关注了:     " + subscribe);

        return jsonObject.getString("subscribe");
    }
//返回JSON字符串 
public static JSONObject doGet(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;

    }

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值