整理及重构

This commit is contained in:
Daniel Qian
2014-10-22 10:29:47 +08:00
parent 67795a092d
commit a8f5d07ff3
212 changed files with 1701 additions and 3459 deletions

View File

@@ -0,0 +1,84 @@
package me.chanjar.weixin.cp.api;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.inject.Binder;
import com.google.inject.Module;
import org.xml.sax.InputSource;
public class ApiTestModule implements Module {
@Override
public void configure(Binder binder) {
try {
InputStream is1 = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxXmlCpInMemoryConfigStorage config = fromXml(WxXmlCpInMemoryConfigStorage.class, is1);
WxCpServiceImpl wxService = new WxCpServiceImpl();
wxService.setWxCpConfigStorage(config);
binder.bind(WxCpServiceImpl.class).toInstance(wxService);
binder.bind(WxCpConfigStorage.class).toInstance(config);
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
public static <T> T fromXml(Class<T> clazz, InputStream is) throws JAXBException {
Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
InputSource inputSource = new InputSource(is);
inputSource.setEncoding("utf-8");
T object = (T) um.unmarshal(inputSource);
return object;
}
@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
public static class WxXmlCpInMemoryConfigStorage extends WxCpInMemoryConfigStorage {
protected String userId;
protected String departmentId;
protected String tagId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getTagId() {
return tagId;
}
public void setTagId(String tagId) {
this.tagId = tagId;
}
@Override
public String toString() {
return super.toString() + " > WxXmlCpConfigStorage{" +
"userId='" + userId + '\'' +
", departmentId='" + departmentId + '\'' +
", tagId='" + tagId + '\'' +
'}';
}
}
}

View File

@@ -0,0 +1,35 @@
package me.chanjar.weixin.cp.api;
import org.apache.commons.lang3.StringUtils;
import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.google.inject.Inject;
/**
* 基础API测试
* @author Daniel Qian
*
*/
@Test(groups = "baseAPI")
@Guice(modules = ApiTestModule.class)
public class WxCpBaseAPITest {
@Inject
protected WxCpServiceImpl wxService;
public void testRefreshAccessToken() throws WxErrorException {
WxCpConfigStorage configStorage = wxService.wxCpConfigStorage;
String before = configStorage.getAccessToken();
wxService.accessTokenRefresh();
String after = configStorage.getAccessToken();
Assert.assertNotEquals(before, after);
Assert.assertTrue(StringUtils.isNotBlank(after));
}
}

View File

@@ -0,0 +1,63 @@
package me.chanjar.weixin.cp.api;
import java.util.List;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.google.inject.Inject;
/**
* 测试部门接口
*
* @author Daniel Qian
*/
@Test(groups = "departAPI", dependsOnGroups = "baseAPI")
@Guice(modules = ApiTestModule.class)
public class WxCpDepartAPITest {
@Inject
protected WxCpServiceImpl wxService;
protected WxCpDepart depart;
public void testDepartCreate() throws WxErrorException {
WxCpDepart depart = new WxCpDepart();
depart.setName("子部门" + System.currentTimeMillis());
depart.setParentId(1);
depart.setOrder(1);
Integer departId = wxService.departCreate(depart);
}
@Test(dependsOnMethods = "testDepartCreate")
public void testDepartGet() throws WxErrorException {
System.out.println("=================获取部门");
List<WxCpDepart> departList = wxService.departGet();
Assert.assertNotNull(departList);
Assert.assertTrue(departList.size() > 0);
for (WxCpDepart g : departList) {
depart = g;
System.out.println(depart.getId() + ":" + depart.getName());
Assert.assertNotNull(g.getName());
}
}
@Test(dependsOnMethods = { "testDepartGet", "testDepartCreate" })
public void testDepartUpdate() throws WxErrorException {
System.out.println("=================更新部门");
depart.setName("子部门改名" + System.currentTimeMillis());
wxService.departUpdate(depart);
}
@Test(dependsOnMethods = "testDepartUpdate")
public void testDepartDelete() throws WxErrorException {
System.out.println("=================删除部门");
System.out.println(depart.getId() + ":" + depart.getName());
wxService.departDelete(depart.getId());
}
}

View File

@@ -0,0 +1,73 @@
package me.chanjar.weixin.cp.api;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.google.inject.Inject;
/**
* 测试多媒体文件上传下载
* @author Daniel Qian
*
*/
//@Test(groups="mediaAPI", dependsOnGroups="baseAPI")
@Test
@Guice(modules = ApiTestModule.class)
public class WxCpMediaAPITest {
@Inject
protected WxCpServiceImpl wxService;
private List<String> media_ids = new ArrayList<String>();
@Test(dataProvider="uploadMedia")
public void testUploadMedia(String mediaType, String fileType, String fileName) throws WxErrorException, IOException {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName);
WxMediaUploadResult res = wxService.mediaUpload(mediaType, fileType, inputStream);
Assert.assertNotNull(res.getType());
Assert.assertNotNull(res.getCreatedAt());
Assert.assertTrue(res.getMediaId() != null || res.getThumbMediaId() != null);
if (res.getMediaId() != null) {
media_ids.add(res.getMediaId());
}
if (res.getThumbMediaId() != null) {
media_ids.add(res.getThumbMediaId());
}
}
@DataProvider
public Object[][] uploadMedia() {
return new Object[][] {
new Object[] { WxCpConsts.MEDIA_IMAGE, WxCpConsts.FILE_JPG, "mm.jpeg" },
new Object[] { WxCpConsts.MEDIA_VOICE, WxCpConsts.FILE_MP3, "mm.mp3" },
new Object[] { WxCpConsts.MEDIA_VIDEO, WxCpConsts.FILE_MP4, "mm.mp4" },
new Object[] { WxCpConsts.MEDIA_FILE, WxCpConsts.FILE_JPG, "mm.jpeg" }
};
}
@Test(dependsOnMethods = { "testUploadMedia" }, dataProvider="downloadMedia")
public void testDownloadMedia(String media_id) throws WxErrorException {
wxService.mediaDownload(media_id);
}
@DataProvider
public Object[][] downloadMedia() {
Object[][] params = new Object[this.media_ids.size()][];
for (int i = 0; i < this.media_ids.size(); i++) {
params[i] = new Object[] { this.media_ids.get(i) };
}
return params;
}
}

View File

@@ -0,0 +1,42 @@
package me.chanjar.weixin.cp.api;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.google.inject.Inject;
/***
* 测试发送消息
* @author Daniel Qian
*
*/
@Test(groups="customMessageAPI", dependsOnGroups = "baseAPI")
@Guice(modules = ApiTestModule.class)
public class WxCpMessageAPITest {
@Inject
protected WxCpServiceImpl wxService;
public void testSendCustomMessage() throws WxErrorException {
ApiTestModule.WxXmlCpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlCpInMemoryConfigStorage) wxService.wxCpConfigStorage;
WxCpMessage message1 = new WxCpMessage();
message1.setAgentId(configStorage.getAgentId());
message1.setMsgType(WxCpConsts.CUSTOM_MSG_TEXT);
message1.setToUser(configStorage.getUserId());
message1.setContent("欢迎欢迎,热烈欢迎\n换行测试\n超链接:<a href=\"http://www.baidu.com\">Hello World</a>");
wxService.messageSend(message1);
WxCpMessage message2 = WxCpMessage
.TEXT()
.agentId(configStorage.getAgentId())
.toUser(configStorage.getUserId())
.content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:<a href=\"http://www.baidu.com\">Hello World</a>")
.build();
wxService.messageSend(message2);
}
}

View File

@@ -0,0 +1,158 @@
package me.chanjar.weixin.cp.api;
import java.util.Map;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* 测试消息路由器
* @author Daniel Qian
*
*/
@Test
public class WxCpMessageRouterTest {
@Test(enabled = false)
public void prepare(boolean async, StringBuffer sb, WxCpMessageRouter router) {
router
.rule()
.async(async)
.msgType(WxCpConsts.XML_MSG_TEXT).event(WxCpConsts.EVT_CLICK).eventKey("KEY_1").content("CONTENT_1")
.handler(new WxEchoCpMessageHandler(sb, "COMBINE_4"))
.end()
.rule()
.async(async)
.msgType(WxCpConsts.XML_MSG_TEXT).event(WxCpConsts.EVT_CLICK).eventKey("KEY_1")
.handler(new WxEchoCpMessageHandler(sb, "COMBINE_3"))
.end()
.rule()
.async(async)
.msgType(WxCpConsts.XML_MSG_TEXT).event(WxCpConsts.EVT_CLICK)
.handler(new WxEchoCpMessageHandler(sb, "COMBINE_2"))
.end()
.rule().async(async).msgType(WxCpConsts.XML_MSG_TEXT).handler(new WxEchoCpMessageHandler(sb, WxCpConsts.XML_MSG_TEXT)).end()
.rule().async(async).event(WxCpConsts.EVT_CLICK).handler(new WxEchoCpMessageHandler(sb, WxCpConsts.EVT_CLICK)).end()
.rule().async(async).eventKey("KEY_1").handler(new WxEchoCpMessageHandler(sb, "KEY_1")).end()
.rule().async(async).content("CONTENT_1").handler(new WxEchoCpMessageHandler(sb, "CONTENT_1")).end()
.rule().async(async).rContent(".*bc.*").handler(new WxEchoCpMessageHandler(sb, "abcd")).end()
.rule().async(async).handler(new WxEchoCpMessageHandler(sb, "ALL")).end();
;
}
@Test(dataProvider="messages-1")
public void testSync(WxCpXmlMessage message, String expected) {
StringBuffer sb = new StringBuffer();
WxCpMessageRouter router = new WxCpMessageRouter();
prepare(false, sb, router);
router.route(message);
Assert.assertEquals(sb.toString(), expected);
}
@Test(dataProvider="messages-1")
public void testAsync(WxCpXmlMessage message, String expected) throws InterruptedException {
StringBuffer sb = new StringBuffer();
WxCpMessageRouter router = new WxCpMessageRouter();
prepare(true, sb, router);
router.route(message);
Thread.sleep(500l);
Assert.assertEquals(sb.toString(), expected);
}
public void testConcurrency() throws InterruptedException {
final WxCpMessageRouter router = new WxCpMessageRouter();
router.rule().handler(new WxCpMessageHandler() {
@Override
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context) {
return null;
}
}).end();
final WxCpXmlMessage m = new WxCpXmlMessage();
Runnable r = new Runnable() {
@Override
public void run() {
router.route(m);
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
}
}
};
for (int i = 0; i < 10; i++) {
new Thread(r).start();
}
Thread.sleep(1000l * 2);
}
@DataProvider(name="messages-1")
public Object[][] messages2() {
WxCpXmlMessage message1 = new WxCpXmlMessage();
message1.setMsgType(WxCpConsts.XML_MSG_TEXT);
WxCpXmlMessage message2 = new WxCpXmlMessage();
message2.setEvent(WxCpConsts.EVT_CLICK);
WxCpXmlMessage message3 = new WxCpXmlMessage();
message3.setEventKey("KEY_1");
WxCpXmlMessage message4 = new WxCpXmlMessage();
message4.setContent("CONTENT_1");
WxCpXmlMessage message5 = new WxCpXmlMessage();
message5.setContent("BLA");
WxCpXmlMessage message6 = new WxCpXmlMessage();
message6.setContent("abcd");
WxCpXmlMessage c2 = new WxCpXmlMessage();
c2.setMsgType(WxCpConsts.XML_MSG_TEXT);
c2.setEvent(WxCpConsts.EVT_CLICK);
WxCpXmlMessage c3 = new WxCpXmlMessage();
c3.setMsgType(WxCpConsts.XML_MSG_TEXT);
c3.setEvent(WxCpConsts.EVT_CLICK);
c3.setEventKey("KEY_1");
WxCpXmlMessage c4 = new WxCpXmlMessage();
c4.setMsgType(WxCpConsts.XML_MSG_TEXT);
c4.setEvent(WxCpConsts.EVT_CLICK);
c4.setEventKey("KEY_1");
c4.setContent("CONTENT_1");
return new Object[][] {
new Object[] { message1, WxCpConsts.XML_MSG_TEXT + "," },
new Object[] { message2, WxCpConsts.EVT_CLICK + "," },
new Object[] { message3, "KEY_1," },
new Object[] { message4, "CONTENT_1," },
new Object[] { message5, "ALL," },
new Object[] { message6, "abcd," },
new Object[] { c2, "COMBINE_2," },
new Object[] { c3, "COMBINE_3," },
new Object[] { c4, "COMBINE_4," }
};
}
public static class WxEchoCpMessageHandler implements WxCpMessageHandler {
private StringBuffer sb;
private String echoStr;
public WxEchoCpMessageHandler(StringBuffer sb, String echoStr) {
this.sb = sb;
this.echoStr = echoStr;
}
@Override
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context) {
sb.append(this.echoStr).append(',');
return null;
}
}
}

