获取微信公众号所有订阅用户,并批量获取用户基本信息

获取微信公众号所有订阅用户,并批量获取用户基本信息

public void syncSubscribe() {
	String appId = ApiConstants.PUBLIC_ACCOUNT_APP_ID;
	// 所有订阅用户
	List<String> openIdList = getUserList(appId);
	// 一个批次只能查100条数据,将List按100的长度进行拆分
	List<List<String>> partitionList = org.apache.commons.collections4.ListUtil.partition(openIdList, 100);
	for (List<String> list : partitionList) {
		R<List<JSONObject>> result = getUserInfoList(appId, list);
		if (result.isSuccess()) {
			List<LkWxXxx> wxList = new ArrayList<>();
			for (JSONObject t : result.getData()) {
				if (t.containsKey("unionid")) {
					String openid = t.getStr("openid");
					String unionid = t.getStr("unionid");
					Long subscribeTime = t.getLong("subscribe_time");
					LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(subscribeTime),
							ZoneId.systemDefault());
					wxList.add(LkWxXxx.builder()
							.openid(openid)
							.unionid(unionid)
							.subscribeTime(localDateTime)
							.build());
				}
			}
			// TODO doShings
		}
	}
}
	
 public static List<String> getUserList(String appId) {
	List<String> userList = new ArrayList<>();
	String nextOpenid = "";
	boolean hasMore = true;
	while (hasMore) {
		String url = String.format("https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s",
				getStableAccessToken(appId), nextOpenid);
		String result = HttpUtil.get(url); //hutool工具类
		JSONObject userListObj = JSONUtil.parseObj(result); //hutool工具类
		if (userListObj.containsKey("data")) {
			userList.addAll(userListObj.getJSONObject("data").getJSONArray("openid").toList(String.class));
		}
		nextOpenid = userListObj.getStr("next_openid");
		hasMore = StrUtil.isNotEmpty(nextOpenid);
	}
	return userList;
}

public static R<List<JSONObject>> getUserInfoList(String appId, List<String> openIdList) {
	try {
		JSONObject openIdBody = new JSONObject().set("user_list", toMapList(openIdList, t -> new JSONObject().set("openid", t)));
		String result = HttpUtil.post(
				StrUtil.format("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token={}", getStableAccessToken(appId)),
				JSONUtil.toJsonStr(openIdBody));
		JSONObject userInfoBatchGet = JSONUtil.parseObj(result);
		if (userInfoBatchGet.containsKey("user_info_list")) {
			return R.ok(userInfoBatchGet.getBeanList("user_info_list", JSONObject.class));
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return R.fail();
}

public static <E, T> List<T> toMapList(Collection<E> collection, Function<E, T> function) {
	if (CollUtil.isEmpty(collection)) return CollUtil.newArrayList();
	return collection
			.stream()
			.map(function)
			.filter(Objects::nonNull)
			.collect(Collectors.toList());
}
/**
* 获取公众号普通的AccessToken
*/
public static String getStableAccessToken(String appId) {
	if (StrUtil.isEmpty(appId)) return "";
	
	String url = "https://api.weixin.qq.com/cgi-bin/token";
	Map<String, Object> request = new HashMap<>(3);
	request.put("grant_type", "client_credential");
	request.put("appid", appId);
	request.put("secret", ApiConstants.getAppSecret(appId));
	try {
		String result = HttpUtil.get(url, request, 30000);
		accessToken = JSONUtil.parseObj(result).getStr("access_token", "");
		if (StrUtil.isNotEmpty(accessToken)) {
			return accessToken;
		}
	} catch (Exception e) {
		log.info("getAccessToken Exception:{}", e.getMessage());
	}
	return "";
}
### Java 实现与微信公众号用户对接的方法 #### 1. 准备工作 为了实现Java程序与微信公众号的对接,首先需要完成一些准备工作。这包括获取`AppId`和`AppSecret`,配置服务器的相关设置[^5]。 #### 2. 使用 WxJava 库简化开发过程 对于希望通过Java语言快速搭建起与微信公众号交互的服务端应用来说,可以考虑采用已经封装好的第三方库——WxJava。该库提供了丰富的API支持,几乎涵盖了所有官方提供的接口调用功能,极大地方便了开发者的工作[^2]。 #### 3. 处理关注事件 当有新用户扫描二维码或点击链接而成为订阅者时,微信公众平台会向预先设定好的URL发送POST请求通知服务端有关此用户的加入情况。此时可以通过解析收到的数据包中的XML格式内容提取出必要的信息,比如OpenID等唯一标识符用于后续的消息推送或其他操作[^1]。 ```xml <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <!-- 用户 OpenID --> ... </xml> ``` #### 4. 授权登录机制 如果想要进一步增强用户体验,则可能涉及到更复杂的场景如授权登录。在这种情况下,前端页面需先引导用户同意授权给当前的应用,之后再由后端利用获得的一次性票据(Code)去换取访问令牌(Access Token),进而查询得到详细的个人信息[^3]。 ```javascript // JavaScript 前端部分示意代码片段 function getUserInfo() { axios.get("/your/api/path/" + wxcode).then(response => { const {data} = response; if (data.code === 200) { console.log('成功获取用户信息'); } else { alert("加载资源失败"); } }).catch(error => {}); } ``` #### 5. 图文消息群发 针对已有的粉丝群体实施精准营销活动也是常见的应用场景之一。这里可以根据不同的策略选择基于标签还是直接指定一批OpenIDs来进行批量信息传递。值得注意的是,在实际执行前还需要先把准备分享出去的内容上传至腾讯云存储空间内,取得相应的Media ID作为附件关联凭证[^4]。 ```java public void sendImageMessage(String openId, String mediaId){ // 构建请求体... } private Map<String,Object> uploadImageAndGetMediaId(){ // 执行文件上载动作... return null; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值