微信开放平台第三方授权(第四篇)-wechat发送客服消息

 

1.发送客服消息

上一张介绍了发送消息需要用到的authorizer_access_token,和发送消息的接口结合使用,上面直接上代码。

  •  重写WechatMpService 获取token,这个发消息会用到
package com.test.wechat.service;


import com.test.wechat.config.WechatMpConfigStorage;
import com.test.wechat.util.ServletUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author Binary Wang
 */
@Service
public class WechatMpService extends WxMpServiceImpl {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WechatMpConfigStorage wechatConfigStorage;
    @PostConstruct
    public void init() {
        super.setWxMpConfigStorage(wechatConfigStorage);
    }
    @Autowired
    WechatOpenService wechatOpenService;
    /**
     * 重写token获取方法
     */
    @Override
    public String getAccessToken(boolean forceRefresh) throws WxErrorException {
        logger.info("getAccessToken getKey:{}",ServletUtil.getKey());
        return wechatOpenService.getAccessToken(ServletUtil.getKey(),forceRefresh);
    }
}
  •  发出消息用到的的接口
package com.test.controller;


import com.test.wechat.service.WechatMpService;
import com.test.wechat.service.WechatOpenService;
import com.test.wechat.service.WechatService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.test.sdk.exception.ImErrorException;
import com.test.sdk.model.result.ApiResponse;
import com.test.sdk.model.result.ApiResponseCode;
import com.test.sdk.model.result.ApiResponseUtil;
import com.test.sdk.service.impl.ImServiceImpl;
import com.test.wechat.util.ServletUtil;

@Controller
@RequestMapping("/Im/portal")
public class ImController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    ImServiceImpl Imservice;
    //@Autowired
    //WechatService wechatService;
    @Autowired
    WechatMpService wechatService;
    @Autowired
    WechatOpenService wechatOpenService;

    /**
     * Im推送消息的入口
     */
    @ResponseBody
    @PostMapping(value = "/{key}", produces = "application/json; charset=UTF-8")
    public ApiResponse post(@PathVariable(name = "key") String key, @RequestBody String requestBody) {
        this.logger.info("\n接收到来自Im的请求:[{}, {}]", key, requestBody);
        //在ThreadLocal中保持key
        try {
            ServletUtil.setKey(key);
            Object route = Imservice.route(requestBody);
            return ApiResponseUtil.success(route);
        } catch (ImErrorException e) {
            ApiResponseCode error = e.getError();
            Integer statusCode = error.getStatusCode();
            logger.info("错误状态码 is {},开始强制刷新微信官方token....",statusCode);
            if (statusCode== 10010) {
                try {
                    wechatOpenService.getAccessToken(key,true);
                } catch (WxErrorException e1) {
                    logger.error("40001 42001 40014情况下强制刷新token失败 失败异常信息 为 {}",e1);
                }
            }
            ServletUtil.setKey(key);
            Object route = Imservice.route(requestBody);
            return ApiResponseUtil.success(route);
        } catch (Exception e) {
            logger.error("catch a Exception ",e);
            return ApiResponseUtil.error(ApiResponseCode.ERROR, e.getMessage());
        }

    }

    @ResponseBody
    @GetMapping("/test")
    public String test() {
        return "success";
    }
}
  •  消息处理发送
package com.test.sdk.service;

import com.test.sdk.api.AccessTokenApi;
import com.test.sdk.api.MessageApi;
import com.test.sdk.controller.ApiController;
import com.test.sdk.model.msg.*;
import com.test.sdk.model.msg.event.in.*;
import com.test.sdk.model.msg.in.ImMassOpenIdsMessage;
import com.test.sdk.model.msg.in.ImNewsMsg;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateIndustry;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

import java.util.List;

public interface ImService extends ApiController {

