liusheng
2025-02-19 3d5d75e25d2e0078814a4efd66b72c5b1b5f93c4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.smartor.service.impl;
 
import com.smartor.domain.WeChatSendVo;
import com.smartor.service.WeChatService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
 
import java.util.List;
 
@Service
public class WeChatServiceImpl implements WeChatService {
    @Value("${appid}")
    private String appid;
 
    @Value("${appSecret}")
    private String appSecret;
 
    @Override
    public Boolean sendMessageToFollowers(WeChatSendVo weChatSendVo) {
        WxMpService wxMpService;
        wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(new WxMpInMemoryConfigStorage());
        WxMpInMemoryConfigStorage wxMpConfigStorage = (WxMpInMemoryConfigStorage) wxMpService.getWxMpConfigStorage();
        wxMpConfigStorage.setAppId(appid);
        wxMpConfigStorage.setSecret(appSecret);
        try {
            List<String> openIdList = wxMpService.getUserService().userList(null).getOpenids();
//            for (String openId : openIdList) {
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().toUser(weChatSendVo.getOpenid()).templateId(weChatSendVo.getTemplateId()).url(weChatSendVo.getUrl()).build();
            for (String key : weChatSendVo.getContent().keySet()) {
                templateMessage.addData(new WxMpTemplateData(key, weChatSendVo.getContent().get(key).toString()));
            }
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
//            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return true;
 
    }
}