me.chanjar.weixin.mp.bean.message.WxMpXmlMessage Java Examples

The following examples show how to use me.chanjar.weixin.mp.bean.message.WxMpXmlMessage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DemoImageHandler.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
                                WxMpService wxMpService, WxSessionManager sessionManager) {
  try {
    WxMediaUploadResult wxMediaUploadResult = wxMpService.getMaterialService()
      .mediaUpload(WxConsts.MediaFileType.IMAGE, TestConstants.FILE_JPG, ClassLoader.getSystemResourceAsStream("mm.jpeg"));
    WxMpXmlOutImageMessage m
      = WxMpXmlOutMessage
      .IMAGE()
      .mediaId(wxMediaUploadResult.getMediaId())
      .fromUser(wxMessage.getToUser())
      .toUser(wxMessage.getFromUser())
      .build();
    return m;
  } catch (WxErrorException e) {
    e.printStackTrace();
  }

  return null;
}
 
Example #2
Source File: LocationHandler.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService wxMpService,
                                WxSessionManager sessionManager) {
    if (wxMessage.getMsgType().equals(XmlMsgType.LOCATION)) {
        //TODO 接收处理用户发送的地理位置消息
        try {
            String content = "感谢反馈,您的的地理位置已收到!";
            return new TextBuilder().build(content, wxMessage, null);
        } catch (Exception e) {
            this.logger.error("位置消息接收处理失败", e);
            return null;
        }
    }

    //上报地理位置事件
    this.logger.info("上报地理位置,纬度 : {},经度 : {},精度 : {}",
        wxMessage.getLatitude(), wxMessage.getLongitude(), String.valueOf(wxMessage.getPrecision()));

    //TODO  可以将用户地理位置信息保存到本地数据库,以便以后使用

    return null;
}
 
Example #3
Source File: WxMpMessageRouter.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
protected boolean isMsgDuplicated(WxMpXmlMessage wxMessage) {
  StringBuilder messageId = new StringBuilder();
  if (wxMessage.getMsgId() == null) {
    messageId.append(wxMessage.getCreateTime())
      .append("-").append(wxMessage.getFromUser())
      .append("-").append(StringUtils.trimToEmpty(wxMessage.getEventKey()))
      .append("-").append(StringUtils.trimToEmpty(wxMessage.getEvent()))
    ;
  } else {
    messageId.append(wxMessage.getMsgId())
      .append("-").append(wxMessage.getCreateTime())
      .append("-").append(wxMessage.getFromUser());
  }

  return this.messageDuplicateChecker.isDuplicate(messageId.toString());

}
 
Example #4
Source File: WxMpMessageRouterTest.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "standardSessionManager")
public void testSessionClean1(StandardSessionManager ism) throws InterruptedException {

  // 两个同步请求,看是否处理完毕后会被清理掉
  final WxMpMessageRouter router = new WxMpMessageRouter(null);
  router.setSessionManager(ism);
  router
    .rule().async(false).handler(new WxSessionMessageHandler()).next()
    .rule().async(false).handler(new WxSessionMessageHandler()).end();

  WxMpXmlMessage msg = new WxMpXmlMessage();
  msg.setFromUser("abc");
  router.route(msg);

  Thread.sleep(2000);
  Assert.assertEquals(ism.getActiveSessions(), 0);

}
 
Example #5
Source File: WxMpMessageRouterTest.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "standardSessionManager")
public void testSessionClean3(StandardSessionManager ism) throws InterruptedException {

  // 2个异步请求,看是否处理完毕后会被清理掉
  final WxMpMessageRouter router = new WxMpMessageRouter(null);
  router.setSessionManager(ism);
  router
    .rule().async(true).handler(new WxSessionMessageHandler()).next()
    .rule().async(true).handler(new WxSessionMessageHandler()).end();

  WxMpXmlMessage msg = new WxMpXmlMessage();
  msg.setFromUser("abc");
  router.route(msg);

  Thread.sleep(2000);
  Assert.assertEquals(ism.getActiveSessions(), 0);

}
 
