目录
- 准备工作
- 1、定义消息转换工具类
- 2、消息类型常量定义
- 3、接收及回复消息说明
- 3.1 消息接收及回复基础实体类定义
- 3.2 接收及回复文本信息
- 3.4 接收及回复图文信息
- 3.5 接收及回复语音信息
- 3.6 接收及回复视频/小视频信息
- 3.7 接收链接信息
- 3.8 接收位置信息
- 4、完整示例代码
准备工作
1、调用微信公众号接口,需要实现获取AccessToken
,参考《获取AccessToken接口调用凭据》
2、在本地进行联调时,为让微信端能够访问到本地服务,需要进行内网穿透,参考《本地服务器内网穿透实现(NATAPP)》
3、配置微信接口配置信息
,用于告诉微信接收消息的回调地址
1、定义消息转换工具类
WeixinMessageUtil
@Component
public class WeixinMessageUtil {
/**
* 将二进制数据转换为16进制字符串
*
* @param src
* @return
*/
public static String byte2HexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (byte b : src) {
String hv = Integer.toHexString(b & 0xFF);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 对字符串进行sha1加签
*
* @param context
* @return
* @throws Exception
*/
public static String sha1(String context) throws Exception {
// 获取sha1算法封装类
MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
// 进行加密
byte[] digestResult = sha1Digest.digest(context.getBytes("UTF-8"));
// 转换为16进制字符串
return WeixinMessageUtil.byte2HexString(digestResult);
}
/**
* 将输入流使用指定编码转化为字符串 获取xml
*
* @param request
* @return
* @throws Exception
*/
public static String inputStream2String(HttpServletRequest request) throws Exception {
InputStream io = request.getInputStream();
// 建立输入流读取类
InputStreamReader reader = new InputStreamReader(io, "UTF-8");
// 设定每次读取字符个数
char[] data = new char[512];
int dataSize = 0;
// 循环读取
StringBuilder stringBuilder = new StringBuilder();
while ((dataSize = reader.read(data)) != -1) {
stringBuilder.append(data, 0, dataSize);
}
return stringBuilder.toString();
}
public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
Map<String, String> map = new HashMap<>();
SAXReader reader = new SAXReader();
InputStream io = request.getInputStream();
Document document = (Document) reader.read(io);
Element root = document.getRootElement();
List<Element> elements = root.elements();
for (Element element : elements) {
map.put(element.getName(), element.getText());
}
io.close();
return map;
}
/**
* 将对象转化为xml字符串。 rootName 为根节点名称
*
* @param obj
* @return
* @throws Exception
*/
public static String obj2Xml(Object obj) {
XStream xstream = new XStream();
xstream.alias("xml", obj.getClass());
return xstream.toXML(obj);
}
}
2、消息类型常量定义
MessageType:
public class MessageType {
/**
* 请求消息类型:文本
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text";
/**
* 请求消息类型:图片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
/**
* 请求消息类型:语音
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
/**
* 请求消息类型:视频
*/
public static final String REQ_MESSAGE_TYPE_VIDEO = "video";
/**
* 请求消息类型:链接
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link";
/**
* 请求消息类型:地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
/**
* 请求消息类型:小视频
*/
public static final String REQ_MESSAGE_TYPE_SHORTVIDEO = "shortvideo";
/**
* 请求消息类型:事件推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event";
/**
* 返回消息类型:文本
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
/**
* 消息返回类型:图片
*/
public static final String RESP_MESSAGE_TYPE_IMAGE = "image";
/**
* 消息返回类型:语音
*/
public static final String RESP_MESSAGE_TYPE_VOICE = "voice";
/**
* 消息返回类型:音乐
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
/**
* 消息返回类型:图文
*/
public static final String RESP_MESSAGE_TYPE_NEWS = "news";
/**
* 消息返回类型:视频
*/
public static final String RESP_MESSAGE_TYPE_VIDEO = "video";
/**
* 事件类型:订阅
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
/**
* 事件类型:取消订阅
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
/**
* 事件类型:scan(关注用户扫描带参二维码)
*/
public static final String EVENT_TYPE_SCAN = "SCAN";
/**
* 事件类型:location(上报地理位置)
*/
public static final String EVENT_TYPE_LOCATION = "LOCATION";
/**
* 事件类型:CLICK(点击菜单拉取消息)
*/
public static final String EVENT_TYPE_CLICK = "CLICK";
/**
* 事件类型:VIEW(自定义菜单URl视图)
*/
public static final String EVENT_TYPE_VIEW = "VIEW";
}
3、接收及回复消息说明
3.1 消息接收及回复基础实体类定义
接收基础实体类:BaseInfo:
@Data
public class BaseInfo {
/**
* 开发者微信号
*/
private String ToUserName;
/**
* 发送方帐号(一个OpenID)
*/
private String FromUserName;
/**
* 文本 图片 语音 视频 小视频 地理位置 链接 事件
*/
private String MsgType;
/**
* 消息创建时间 (整型)
*/
private long CreateTime;
/**
* 消息id
*/
private String MsgId;
}
回复基础实体类:BaseResult:
@Data
public class BaseResult {
/**
* 接收方帐号(收到的OpenID)
*/
private String ToUserName;
/**
* 开发者微信号
*/
private String FromUserName;
/**
* 消息创建时间 (整型)
*/
private Long CreateTime;
/**
* 消息类型(text/music/news)
*/
private String MsgType;
}
回复多媒体实体类:MultimediaResult:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MultimediaResult {
/**
* 通过素材管理中的接口上传多媒体文件或者接收用户的多媒体消息,得到的id
*/
private String MediaId;
/**
* 视频/音频消息的标题
*/
private String Title;
/**
* 视频/音频消息的描述
*/
private String Description;
/**
* 图文消息:图片链接,支持JPG、PNG格式,较好的效果为大图360*200,小图200*200
*/
private String PicUrl;
/**
* 图文消息:点击图文消息跳转链接
*/
private String Url;
}
3.2 接收及回复文本信息
定义接收文本消息实体类:TextMessage
@EqualsAndHashCode(callSuper = true)
@Data
public class TextMessage extends BaseInfo {
/**
* 接收用户发送的文字消息
*/
private String Content;
}
定义回复文本消息实体类:TextResult
@EqualsAndHashCode(callSuper = true)
@Data
public class TextResult extends BaseResult {
/**
* 回复的消息内容
*/
private String Content;
}
接收消息示例:
@Service
@Slf4j
public class MessageService {
public String receiveAndResponseMessage(HttpServletRequest request) {
// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
Map<String, String> map = WeixinMessageUtil.xmlToMap(request);
String jsonString = JSON.toJSONString(map);
TextMessage message = JSON.parseObject(jsonString, TextMessage.class);
log.info("接收的文本信息:{}", message.getContent());
// 返回消息
return BuildResponseMessageUtil.buildTextMessage(toUserName, fromUserName, "这是一个普通消息");
}
}
回复消息示例:
public class BuildResponseMessageUtil {
/**
* 文本消息
*
* @param fromUserName
* @param toUserName
* @param content
* @return
*/
public static String buildTextMessage(String fromUserName, String toUserName, String content) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_TEXT);
TextResult resultMessage = new TextResult();
BeanUtils.copyProperties(baseResult, resultMessage);
resultMessage.setContent(content);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
}
3.4 接收及回复图文信息
定义接收图片消息实体类:ImageMessage
@EqualsAndHashCode(callSuper = true)
@Data
public class ImageMessage extends BaseInfo {
/**
* 图片链接
*/
private String PicUrl;
/**
* 图片消息媒体id,可以调用获取临时素材接口拉取数据。
*/
private String MediaId;
}
定义回复图片消息实体类:ImageResult
@EqualsAndHashCode(callSuper = true)
@Data
public class ImageResult extends BaseResult {
/**
* 回复的图片
*/
private MultimediaResult Image;
public void setMediaId(String MediaId) {
Image = new MultimediaResult(MediaId, null, null,null,null);
}
}
定义回复图文消息实体类:ImageNewsResult、ImageNewsArticles
@Data
public class ImageNewsArticles {
/**
* 回复的图文
*/
private MultimediaResult item;
public void setMediaId(String Title, String Description, String PicUrl, String Url) {
item = new MultimediaResult(null, Title, Description, PicUrl, Url);
}
}
@EqualsAndHashCode(callSuper = true)
@Data
public class ImageNewsResult extends BaseResult {
ImageNewsArticles Articles;
String ArticleCount;
}
接收消息示例:
@Service
@Slf4j
public class MessageService {
public String receiveAndResponseMessage(HttpServletRequest request) {
// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
Map<String, String> map = WeixinMessageUtil.xmlToMap(request);
String jsonString = JSON.toJSONString(map);
ImageMessage message = JSON.parseObject(jsonString, ImageMessage.class);
log.info("接收的图片信息:{}", message.getPicUrl());
// 回复图片
return BuildResponseMessageUtil.buildImageMessage(toUserName, fromUserName, message.getMediaId());
// 回复图文
// return BuildResponseMessageUtil.buildNewsMessage(toUserName, fromUserName, "图片标题", "图片描述", message.getPicUrl(), "http://www.baidu.com");
}
}
回复消息示例:
public class BuildResponseMessageUtil {
/**
* 图片消息
*
* @param fromUserName
* @param toUserName
* @param mediaId
* @return
*/
public static String buildImageMessage(String fromUserName, String toUserName, String mediaId) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_IMAGE);
ImageResult resultMessage = new ImageResult();
BeanUtils.copyProperties(baseResult, resultMessage);
resultMessage.setMediaId(mediaId);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
/**
* 图文消息
*
* @param fromUserName
* @param toUserName
* @param Title
* @param Description
* @param PicUrl
* @param Url
* @return
*/
public static String buildNewsMessage(String fromUserName, String toUserName, String Title, String Description, String PicUrl, String Url) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_NEWS);
ImageNewsArticles articles = new ImageNewsArticles();
ImageNewsResult resultMessage = new ImageNewsResult();
BeanUtils.copyProperties(baseResult, resultMessage);
articles.setMediaId(Title, Description, PicUrl, Url);
resultMessage.setArticleCount("1");
resultMessage.setArticles(articles);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
}
3.5 接收及回复语音信息
定义接收语音消息实体类:VoiceMessage
@EqualsAndHashCode(callSuper = true)
@Data
public class VoiceMessage extends BaseInfo {
/**
* 语音格式,如amr,speex等
*/
private String Format;
/**
* 图片消息媒体id,可以调用获取临时素材接口拉取数据。
*/
private String MediaId;
/**
* 语言识别结果
*/
private String Recognition;
}
定义回复语音消息实体类:VoiceResult
@EqualsAndHashCode(callSuper = true)
@Data
public class VoiceResult extends BaseResult {
/**
* 语音
*/
private MultimediaResult Voice;
public void setMediaId(String MediaId) {
Voice = new MultimediaResult(MediaId, null, null, null, null);
}
}
接收消息示例:
@Service
@Slf4j
public class MessageService {
public String receiveAndResponseMessage(HttpServletRequest request) {
// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
Map<String, String> map = WeixinMessageUtil.xmlToMap(request);
String jsonString = JSON.toJSONString(map);
VoiceMessage message = JSON.parseObject(jsonString, VoiceMessage.class);
log.info("接收的语音信息:{}", message.getMediaId());
// 返回消息
return BuildResponseMessageUtil.buildVoiceMessage(toUserName, fromUserName, message.getMediaId());
}
}
回复消息示例:
public class BuildResponseMessageUtil {
/**
* 语音消息
*
* @param fromUserName
* @param toUserName
* @param mediaId
* @return
*/
public static String buildVoiceMessage(String fromUserName, String toUserName, String mediaId) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_VOICE);
VoiceResult resultMessage = new VoiceResult();
BeanUtils.copyProperties(baseResult, resultMessage);
resultMessage.setMediaId(mediaId);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
}
3.6 接收及回复视频/小视频信息
定义接收视频/小视频消息实体类:VideoMessage
@EqualsAndHashCode(callSuper = true)
@Data
public class VideoMessage extends BaseInfo {
/**
* 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String ThumbMediaId;
/**
* 视频消息媒体id,可以调用获取临时素材接口拉取数据。
*/
private String MediaId;
}
定义回复视频/小视频消息实体类:VideoResult
@EqualsAndHashCode(callSuper = true)
@Data
public class VideoResult extends BaseResult {
/**
* 回复视频
*/
private MultimediaResult Video;
public void setMediaId(String MediaId, String Title, String Description) {
Video = new MultimediaResult(MediaId, Title, Description, null, null);
}
}
接收消息示例:
@Service
@Slf4j
public class MessageService {
public String receiveAndResponseMessage(HttpServletRequest request) {
// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
Map<String, String> map = WeixinMessageUtil.xmlToMap(request);
String jsonString = JSON.toJSONString(map);
VideoMessage message = JSON.parseObject(jsonString, VideoMessage.class);
log.info("接收的视频信息:{}", message.getMediaId());
// 返回消息
return BuildResponseMessageUtil.buildVideoMessage(toUserName, fromUserName, message.getMediaId(), "视频标题", "视频描述");
}
}
回复消息示例:
public class BuildResponseMessageUtil {
/**
* 视频消息
*
* @param fromUserName
* @param toUserName
* @param mediaId
* @param title
* @param description
* @return
*/
public static String buildVideoMessage(String fromUserName, String toUserName, String mediaId, String title, String description) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_VIDEO);
VideoResult resultMessage = new VideoResult();
BeanUtils.copyProperties(baseResult, resultMessage);
resultMessage.setMediaId(mediaId, title, description);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
}
3.7 接收链接信息
定义接收链接消息实体类:TextMessage
@EqualsAndHashCode(callSuper = true)
@Data
public class LinkMessage extends BaseInfo {
/**
* 消息标题
*/
private String Title;
/**
* 消息描述
*/
private String Description;
/**
* 消息链接
*/
private String Url;
}
接收消息示例:
@Service
@Slf4j
public class MessageService {
public String receiveAndResponseMessage(HttpServletRequest request) {
// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
Map<String, String> map = WeixinMessageUtil.xmlToMap(request);
String jsonString = JSON.toJSONString(map);
LinkMessage message = JSON.parseObject(jsonString, LinkMessage.class);
log.info("接收的链接信息:{}", message.getUrl());
}
}
3.8 接收位置信息
定义接收位置消息实体类:LocationMessage
@EqualsAndHashCode(callSuper = true)
@Data
public class LocationMessage extends BaseInfo {
/**
* 地理位置维度
*/
private String Location_X;
/**
* 地理位置经度
*/
private String Location_Y;
/**
* 地图缩放大小
*/
private String Scale;
/**
* 地理位置信息(具体位置)
*/
private String Label;
}
接收消息示例:
@Service
@Slf4j
public class MessageService {
public String receiveAndResponseMessage(HttpServletRequest request) {
// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
Map<String, String> map = WeixinMessageUtil.xmlToMap(request);
String jsonString = JSON.toJSONString(map);
LocationMessage message = JSON.parseObject(jsonString, LocationMessage.class);
log.info("接收的地理位置信息:{}", message.getLabel());
}
4、完整示例代码
Controller:
@Slf4j
@Controller
public class MessageController {
/**
* 接收微信消息(普通消息+事件消息)以及自动回复对应类型消息
*
* @param request
* @param response
* @throws Exception
*/
@PostMapping(value = "/message")
@ApiOperation(value = "接收微信消息(普通消息+事件消息)以及自动回复对应类型消息", notes = "接收微信消息(普通消息+事件消息)以及自动回复对应类型消息")
public void receiveAndResponseMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("----------------开始处理微信发过来的消息------------------");
// 微信服务器POST消息时用的是UTF-8编码,在接收时也要用同样的编码,否则中文会乱码;
request.setCharacterEncoding("UTF-8");
// 在响应消息(回复消息给用户)时,也将编码方式设置为UTF-8,原理同上;
response.setCharacterEncoding("UTF-8");
//如果有消息回复会返回消息的XML
String message = messageService.receiveAndResponseMessage(request);
responseMessage(message, response);
}
/**
* 验证微信消息
*
* @param request
* @param response
* @throws Exception
*/
@GetMapping(value = "/message")
@ApiOperation(value = "验证微信消息", notes = "验证微信消息")
public void getWeiXinMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("----------------验证微信发过来的消息------------------");
// 签名
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串,返回给微信客户端
String message = request.getParameter("echostr");
log.info("##### 微信服务器签名 :{} #####", signature);
log.info("##### 微信服务器随机串 :{} #####", nonce);
responseMessage(message, response);
}
private void responseMessage(String message, HttpServletResponse response) {
try (PrintWriter out = response.getWriter()) {
if (message != null) {
log.info("----------------自定义响应------------------");
out.write(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Service:
@Service
@Slf4j
public class MessageService {
public String receiveAndResponseMessage(HttpServletRequest request) {
log.info("------------微信消息开始处理-------------");
try {
// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
Map<String, String> map = WeixinMessageUtil.xmlToMap(request);
String jsonString = JSON.toJSONString(map);
// 发送方账号(用户方)
String fromUserName = map.get("FromUserName");
// 接受方账号(公众号)
String toUserName = map.get("ToUserName");
// 消息类型
String msgType = map.get("MsgType");
log.info("fromUserName is:" + fromUserName + " toUserName is:" + toUserName + " msgType is:" + msgType);
//普通消息类型
switch (msgType) {
case MessageType.REQ_MESSAGE_TYPE_TEXT: {
TextMessage message = JSON.parseObject(jsonString, TextMessage.class);
log.info("接收的文本信息:{}", message.getContent());
// 返回消息
return BuildResponseMessageUtil.buildTextMessage(toUserName, fromUserName, "这是一个普通消息");
}
case MessageType.REQ_MESSAGE_TYPE_IMAGE: {
ImageMessage message = JSON.parseObject(jsonString, ImageMessage.class);
log.info("接收的图片信息:{}", message.getPicUrl());
// 返回消息
imageType++;
if (imageType % 2 == 0) {
return BuildResponseMessageUtil.buildImageMessage(toUserName, fromUserName, message.getMediaId());
} else {
return BuildResponseMessageUtil.buildNewsMessage(toUserName, fromUserName, "图片标题", "图片描述", message.getPicUrl(), "http://www.baidu.com");
}
}
case MessageType.REQ_MESSAGE_TYPE_VOICE: {
VoiceMessage message = JSON.parseObject(jsonString, VoiceMessage.class);
log.info("接收的语音信息:{}", message.getMediaId());
// 返回消息
return BuildResponseMessageUtil.buildVoiceMessage(toUserName, fromUserName, message.getMediaId());
}
case MessageType.REQ_MESSAGE_TYPE_VIDEO: {
VideoMessage message = JSON.parseObject(jsonString, VideoMessage.class);
log.info("接收的视频信息:{}", message.getMediaId());
// 返回消息
return BuildResponseMessageUtil.buildVideoMessage(toUserName, fromUserName, message.getMediaId(), "视频标题", "视频描述");
}
case MessageType.REQ_MESSAGE_TYPE_SHORTVIDEO: {
ShortVideoMessage message = JSON.parseObject(jsonString, ShortVideoMessage.class);
log.info("接收的小视频信息:{}", message.getMediaId());
// 返回消息
return BuildResponseMessageUtil.buildVideoMessage(toUserName, fromUserName, message.getMediaId(), "视频标题", "视频描述");
}
case MessageType.REQ_MESSAGE_TYPE_LINK: {
LinkMessage message = JSON.parseObject(jsonString, LinkMessage.class);
log.info("接收的链接信息:{}", message.getUrl());
// 返回消息
return BuildResponseMessageUtil.buildTextMessage(toUserName, fromUserName, "这是一个链接消息");
}
// 用户主动发送地理位置消息(根据地图位置)
case MessageType.REQ_MESSAGE_TYPE_LOCATION: {
LocationMessage message = JSON.parseObject(jsonString, LocationMessage.class);
log.info("接收的地理位置信息:{}", message.getLabel());
// 返回消息
return BuildResponseMessageUtil.buildTextMessage(toUserName, fromUserName, "这是一个地理位置消息");
}
// 事件推送
case MessageType.REQ_MESSAGE_TYPE_EVENT:
// 事件类型
String eventType = map.get("Event");
log.info("消息事件推送类型:" + eventType);
// 用户同意上报地理位置后,用户在关注后进入公众号会话时,会弹框让用户确认是否允许公众号使用其地理位置
// 弹框只在关注后出现一次,用户以后可以在公众号详情页面进行操作
// 每次进入公众号会话时,都会在进入时上报地理位置
// 在进入会话后每5秒上报一次地理位置,即使在公众号里面打开其他网页也会上报位置
if (eventType.equals(MessageType.EVENT_TYPE_LOCATION)) {
log.info("上报地理位置");
String lng = message.getLongitude();
String lat = message.getLatitude();
return null;
}
// 关注处理
else if (eventType.equals(MessageType.EVENT_TYPE_SUBSCRIBE)) {
BaseEvent message = JSON.parseObject(jsonString, BaseEvent.class);
log.info("关注成功 {}", message);
}
// 取消关注
else if (eventType.equals(MessageType.EVENT_TYPE_UNSUBSCRIBE)) {
BaseEvent message = JSON.parseObject(jsonString, BaseEvent.class);
log.info("取消关注,删除用户消息。{}", message.getFromUserName());
}
default:
return null;
}
} catch (Exception e) {
e.printStackTrace();
log.error("系统出错");
return null;
}
}
}
BuildResponseMessageUtil:
public class BuildResponseMessageUtil {
private static BaseResult getBaseResult(String fromUserName, String toUserName, String msgType) {
BaseResult baseResult = new BaseResult();
baseResult.setCreateTime(System.currentTimeMillis());
// 微信回复消息时,toUserName就是用户方(接收时的fromUserName),fromUserName为当前公众号账户(接收时的toUserName)
baseResult.setToUserName(toUserName);
baseResult.setFromUserName(fromUserName);
baseResult.setMsgType(msgType);
return baseResult;
}
/**
* 文本消息
*
* @param fromUserName
* @param toUserName
* @param content
* @return
*/
public static String buildTextMessage(String fromUserName, String toUserName, String content) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_TEXT);
TextResult resultMessage = new TextResult();
BeanUtils.copyProperties(baseResult, resultMessage);
resultMessage.setContent(content);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
/**
* 图片消息
*
* @param fromUserName
* @param toUserName
* @param mediaId
* @return
*/
public static String buildImageMessage(String fromUserName, String toUserName, String mediaId) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_IMAGE);
ImageResult resultMessage = new ImageResult();
BeanUtils.copyProperties(baseResult, resultMessage);
resultMessage.setMediaId(mediaId);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
/**
* 图文消息
*
* @param fromUserName
* @param toUserName
* @param Title
* @param Description
* @param PicUrl
* @param Url
* @return
*/
public static String buildNewsMessage(String fromUserName, String toUserName, String Title, String Description, String PicUrl, String Url) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_NEWS);
ImageNewsArticles articles = new ImageNewsArticles();
ImageNewsResult resultMessage = new ImageNewsResult();
BeanUtils.copyProperties(baseResult, resultMessage);
articles.setMediaId(Title, Description, PicUrl, Url);
resultMessage.setArticleCount("1");
resultMessage.setArticles(articles);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
/**
* 语音消息
*
* @param fromUserName
* @param toUserName
* @param mediaId
* @return
*/
public static String buildVoiceMessage(String fromUserName, String toUserName, String mediaId) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_VOICE);
VoiceResult resultMessage = new VoiceResult();
BeanUtils.copyProperties(baseResult, resultMessage);
resultMessage.setMediaId(mediaId);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
/**
* 视频消息
*
* @param fromUserName
* @param toUserName
* @param mediaId
* @param title
* @param description
* @return
*/
public static String buildVideoMessage(String fromUserName, String toUserName, String mediaId, String title, String description) {
BaseResult baseResult = getBaseResult(fromUserName, toUserName, MessageType.RESP_MESSAGE_TYPE_VIDEO);
VideoResult resultMessage = new VideoResult();
BeanUtils.copyProperties(baseResult, resultMessage);
resultMessage.setMediaId(mediaId, title, description);
return WeixinMessageUtil.obj2Xml(resultMessage);
}
}