View File

@@ -0,0 +1,66 @@
package me.chanjar.weixin.cp.api;
import com.google.inject.Inject;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
@Test(groups = "departAPI", dependsOnGroups = "baseAPI")
@Guice(modules = ApiTestModule.class)
public class WxCpTagAPITest {
@Inject
protected WxCpServiceImpl wxService;
@Inject
protected WxCpConfigStorage configStorage;
protected String tagId;
public void testTagCreate() throws Exception {
tagId = wxService.tagCreate("测试标签4");
System.out.println(tagId);
}
@Test(dependsOnMethods = "testTagCreate")
public void testTagUpdate() throws Exception {
wxService.tagUpdate(tagId, "测试标签-改名");
}
@Test(dependsOnMethods = "testTagUpdate")
public void testTagGet() throws Exception {
List<WxCpTag> tags = wxService.tagGet();
Assert.assertNotEquals(tags.size(), 0);
}
@Test(dependsOnMethods = "testTagGet")
public void testTagAddUsers() throws Exception {
List<String> userIds = new ArrayList<String>();
userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage)configStorage).getUserId());
wxService.tagAddUsers(tagId, userIds);
}
@Test(dependsOnMethods = "testTagAddUsers")
public void testTagGetUsers() throws Exception {
List<WxCpUser> users = wxService.tagGetUsers(tagId);
Assert.assertNotEquals(users.size(), 0);
}
@Test(dependsOnMethods = "testTagGetUsers")
public void testTagRemoveUsers() throws Exception {
List<String> userIds = new ArrayList<String>();
userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage)configStorage).getUserId());
wxService.tagRemoveUsers(tagId, userIds);
}
@Test(dependsOnMethods = "testTagRemoveUsers")
public void testTagDelete() throws Exception {
wxService.tagDelete(tagId);
}
}

