-
Notifications
You must be signed in to change notification settings - Fork 17
1 wechat framework响应用户信息
vcdemon edited this page Jun 1, 2016
·
1 revision
你的微信应用程序接收到用户发送的消息事件之后,可以进行响应。wechat-framework支持多种消息的响应。
wechat-framework响应消息的部分在wechat-framework的入口WechatSupport.java中定义,直接使用即可。如下以接收文本消息然后回复给用户文本消息为例来说明。
import com.itfvck.wechatframework.core.support.WechatSupport;
/**
* 用户自定义消息处理中心,若要该类起作用,则需配置在wem.xml中
*
* @author
*
*/
public class MyService extends WechatSupport {
static Logger logger = LoggerFactory.getLogger(MyService.class);
/**
* 文本消息处理Msgtype=text
*
* @param wechatRequest
* 请求对象
* @return
* @throws Exception
*/
@Override
protected String onText(WechatRequest wechatRequest) throws Exception {
String xml = null;
if (wechatRequest.getContent().indexOf("收到不支持的消息类型") > 0) {
xml = onUnknown(wechatRequest);
} else {
logger.info("wechatRequest:", wechatRequest.toString());
String content = wechatRequest.getContent().trim();
// TODO 这里写具体的业务
// 返回的消息对象,任何返回消息都构造为WechatResponse
WechatResponse wechatResponse = new WechatResponse();
wechatResponse.setContent("文本回复:" + content);
wechatResponse.setMsgType(MsgType.text.name());
// 消息对象构造完成之后,调用formatWechatResponse方法即可
// formatWechatResponse方法会自动对ToUserName,FromUserName,CreateTime赋值
xml = formatWechatResponse(wechatRequest, wechatResponse);
logger.info("WechatResponse:", wechatResponse.toString());
logger.info("onText Xml:", xml);
}
return xml;
}
}上面代码的意思就是创建一个你自己的微信消息处理中心MyService.java必须继承wechatframework的WechatSupport。实现其onText事件。通过WechatResponse对象设置wechatResponse.setContent(String content);设置回复内容,然后使用formatWechatResponse(wechatRequest, wechatResponse)得到回复消息的XML字符串,然后将其返回。
-
wechatResponse.setMsgType(MsgType.text.name());通过设置MsgType参数的值来确定返回消息的类型,所有的消息类型在枚举MsgType类中都有定义,用户直接取值即可,例如:MsgType.text表示文本消息类型,MsgType.image表示图片消息类型等,通过MsgType.text.name()方法将枚举值转变为字符串类型。