    /**
     * 全媒体网管服务器调用唯一入口,即在开发者中心输入的 URL 必须调用此方法
     */
    default Object route(String requestBody) {

        //TODO  ImMassOpenIdsMessage 需要继承 ImMsg 规范代码
        if (requestBody.contains("toUsers") && requestBody.contains("mediaId")) {
            ImMassOpenIdsMessage msg = ImMassOpenIdsMessage.fromjson(requestBody);
            return processMassOpenIdsMessage(msg, msg.getMsgType(), null);
        }

        if (requestBody != null) {
            ImMsg msg = ImMsg.fromjson(requestBody);
            if (msg instanceof ImTextMsg) {
                return processInTextMsg((ImTextMsg) msg);
            } else if (msg instanceof ImImageMsg) {
                return processInImageMsg((ImImageMsg) msg);
            } else if (msg instanceof ImMusicMsg) {
                return processInMusicMsg((ImMusicMsg) msg);
            } else if (msg instanceof ImNewsMsg) {
                return processInNewsMsg((ImNewsMsg) msg);
            } else if (msg instanceof ImVideoMsg) {
                return processInVideoMsg((ImVideoMsg) msg);
            } else if (msg instanceof ImVoiceMsg) {
                return processInVoiceMsg((ImVoiceMsg) msg);
            } else if (msg instanceof ImFileMsg) {
                return processInFileMsg((ImFileMsg) msg);
            } else if (msg instanceof ImRefreshMenuEvent) {
                return processInImCreateMenuEvent((ImRefreshMenuEvent) msg);
            } else if (msg instanceof ImTemplateMsg) {
                return processInTemplateMsg((ImTemplateMsg) msg);
            } else if (msg instanceof ImGetUserInfoEvent) {
                return processGetUserInfoEvent((ImGetUserInfoEvent) msg);
            } else if (msg instanceof ImBatchGetUserInfoEvent) {
                return processBatchGetUserInfoEvent((ImBatchGetUserInfoEvent) msg);
            } else if (msg instanceof ImUserGetEvent) {
                return processUserGetEvent((ImUserGetEvent) msg);
            } else if (msg instanceof ImSetIndustryEvent) {
                return processSetIndustryEvent((ImSetIndustryEvent) msg);
            } else if (msg instanceof ImGetIndustryEvent) {
                return processGetIndustryEvent((ImGetIndustryEvent) msg);
            } else if (msg instanceof ImGetAllTemplateEvent) {
                return processGetAllTemplateEvent((ImGetAllTemplateEvent) msg);
            } else if (msg instanceof ImAddTemplateEvent) {
                return processAddTemplateEvent((ImAddTemplateEvent) msg);
            } else if (msg instanceof ImDelTemplateEvent) {
                return processDelTemplateEvent((ImDelTemplateEvent) msg);
            } else if (msg instanceof NotDefinedEvent) {
                return processIsNotDefinedEvent((NotDefinedEvent) msg);
            } else {
                return processIsNotDefinedMsg(requestBody);
            }

        }
        return null;
        // 解析消息并根据消息类型分发到相应的处理方法

    }

    Object processInFileMsg(ImFileMsg msg);

    Object processDelTemplateEvent(ImDelTemplateEvent msg);

    Object processAddTemplateEvent(ImAddTemplateEvent msg);

    Object processGetAllTemplateEvent(ImGetAllTemplateEvent msg);

    Object processGetIndustryEvent(ImGetIndustryEvent msg);

    Object processSetIndustryEvent(ImSetIndustryEvent msg);

    Object processBatchGetUserInfoEvent(ImBatchGetUserInfoEvent msg);

    Object processGetUserInfoEvent(ImGetUserInfoEvent msg);

    Object processUserGetEvent(ImUserGetEvent msg);

    ImMsg processInNewsMsg(ImNewsMsg msg);

    // 处理接收到的文本消息
    ImMsg processInTextMsg(ImTextMsg inTextMsg);

    ImMsg processInImageMsg(ImImageMsg inTextMsg);

    ImMsg processInMusicMsg(ImMusicMsg inTextMsg);

    ImMsg processInVideoMsg(ImVideoMsg inTextMsg);

    ImMsg processInVoiceMsg(ImVoiceMsg inTextMsg);


    ImMsg processInImCreateMenuEvent(ImRefreshMenuEvent msg);


    ImMsg processIsNotDefinedMsg(String requestBody);

    ImMsg processIsNotDefinedEvent(NotDefinedEvent msg);
    // 发送文本消息
    // 群发文本消息

    AccessTokenApi getAccessTokenApi();

    MessageApi getMessageApi();

    //   ImApiConfig getApiConfig();
    ImMsg processInTemplateMsg(ImTemplateMsg inTemplateMsg);


    ImMsg processMassOpenIdsMessage(ImMassOpenIdsMessage ImMassOpenIdsMessage, String msgType, String content);


