如果需要同步微信公眾號的所有用戶税产,那怎么處理呢?微信有API接口咆贬,文檔如下:
https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_User_List.html
發(fā)現(xiàn)這個接口不友好的地方在于:
1败徊、不能根據(jù)關注時間查詢
2、只返回總量和當前頁用戶的openid掏缎,沒有詳細信息
微信公眾號的事件可以通過配置回調(diào)地址傳遞給我們服務器皱蹦,但是如果因為網(wǎng)絡或其他原因?qū)е禄卣{(diào)失敗的話煤杀,微信后臺也沒有重傳機制,這一點很難保證你同步到數(shù)據(jù)庫的用戶根欧,和微信公眾號的用戶一致怜珍。
為了解決這個問題,思路如下:
1凤粗、通過“獲取用戶列表” 將歷史數(shù)據(jù)同步過來(同步過來的用戶都是目前關注的用戶)
2、開啟配置今豆,并加入消息回調(diào)邏輯
image.png
文檔: https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html
3嫌拣、如果出現(xiàn)錯誤報警時修正:
假設今天服務器異常,沒有收到微信的關注人數(shù)回調(diào)通知呆躲,那么實際關注人數(shù)和數(shù)據(jù)庫人數(shù)就不準確了异逐,矯正思路如下:
3.1 拉取所有的關注人數(shù)存入臨時表 twx_mp_temp
操作微信API使用的是第三方的一個jar包:
可參考:https://github.com/binarywang/weixin-java-mp-demo-springboot
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.3.0</version>
</dependency>
拉取服務號代碼
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<String> 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);
}
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)