欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

判断微信用户是否关注了公众号

业务描述:当微信用户打开这个页面的链接即判断他/她是否已关注了“我”的公众号。 
在微信开发文档中,有一个通过token和openid获取用户信息的接口:

https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

返回参数:

参 数说明
subscribe用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。
openid用户的标识,对当前公众号唯一
nickname用户的昵称
headimgurl用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。

token通过appid、secret调用接口:

https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret

即可获取。(token的缓存后面再写) 
 但现在这里出现可一个问题。当微信用户和“我”的公众号没有消息的交互,只是在微信浏览器中打开了一个朋友转发的网页链接,我该如何获取openid呢?毕竟,openid是微信用户针对某一个公众号而存在的。最后“我”通过隐式的网页授权登录,也就是网页授权的登录时scope的参数设置为”snsapi_base”。 
通过网页授权code即可获取网页授权token信息以及openid.

/**
 * 判断用户是否关注了公众号
 * @param token
 * @param openid
 * @return
 */
public static boolean judgeIsFollow(String token,String openid){
    Integer subscribe
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+openid+"&lang=zh_CN";
    try {  
            URL urlGet = new URL(url);  
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();  
            http.setRequestMethod("GET"); // 必须是get方式请求  
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
            http.setDoOutput(true);  
            http.setDoInput(true);  
            http.connect();  
            InputStream is = http.getInputStream();  
            int size = is.available();  
            byte[] jsonBytes = new byte[size];  
            is.read(jsonBytes);  
            String message = new String(jsonBytes, "UTF-8");  
            JSONObject demoJson = JSONObject.fromObject(message);  
            //System.out.println("JSON字符串:"+demoJson);  
            subscribe = demoJson.getInt("subscribe");

            is.close();  
    } catch (Exception e) {  
            e.printStackTrace();  
    }
    return 1==subscribe?true:false;
}

参考微信开发文档中的微信网页授权

版权声明:本文为博主原创文章,未经博主允许不得转载。

https://blog.csdn.net/qq_23842683/article/details/53888927
普通分类: