Java Code Examples for me.chanjar.weixin.common.error.WxErrorException#printStackTrace()

The following examples show how to use me.chanjar.weixin.common.error.WxErrorException#printStackTrace() . 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: 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 2
Source File: TemplateUtil.java    From WePush with MIT License 6 votes vote down vote up
public static String evaluate(String content, VelocityContext velocityContext) {

        if (content.contains("NICK_NAME")) {
            WxMpService wxMpService = WxMpTemplateMsgSender.getWxMpService();
            String nickName = "";
            try {
                nickName = wxMpService.getUserService().userInfo(velocityContext.get(PushControl.TEMPLATE_VAR_PREFIX + "0").toString()).getNickname();
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
            velocityContext.put("NICK_NAME", nickName);
        }

        velocityContext.put("ENTER", "\n");

        StringWriter writer = new StringWriter();
        velocityEngine.evaluate(velocityContext, writer, "", content);

        return writer.toString();
    }
 
Example 3
Source File: MemberListener.java    From WePush with MIT License 6 votes vote down vote up
/**
 * 导入微信全员
 */
public static void importWxAll() {
    JPanel memberPanel = MemberForm.getInstance().getMemberPanel();
    JProgressBar progressBar = MemberForm.getInstance().getMemberTabImportProgressBar();
    MemberForm.getInstance().getMemberImportAllButton().setEnabled(false);

    try {
        getMpUserList();
        renderMemberListTable();
        if (!PushData.fixRateScheduling) {
            JOptionPane.showMessageDialog(memberPanel, "导入完成!", "完成", JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (WxErrorException e1) {
        JOptionPane.showMessageDialog(memberPanel, "导入失败!\n\n" + e1.getMessage(), "失败",
                JOptionPane.ERROR_MESSAGE);
        logger.error(e1);
        e1.printStackTrace();
    } finally {
        progressBar.setIndeterminate(false);
        progressBar.setVisible(false);
        MemberForm.getInstance().getMemberImportAllButton().setEnabled(true);
    }
}
 
Example 4
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 5
Source File: WxMessageController.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/sendCurrency/{wechatId}")
public HttpResult sendWeixinCurrencyTemplateMessage(@PathVariable("wechatId") String wechatId,
		@RequestParam("message") String message) {
	if (StringHelper.isBlank(message)) return new HttpResult().failure("发送消息内容不能为空");

	WechatInfo wechatInfo = wechatInfoService.findByWechatId(wechatId);
	if (null == wechatInfo)
		return new HttpResult().failure("公众号wechatId[" + wechatId + "]不存在");

	log.info("公众号消息发送:|wechatId[{}]|reqKey[{}]|message[{}]", wechatId, wechatInfo.getReqKey(), message);
	String decryptMessage = Crypt.getInstance().decrypt(message, wechatInfo.getReqKey());
	if (StringHelper.isBlank(decryptMessage)) return new HttpResult().failure("发送消息内容签名不正确");

	MsgBean msgBean = JSONObject.parseObject(decryptMessage, MsgBean.class);
	if (null == msgBean) return new HttpResult().failure("发送消息内容转换失败");
	try {
		boolean isOk = messageService.sendWeixinCurrencyTemplateMessage(msgBean);
		if (isOk) return new HttpResult().success("SUCCESS");
	} catch (WxErrorException e) {
		e.printStackTrace();
		return new HttpResult().failure("发送消息失败[" + e.getMessage() + "]");
	}

	return new HttpResult().failure("消息发送失败!");
}
 
Example 6
Source File: WxJsdkController.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
@RequestMapping(value = "/wechatParam")
@ResponseBody
public HttpResult wechatParam(@RequestParam("url") String url) {
	long start = System.currentTimeMillis();
	if (StringHelper.isBlank(url)) return new HttpResult().failure("url 参数验证失败!");

	String jsdkUrl = WebUtils.buildURLDecoder(url);
	try {
		WxJsapiSignature jsapi = wxService.createJsapiSignature(WebUtils
				.buildURLDecoder(jsdkUrl));
		log.info("[微信jsdk],请求{},获取耗时{}", jsdkUrl, (System.currentTimeMillis() - start));
		return new HttpResult().data(jsapi).success();
	} catch (WxErrorException e) {
		e.printStackTrace();
	}

	return new HttpResult().failure("获取微信签名数据失败!");
}
 
Example 7
Source File: WxMaDemoServer.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(WxMaMessage wxMessage, Map<String, Object> context,
                   WxMaService service, WxSessionManager sessionManager) throws WxErrorException {
  try {
    final File file = service.getQrcodeService().createQrcode("123", 430);
    WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia(WxMaConstants.MediaType.IMAGE, file);
    service.getMsgService().sendKefuMsg(
      WxMaKefuMessage
        .newImageBuilder()
        .mediaId(uploadResult.getMediaId())
        .toUser(wxMessage.getFromUser())
        .build());
  } catch (WxErrorException e) {
    e.printStackTrace();
  }
}
 
Example 8
Source File: WxMaDemoServer.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(WxMaMessage wxMessage, Map<String, Object> context,
                   WxMaService service, WxSessionManager sessionManager) throws WxErrorException {
  try {
    WxMediaUploadResult uploadResult = service.getMediaService()
      .uploadMedia(WxMaConstants.MediaType.IMAGE, "png",
        ClassLoader.getSystemResourceAsStream("tmp.png"));
    service.getMsgService().sendKefuMsg(
      WxMaKefuMessage
        .newImageBuilder()
        .mediaId(uploadResult.getMediaId())
        .toUser(wxMessage.getFromUser())
        .build());
  } catch (WxErrorException e) {
    e.printStackTrace();
  }
}
 
Example 9
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 10
Source File: WxCpOAuth2Servlet.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
  throws IOException {

  response.setContentType("text/html;charset=utf-8");
  response.setStatus(HttpServletResponse.SC_OK);

  String code = request.getParameter("code");
  try {
    response.getWriter().println("<h1>code</h1>");
    response.getWriter().println(code);

    String[] res = this.wxCpService.getOauth2Service().getUserInfo(code);
    response.getWriter().println("<h1>result</h1>");
    response.getWriter().println(Arrays.toString(res));
  } catch (WxErrorException e) {
    e.printStackTrace();
  }

  response.getWriter().flush();
  response.getWriter().close();

}
 
Example 11
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 12
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 13
Source File: WxMaterialController.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
@RequestMapping(value = "getFile", method = RequestMethod.GET)
public R<WxMpMaterialFileBatchGetResult> getFile(HttpServletRequest request,
		HttpServletResponse response) {
	try {
		WxMpMaterialFileBatchGetResult newsResult = wxService.getMaterialService()
				.materialFileBatchGet("image", 0, 20);
		return new R<WxMpMaterialFileBatchGetResult>().data(newsResult).success();
	} catch (WxErrorException e) {
		e.printStackTrace();
	}
	return new R<WxMpMaterialFileBatchGetResult>().failure();
}
 
Example 14
Source File: WxMessageController.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
@ResponseBody
@Deprecated
@RequestMapping(value = "/send/{wechatId}")
public HttpResult sendWeixinTemplateMessage(@PathVariable("wechatId") String wechatId,
		@RequestParam("message") String message) {
	if (StringHelper.isBlank(message)) return new HttpResult().failure("发送消息内容不能为空");

	WechatInfo wechatInfo = wechatInfoService.findByWechatId(wechatId);
	if (null == wechatInfo)
		return new HttpResult().failure("公众号wechatId[" + wechatId + "]不存在");

	log.info(
			"公众号消息发送:|wechatId[{}]|reqKey[{}]|message[{}]", wechatId, wechatInfo.getReqKey(),
			message);
	String decryptMessage = Crypt.getInstance().decrypt(message, wechatInfo.getReqKey());
	if (StringHelper.isBlank(decryptMessage)) return new HttpResult().failure("发送消息内容签名不正确");

	MsgBean msgBean = JSONObject.parseObject(decryptMessage, MsgBean.class);
	if (null == msgBean) return new HttpResult().failure("发送消息内容转换失败");

	WxTemplateEnum wxTemplateEnum = WxTemplateEnum.of(msgBean.getTemplateId());
	try {
		boolean isOk = messageService.sendWeixinTemplateMessage(wxTemplateEnum, msgBean);
		if (isOk) return new HttpResult().success("SUCCESS");
	} catch (WxErrorException e) {
		e.printStackTrace();
		return new HttpResult().failure("发送消息失败[" + e.getMessage() + "]");
	}

	return new HttpResult().failure("消息发送失败!");
}
 
Example 15
Source File: WxMpOAuth2Servlet.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
  throws IOException {

  response.setContentType("text/html;charset=utf-8");
  response.setStatus(HttpServletResponse.SC_OK);

  String code = request.getParameter("code");
  try {
    response.getWriter().println("<h1>code</h1>");
    response.getWriter().println(code);

    WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxMpService.oauth2getAccessToken(code);
    response.getWriter().println("<h1>access token</h1>");
    response.getWriter().println(wxMpOAuth2AccessToken.toString());

    WxMpUser wxMpUser = this.wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
    response.getWriter().println("<h1>user info</h1>");
    response.getWriter().println(wxMpUser.toString());

    wxMpOAuth2AccessToken = this.wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
    response.getWriter().println("<h1>after refresh</h1>");
    response.getWriter().println(wxMpOAuth2AccessToken.toString());

  } catch (WxErrorException e) {
    e.printStackTrace();
  }

  response.getWriter().flush();
  response.getWriter().close();

}
 
Example 16
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 17
Source File: WechatRabbitListener.java    From fw-cloud-framework with MIT License 4 votes vote down vote up
@RabbitHandler
public void receive(WechatNotifyBean wechatNotifyBean) {
	long start = System.currentTimeMillis();
	log.info("【wxauth.wechatRabbit】:exec receive start|" + start);
	WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wechatNotifyBean.getWxMpOAuth2AccessToken();
	if (null == wxMpOAuth2AccessToken || StringHelper.isBlank(wechatNotifyBean.getWechatId())
			|| StringHelper.isBlank(wxMpOAuth2AccessToken.getOpenId())) return;
	log.info("【wxauth.wechatRabbit】:exec start");
	try {
		WxMpUser wxMpUser = null;
		String openId = wxMpOAuth2AccessToken.getOpenId();
		AuthInfo authInfo = authInfoService.findByOpenIdAndWechatId(openId, wechatNotifyBean
				.getWechatId());
		if (null == authInfo // 大于2小时
				|| System.currentTimeMillis() - authInfo.getUpdateTime().getTime() > 7200000) {
			boolean isSopeBase = wechatNotifyBean.isSopeBase();
			if (isSopeBase) {
				log.info("【wxauth.openId】静默登录");
				wxMpUser = wxService.getUserService().userInfo(openId);
			} else {
				// refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权。
				String refreshToken = wxMpOAuth2AccessToken.getRefreshToken();
				wxMpOAuth2AccessToken = wxService.oauth2refreshAccessToken(refreshToken);
				log.info("【wxauth.openId】主动登录");
				// 拉取用户信息(需scope为 snsapi_userinfo)
				wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
			}

			if (null != wxMpUser) {
				if (null == authInfo) authInfo = new AuthInfo();
				authInfo.setOpenId(openId);
				authInfo.setWechatId(wechatNotifyBean.getWechatId());
				authInfo.setNickName(WebUtils.buildURLEncoder(EmojiUtils.toHtml(wxMpUser
						.getNickname())));
				authInfo.setHeadImgUrl(wxMpUser.getHeadImgUrl());
				authInfo.setCity(wxMpUser.getCity());
				authInfo.setProvince(wxMpUser.getProvince());
				authInfo.setLanguage(wxMpUser.getLanguage());
				authInfo.setRemark(wxMpUser.getRemark());
				authInfo.setSexDesc(wxMpUser.getSexDesc());
				authInfo.setSex(wxMpUser.getSex());
				authInfo.setCountry(wxMpUser.getCountry());
				authInfo.setRefreshToken(wxMpOAuth2AccessToken.getRefreshToken());
				if (null == authInfo.getCreateTime()) authInfo.setCreateTime(new Date());
				authInfo.setUpdateTime(new Date());
				authInfoService.saveOrUpdate(authInfo);
			}
		}
		log.info("【wxauth.wechatRabbit】:openId|" + openId);
	} catch (WxErrorException ex) {
		ex.printStackTrace();
		log.info("【wxauth.wechatRabbit】exception:" + ex.getError().getErrorMsg());
	}
	log.info("【wxauth.wechatRabbit】:exec finished 耗时:" + (System.currentTimeMillis() - start));
}