Example #6
Source File: LocationHandler.java    From black-shop with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
		WxSessionManager sessionManager) {
	if (wxMessage.getMsgType().equals(XmlMsgType.LOCATION)) {
		// TODO 接收处理用户发送的地理位置消息
		try {
			String content = "感谢反馈,您的的地理位置已收到!";
			return new TextBuilder().build(content, wxMessage, null);
		} catch (Exception e) {
			this.logger.error("位置消息接收处理失败", e);
			return null;
		}
	}

	// 上报地理位置事件
	this.logger.info("上报地理位置,纬度 : {},经度 : {},精度 : {}", wxMessage.getLatitude(), wxMessage.getLongitude(),
			String.valueOf(wxMessage.getPrecision()));

	// TODO 可以将用户地理位置信息保存到本地数据库,以便以后使用

	return null;
}
 
Example #7
Source File: LocationHandler.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService wxMpService,
                                WxSessionManager sessionManager) {
    if (wxMessage.getMsgType().equals(XmlMsgType.LOCATION)) {
        //TODO 接收处理用户发送的地理位置消息
        try {
            String content = "感谢反馈,您的的地理位置已收到!";
            return new TextBuilder().build(content, wxMessage, null);
        } catch (Exception e) {
            this.logger.error("位置消息接收处理失败", e);
            return null;
        }
    }

    //上报地理位置事件
    this.logger.info("上报地理位置,纬度 : {},经度 : {},精度 : {}",
        wxMessage.getLatitude(), wxMessage.getLongitude(), String.valueOf(wxMessage.getPrecision()));

    //TODO  可以将用户地理位置信息保存到本地数据库,以便以后使用

    return null;
}
 
Example #8
Source File: MenuHandler.java    From black-shop with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService weixinService,
                                WxSessionManager sessionManager) {

    String msg = String.format("type:%s, event:%s, key:%s",
        wxMessage.getMsgType(), wxMessage.getEvent(),
        wxMessage.getEventKey());
    if (MenuButtonType.VIEW.equals(wxMessage.getEvent())) {
        return null;
    }

    return WxMpXmlOutMessage.TEXT().content(msg)
        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
        .build();
}
 
Example #9
Source File: MenuHandler.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService weixinService,
                                WxSessionManager sessionManager) {

    String msg = String.format("type:%s, event:%s, key:%s",
        wxMessage.getMsgType(), wxMessage.getEvent(),
        wxMessage.getEventKey());
    if (MenuButtonType.VIEW.equals(wxMessage.getEvent())) {
        return null;
    }

    return WxMpXmlOutMessage.TEXT().content(msg)
        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
        .build();
}
 
Example #10
Source File: MsgHandler.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
		WxMpService weixinService, WxSessionManager sessionManager) {

	if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
		// TODO 可以选择将消息保存到本地
	}

	// 当用户输入关键词如“你好”,“客服”等,并且有客服在线时,把消息转发给在线客服
	try {
		if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
				&& weixinService.getKefuService().kfOnlineList().getKfOnlineList().size() > 0) { return WxMpXmlOutMessage
				.TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser()).toUser(
						wxMessage.getFromUser()).build(); }
	} catch (WxErrorException e) {
		e.printStackTrace();
	}

	// TODO 组装回复消息
	String content = "收到信息内容:" + JsonUtils.toJson(wxMessage);

	return new TextBuilder().build(content, wxMessage, weixinService);

}
 
Example #11
Source File: MenuHandler.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService weixinService,
                                WxSessionManager sessionManager) {

    String msg = String.format("type:%s, event:%s, key:%s",
        wxMessage.getMsgType(), wxMessage.getEvent(),
        wxMessage.getEventKey());
    if (MenuButtonType.VIEW.equals(wxMessage.getEvent())) {
        return null;
    }

    return WxMpXmlOutMessage.TEXT().content(msg)
        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
        .build();
}
 
Example #12
Source File: ImageBuilder.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
@Override
public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, WxMpService service) {

	WxMpXmlOutImageMessage m = WxMpXmlOutMessage.IMAGE().mediaId(content).fromUser(
			wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();

	return m;
}
 
Example #13
Source File: TextBuilder.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage,
                               WxMpService service) {
    WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
        .build();
    return m;
}
 
Example #14
Source File: KfSessionHandler.java    From black-shop with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService wxMpService,
                                WxSessionManager sessionManager) {
    //TODO 对会话做处理
    return null;
}
 
Example #15
Source File: WechatController.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
private WxMpXmlOutMessage route(WxMpXmlMessage message) {
	try {
		return this.router.route(message);
	} catch (Exception e) {
		this.logger.error(e.getMessage(), e);
	}

	return null;
}
 
Example #16
Source File: ImageBuilder.java    From black-shop with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, WxMpService service) {

  WxMpXmlOutImageMessage m = WxMpXmlOutMessage.IMAGE().mediaId(content).fromUser(wxMessage.getToUser())
      .toUser(wxMessage.getFromUser()).build();

  return m;
}
 
Example #17
Source File: UnsubscribeHandler.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
		WxMpService wxMpService, WxSessionManager sessionManager) {
	String openId = wxMessage.getFromUser();
	this.logger.info("取消关注用户 OPENID: " + openId);
	// TODO 可以更新本地数据库为取消关注状态
	return null;
}
 
Example #18
Source File: MsgHandler.java    From black-shop with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService weixinService,
								WxSessionManager sessionManager) {

	if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
		// TODO 可以选择将消息保存到本地
	}

	// 当用户输入关键词如“你好”,“客服”等,并且有客服在线时,把消息转发给在线客服
	try {
		if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
				&& weixinService.getKefuService().kfOnlineList().getKfOnlineList().size() > 0) {
			return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
					.toUser(wxMessage.getFromUser()).build();
		}
	} catch (WxErrorException e) {
		e.printStackTrace();
	}
	// 1. 获取微信客户端发送的消息
	String fromContent = wxMessage.getContent();
	// 2.使用正则表达式验证消息是否为手机号码格式
	if (RegexUtils.checkMobile(fromContent)) {
		// 1.根据手机号码调用会员服务接口查询用户信息是否存在
		ResponseResult<Boolean> result = sysUserServiceClient.existMobileNumber(fromContent);
		if (!result.getResult()) {
			return new TextBuilder().build("该手机号码" + fromContent + "已经存在!", wxMessage, weixinService);
		}
		// 3.如果是手机号码格式的话,随机生产4位数字注册码
		int registCode = registCode();
		String content = registrationCodeMessage.format(registrationCodeMessage, registCode);
		// 将注册码存入在redis中 key为手机号码
		//redisUtil.setString(Constants.WECHET_CODE_KEY + fromContent, registCode + "", Constants.WECHET_CODE_TIMEOUT);
		return new TextBuilder().build(content, wxMessage, weixinService);
	}
	// 否则情况下返回默认消息 调用第三方机器人接口
	return new TextBuilder().build(defaultRegistrationCodeMessage, wxMessage, weixinService);

}
 
Example #19
Source File: StoreCheckNotifyHandler.java    From black-shop with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService wxMpService,
                                WxSessionManager sessionManager) {
    // TODO 处理门店审核事件
    return null;
}
 
Example #20
Source File: UnsubscribeHandler.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService wxMpService,
                                WxSessionManager sessionManager) {
    String openId = wxMessage.getFromUser();
    this.logger.info("取消关注用户 OPENID: " + openId);
    // TODO 可以更新本地数据库为取消关注状态
    return null;
}
 
Example #21
Source File: WxPortalController.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
private WxMpXmlOutMessage route(WxMpXmlMessage message) {
    try {
        return wxMpMessageRouter.route(message);
    } catch (Exception e) {
        this.logger.error("路由消息时出现异常!", e);
    }
    return null;
}
 
Example #22
Source File: WxMpMessageRouterTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "messages-1")
public void testExternalExcutorService(WxMpXmlMessage message, String expected) throws InterruptedException {
  StringBuffer sb = new StringBuffer();
  ExecutorService executorService = Executors.newFixedThreadPool(100);
  WxMpMessageRouter router = new WxMpMessageRouter(null, executorService);
  prepare(true, sb, router);
  router.route(message);
  Thread.sleep(500);
  executorService.shutdown();
  Assert.assertEquals(sb.toString(), expected);
}
 
Example #23
Source File: WxPortalController.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
private WxMpXmlOutMessage route(WxMpXmlMessage message, String appid) {
    try {
        return WxMpConfiguration.getRouters().get(appid).route(message);
    } catch (Exception e) {
        log.error("路由消息时出现异常!", e);
    }

    return null;
}
 
Example #24
Source File: WxMpMessageRouterTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "messages-1")
public void testAsync(WxMpXmlMessage message, String expected) throws InterruptedException {
  StringBuffer sb = new StringBuffer();
  WxMpMessageRouter router = new WxMpMessageRouter(null);
  prepare(true, sb, router);
  router.route(message);
  Thread.sleep(500);
  router.shutDownExecutorService();
  Assert.assertEquals(sb.toString(), expected);
}
 
