校验微信公众号同步人数平台

如果需要同步微信公众号的所有用户,那怎么处理呢?微信有API接口,文档如下:
https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_User_List.html

发现这个接口不友好的地方在于:
1、不能根据关注时间查询
2、只返回总量和当前页用户的openid,没有详细信息

微信公众号的事件可以通过配置回调地址传递给我们服务器,但是如果因为网络或其他原因导致回调失败的话,微信后台也没有重传机制,这一点很难保证你同步到数据库的用户,和微信公众号的用户一致。

为了解决这个问题,思路如下:
1、通过“获取用户列表” 将历史数据同步过来(同步过来的用户都是目前关注的用户)
2、开启配置,并加入消息回调逻辑

校验微信公众号同步人数平台_第1张图片
image.png

文档: https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html
3、如果出现错误报警时修正:

假设今天服务器异常,没有收到微信的关注人数回调通知,那么实际关注人数和数据库人数就不准确了,矫正思路如下:
3.1 拉取所有的关注人数存入临时表 twx_mp_temp

操作微信API使用的是第三方的一个jar包:
可参考:https://github.com/binarywang/weixin-java-mp-demo-springboot


     com.github.binarywang
     weixin-java-mp
     3.3.0

拉取服务号代码

            wxMpUserList = wxMpService.getUserService().userList(null);
            batchInsertOpenIds(wxMpUserList);
            String nextOpenId = wxMpUserList.getNextOpenid();
            if (StringUtils.isBlank(nextOpenId)) {
                return wxMpUserList;
            }
            while (StringUtils.isNotBlank(nextOpenId)) {
                wxMpUserList = wxMpService.getUserService().userList(nextOpenId);
                batchInsertOpenIds(platformEnum.getApp(), wxMpUserList);
                nextOpenId = wxMpUserList.getNextOpenid();
            }

3.2 计算出哪些用户是在微信关注用户表(twx_user)里面没有, 把没有的用户同步一遍
3.2 将取消关注的用户从(twx_user 表)删除

 List openIds = new ArrayList<>();
        int rows = 0;
        int size = newSubscribeList.size();
        for (int i = 0; i < size; i++) {
            WxMpSubscribe wxMpSubscribe = newSubscribeList.get(i);
            openIds.add(wxMpSubscribe.getOpenId());
            if ((i + 1) % 1000 == 0) {
                WxUserUpdate update = new WxUseUpdate(openIds);
                 rows += wxUseMapper.batchUpdate(update);
                openIds.clear();
            }
        }
        if (!openIds.isEmpty()) {
            WxUserInfoUpdate update = new WxUserInfoUpdate(openIds);
            rows += wxUseMapper.batchUpdate(update);
        }
校验微信公众号同步人数平台_第2张图片
image.png

SQL:

 SELECT open_id
    FROM twx_mp_temp
    WHERE open_id NOT IN(SELECT open_id FROM twx_user )
 SELECT open_id
    FROM twx_user 
    WHERE open_id NOT IN(SELECT open_id FROM twx_mp_temp)

你可能感兴趣的:(校验微信公众号同步人数平台)