me.chanjar.weixin.mp.api.WxMpService Java Examples

The following examples show how to use me.chanjar.weixin.mp.api.WxMpService. 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: FocusMeMessage.java    From mywx 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) throws WxErrorException {
   // String msg = source.getMessage("message.welcome", null, Locale.getDefault());
    String event = StringUtils.isBlank(wxMessage.getEvent()) ? StringUtils.EMPTY : wxMessage.getEvent();
    WxMpXmlOutTextMessage m = null;
    if (WxConsts.EVT_SUBSCRIBE.equals(event)) {
        m
                = WxMpXmlOutMessage
                .TEXT()
                .content("message.welcome")
                .fromUser(wxMessage.getToUserName())
                .toUser(wxMessage.getFromUserName())
                .build();
    } else if (WxConsts.EVT_UNSUBSCRIBE.equals(event)) {
    }
    log.info("{} ---> {}", event, ToStringBuilder.reflectionToString(wxMessage));
    return m;
}
 
Example #2
Source File: WxMpConfiguration.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
@Bean
public Object services() {
    mpServices = this.properties.getConfigs()
            .stream()
            .map(a -> {
                WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
                configStorage.setAppId(a.getAppId());
                configStorage.setSecret(a.getSecret());
                configStorage.setToken(a.getToken());
                configStorage.setAesKey(a.getAesKey());

                WxMpService service = new WxMpServiceImpl();
                service.setWxMpConfigStorage(configStorage);
                routers.put(a.getAppId(), this.newRouter(service));
                return service;
            }).collect(Collectors.toMap(s -> s.getWxMpConfigStorage().getAppId(), a -> a));

    return Boolean.TRUE;
}
 
Example #3
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 #4
Source File: WxMpTemplateMessageServiceImpl.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
public String sendWxMpTemplateMessage(String openId, String templateId, String url, Map<String,String> map){
    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
            .toUser(openId)
            .templateId(templateId)
            .url(url)
            .build();
    map.forEach( (k,v)-> { templateMessage.addData(new WxMpTemplateData(k, v, "#000000"));} );
    String msgId = null;
    WxMpService wxService = WxMpConfiguration.getWxMpService();
    try {
        msgId =   wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    } catch (WxErrorException e) {
        e.printStackTrace();
    }
    return msgId;
}
 
Example #5
Source File: ApiTestModule.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(Binder binder) {
  try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(TEST_CONFIG_XML)) {
    if (inputStream == null) {
      throw new RuntimeException("测试配置文件【" + TEST_CONFIG_XML + "】未找到,请参照test-config-sample.xml文件生成");
    }

    TestConfigStorage config = this.fromXml(TestConfigStorage.class, inputStream);
    config.setAccessTokenLock(new ReentrantLock());
    WxMpService wxService = new WxMpServiceHttpClientImpl();
    wxService.setWxMpConfigStorage(config);

    binder.bind(WxMpService.class).toInstance(wxService);
    binder.bind(WxMpConfigStorage.class).toInstance(config);
  } catch (IOException e) {
    this.log.error(e.getMessage(), e);
  }
}
 
Example #6
Source File: WxMpTemplateMsgSender.java    From WePush with MIT License 6 votes vote down vote up
/**
 * 获取微信公众号工具服务
 *
 * @return WxMpService
 */
public static WxMpService getWxMpService() {
    if (wxMpConfigStorage == null) {
        synchronized (WxMpTemplateMsgSender.class) {
            if (wxMpConfigStorage == null) {
                wxMpConfigStorage = wxMpConfigStorage();
            }
        }
    }
    if (wxMpService == null && wxMpConfigStorage != null) {
        synchronized (WxMpTemplateMsgSender.class) {
            if (wxMpService == null && wxMpConfigStorage != null) {
                wxMpService = new WeWxMpServiceImpl();
                wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
            }
        }
    }
    return wxMpService;
}
 
Example #7
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 #8
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 #9
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 #10
Source File: WxMpConfiguration.java    From black-shop with Apache License 2.0 6 votes vote down vote up
@Bean
public Object services() {
  // 代码里getConfigs()处报错的同学,请注意仔细阅读项目说明,你的IDE需要引入lombok插件!!!!
  final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs();
  if (configs == null) {
    throw new RuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
  }

  mpServices = configs.stream().map(a -> {
    WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
    configStorage.setAppId(a.getAppId());
    configStorage.setSecret(a.getSecret());
    configStorage.setToken(a.getToken());
    configStorage.setAesKey(a.getAesKey());

    WxMpService service = new WxMpServiceImpl();
    service.setWxMpConfigStorage(configStorage);
    routers.put(a.getAppId(), this.newRouter(service));
    return service;
  }).collect(Collectors.toMap(s -> s.getWxMpConfigStorage().getAppId(), a -> a, (o, n) -> o));

  return Boolean.TRUE;
}
 
Example #11
Source File: WxMpServiceOkHttpImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
  this.log.debug("WxMpServiceOkHttpImpl is running");
  Lock lock = this.getWxMpConfigStorage().getAccessTokenLock();
  try {
    lock.lock();

    if (this.getWxMpConfigStorage().isAccessTokenExpired() || forceRefresh) {
      String url = String.format(WxMpService.GET_ACCESS_TOKEN_URL,
        this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret());

      Request request = new Request.Builder().url(url).get().build();
      Response response = getRequestHttpClient().newCall(request).execute();
      String resultContent = response.body().string();
      WxError error = WxError.fromJson(resultContent, WxType.MP);
      if (error.getErrorCode() != 0) {
        throw new WxErrorException(error);
      }
      WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
      this.getWxMpConfigStorage().updateAccessToken(accessToken.getAccessToken(),
        accessToken.getExpiresIn());
    }
  } catch (IOException e) {
    this.log.error(e.getMessage(), e);
  } finally {
    lock.unlock();
  }
  return this.getWxMpConfigStorage().getAccessToken();
}
 
Example #12
Source File: WxMpServiceHttpClientImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
  Lock lock = this.getWxMpConfigStorage().getAccessTokenLock();
  try {
    lock.lock();
    if (this.getWxMpConfigStorage().isAccessTokenExpired() || forceRefresh) {
      String url = String.format(WxMpService.GET_ACCESS_TOKEN_URL,
        this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret());
      try {
        HttpGet httpGet = new HttpGet(url);
        if (this.getRequestHttpProxy() != null) {
          RequestConfig config = RequestConfig.custom().setProxy(this.getRequestHttpProxy()).build();
          httpGet.setConfig(config);
        }
        try (CloseableHttpResponse response = getRequestHttpClient().execute(httpGet)) {
          String resultContent = new BasicResponseHandler().handleResponse(response);
          WxError error = WxError.fromJson(resultContent, WxType.MP);
          if (error.getErrorCode() != 0) {
            throw new WxErrorException(error);
          }
          WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
          this.getWxMpConfigStorage().updateAccessToken(accessToken.getAccessToken(),
            accessToken.getExpiresIn());
        } finally {
          httpGet.releaseConnection();
        }
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  } finally {
    lock.unlock();
  }
  return this.getWxMpConfigStorage().getAccessToken();
}
 
Example #13
Source File: WxMpServiceJoddHttpImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
  Lock lock = this.getWxMpConfigStorage().getAccessTokenLock();
  try {
    lock.lock();

    if (this.getWxMpConfigStorage().isAccessTokenExpired() || forceRefresh) {
      String url = String.format(WxMpService.GET_ACCESS_TOKEN_URL,
        this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret());

      HttpRequest request = HttpRequest.get(url);

      if (this.getRequestHttpProxy() != null) {
        SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider();
        provider.useProxy(getRequestHttpProxy());

        request.withConnectionProvider(provider);
      }
      HttpResponse response = request.send();
      String resultContent = response.bodyText();
      WxError error = WxError.fromJson(resultContent, WxType.MP);
      if (error.getErrorCode() != 0) {
        throw new WxErrorException(error);
      }
      WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
      this.getWxMpConfigStorage().updateAccessToken(accessToken.getAccessToken(),
        accessToken.getExpiresIn());
    }
  } finally {
    lock.unlock();
  }
  return this.getWxMpConfigStorage().getAccessToken();
}
 
Example #14
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 #15
Source File: MsgHandler.java    From yshopmall 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();
    }

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

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

}
 
Example #16
Source File: WxOpenComponentServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpService getWxMpServiceByAppid(String appId) {
  WxMpService wxMpService = WX_OPEN_MP_SERVICE_MAP.get(appId);
  if (wxMpService == null) {
    synchronized (WX_OPEN_MP_SERVICE_MAP) {
      wxMpService = WX_OPEN_MP_SERVICE_MAP.get(appId);
      if (wxMpService == null) {
        wxMpService = new WxOpenMpServiceImpl(this, appId, getWxOpenConfigStorage().getWxMpConfigStorage(appId));

        WX_OPEN_MP_SERVICE_MAP.put(appId, wxMpService);
      }
    }
  }
  return wxMpService;
}
 