View File

@@ -0,0 +1,66 @@
package me.chanjar.weixin.cp.api;
import com.google.inject.Inject;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.List;
/**
* 测试用户接口
*
* @author Daniel Qian
*/
@Test(groups = "userAPI", dependsOnGroups = "baseAPI")
@Guice(modules = ApiTestModule.class)
public class WxCpUserAPITest {
@Inject
protected WxCpServiceImpl wxService;
protected WxCpDepart depart;
public void testUserCreate() throws WxErrorException {
WxCpUser user = new WxCpUser();
user.setUserId("xiaohe.yang");
user.setName("杨宝");
user.setDepartIds(new Integer[] { 9, 8 });
user.setEmail("yangxiaohe@ddd.com");
user.setGender("");
user.setMobile("13564684979");
user.setPosition("老婆");
user.setTel("3300393");
user.addExtAttr("爱好", "老公");
wxService.userCreate(user);
}
@Test(dependsOnMethods = "testUserCreate")
public void testUserUpdate() throws WxErrorException {
WxCpUser user = new WxCpUser();
user.setUserId("xiaohe.yang");
user.setName("杨宝");
user.addExtAttr("爱好", "老公2");
wxService.userUpdate(user);
}
@Test(dependsOnMethods = "testUserUpdate")
public void testUserGet() throws WxErrorException {
WxCpUser user = wxService.userGet("xiaohe.yang");
Assert.assertNotNull(user);
}
@Test(dependsOnMethods = "testUserGet")
public void testDepartGetUsers() throws WxErrorException {
List<WxCpUser> users = wxService.departGetUsers(1, true, 0);
Assert.assertNotEquals(users.size(), 0);
}
@Test(dependsOnMethods = "testDepartGetUsers")
public void testUserDelete() throws WxErrorException {
wxService.userDelete("xiaohe.yang");
}
}

View File

@@ -0,0 +1,91 @@
package me.chanjar.weixin.cp.api;
import javax.xml.bind.JAXBException;
import me.chanjar.weixin.common.bean.WxMenu;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import com.google.inject.Inject;
import me.chanjar.weixin.common.bean.WxMenu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
/**
* 测试菜单
* @author Daniel Qian
*
*/
@Test(groups="menuAPI", dependsOnGroups="baseAPI")
@Guice(modules = ApiTestModule.class)
public class WxMenuAPITest {
@Inject
protected WxCpServiceImpl wxService;
@Test(dataProvider = "menu")
public void testCreateMenu(WxMenu wxMenu) throws WxErrorException {
wxService.menuCreate(wxMenu);
}
@Test(dependsOnMethods = { "testCreateMenu"})
public void testGetMenu() throws WxErrorException {
Assert.assertNotNull(wxService.menuGet());
}
@Test(dependsOnMethods = { "testGetMenu"})
public void testDeleteMenu() throws WxErrorException {
wxService.menuDelete();
}
@DataProvider(name="menu")
public Object[][] getMenu() throws JAXBException {
WxMenu menu = new WxMenu();
WxMenuButton button1 = new WxMenuButton();
button1.setType(WxCpConsts.BUTTON_CLICK);
button1.setName("今日歌曲");
button1.setKey("V1001_TODAY_MUSIC");
WxMenuButton button2 = new WxMenuButton();
button2.setType(WxCpConsts.BUTTON_CLICK);
button2.setName("歌手简介");
button2.setKey("V1001_TODAY_SINGER");
WxMenuButton button3 = new WxMenuButton();
button3.setName("菜单");
menu.getButtons().add(button1);
menu.getButtons().add(button2);
menu.getButtons().add(button3);
WxMenuButton button31 = new WxMenuButton();
button31.setType(WxCpConsts.BUTTON_VIEW);
button31.setName("搜索");
button31.setUrl("http://www.soso.com/");
WxMenuButton button32 = new WxMenuButton();
button32.setType(WxCpConsts.BUTTON_VIEW);
button32.setName("视频");
button32.setUrl("http://v.qq.com/");
WxMenuButton button33 = new WxMenuButton();
button33.setType(WxCpConsts.BUTTON_CLICK);
button33.setName("赞一下我们");
button33.setKey("V1001_GOOD");
button3.getSubButtons().add(button31);
button3.getSubButtons().add(button32);
button3.getSubButtons().add(button33);
return new Object[][] {
new Object[] {
menu
}
};
}
}