    /**
     * <pre>
     * 设置所属行业
     * 官方文档中暂未告知响应内容
     * 详情请见:http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
     * </pre>
     *
     * @return 是否成功
     */
    boolean setIndustry(ImSetIndustryEvent wxMpIndustry) throws WxErrorException;

    /***
     * <pre>
     * 获取设置的行业信息
     * 详情请见:http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
     * </pre>
     *
     * @return wxMpIndustry
     */
    WxMpTemplateIndustry getIndustry() throws WxErrorException;

    /**
     * <pre>
     * 发送模板消息
     * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
     * </pre>
     *
     * @return 消息Id
     */
    String sendTemplateMsg(WxMpTemplateMessage templateMessage) throws WxErrorException;

    /**
     * <pre>
     * 获得模板ID
     * 从行业模板库选择模板到帐号后台,获得模板ID的过程可在MP中完成
     * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
     * 接口地址格式:https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=ACCESS_TOKEN
     * </pre>
     *
     * @param shortTemplateId 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
     * @return templateId 模板Id
     */
    String addTemplate(String shortTemplateId) throws WxErrorException;

    /**
     * <pre>
     * 获取模板列表
     * 获取已添加至帐号下所有模板列表,可在MP中查看模板列表信息,为方便第三方开发者,提供通过接口调用的方式来获取帐号下所有模板信息
     * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
     * 接口地址格式:https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN
     * </pre>
     *
     * @return templateId 模板Id
     */
    List<WxMpTemplate> getAllPrivateTemplate() throws WxErrorException;

    /**
     * <pre>
     * 删除模板
     * 删除模板可在MP中完成,为方便第三方开发者,提供通过接口调用的方式来删除某帐号下的模板
     * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
     * 接口地址格式:https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=ACCESS_TOKEN
     * </pre>
     *
     * @param templateId 模板Id
     */
    boolean delPrivateTemplate(String templateId) throws WxErrorException;

}
  •  ImServiceImpl 实现,参考wx-java-mp代码发送消息部分,下面是核心部分。

 boolean bl = wechatservice.getKefuService().sendKefuMessage(
                    WxMpKefuMessage.TEXT().toUser(inTextMsg.getToUser()).content(
                            inTextMsg.getText().getContent()).build()); 

package com.test.sdk.service.impl;

