java验证用户是否关注了微信公众号

 第一步:获取公众号的access_token,记得将access_token进行缓存,这个每天只有2000次访问限制。

/**
 * 是否关注了微信公众号
 * @param openId
 * @return
 * @throws BusinessException
 * @return Object ,true:已关注,false:未关注
 * @author tyg
 * @date   2019年1月14日上午11:51:05
 */
@Override
public String getStoreDistributionAccessToken() {
	String access_token = null;
	try {
	//查询是否还有缓存
		BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(CacheUnifiedEnum.accessToken.getKey());
		//缓存时长
		if(StringUtils.isBlank(ops.get()) || ops.getExpire().longValue() < 20L) {
			Map<String, String> params = new HashMap<String, String>();
			params.put("grant_type", "client_credential");
			params.put("appid", "wx12fdsf4a5f4d6");
			params.put("secret", "fdf456f46fd");
			String respData = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
			System.out.println("getaccess_token=====\n"+respData);
			json = JSON.parseObject(respData);
			ops.set(json.getString("access_token"));
			ops.expire(CacheUnifiedEnum.accessToken.getTime(), TimeUnit.SECONDS);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return access_token;
}

第二步:subscribe如果为1,则表示已经关注了微信公众号.

/**
 * 是否关注了微信公众号
 * @param openId
 * @return
 * @throws BusinessException
 * @return Object ,true:已关注,false:未关注
 * @author tyg
 * @date   2019年1月14日上午11:51:05
 */
public Object isXSNSubscribe(String openId) throws BusinessException {
	Assert.isBlank(openId, "openId can't be null");
	// 微信的access_token
	String access_token = wechatI.getStoreDistributionAccessToken();
	// 请求地址
	String url = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN", access_token, openId);
	String result = HttpTookit.doGet(url, null, "UTF-8", true);
	System.out.println(result);
	Assert.isBlank(result, "微信用户信息有误!");
	JSONObject json = JSON.parseObject(result);
	return ResultUtil.success("1".equals(json.getString("subscribe")));
}

猜你喜欢

转载自blog.csdn.net/qq_26365837/article/details/89968796