View File

@@ -0,0 +1,108 @@
package me.chanjar.weixin.cp.bean;
import me.chanjar.weixin.cp.api.WxCpConsts;
import org.testng.Assert;
import org.testng.annotations.Test;
import me.chanjar.weixin.cp.bean.WxCpMessage.WxArticle;
@Test
public class WxCpMessageTest {
public void testTextReply() {
WxCpMessage reply = new WxCpMessage();
reply.setToUser("OPENID");
reply.setMsgType(WxCpConsts.CUSTOM_MSG_TEXT);
reply.setContent("sfsfdsdf");
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"text\",\"text\":{\"content\":\"sfsfdsdf\"}}");
}
public void testTextBuild() {
WxCpMessage reply = WxCpMessage.TEXT().toUser("OPENID").content("sfsfdsdf").build();
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"text\",\"text\":{\"content\":\"sfsfdsdf\"}}");
}
public void testImageReply() {
WxCpMessage reply = new WxCpMessage();
reply.setToUser("OPENID");
reply.setMsgType(WxCpConsts.CUSTOM_MSG_IMAGE);
reply.setMediaId("MEDIA_ID");
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"MEDIA_ID\"}}");
}
public void testImageBuild() {
WxCpMessage reply = WxCpMessage.IMAGE().toUser("OPENID").mediaId("MEDIA_ID").build();
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"MEDIA_ID\"}}");
}
public void testVoiceReply() {
WxCpMessage reply = new WxCpMessage();
reply.setToUser("OPENID");
reply.setMsgType(WxCpConsts.CUSTOM_MSG_VOICE);
reply.setMediaId("MEDIA_ID");
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"voice\",\"voice\":{\"media_id\":\"MEDIA_ID\"}}");
}
public void testVoiceBuild() {
WxCpMessage reply = WxCpMessage.VOICE().toUser("OPENID").mediaId("MEDIA_ID").build();
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"voice\",\"voice\":{\"media_id\":\"MEDIA_ID\"}}");
}
public void testVideoReply() {
WxCpMessage reply = new WxCpMessage();
reply.setToUser("OPENID");
reply.setMsgType(WxCpConsts.CUSTOM_MSG_VIDEO);
reply.setMediaId("MEDIA_ID");
reply.setThumbMediaId("MEDIA_ID");
reply.setTitle("TITLE");
reply.setDescription("DESCRIPTION");
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"video\",\"video\":{\"media_id\":\"MEDIA_ID\",\"thumb_media_id\":\"MEDIA_ID\",\"title\":\"TITLE\",\"description\":\"DESCRIPTION\"}}");
}
public void testVideoBuild() {
WxCpMessage reply = WxCpMessage.VIDEO().toUser("OPENID").title("TITLE").mediaId("MEDIA_ID").thumbMediaId("MEDIA_ID").description("DESCRIPTION").build();
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"video\",\"video\":{\"media_id\":\"MEDIA_ID\",\"thumb_media_id\":\"MEDIA_ID\",\"title\":\"TITLE\",\"description\":\"DESCRIPTION\"}}");
}
public void testNewsReply() {
WxCpMessage reply = new WxCpMessage();
reply.setToUser("OPENID");
reply.setMsgType(WxCpConsts.CUSTOM_MSG_NEWS);
WxArticle article1 = new WxArticle();
article1.setUrl("URL");
article1.setPicUrl("PIC_URL");
article1.setDescription("Is Really A Happy Day");
article1.setTitle("Happy Day");
reply.getArticles().add(article1);
WxArticle article2 = new WxArticle();
article2.setUrl("URL");
article2.setPicUrl("PIC_URL");
article2.setDescription("Is Really A Happy Day");
article2.setTitle("Happy Day");
reply.getArticles().add(article2);
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"news\",\"articles\":[{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"},{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"}]}");
}
public void testNewsBuild() {
WxArticle article1 = new WxArticle();
article1.setUrl("URL");
article1.setPicUrl("PIC_URL");
article1.setDescription("Is Really A Happy Day");
article1.setTitle("Happy Day");
WxArticle article2 = new WxArticle();
article2.setUrl("URL");
article2.setPicUrl("PIC_URL");
article2.setDescription("Is Really A Happy Day");
article2.setTitle("Happy Day");
WxCpMessage reply = WxCpMessage.NEWS().toUser("OPENID").addArticle(article1).addArticle(article2).build();
Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"news\",\"articles\":[{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"},{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"}]}");
}
}

View File

