me.chanjar.weixin.common.error.WxErrorException Java Examples
The following examples show how to use
me.chanjar.weixin.common.error.WxErrorException.
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: ApacheMediaUploadRequestExecutor.java From weixin-java-tools with Apache License 2.0 | 6 votes |
@Override public WxMediaUploadResult execute(String uri, File file) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpPost.setConfig(config); } if (file != null) { HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", file) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); } try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaUploadResult.fromJson(responseContent); } finally { httpPost.releaseConnection(); } }
Example #2
Source File: WxCpUserServiceImpl.java From weixin-java-tools with Apache License 2.0 | 6 votes |
@Override public List<WxCpUser> listSimpleByDepartment(Integer departId, Boolean fetchChild, Integer status) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?department_id=" + departId; String params = ""; if (fetchChild != null) { params += "&fetch_child=" + (fetchChild ? "1" : "0"); } if (status != null) { params += "&status=" + status; } else { params += "&status=0"; } String responseContent = this.mainService.get(url, params); JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("userlist"), new TypeToken<List<WxCpUser>>() { }.getType() ); }
Example #3
Source File: BaseWxMpServiceImpl.java From weixin-java-tools with Apache License 2.0 | 6 votes |
@Override public WxMpUser oauth2getUserInfo(WxMpOAuth2AccessToken token, String lang) throws WxErrorException { if (lang == null) { lang = "zh_CN"; } String url = String.format(WxMpService.OAUTH2_USERINFO_URL, token.getAccessToken(), token.getOpenId(), lang); try { RequestExecutor<String, String> executor = SimpleGetRequestExecutor.create(this); String responseText = executor.execute(url, null); return WxMpUser.fromJson(responseText); } catch (IOException e) { throw new RuntimeException(e); } }
Example #4
Source File: TemplateUtil.java From WePush with MIT License | 6 votes |
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 #5
Source File: WxMpUserTagServiceImpl.java From weixin-java-tools with Apache License 2.0 | 6 votes |
@Override public Boolean tagDelete(Long id) throws WxErrorException { String url = API_URL_PREFIX + "/delete"; JsonObject json = new JsonObject(); JsonObject tagJson = new JsonObject(); tagJson.addProperty("id", id); json.add("tag", tagJson); String responseContent = this.wxMpService.post(url, json.toString()); WxError wxError = WxError.fromJson(responseContent, WxType.MP); if (wxError.getErrorCode() == 0) { return true; } throw new WxErrorException(wxError); }
Example #6
Source File: WxMpStoreServiceImpl.java From weixin-java-tools with Apache License 2.0 | 6 votes |
@Override public List<WxMpStoreInfo> listAll() throws WxErrorException { int limit = 50; WxMpStoreListResult list = this.list(0, limit); List<WxMpStoreInfo> stores = list.getBusinessList(); if (list.getTotalCount() > limit) { int begin = limit; WxMpStoreListResult followingList = this.list(begin, limit); while (followingList.getBusinessList().size() > 0) { stores.addAll(followingList.getBusinessList()); begin += limit; if (begin >= list.getTotalCount()) { break; } followingList = this.list(begin, limit); } } return stores; }
Example #7
Source File: WxOpenComponentServiceImpl.java From weixin-java-tools with Apache License 2.0 | 6 votes |
@Override public WxOpenQueryAuthResult getQueryAuth(String authorizationCode) throws WxErrorException { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("component_appid", getWxOpenConfigStorage().getComponentAppId()); jsonObject.addProperty("authorization_code", authorizationCode); String responseContent = post(API_QUERY_AUTH_URL, jsonObject.toString()); WxOpenQueryAuthResult queryAuth = WxOpenGsonBuilder.create().fromJson(responseContent, WxOpenQueryAuthResult.class); if (queryAuth == null || queryAuth.getAuthorizationInfo() == null) { return queryAuth; } WxOpenAuthorizationInfo authorizationInfo = queryAuth.getAuthorizationInfo(); if (authorizationInfo.getAuthorizerAccessToken() != null) { getWxOpenConfigStorage().updateAuthorizerAccessToken(authorizationInfo.getAuthorizerAppid(), authorizationInfo.getAuthorizerAccessToken(), authorizationInfo.getExpiresIn()); } if (authorizationInfo.getAuthorizerRefreshToken() != null) { getWxOpenConfigStorage().setAuthorizerRefreshToken(authorizationInfo.getAuthorizerAppid(), authorizationInfo.getAuthorizerRefreshToken()); } return queryAuth; }
Example #8
Source File: WxMpCardServiceImpl.java From weixin-java-tools with Apache License 2.0 | 6 votes |
@Override public String getCardDetail(String cardId) throws WxErrorException { JsonObject param = new JsonObject(); param.addProperty("card_id", cardId); String responseContent = this.wxMpService.post(CARD_GET, param.toString()); // 判断返回值 JsonObject json = (new JsonParser()).parse(responseContent).getAsJsonObject(); String errcode = json.get("errcode").getAsString(); if (!"0".equals(errcode)) { String errmsg = json.get("errmsg").getAsString(); throw new WxErrorException(WxError.builder() .errorCode(Integer.valueOf(errcode)).errorMsg(errmsg) .build()); } return responseContent; }
Example #9
Source File: DemoImageHandler.java From weixin-java-tools with Apache License 2.0 | 6 votes |
@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: MaterialVoiceAndImageDownloadJoddHttpRequestExecutor.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public InputStream execute(String uri, String materialId) throws WxErrorException, IOException { HttpRequest request = HttpRequest.post(uri); if (requestHttp.getRequestHttpProxy() != null) { requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); } request.withConnectionProvider(requestHttp.getRequestHttpClient()); request.query("media_id", materialId); HttpResponse response = request.send(); response.charset(StringPool.UTF_8); try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) { // 下载媒体文件出错 byte[] responseContent = IOUtils.toByteArray(inputStream); String responseContentString = new String(responseContent, StandardCharsets.UTF_8); if (responseContentString.length() < 100) { try { WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class); if (wxError.getErrorCode() != 0) { throw new WxErrorException(wxError); } } catch (com.google.gson.JsonSyntaxException ex) { return new ByteArrayInputStream(responseContent); } } return new ByteArrayInputStream(responseContent); } }
Example #11
Source File: WxMessageController.java From fw-cloud-framework with MIT License | 5 votes |
@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 #12
Source File: WxCpMessageRouterRule.java From weixin-java-tools with Apache License 2.0 | 5 votes |
/** * 处理微信推送过来的消息 * * @param wxMessage * @return true 代表继续执行别的router,false 代表停止执行别的router */ protected WxCpXmlOutMessage service(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService wxCpService, WxSessionManager sessionManager, WxErrorExceptionHandler exceptionHandler) { if (context == null) { context = new HashMap<>(); } try { // 如果拦截器不通过 for (WxCpMessageInterceptor interceptor : this.interceptors) { if (!interceptor.intercept(wxMessage, context, wxCpService, sessionManager)) { return null; } } // 交给handler处理 WxCpXmlOutMessage res = null; for (WxCpMessageHandler handler : this.handlers) { // 返回最后handler的结果 res = handler.handle(wxMessage, context, wxCpService, sessionManager); } return res; } catch (WxErrorException e) { exceptionHandler.handle(e); } return null; }
Example #13
Source File: BaseWxMpServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public String[] getCallbackIP() throws WxErrorException { String responseContent = this.get(WxMpService.GET_CALLBACK_IP_URL, null); JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); JsonArray ipList = tmpJsonElement.getAsJsonObject().get("ip_list").getAsJsonArray(); String[] ipArray = new String[ipList.size()]; for (int i = 0; i < ipList.size(); i++) { ipArray[i] = ipList.get(i).getAsString(); } return ipArray; }
Example #14
Source File: WxMpMaterialServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public File mediaDownload(String mediaId) throws WxErrorException { return this.wxMpService.execute( BaseMediaDownloadRequestExecutor.create(this.wxMpService.getRequestHttp(), this.wxMpService.getWxMpConfigStorage().getTmpDirFile()), MEDIA_GET_URL, "media_id=" + mediaId); }
Example #15
Source File: WxMpUserServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public WxMpUserList userList(String next_openid) throws WxErrorException { String url = API_URL_PREFIX + "/get"; String responseContent = this.wxMpService.get(url, next_openid == null ? null : "next_openid=" + next_openid); return WxMpUserList.fromJson(responseContent); }
Example #16
Source File: WxMpAiOpenServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public String queryRecognitionResult(String voiceId, AiLangType lang) throws WxErrorException { if (lang == null) { lang = AiLangType.zh_CN; } final String responseContent = this.wxMpService.get(VOICE_QUERY_RESULT_URL, String.format("voice_id=%s&lang=%s", voiceId, lang.getCode())); final JsonObject jsonObject = JSON_PARSER.parse(responseContent).getAsJsonObject(); if (jsonObject.get("errcode") == null || jsonObject.get("errcode").getAsInt() == 0) { return jsonObject.get("result").getAsString(); } throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP)); }
Example #17
Source File: WxMpAiOpenServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public void uploadVoice(String voiceId, AiLangType lang, File voiceFile) throws WxErrorException { if (lang == null) { lang = AiLangType.zh_CN; } this.wxMpService.execute(VoiceUploadRequestExecutor.create(this.wxMpService.getRequestHttp()), String.format(VOICE_UPLOAD_URL, "mp3", voiceId, lang.getCode()), voiceFile); }
Example #18
Source File: WxMaDemoServer.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public void handle(WxMaMessage wxMessage, Map<String, Object> context, WxMaService service, WxSessionManager sessionManager) throws WxErrorException { System.out.println("收到消息:" + wxMessage.toString()); service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson()) .toUser(wxMessage.getFromUser()).build()); }
Example #19
Source File: BeanUtils.java From weixin-java-tools with Apache License 2.0 | 5 votes |
/** * 检查bean里标记为@Required的field是否为空,为空则抛异常 * * @param bean 要检查的bean对象 */ public static void checkRequiredFields(Object bean) throws WxErrorException { List<String> requiredFields = Lists.newArrayList(); List<Field> fields = new ArrayList<>(Arrays.asList(bean.getClass().getDeclaredFields())); fields.addAll(Arrays.asList(bean.getClass().getSuperclass().getDeclaredFields())); for (Field field : fields) { try { boolean isAccessible = field.isAccessible(); field.setAccessible(true); if (field.isAnnotationPresent(Required.class)) { // 两种情况,一种是值为null, // 另外一种情况是类型为字符串,但是字符串内容为空的,都认为是没有提供值 boolean isRequiredMissing = field.get(bean) == null || (field.get(bean) instanceof String && StringUtils.isBlank(field.get(bean).toString()) ); if (isRequiredMissing) { requiredFields.add(field.getName()); } } field.setAccessible(isAccessible); } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { log.error(e.getMessage(), e); } } if (!requiredFields.isEmpty()) { String msg = "必填字段 " + requiredFields + " 必须提供值"; log.debug(msg); throw new WxErrorException(WxError.builder().errorMsg(msg).build()); } }
Example #20
Source File: WxMpUserServiceImplTest.java From weixin-java-tools with Apache License 2.0 | 5 votes |
public void testUserList() throws WxErrorException { WxMpUserList wxMpUserList = this.wxService.getUserService().userList(null); Assert.assertNotNull(wxMpUserList); Assert.assertFalse(wxMpUserList.getCount() == -1); Assert.assertFalse(wxMpUserList.getTotal() == -1); Assert.assertFalse(wxMpUserList.getOpenids().size() == -1); System.out.println(wxMpUserList); }
Example #21
Source File: WxMpMenuServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public WxMpMenu menuGet() throws WxErrorException { String url = API_URL_PREFIX + "/get"; try { String resultContent = this.wxMpService.get(url, null); return WxMpMenu.fromJson(resultContent); } catch (WxErrorException e) { // 46003 不存在的菜单数据 if (e.getError().getErrorCode() == 46003) { return null; } throw e; } }
Example #22
Source File: WxMpShakeServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public WxMpShakeAroundPageAddResult pageAdd(WxMpShakeAroundPageAddQuery shakeAroundPageAddQuery) throws WxErrorException { String url = "https://api.weixin.qq.com/shakearound/page/add"; String postData = shakeAroundPageAddQuery.toJsonString(); String responseContent = this.wxMpService.post(url, postData); return WxMpShakeAroundPageAddResult.fromJson(responseContent); }
Example #23
Source File: WxCpTagServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public WxCpTagAddOrRemoveUsersResult addUsers2Tag(String tagId, List<String> userIds, List<String> partyIds) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("tagid", tagId); this.addUserIdsAndPartyIdsToJson(userIds, partyIds, jsonObject); return WxCpTagAddOrRemoveUsersResult.fromJson(this.mainService.post(url, jsonObject.toString())); }
Example #24
Source File: WxMpDeviceServiceImplTest.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Test(dataProvider = "productId") public void testGetQrcode(String productId) { try { WxDeviceQrCodeResult result = wxService.getDeviceService().getQrCode(productId); println(result.toJson()); } catch (WxErrorException e) { println(e.getMessage()); } }
Example #25
Source File: WxMpMaterialServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public WxMpMaterialUploadResult materialNewsUpload(WxMpMaterialNews news) throws WxErrorException { if (news == null || news.isEmpty()) { throw new IllegalArgumentException("news is empty!"); } String responseContent = this.wxMpService.post(NEWS_ADD_URL, news.toJson()); return WxMpMaterialUploadResult.fromJson(responseContent); }
Example #26
Source File: MediaImgUploadApacheHttpRequestExecutor.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public WxMediaImgUploadResult execute(String uri, File data) throws WxErrorException, IOException { if (data == null) { throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("文件对象为空").build()); } HttpPost httpPost = new HttpPost(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpPost.setConfig(config); } HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", data) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent, WxType.MP); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaImgUploadResult.fromJson(responseContent); } finally { httpPost.releaseConnection(); } }
Example #27
Source File: WxMpQrcodeServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public WxMpQrCodeTicket qrCodeCreateLastTicket(String sceneStr) throws WxErrorException { String url = API_URL_PREFIX + "/create"; JsonObject json = new JsonObject(); json.addProperty("action_name", "QR_LIMIT_STR_SCENE"); JsonObject actionInfo = new JsonObject(); JsonObject scene = new JsonObject(); scene.addProperty("scene_str", sceneStr); actionInfo.add("scene", scene); json.add("action_info", actionInfo); String responseContent = this.wxMpService.post(url, json.toString()); return WxMpQrCodeTicket.fromJson(responseContent); }
Example #28
Source File: WxMpQrcodeServiceImplTest.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Test(dataProvider = "sceneIds") public void testQrCodeCreateTmpTicket(int sceneId) throws WxErrorException { WxMpQrCodeTicket ticket = this.wxService.getQrcodeService().qrCodeCreateTmpTicket(sceneId, null); Assert.assertNotNull(ticket.getUrl()); Assert.assertNotNull(ticket.getTicket()); Assert.assertTrue(ticket.getExpireSeconds() != -1); System.out.println(ticket); }
Example #29
Source File: ApacheMediaDownloadRequestExecutor.java From weixin-java-tools with Apache License 2.0 | 5 votes |
@Override public File execute(String uri, String queryParam) throws WxErrorException, IOException { if (queryParam != null) { if (uri.indexOf('?') == -1) { uri += '?'; } uri += uri.endsWith("?") ? queryParam : '&' + queryParam; } HttpGet httpGet = new HttpGet(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpGet.setConfig(config); } try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet); InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response)) { Header[] contentTypeHeader = response.getHeaders("Content-Type"); if (contentTypeHeader != null && contentTypeHeader.length > 0) { if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) { // application/json; encoding=utf-8 下载媒体文件出错 String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); throw new WxErrorException(WxError.fromJson(responseContent)); } } String fileName = new HttpResponseProxy(response).getFileName(); if (StringUtils.isBlank(fileName)) { return null; } return FileUtils.createTmpFile(inputStream, FilenameUtils.getBaseName(fileName), FilenameUtils.getExtension(fileName), super.tmpDirFile); } finally { httpGet.releaseConnection(); } }
Example #30
Source File: WxMpMemberCardServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
/** * 拉取会员信息接口 * * @param cardId 会员卡的CardId,微信分配 * @param code 领取会员的会员卡Code * @return 会员信息的结果对象 * @throws WxErrorException 接口调用失败抛出的异常 */ @Override public WxMpMemberCardUserInfoResult getUserInfo(String cardId, String code) throws WxErrorException { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("card_id", cardId); jsonObject.addProperty("code",code); String responseContent = this.getWxMpService().post(MEMBER_CARD_USER_INFO_GET, jsonObject.toString()); JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement, new TypeToken<WxMpMemberCardUserInfoResult>() { }.getType()); }