-
Notifications
You must be signed in to change notification settings - Fork 17
4 设置响应微信参数
vcdemon edited this page Jun 1, 2016
·
1 revision
开发者向微信平台发送消息,需要将返回的消息构建成xml格式的数据发送到微信服务器,当你使用了wechat-framework之后,做到这一步是非常方便的。
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;
}
}上面代码中的
// 返回的消息对象,任何返回消息都构造为WechatResponse
WechatResponse wechatResponse = new WechatResponse();
wechatResponse.setContent("文本回复:" + content);
wechatResponse.setMsgType(MsgType.text.name());
// 消息对象构造完成之后,调用formatWechatResponse方法即可
// formatWechatResponse方法会自动对ToUserName,FromUserName,CreateTime赋值
xml = formatWechatResponse(wechatRequest, wechatResponse);即是得到返回给微信的xml数据。
- 第一步,创建消息返回对象
WechatResponse wechatResponse = new WechatResponse() - 第二步,构建消息返回对象数据
wechatResponse.setContent("文本回复:" + content); wechatResponse.setMsgType(MsgType.text.name());,其中,FromUserName,ToUserName,CreateTime这三个字段不需要用户手动赋值,wechat-framework会自动赋值。 - 第三步,调用对象转
xml数据的方法String xml = formatWechatResponse(wechatRequest, wechatResponse)得到返回xml数据。 - 最后返回
xml字符串,其中加解密wechat-framework已经自动完成。