@@ -0,0 +1,91 @@
package me.chanjar.weixin.cp.bean;
import me.chanjar.weixin.cp.api.WxCpConsts;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public class WxCpXmlMessageTest {
public void testFromXml() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName> "
+ "<CreateTime>1348831860</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[this is a test]]></Content>"
+ "<MsgId>1234567890123456</MsgId>"
+ "<PicUrl><![CDATA[this is a url]]></PicUrl>"
+ "<MediaId><![CDATA[media_id]]></MediaId>"
+ "<Format><![CDATA[Format]]></Format>"
+ "<ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId>"
+ "<Location_X>23.134521</Location_X>"
+ "<Location_Y>113.358803</Location_Y>"
+ "<Scale>20</Scale>"
+ "<Label><![CDATA[位置信息]]></Label>"
+ "<Description><![CDATA[公众平台官网链接]]></Description>"
+ "<Url><![CDATA[url]]></Url>"
+ "<Title><![CDATA[公众平台官网链接]]></Title>"
+ "<Event><![CDATA[subscribe]]></Event>"
+ "<EventKey><![CDATA[qrscene_123123]]></EventKey>"
+ "<Ticket><![CDATA[TICKET]]></Ticket>"
+ "<Latitude>23.137466</Latitude>"
+ "<Longitude>113.352425</Longitude>"
+ "<Precision>119.385040</Precision>"
+ "<ScanCodeInfo>"
+ " <ScanType><![CDATA[qrcode]]></ScanType>"
+ " <ScanResult><![CDATA[1]]></ScanResult>"
+ "</ScanCodeInfo>"
+ "<SendPicsInfo>"
+ " <Count>1</Count>\n"
+ " <PicList>"
+ " <item>"
+ " <PicMd5Sum><![CDATA[1b5f7c23b5bf75682a53e7b6d163e185]]></PicMd5Sum>"
+ " </item>"
+ " </PicList>"
+ "</SendPicsInfo>"
+ "<SendLocationInfo>"
+ " <Location_X><![CDATA[23]]></Location_X>\n"
+ " <Location_Y><![CDATA[113]]></Location_Y>\n"
+ " <Scale><![CDATA[15]]></Scale>\n"
+ " <Label><![CDATA[ 广州市海珠区客村艺苑路 106号]]></Label>\n"
+ " <Poiname><![CDATA[wo de poi]]></Poiname>\n"
+ "</SendLocationInfo>"
+ "</xml>";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml);
Assert.assertEquals(wxMessage.getToUserName(), "toUser");
Assert.assertEquals(wxMessage.getFromUserName(), "fromUser");
Assert.assertEquals(wxMessage.getCreateTime(), new Long(1348831860l));
Assert.assertEquals(wxMessage.getMsgType(), WxCpConsts.XML_MSG_TEXT);
Assert.assertEquals(wxMessage.getContent(), "this is a test");
Assert.assertEquals(wxMessage.getMsgId(), new Long(1234567890123456l));
Assert.assertEquals(wxMessage.getPicUrl(), "this is a url");
Assert.assertEquals(wxMessage.getMediaId(), "media_id");
Assert.assertEquals(wxMessage.getFormat(), "Format");
Assert.assertEquals(wxMessage.getThumbMediaId(), "thumb_media_id");
Assert.assertEquals(wxMessage.getLocationX(), new Double(23.134521d));
Assert.assertEquals(wxMessage.getLocationY(), new Double(113.358803d));
Assert.assertEquals(wxMessage.getScale(), new Double(20));
Assert.assertEquals(wxMessage.getLabel(), "位置信息");
Assert.assertEquals(wxMessage.getDescription(), "公众平台官网链接");
Assert.assertEquals(wxMessage.getUrl(), "url");
Assert.assertEquals(wxMessage.getTitle(), "公众平台官网链接");
Assert.assertEquals(wxMessage.getEvent(), "subscribe");
Assert.assertEquals(wxMessage.getEventKey(), "qrscene_123123");
Assert.assertEquals(wxMessage.getTicket(), "TICKET");
Assert.assertEquals(wxMessage.getLatitude(), new Double(23.137466));
Assert.assertEquals(wxMessage.getLongitude(), new Double(113.352425));
Assert.assertEquals(wxMessage.getPrecision(), new Double(119.385040));
Assert.assertEquals(wxMessage.getScanCodeInfo().getScanType(), "qrcode");
Assert.assertEquals(wxMessage.getScanCodeInfo().getScanResult(), "1");
Assert.assertEquals(wxMessage.getSendPicsInfo().getCount(), new Long(1l));
Assert.assertEquals(wxMessage.getSendPicsInfo().getPicList().get(0).getPicMd5Sum(), "1b5f7c23b5bf75682a53e7b6d163e185");
Assert.assertEquals(wxMessage.getSendLocationInfo().getLocationX(), "23");
Assert.assertEquals(wxMessage.getSendLocationInfo().getLocationY(), "113");
Assert.assertEquals(wxMessage.getSendLocationInfo().getScale(), "15");
Assert.assertEquals(wxMessage.getSendLocationInfo().getLabel(), " 广州市海珠区客村艺苑路 106号");
Assert.assertEquals(wxMessage.getSendLocationInfo().getPoiname(), "wo de poi");
}
}