Example #25
Source File: WxMpMessageRouterTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "messages-1")
public void testSync(WxMpXmlMessage message, String expected) {
  StringBuffer sb = new StringBuffer();
  WxMpMessageRouter router = new WxMpMessageRouter(null);
  prepare(false, sb, router);
  router.route(message);
  Assert.assertEquals(sb.toString(), expected);
}
 
Example #26
Source File: WxMpMessageRouterTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test(enabled = false)
public void prepare(boolean async, StringBuffer sb, WxMpMessageRouter router) {
  router
    .rule()
    .async(async)
    .msgType(WxConsts.XmlMsgType.TEXT).event(WxConsts.EventType.CLICK).eventKey("KEY_1").content("CONTENT_1")
    .handler(new WxEchoMpMessageHandler(sb, "COMBINE_4"))
    .end()
    .rule()
    .async(async)
    .msgType(WxConsts.XmlMsgType.TEXT).event(WxConsts.EventType.CLICK).eventKey("KEY_1")
    .handler(new WxEchoMpMessageHandler(sb, "COMBINE_3"))
    .end()
    .rule()
    .async(async)
    .msgType(WxConsts.XmlMsgType.TEXT).event(WxConsts.EventType.CLICK)
    .handler(new WxEchoMpMessageHandler(sb, "COMBINE_2"))
    .end()
    .rule().async(async).msgType(WxConsts.XmlMsgType.TEXT).handler(new WxEchoMpMessageHandler(sb, WxConsts.XmlMsgType.TEXT)).end()
    .rule().async(async).event(WxConsts.EventType.CLICK).handler(new WxEchoMpMessageHandler(sb, WxConsts.EventType.CLICK)).end()
    .rule().async(async).eventKey("KEY_1").handler(new WxEchoMpMessageHandler(sb, "KEY_1")).end()
    .rule().async(async).eventKeyRegex("KEY_1*").handler(new WxEchoMpMessageHandler(sb, "KEY_123")).end()
    .rule().async(async).content("CONTENT_1").handler(new WxEchoMpMessageHandler(sb, "CONTENT_1")).end()
    .rule().async(async).rContent(".*bc.*").handler(new WxEchoMpMessageHandler(sb, "abcd")).end()
    .rule().async(async).matcher(new WxMpMessageMatcher() {
    @Override
    public boolean match(WxMpXmlMessage message) {
      return "strangeformat".equals(message.getFormat());
    }
  }).handler(new WxEchoMpMessageHandler(sb, "matcher")).end()
    .rule().async(async).handler(new WxEchoMpMessageHandler(sb, "ALL")).end();
}
 
Example #27
Source File: DemoOAuth2Handler.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService wxMpService,
                                WxSessionManager sessionManager) {
  String href = "<a href=\"" + wxMpService.oauth2buildAuthorizationUrl(
    wxMpService.getWxMpConfigStorage().getOauth2redirectUri(),
    WxConsts.OAuth2Scope.SNSAPI_USERINFO, null) + "\">测试oauth2</a>";
  return WxMpXmlOutMessage.TEXT().content(href)
    .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
    .build();
}
 
Example #28
Source File: StoreCheckNotifyHandler.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                Map<String, Object> context, WxMpService wxMpService,
                                WxSessionManager sessionManager) {
    // TODO 处理门店审核事件
    return null;
}
 
Example #29
Source File: WxMpMessageRouterTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public void testConcurrency() throws InterruptedException {
  final WxMpMessageRouter router = new WxMpMessageRouter(null);
  router.rule().handler(new WxMpMessageHandler() {
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
      return null;
    }
  }).end();

  final WxMpXmlMessage m = new WxMpXmlMessage();
  Runnable r = new Runnable() {
    @Override
    public void run() {
      router.route(m);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
      }
    }
  };
  for (int i = 0; i < 10; i++) {
    new Thread(r).start();
  }

  Thread.sleep(2000);
}
 
Example #30
Source File: WxOpenXmlMessage.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public static WxMpXmlMessage fromEncryptedMpXml(String encryptedXml,
                                                WxOpenConfigStorage wxOpenConfigStorage, String timestamp, String nonce,
                                                String msgSignature) {
  WxOpenCryptUtil cryptUtil = new WxOpenCryptUtil(wxOpenConfigStorage);
  String plainText = cryptUtil.decrypt(msgSignature, timestamp, nonce,
    encryptedXml);
  return WxMpXmlMessage.fromXml(plainText);
}