今天项目中的公众号发推文,中间有个阅读全文连接到我指定的表单,但是这个表单在微信不关注公众号的时候也可以填写,遂而写个方法,来判断用户是否关注了公众号
首先是一个判断是否关注公众号的方法,引用于:https://blog.csdn.net/qq_23842683/article/details/53888927
public boolean judgeIsFollow(String token,String openid){ Integer subscribe = null; 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; }
然后就是判断方法啦,这里需要openid和token,
首先获取openid,页面获取code
public ApiResult userdetail(){ //必须要加 ApiConfigKit.setThreadLocalApiConfig(getApiConfig()); //获取code String code=getPara("code"); //根据appid-秘钥-code获取openid SnsAccessToken s= SnsAccessTokenApi.getSnsAccessToken(appId(),appSecret(),code); //根据获取到的openid来获取用户详细数据 ApiResult user = SnsApi.getUserInfo(s.getAccessToken(),s.getOpenid()); return user; }
开始方法
ublic void user(){ //获取用户数据 apiResult=userdetail(); String openid=apiResult.get("openid"); if(openid==null){ int siz=getParaToInt("siz",10); this.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId()+"&redirect_uri=http://"+chengDong()+"/question/user&response_type=code&scope=snsapi_userinfo&state="+siz+"#wechat_redirect"); }else { String uu = "https://api.weixin.qq.com/cgi-bin/token?"; String param = "appid=" + appId() + "&secret=" + appSecret() + "&grant_type=client_credential"; String dd = HttpUtils.get(uu + param); JSONObject jj = JSONObject.fromObject(dd); String token = String.valueOf(jj.get("access_token")); System.out.println("token-----------" + token); if(judgeIsFollow(token,openid)){ System.out.println("已经关注"); }else { System.out.println("没有关注"); } }}这样就可以判断用户是否关注该公众号