View File

@@ -0,0 +1,50 @@
package me.chanjar.weixin.cp.bean;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public class WxCpXmlOutImageMessageTest {
public void test() {
WxCpXmlOutImageMessage m = new WxCpXmlOutImageMessage();
m.setMediaId("ddfefesfsdfef");
m.setCreateTime(1122l);
m.setFromUserName("from");
m.setToUserName("to");
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[image]]></MsgType>"
+ "<Image><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Image>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
public void testBuild() {
WxCpXmlOutImageMessage m = WxCpXmlOutMessage.IMAGE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build();
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[image]]></MsgType>"
+ "<Image><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Image>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}

View File

@@ -0,0 +1,95 @@
package me.chanjar.weixin.cp.bean;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public class WxCpXmlOutNewsMessageTest {
public void test() {
WxCpXmlOutMewsMessage m = new WxCpXmlOutMewsMessage();
m.setCreateTime(1122l);
m.setFromUserName("fromUser");
m.setToUserName("toUser");
WxCpXmlOutMewsMessage.Item item = new WxCpXmlOutMewsMessage.Item();
item.setDescription("description");
item.setPicUrl("picUrl");
item.setTitle("title");
item.setUrl("url");
m.addArticle(item);
m.addArticle(item);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[news]]></MsgType>"
+ " <ArticleCount>2</ArticleCount>"
+ " <Articles>"
+ " <item>"
+ " <Title><![CDATA[title]]></Title>"
+ " <Description><![CDATA[description]]></Description>"
+ " <PicUrl><![CDATA[picUrl]]></PicUrl>"
+ " <Url><![CDATA[url]]></Url>"
+ " </item>"
+ " <item>"
+ " <Title><![CDATA[title]]></Title>"
+ " <Description><![CDATA[description]]></Description>"
+ " <PicUrl><![CDATA[picUrl]]></PicUrl>"
+ " <Url><![CDATA[url]]></Url>"
+ " </item>"
+ " </Articles>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
public void testBuild() {
WxCpXmlOutMewsMessage.Item item = new WxCpXmlOutMewsMessage.Item();
item.setDescription("description");
item.setPicUrl("picUrl");
item.setTitle("title");
item.setUrl("url");
WxCpXmlOutMewsMessage m = WxCpXmlOutMessage.NEWS()
.fromUser("fromUser")
.toUser("toUser")
.addArticle(item)
.addArticle(item)
.build();
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[news]]></MsgType>"
+ " <ArticleCount>2</ArticleCount>"
+ " <Articles>"
+ " <item>"
+ " <Title><![CDATA[title]]></Title>"
+ " <Description><![CDATA[description]]></Description>"
+ " <PicUrl><![CDATA[picUrl]]></PicUrl>"
+ " <Url><![CDATA[url]]></Url>"
+ " </item>"
+ " <item>"
+ " <Title><![CDATA[title]]></Title>"
+ " <Description><![CDATA[description]]></Description>"
+ " <PicUrl><![CDATA[picUrl]]></PicUrl>"
+ " <Url><![CDATA[url]]></Url>"
+ " </item>"
+ " </Articles>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}

View File

@@ -0,0 +1,52 @@
package me.chanjar.weixin.cp.bean;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public class WxCpXmlOutTextMessageTest {
public void test() {
WxCpXmlOutTextMessage m = new WxCpXmlOutTextMessage();
m.setContent("content");
m.setCreateTime(1122l);
m.setFromUserName("from");
m.setToUserName("to");
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[content]]></Content>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
public void testBuild() {
WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("content").fromUser("from").toUser("to").build();
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[content]]></Content>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}

View File

@@ -0,0 +1,66 @@
package me.chanjar.weixin.cp.bean;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public class WxCpXmlOutVideoMessageTest {
public void test() {
WxCpXmlOutVideoMessage m = new WxCpXmlOutVideoMessage();
m.setMediaId("media_id");
m.setTitle("title");
m.setDescription("ddfff");
m.setCreateTime(1122l);
m.setFromUserName("fromUser");
m.setToUserName("toUser");
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[video]]></MsgType>"
+ "<Video>"
+ "<MediaId><![CDATA[media_id]]></MediaId>"
+ "<Title><![CDATA[title]]></Title>"
+ "<Description><![CDATA[ddfff]]></Description>"
+ "</Video> "
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
public void testBuild() {
WxCpXmlOutVideoMessage m = WxCpXmlOutMessage.VIDEO()
.mediaId("media_id")
.fromUser("fromUser")
.toUser("toUser")
.title("title")
.description("ddfff")
.build();
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[video]]></MsgType>"
+ "<Video>"
+ "<MediaId><![CDATA[media_id]]></MediaId>"
+ "<Title><![CDATA[title]]></Title>"
+ "<Description><![CDATA[ddfff]]></Description>"
+ "</Video> "
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}

View File

@@ -0,0 +1,50 @@
package me.chanjar.weixin.cp.bean;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public class WxCpXmlOutVoiceMessageTest {
public void test() {
WxCpXmlOutVoiceMessage m = new WxCpXmlOutVoiceMessage();
m.setMediaId("ddfefesfsdfef");
m.setCreateTime(1122l);
m.setFromUserName("from");
m.setToUserName("to");
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[voice]]></MsgType>"
+ "<Voice><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Voice>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
public void testBuild() {
WxCpXmlOutVoiceMessage m = WxCpXmlOutMessage.VOICE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build();
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[voice]]></MsgType>"
+ "<Voice><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Voice>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}

View File

@@ -0,0 +1,35 @@
package me.chanjar.weixin.cp.demo;
import me.chanjar.weixin.cp.api.WxCpInMemoryConfigStorage;
import org.xml.sax.InputSource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.InputStream;
/**
* @author Daniel Qian
*/
@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
class WxCpDemoInMemoryConfigStorage extends WxCpInMemoryConfigStorage {
@Override
public String toString() {
return "SimpleWxConfigProvider [appidOrCorpid=" + corpId + ", corpSecret=" + corpSecret + ", accessToken=" + accessToken
+ ", expiresIn=" + expiresIn + ", token=" + token + ", aesKey=" + aesKey + "]";
}
public static WxCpDemoInMemoryConfigStorage fromXml(InputStream is) throws JAXBException {
Unmarshaller um = JAXBContext.newInstance(WxCpDemoInMemoryConfigStorage.class).createUnmarshaller();
InputSource inputSource = new InputSource(is);
inputSource.setEncoding("utf-8");
return (WxCpDemoInMemoryConfigStorage) um.unmarshal(inputSource);
}
}

View File

@@ -0,0 +1,20 @@
package me.chanjar.weixin.cp.demo;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
/**
* @author Daniel Qian
*/
public class WxCpDemoServer {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(WxCpDemoServlet.class, "/*");
server.start();
server.join();
}
}

View File

@@ -0,0 +1,99 @@
package me.chanjar.weixin.cp.demo;
import me.chanjar.weixin.cp.api.*;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutTextMessage;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
/**
* @author Daniel Qian
*/
public class WxCpDemoServlet extends HttpServlet {
protected WxCpService wxCpService;
protected WxCpConfigStorage wxCpConfigStorage;
protected WxCpMessageRouter wxCpMessageRouter;
@Override public void init() throws ServletException {
//
super.init();
try {
InputStream is1 = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(is1);
wxCpConfigStorage = config;
wxCpService = new WxCpServiceImpl();
wxCpService.setWxCpConfigStorage(config);
WxCpMessageHandler handler = new WxCpMessageHandler() {
@Override public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context) {
WxCpXmlOutTextMessage m = WxCpXmlOutMessage
.TEXT()
.content("测试加密消息")
.fromUser(wxMessage.getToUserName())
.toUser(wxMessage.getFromUserName())
.build();
return m;
}
};
wxCpMessageRouter = new WxCpMessageRouter();
wxCpMessageRouter
.rule()
.async(false)
.content("哈哈") // 拦截内容为“哈哈”的消息
.handler(handler)
.end();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
@Override protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String msgSignature = request.getParameter("msg_signature");
String nonce = request.getParameter("nonce");
String timestamp = request.getParameter("timestamp");
String echostr = request.getParameter("echostr");
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
if (StringUtils.isNotBlank(echostr)) {
if (!wxCpService.checkSignature(msgSignature, timestamp, nonce, echostr)) {
// 消息签名不正确,说明不是公众平台发过来的消息
response.getWriter().println("非法请求");
return;
}
WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage);
String plainText = cryptUtil.decrypt(echostr);
// 说明是一个仅仅用来验证的请求回显echostr
response.getWriter().println(plainText);
return;
}
WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(request.getInputStream(), wxCpConfigStorage, timestamp, nonce, msgSignature);
WxCpXmlOutMessage outMessage = wxCpMessageRouter.route(inMessage);
if (outMessage != null) {
response.getWriter().write(outMessage.toEncryptedXml(wxCpConfigStorage));
}
return;
}
}