import com.test.sdk.api.AccessTokenApi;
import com.test.sdk.api.MessageApi;
import com.test.sdk.builder.ImGsonBuilder;
import com.test.sdk.config.ImApiConfig;
import com.test.sdk.exception.ImErrorException;
import com.test.sdk.feign.ImStorageClient;
import com.test.sdk.model.msg.*;
import com.test.sdk.model.msg.event.in.*;
import com.test.sdk.model.msg.event.in.Menu.Butten;
import com.test.sdk.model.msg.in.ImMassOpenIdsMessage;
import com.test.sdk.model.msg.in.ImNewsMsg;
import com.test.sdk.model.msg.in.News;
import com.test.sdk.model.result.ApiResponseCode;
import com.test.sdk.service.ImService;
import com.test.wechat.config.ImConfig;
import com.test.wechat.config.ImRedisAccessTokenCache;
import com.test.wechat.service.FileStorageService;
import com.test.wechat.service.WechatMpService;
import com.test.wechat.service.WechatOpenService;
import com.test.wechat.service.WechatService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateIndustry;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateIndustry.Industry;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.builder.kefu.NewsBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ImServiceImpl implements ImService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    public final static String WECHATSERVICEROOT = "WECHATSERVICEROOT:";
   // @Autowired
   // private WechatService wechatservice;
    @Autowired
    private ValueOperations<String, Object> valOps;
    @Autowired
    @Lazy
    private AccessTokenApi accesstokenapi;
    @Autowired
    @Lazy
    private MessageApi messageapi;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ImConfig ImConfig;
    @Autowired
    private ImStorageClient ImStorageClient;
    @Autowired
    private WechatMpService wechatservice;


    @Override
    public ImMsg processInTextMsg(ImTextMsg inTextMsg) {
        try {
            boolean bl = wechatservice.getKefuService().sendKefuMessage(
                    WxMpKefuMessage.TEXT().toUser(inTextMsg.getToUser()).content(
                            inTextMsg.getText().getContent()).build());
            if (!bl) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e.getError().toString());
        }
        return null;
    }


    @Override
    public ImApiConfig getApiConfig() {
        return this.ImConfig;
    }

    public void processWhenDownloadFileFail(ImMsg inMsg) {
        try {
            boolean bl = wechatservice.getKefuService().sendKefuMessage(
                    WxMpKefuMessage.TEXT().toUser(inMsg.getToUser()).content("文件下载失败").build());
            if (!bl) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
    }

    @Override
    public ImMsg processInImageMsg(ImImageMsg inTextMsg) {
        try {
            //File file = getMediaapi().downloadFile(inTextMsg.getImage().getMediaId(),inTextMsg.getImage().getMediaId() + ".jpg");

            File file = fileStorageService.downloadFile(inTextMsg.getImage().getMediaId(), WxConsts.MediaFileType.IMAGE,
                    inTextMsg.getImage().getMediaId());

            if (file == null) {
                processWhenDownloadFileFail(inTextMsg);
                return null;
            }

            WxMediaUploadResult result = wechatservice.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE,
                    file);
            file.delete();
            boolean bl = wechatservice.getKefuService().sendKefuMessage(
                    WxMpKefuMessage.IMAGE().toUser(inTextMsg.getToUser()).mediaId(result.getMediaId()).build());
            if (!bl) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
        return null;
    }

    @Override
    public ImMsg processInMusicMsg(ImMusicMsg inTextMsg) {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public ImMsg processInVideoMsg(ImVideoMsg inTextMsg) {
        try {
            //File file = getMediaapi().downloadFile(inTextMsg.getVideo().getMediaId(), inTextMsg.getVideo().getMediaId() + ".mp4");

            File file = fileStorageService.downloadFile(inTextMsg.getVideo().getMediaId(), WxConsts.MediaFileType.VIDEO,
                    inTextMsg.getVideo().getMediaId());

            if (file == null) {
                processWhenDownloadFileFail(inTextMsg);
                return null;
            }

            WxMediaUploadResult result = wechatservice.getMaterialService().mediaUpload(WxConsts.MediaFileType.VIDEO,
                    file);
            file.delete();
            boolean bl = wechatservice.getKefuService().sendKefuMessage(
                    WxMpKefuMessage.VIDEO().toUser(inTextMsg.getToUser()).mediaId(result.getMediaId()).build());
            if (!bl) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
        return null;
    }

    @Override
    public Object processInFileMsg(ImFileMsg msg) {
        try {
            String content = msg.getFile().getTitle() + "\r\n点击下载:" + ImStorageClient.getImStorageDownloadUrl() + msg.getFile().getMediaId();
            boolean bl = wechatservice.getKefuService().sendKefuMessage(WxMpKefuMessage.TEXT().
                    toUser(msg.getToUser()).
                    content(content).build());
            if (!bl) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e.getError().toString());
        }
        return null;
    }

    @Override
    public ImMsg processInVoiceMsg(ImVoiceMsg inTextMsg) {
        try {
            //File file = getMediaapi().downloadFile(inTextMsg.getVoice().getMediaId(), inTextMsg.getVoice().getMediaId() + ".mp3");

            File file = fileStorageService.downloadFile(inTextMsg.getVoice().getMediaId(), WxConsts.MediaFileType.VOICE,
                    inTextMsg.getVoice().getMediaId());

            if (file == null) {
                processWhenDownloadFileFail(inTextMsg);
                return null;
            }

            WxMediaUploadResult result = wechatservice.getMaterialService().mediaUpload(WxConsts.MediaFileType.VOICE,
                    file);
            file.delete();
            boolean bl = wechatservice.getKefuService().sendKefuMessage(
                    WxMpKefuMessage.VOICE().toUser(inTextMsg.getToUser()).mediaId(result.getMediaId()).build());
            if (!bl) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
        return null;
    }


    @Override
    public ImMsg processIsNotDefinedMsg(String requestBody) {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public ImMsg processIsNotDefinedEvent(NotDefinedEvent msg) {

        return null;
    }


    @Override
    public AccessTokenApi getAccessTokenApi() {
        return accesstokenapi;
    }


    @Override
    public MessageApi getMessageApi() {
        return messageapi;
    }

    @Autowired
    ImRedisAccessTokenCache Imredisaccesstokencache;
    @Autowired
    ImConfig Imconfig;

    private void ImMenuToWxMenu(List<Butten> butten, List<WxMenuButton> buttons) {
        for (Butten bt : butten) {
            WxMenuButton wxbt = new WxMenuButton();
            wxbt.setName(bt.getName());
            if (bt.getSubbutten() == null || bt.getSubbutten().size() == 0) {
                wxbt.setType(bt.getType());
                wxbt.setKey(bt.getKey());
                wxbt.setUrl(bt.getUrl());
                if ("miniprogram".equals(bt.getType())) {
                    wxbt.setAppId(bt.getAppid());
                    wxbt.setPagePath(bt.getPagepath());
                }
            } else {
                ImMenuToWxMenu(bt.getSubbutten(), wxbt.getSubButtons());
            }
            buttons.add(wxbt);
        }
    }

    @Override
    public ImMsg processInImCreateMenuEvent(ImRefreshMenuEvent msg) {
        List<Butten> menu = msg.getMenu().getButten();
        List<WxMenuButton> buttons = new ArrayList<WxMenuButton>();
        ImMenuToWxMenu(menu, buttons);
        WxMenu wxmenu = new WxMenu();
        wxmenu.setButtons(buttons);
        try {
            wechatservice.getMenuService().menuCreate(wxmenu);
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
        return null;
    }


    @Override
    public ImMsg processInNewsMsg(ImNewsMsg msg) {
        //TODO 图文重新做,不要暴露Imserver
        try {
            NewsBuilder builder = WxMpKefuMessage.NEWS().toUser(msg.getToUser());
            List<News.Article> imarticles = msg.getNews().getArticles();
            for (int i = 0; i < imarticles.size(); i++) {
                News.Article imarticle = imarticles.get(i);
                WxMpKefuMessage.WxArticle article = new WxMpKefuMessage.WxArticle();
                article.setDescription(imarticle.getDescription());//Imconfig
                article.setPicUrl(imarticle.getThumbMediaUrl());
                article.setTitle(imarticle.getTitle());
                article.setUrl(imarticle.getArticleUrl());
                builder.addArticle(article);
            }
            boolean bl = wechatservice.getKefuService().sendKefuMessage(builder.build());
            if (!bl) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
        } catch (WxErrorException e) {
            new ImErrorException(ApiResponseCode.DriverError, e);
        }
        return null;
    }


    @Override
    public ImMsg processInTemplateMsg(ImTemplateMsg inTemplateMsg) {
        logger.info("模板消息接收的参数:" + inTemplateMsg.tojson());
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        wxMpTemplateMessage.setToUser(inTemplateMsg.getToUser());
        wxMpTemplateMessage.setTemplateId(inTemplateMsg.getTemplateMessage().getTemplateId());
        wxMpTemplateMessage.setUrl(inTemplateMsg.getTemplateMessage().getUrl());
        List<TemplateData> templateDataList = inTemplateMsg.getTemplateMessage().getData();
        List<WxMpTemplateData> dataList = new ArrayList<WxMpTemplateData>();
        TemplateData templateData = null;
        for (int i = 0; i < templateDataList.size(); i++) {
            templateData = templateDataList.get(i);
            WxMpTemplateData wxMpTemplateData = new WxMpTemplateData();
            wxMpTemplateData.setColor(templateData.getColor());
            wxMpTemplateData.setName(templateData.getName());
            wxMpTemplateData.setValue(templateData.getValue());
            dataList.add(wxMpTemplateData);
        }
        wxMpTemplateMessage.setData(dataList);
        try {
            wechatservice.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
        return null;
    }

//    @Override
//    public ImMsg processMassOpenIdsMessage(ImMassOpenIdsMessage ImMassOpenIdsMessage) {
//        return null;
//    }


    @Override
    public ImMsg processMassOpenIdsMessage(ImMassOpenIdsMessage massOpenIdsMessage, String msgType, String content) {

        final String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send";
        try {
            WxMpMassOpenIdsMessage wxMpMassOpenIdsMessage = new WxMpMassOpenIdsMessage();
            wxMpMassOpenIdsMessage.setMediaId(massOpenIdsMessage.getMediaId());
            wxMpMassOpenIdsMessage.setMsgType(msgType);
            wxMpMassOpenIdsMessage.setContent(content);
            wxMpMassOpenIdsMessage.setToUsers(massOpenIdsMessage.getToUsers());
            wxMpMassOpenIdsMessage.setSendIgnoreReprint(false);
            WxMpMassSendResult massResult = this.wechatservice.getMassMessageService()
                    .massOpenIdsMessageSend(wxMpMassOpenIdsMessage);
            logger.info(massResult.toString());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object processGetUserInfoEvent(ImGetUserInfoEvent msg) {
        try {
            WxMpUser wxMpUser = wechatservice.getUserService().userInfo(msg.getOpenid());
            return wxMpUser;
        } catch (WxErrorException e) {
            logger.error("can not get user info, openid:{}", msg.getOpenid(), e);
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }

    }

    @Override
    public Object processBatchGetUserInfoEvent(ImBatchGetUserInfoEvent msg) {
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget";
            Map<String, Object> map = new HashMap<>();
            map.put("user_list", msg.getUserList());

            String responseContent = wechatservice.post(url, ImGsonBuilder.create().toJson(map));
            return JsonParserFactory.getJsonParser().parseMap(responseContent);
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
    }

    @Override
    public Object processUserGetEvent(ImUserGetEvent msg) {
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/user/get";
            String responseContent = wechatservice.get(url, "next_openid=" + msg.getNextOpenid());
            return JsonParserFactory.getJsonParser().parseMap(responseContent);
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
    }

    @Override
    public boolean setIndustry(ImSetIndustryEvent msg) throws WxErrorException {
        wechatservice.getTemplateMsgService().setIndustry(new WxMpTemplateIndustry(
                new Industry(msg.getPrimaryIndustry().getId(), msg.getPrimaryIndustry().getFirstClass(),
                        msg.getPrimaryIndustry().getSecondClass()),
                new Industry(msg.getSecondIndustry().getId(), msg.getSecondIndustry().getFirstClass(),
                        msg.getSecondIndustry().getSecondClass())));
        return false;
    }


    @Override
    public WxMpTemplateIndustry getIndustry() throws WxErrorException {
        return wechatservice.getTemplateMsgService().getIndustry();
    }


    @Override
    public String sendTemplateMsg(WxMpTemplateMessage templateMessage) throws WxErrorException {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public String addTemplate(String shortTemplateId) throws WxErrorException {
        wechatservice.getTemplateMsgService().addTemplate(shortTemplateId);
        return null;
    }


    @Override
    public List<WxMpTemplate> getAllPrivateTemplate() throws WxErrorException {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public boolean delPrivateTemplate(String templateId) throws WxErrorException {
        // TODO Auto-generated method stub
        return false;
    }


    @Override
    public Object processGetIndustryEvent(ImGetIndustryEvent msg) {
        try {
            WxMpTemplateIndustry industry = wechatservice.getTemplateMsgService().getIndustry();
            Industry primaryIndustry = industry.getPrimaryIndustry();
            Industry secondIndustry = industry.getSecondIndustry();
            TemplateIndustry templateIndustry = new TemplateIndustry();
            templateIndustry.setPrimaryIndustry(
                    new TemplateIndustry.Industry(primaryIndustry.getId(), primaryIndustry.getFirstClass(),
                            primaryIndustry.getSecondClass()));
            templateIndustry.setSecondIndustry(
                    new TemplateIndustry.Industry(secondIndustry.getId(), secondIndustry.getFirstClass(),
                            secondIndustry.getSecondClass()));
            return templateIndustry;
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }


    }


    @Override
    public Object processSetIndustryEvent(ImSetIndustryEvent msg) {
        WxMpTemplateIndustry industry = new WxMpTemplateIndustry();
        industry.setPrimaryIndustry(new Industry(msg.getPrimaryIndustry().getId()));
        industry.setSecondIndustry(new Industry(msg.getSecondIndustry().getId()));
        try {
            boolean b = wechatservice.getTemplateMsgService().setIndustry(industry);
            if (!b) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
            return null;
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }

    }


    @Override
    public Object processGetAllTemplateEvent(ImGetAllTemplateEvent msg) {
        try {
            List<WxMpTemplate> industry = wechatservice.getTemplateMsgService().getAllPrivateTemplate();
            return industry;
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
    }


    @Override
    public Object processAddTemplateEvent(ImAddTemplateEvent msg) {
        try {
            String templateId = wechatservice.getTemplateMsgService().addTemplate(msg.getTemplateIdShort());
            return templateId;
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
    }


    @Override
    public Object processDelTemplateEvent(ImDelTemplateEvent msg) {
        try {
            boolean b = wechatservice.getTemplateMsgService().delPrivateTemplate(msg.getTemplateId());
            if (!b) {
                throw new ImErrorException(ApiResponseCode.DriverError);
            }
            return null;
        } catch (WxErrorException e) {
            throw new ImErrorException(ApiResponseCode.DriverError, e);
        }
    }


}

2.总结

例子提供思路,不能直接复制使用,因为有些类缺少,但是微信集成wx-java-mp发消息是全的,看核心代码即可 。

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/360869.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Roxlabs全球IP代理服务:解锁高效数据采集与网络应用新境界

引言 在这个数字化迅速发展的时代&#xff0c;数据采集和网络应用的重要性显得愈发突出。江苏阿克索网络科技有限公司旗下的Roxlabs&#xff0c;以其卓越的全球IP代理服务&#xff0c;正引领着这一领域的创新和发展。Roxlabs不仅提供遍及200多个国家和地区的高质量动态住宅IP资…

10个最好的免费数据恢复软件工具分享【合集】

数据丢失经常发生。它可能是由于恶意软件、有缺陷的更新或疏忽造成的。无论哪种情况&#xff0c;这都是一个麻烦的事件。 许多人认为不可能恢复已删除的文件。这是一个错误的印象。 从回收站删除的文件很有可能仍然可以恢复。免费的开源数据恢复软件可以在这里为您提供帮助&a…

Linux下使用信号量实现PV操作

一.信号量与PV操作概述 在多道程序系统中&#xff0c;由于资源共享与进程合作&#xff0c;使各进程之间可能产生两种形式的制约关系&#xff0c;一种是间接相互制约&#xff0c;例如&#xff0c;在仅有一台打印机的系统&#xff0c;同一时刻只能有一个进程分配到到打印机&…

Python算法题集_最大子数组和

本文为Python算法题集之一的代码示例 题目53&#xff1a;最大子数组和 说明&#xff1a;给你一个整数数组 nums &#xff0c;请你找出一个具有最大和的连续子数组&#xff08;子数组最少包含一个元素&#xff09;&#xff0c;返回其最大和。 子数组 是数组中的一个连续部分。…

实战教程:使用Spring Boot和Vue.js开发社区团购管理系统

✍✍计算机编程指导师 ⭐⭐个人介绍&#xff1a;自己非常喜欢研究技术问题&#xff01;专业做Java、Python、微信小程序、安卓、大数据、爬虫、Golang、大屏等实战项目。 ⛽⛽实战项目&#xff1a;有源码或者技术上的问题欢迎在评论区一起讨论交流&#xff01; ⚡⚡ Java实战 |…

本地配置Joplin Server用于Joplin笔记同步并实现公网远程访问

文章目录 1. 安装Docker2. 自建Joplin服务器3. 搭建Joplin Sever4. 安装cpolar内网穿透5. 创建远程连接的固定公网地址 Joplin 是一个开源的笔记工具&#xff0c;拥有 Windows/macOS/Linux/iOS/Android/Terminal 版本的客户端。多端同步功能是笔记工具最重要的功能&#xff0c;…

关于JavaWeb的不使用模板创建方法

首先说一个特别重要的 , pom配置文件写完他不自动更新 就得这么办 , 不更新 idea就无法识别javaweb项目很烦

ASTORS国土安全奖:ManageEngine AD360荣获银奖

美国安全今日&#xff08;AST&#xff09;的年度“ASTORS”国土安全奖计划是一个备受瞩目的活动&#xff0c;致力于突显国土安全领域的创新与进步。这一奖项旨在表彰在保护国家免受安全威胁方面做出卓越贡献的个人和组织。该计划汇聚了执法、公共安全和行业领袖&#xff0c;不仅…

c4d线条放样模型的教程

c4d放样工具怎么使用&#xff1f;c4d中想要将线条放样成三维模型&#xff0c;该怎么放样呢&#xff1f;下面我们就来看看c4d线条放样模型的教程&#xff0c;需要的朋友可以参考下 c4d绘制的线条图形&#xff0c;想要放样成三维模型&#xff0c;该怎么放样呢&#xff1f;下面我…

谷歌上架防关联VPS开到和原来一样的IP造成关联?应该怎么选?

随着Google paly的发展&#xff0c;竞争越来越激烈&#xff0c;开发者们也面临的越来越多的挑战。其中&#xff0c;如何降低关联风险是开发者们重点关注的问题。 为了防止开发者账号的滥用或欺诈&#xff0c;谷歌会通过判断账号之间是否存在关联&#xff0c;并对违规账号进行处…

【Axure教程0基础入门】00Axure9汉化版下载、安装、汉化、注册+01制作线框图

写在前面&#xff1a;在哔哩哔哩上面找到的Axure自学教程0基础入门课程&#xff0c;播放量最高&#xff0c;5个多小时。课程主要分为4个部分&#xff0c;快速入门、动态面板、常用动效、项目设计。UP主账号【Song老师产品经理课堂】。做个有素质的白嫖er&#xff0c;一键三连必…

Qt QWidget Loading界面并覆盖在其他控件上面

目录 一、效果图二、Loading三、使用 一、效果图 界面中有一个Label&#xff0c;一个Button 点击Buttion&#xff0c;显示Loading的界面&#xff0c;并覆盖到Label和Button上面 二、Loading loadingwidget.h #ifndef LOADINGWIDGET_H #define LOADINGWIDGET_H#include <…

Python中类的相关术语(附带案例)

目录 1、面向对象 2、类 3、实例 4、初始化方法 5、魔法方法 6、字符串方法 7、self 8、数据、属性、操作、行为 9、父类、基类、超类 or 子类、派生类 10、多态 11、重载多态 and 重写多态 12、名称解释 1、面向对象 在Python中&#xff0c;面向对象编程&…

哪款洗地机好用?2024年洗地机推荐

家居清洁工作却是一项既重要又耗时的任务&#xff0c;尤其是地面的清扫工作&#xff0c;既要保证清洁&#xff0c;又要尽量减少对地板的磨损。吸拖一体的洗地机出现&#xff0c;让全职妈妈、忙碌的上班族以及健康状况欠佳的长者都能从繁重的家务活中解脱出来&#xff0c;享受自…

让MySQL和Redis数据保持一致的4种策略

1 前言 先阐明一下 MySQL 和 Redis 的关系&#xff1a;MySQL 是数据库&#xff0c;用来持久化数据&#xff0c;一定程度上保证数据的可靠性&#xff1b;Redis 是用来当缓存&#xff0c;用来提升数据访问的性能。 关于如何保证 MySQL 和 Redis 中的数据一致&#xff08;即缓存…

[服务器]ESXi 8安装centos7

文章目录 创建虚拟机创建虚拟机选择centos7选择存储选择镜像文件上传ios镜像文件 安装即将完成 启动虚拟机自动获取ip设置root密码安装成功 创建虚拟机 创建虚拟机 选择centos7 选择存储 选择镜像文件 上传ios镜像文件 如图显示上传进度&#xff0c;上传完毕之后&#xff0c;将…

CleanMyMac X.4.14.6中文版新功能介绍,mac系统垃圾清理

近些年伴随着苹果生态的蓬勃发展&#xff0c;越来越多的用户开始尝试接触Mac电脑。然而很多人上手Mac后会发现&#xff0c;它的使用逻辑与Windows存在很多不同&#xff0c;而且随着使用时间的增加&#xff0c;一些奇奇怪怪的文件也会占据有限的磁盘空间&#xff0c;进而影响使用…

AIGC项目——Meta:根据对话音频生成带动作和手势的3d逼真数字人

From Audio to Photoreal Embodiment: Synthesizing Humans in Conversations From Audio to Photoreal Embodiment:Synthesizing Humans in Conversations 从二元对话的音频中&#xff0c;我们生成相应的逼真的面部、身体和手势。 概括性:角色是由作者的声音驱动的(而不是模…

flink cdc,standalone模式下,任务运行一段时间taskmanager挂掉

在使用flink cdc&#xff0c;配置任务运行&#xff0c;过了几天后&#xff0c;任务无故取消&#xff0c;超时&#xff0c;导致taskmanager挂掉&#xff0c;相关异常如下&#xff1a; 异常1&#xff1a; did not react to cancelling signal interrupting; it is stuck for 30 s…

(1)SpringBoot学习——芋道源码

Spring Boot 的快速入门 一.、概述 使用 Spring Boot 可以很容易地创建出能直接运行的独立的、生产级别的基于 Spring 的应用。 二、快速入门 2.1 创建 Maven 项目 打开 IDEA&#xff0c;点击菜单 File -> New -> Project.来创建项目选择 Maven 类型&#xff0c;点击「…