Example #17
Source File: WechatMenuController.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "创建菜单")
@PostMapping(value = "/YxWechatMenu")
@PreAuthorize("@el.check('admin','YxWechatMenu_ALL','YxWechatMenu_CREATE')")
public ResponseEntity create( @RequestBody String jsonStr){

    JSONObject jsonObject = JSON.parseObject(jsonStr);
    String jsonButton = jsonObject.get("buttons").toString();
    YxWechatMenu YxWechatMenu = new YxWechatMenu();
    Boolean isExist = YxWechatMenuService.isExist("wechat_menus");
    WxMenu menu = JSONObject.parseObject(jsonStr,WxMenu.class);

    WxMpService wxService = WxMpConfiguration.getWxMpService();
    if(isExist){
        YxWechatMenu.setKey("wechat_menus");
        YxWechatMenu.setResult(jsonButton);
        YxWechatMenuService.saveOrUpdate(YxWechatMenu);
    }else {
        YxWechatMenu.setKey("wechat_menus");
        YxWechatMenu.setResult(jsonButton);
        YxWechatMenu.setAddTime(OrderUtil.getSecondTimestampTwo());
        YxWechatMenuService.save(YxWechatMenu);
    }


    //创建菜单
    try {
        wxService.getMenuService().menuDelete();
        wxService.getMenuService().menuCreate(menu);
    } catch (WxErrorException e) {
        throw new BadRequestException(e.getMessage());
       // e.printStackTrace();
    }

    return new ResponseEntity(HttpStatus.OK);
}
 
Example #18
Source File: MenuHandler.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 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 #19
Source File: MsgHandler.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 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 #20
Source File: WxRedirectController.java    From black-shop with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/greet")
public String greetUser(@PathVariable String appid, @RequestParam String code, ModelMap map) {

	WxMpService mpService = WxMpConfiguration.getMpServices().get(appid);

	try {
		WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
		WxMpUser user = mpService.oauth2getUserInfo(accessToken, null);
		map.put("user", user);
	} catch (WxErrorException e) {
		e.printStackTrace();
	}

	return "greet_user";
}
 
Example #21
Source File: WeixinServiceImpl.java    From jframe with Apache License 2.0 5 votes vote down vote up
private WxMpService createMpService(String id) {
    WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
    config.setAppId(_conf.getConf(id, WxPropsConf.P_appId));
    config.setSecret(_conf.getConf(id, WxPropsConf.P_secret));
    // config.setSSLContext(context);

    WxMpService mp = new WxMpServiceImpl();
    mp.setWxMpConfigStorage(config);
    return mp;
}
 
Example #22
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 #23
Source File: DemoTextHandler.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) {
  WxMpXmlOutTextMessage m
      = WxMpXmlOutMessage.TEXT().content("测试加密消息").fromUser(wxMessage.getToUserName())
      .toUser(wxMessage.getFromUserName()).build();
  return m;
}
 
Example #24
Source File: UnsubscribeHandler.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) {
    String openId = wxMessage.getFromUser();
    this.logger.info("取消关注用户 OPENID: " + openId);
    // TODO 可以更新本地数据库为取消关注状态
    return null;
}
 
Example #25
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 #26
Source File: WeixinServiceImpl.java    From jframe with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpService getWxMpService(String id) {
    WxMpService wx = mpMap.get(id);
    if (wx == null) {
        mpMap.putIfAbsent(id, createMpService(id));
        wx = mpMap.get(id);
    }
    return wx;
}
 
Example #27
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 #28
Source File: WechatAuthenticationConfigurer.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
public WechatAuthenticationConfigurer(WxMpService wxMpService, UserDetailsService userDetailsService,
                                      AuthenticationFailureHandler authenticationFailureHandler,
                                      AuthenticationSuccessHandler authenticationSuccessHandler) {
    this.wxMpService = wxMpService;
    this.userDetailsService = userDetailsService;
    this.authenticationFailureHandler = authenticationFailureHandler;
    this.authenticationSuccessHandler = authenticationSuccessHandler;
}
 
Example #29
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 #30
Source File: LogHandler.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) {
    this.logger.info("\n接收到请求消息,内容:{}", JsonUtils.toJson(wxMessage));
    return null;
}