上一张介绍了发送消息需要用到的authorizer_access_token,和发送消息的接口结合使用,上面直接上代码。
com.github.binarywang weixin-java-open 3.3.0 com.github.binarywang weixin-java-mp 3.3.0
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);
/**
*
* 设置所属行业
* 官方文档中暂未告知响应内容
* 详情请见:http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
*
*
* @return 是否成功
*/
boolean setIndustry(ImSetIndustryEvent wxMpIndustry) throws WxErrorException;
/***
*
* 获取设置的行业信息
* 详情请见:http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
*
*
* @return wxMpIndustry
*/
WxMpTemplateIndustry getIndustry() throws WxErrorException;
/**
*
* 发送模板消息
* 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
*
*
* @return 消息Id
*/
String sendTemplateMsg(WxMpTemplateMessage templateMessage) throws WxErrorException;
/**
*
* 获得模板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
*
*
* @param shortTemplateId 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
* @return templateId 模板Id
*/
String addTemplate(String shortTemplateId) throws WxErrorException;
/**
*
* 获取模板列表
* 获取已添加至帐号下所有模板列表,可在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
*
*
* @return templateId 模板Id
*/
List getAllPrivateTemplate() throws WxErrorException;
/**
*
* 删除模板
* 删除模板可在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
*
*
* @param templateId 模板Id
*/
boolean delPrivateTemplate(String templateId) throws WxErrorException;
}
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 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, List 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 menu = msg.getMenu().getButten();
List buttons = new ArrayList();
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 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 templateDataList = inTemplateMsg.getTemplateMessage().getData();
List dataList = new ArrayList();
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 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 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 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);
}
}
}
例子提供思路,不能直接复制使用,因为有些类缺少,但是微信集成wx-java-mp发消息是全的,看核心代码即可 。