diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..50339b8e --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +# EditorConfig: http://editorconfig.org/ + +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false diff --git a/README.md b/README.md index 93da5c67..aba634dd 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ ### 注意: 1. ***本项目Fork自chanjarster/weixin-java-tools,但由于原项目已停止维护,故单独维护和发布,且发布到maven上的groupId也会不同,详细信息见下文。*** 1. ***自2.0.0版本以来,主要是公众号的接口调整比较大,主要是为了解决主接口类过于庞大不方便管理的问题,将接口实现代码按模块进行拆分。*** -1. 最新更新:2016-08-31 发布2.1.0正式版! +1. 最新更新:2016-09-30 发布2.2.0正式版! =========== @@ -33,12 +33,12 @@ maven: com.github.binarywang weixin-java-mp - 2.1.0 + 2.2.0 ``` gradle: ```groovy -compile 'com.github.binarywang:weixin-java-mp:2.1.0' +compile 'com.github.binarywang:weixin-java-mp:2.2.0' ``` * 企业号: @@ -48,12 +48,12 @@ maven: com.github.binarywang weixin-java-cp - 2.1.0 + 2.2.0 ``` gradle: ```groovy -compile 'com.github.binarywang:weixin-java-cp:2.1.0' +compile 'com.github.binarywang:weixin-java-cp:2.2.0' ``` #### 本项目主要存放在github上,地址为 : @@ -74,4 +74,4 @@ compile 'com.github.binarywang:weixin-java-cp:2.1.0' * 本项目可以采用两种方式接受代码贡献: 1. 第一种就是基于[Git Flow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow)开发流程,因此在发起Pull Request的时候请选择develop分支。 -1. 另外一种贡献代码的方式就是加入SDK Developers开发组,如果对自己的代码足够自信,可以随时提交代码,注意要随时进行单元测试,保证提交代码没有明显问题,具体加入方式,请咨询管理员。 +1. 另外一种贡献代码的方式就是加入SDK Developers开发组,前提是对自己的代码足够自信就可以申请加入,加入之后可以随时直接提交代码,但要注意对所做的修改或新增的代码进行单元测试,保证提交代码没有明显问题,具体加入方式,请咨询管理员。 diff --git a/build.gradle b/build.gradle index cb727c46..108e69c0 100644 --- a/build.gradle +++ b/build.gradle @@ -2,7 +2,7 @@ allprojects { apply plugin: 'maven' group = 'com.github.binarywang' - version = '2.1.0-SNAPSHOT' + version = '2.2.0' } subprojects { @@ -13,8 +13,8 @@ subprojects { repositories { mavenLocal() - - maven { url "http://maven.aliyun.com/nexus/content/groups/public" } + maven { url "http://central.maven.org/maven2" } + //maven { url "http://maven.aliyun.com/nexus/content/groups/public" } } @@ -24,6 +24,8 @@ subprojects { compile group: 'org.apache.httpcomponents', name: 'httpmime', version:'4.5' compile group: 'org.jodd', name: 'jodd-http', version:'3.6.7' compile group: 'com.google.code.gson', name: 'gson', version:'2.7' + compile group: 'com.google.guava', name: 'guava', version:'19.0' + compile group: 'org.jooq', name: 'joor', version:'0.9.6' compile group: 'commons-codec', name: 'commons-codec', version:'1.10' compile group: 'commons-io', name: 'commons-io', version:'2.5' compile group: 'org.apache.commons', name: 'commons-lang3', version:'3.4' diff --git a/pom.xml b/pom.xml index dded0cab..e94e5fc1 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.github.binarywang weixin-java-parent - 2.1.0 + 2.2.0 pom WeiXin Java Tools - Parent 微信公众号、企业号上级POM @@ -49,9 +49,10 @@ 1.7.10 1.1.2 3.6.7 - 2.8.0 2.9.0 2.7 + 19.0 + 0.9.6 3.4 2.5 1.10 @@ -106,15 +107,19 @@ commons-lang3 ${commons-lang3.version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - redis.clients jedis ${jedis.version} + provided + + + com.google.guava + guava + + + org.jooq + joor @@ -156,6 +161,16 @@ ${jetty.version} test + + com.google.guava + guava + ${guava.version} + + + org.jooq + joor + ${joor.version} + diff --git a/weixin-java-common/pom.xml b/weixin-java-common/pom.xml index b916ccfa..667aaf76 100644 --- a/weixin-java-common/pom.xml +++ b/weixin-java-common/pom.xml @@ -6,7 +6,7 @@ com.github.binarywang weixin-java-parent - 2.1.0 + 2.2.0 weixin-java-common diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java new file mode 100644 index 00000000..9ed249da --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java @@ -0,0 +1,19 @@ +package me.chanjar.weixin.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 标识某个字段是否是必填的 + * + * Created by Binary Wang on 2016/9/25. + * @author binarywang (https://github.com/binarywang) + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Required { + +} \ No newline at end of file diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java index ce2a16a4..6a1e4380 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java @@ -30,6 +30,7 @@ public class WxConsts { public static final String CUSTOM_MSG_MUSIC = "music"; public static final String CUSTOM_MSG_NEWS = "news"; public static final String CUSTOM_MSG_FILE = "file"; + public static final String CUSTOM_MSG_WXCARD = "wxcard"; public static final String CUSTOM_MSG_TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service"; public static final String CUSTOM_MSG_SAFE_NO = "0"; public static final String CUSTOM_MSG_SAFE_YES = "1"; @@ -61,7 +62,7 @@ public class WxConsts { /** * 群发反馈消息代码所对应的文字描述 */ - public static final Map MASS_ST_2_DESC = new HashMap(); + public static final Map MASS_ST_2_DESC = new HashMap<>(); /////////////////////// // 微信端推送过来的事件类型 /////////////////////// @@ -92,6 +93,8 @@ public class WxConsts { public static final String EVT_KF_CREATE_SESSION = "kf_create_session"; // 客服接入会话 public static final String EVT_KF_CLOSE_SESSION = "kf_close_session"; // 客服关闭会话 public static final String EVT_KF_SWITCH_SESSION = "kf_switch_session"; // 客服转接会话 + public static final String EVT_POI_CHECK_NOTIFY = "poi_check_notify"; //门店审核事件推送 + /////////////////////// // 上传多媒体文件的类型 /////////////////////// diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java index e0d4d08c..1281e260 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java @@ -25,7 +25,7 @@ public class WxMessageInMemoryDuplicateChecker implements WxMessageDuplicateChec /** * 消息id->消息时间戳的map */ - private final ConcurrentHashMap msgId2Timestamp = new ConcurrentHashMap(); + private final ConcurrentHashMap msgId2Timestamp = new ConcurrentHashMap<>(); /** * 后台清理线程是否已经开启 @@ -56,7 +56,7 @@ public class WxMessageInMemoryDuplicateChecker implements WxMessageDuplicateChec } protected void checkBackgroundProcessStarted() { - if (backgroundProcessStarted.getAndSet(true)) { + if (this.backgroundProcessStarted.getAndSet(true)) { return; } Thread t = new Thread(new Runnable() { @@ -64,11 +64,11 @@ public class WxMessageInMemoryDuplicateChecker implements WxMessageDuplicateChec public void run() { try { while (true) { - Thread.sleep(clearPeriod); + Thread.sleep(WxMessageInMemoryDuplicateChecker.this.clearPeriod); Long now = System.currentTimeMillis(); - for (Map.Entry entry : msgId2Timestamp.entrySet()) { - if (now - entry.getValue() > timeToLive) { - msgId2Timestamp.entrySet().remove(entry); + for (Map.Entry entry : WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet()) { + if (now - entry.getValue() > WxMessageInMemoryDuplicateChecker.this.timeToLive) { + WxMessageInMemoryDuplicateChecker.this.msgId2Timestamp.entrySet().remove(entry); } } } @@ -87,7 +87,7 @@ public class WxMessageInMemoryDuplicateChecker implements WxMessageDuplicateChec return false; } checkBackgroundProcessStarted(); - Long timestamp = msgId2Timestamp.putIfAbsent(messageId, System.currentTimeMillis()); + Long timestamp = this.msgId2Timestamp.putIfAbsent(messageId, System.currentTimeMillis()); return timestamp != null; } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxAccessToken.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxAccessToken.java index eedecb84..6476205a 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxAccessToken.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxAccessToken.java @@ -16,7 +16,7 @@ public class WxAccessToken implements Serializable { } public String getAccessToken() { - return accessToken; + return this.accessToken; } public void setAccessToken(String accessToken) { @@ -24,7 +24,7 @@ public class WxAccessToken implements Serializable { } public int getExpiresIn() { - return expiresIn; + return this.expiresIn; } public void setExpiresIn(int expiresIn) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxCardApiSignature.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxCardApiSignature.java index 898decfa..2ff252c3 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxCardApiSignature.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxCardApiSignature.java @@ -39,7 +39,7 @@ public class WxCardApiSignature implements Serializable { } public String getAppId() { - return appId; + return this.appId; } public void setAppId(String appId) { @@ -47,7 +47,7 @@ public class WxCardApiSignature implements Serializable { } public String getCardId() { - return cardId; + return this.cardId; } public void setCardId(String cardId) { @@ -55,7 +55,7 @@ public class WxCardApiSignature implements Serializable { } public String getCardType() { - return cardType; + return this.cardType; } public void setCardType(String cardType) { @@ -63,7 +63,7 @@ public class WxCardApiSignature implements Serializable { } public String getLocationId() { - return locationId; + return this.locationId; } public void setLocationId(String locationId) { @@ -71,7 +71,7 @@ public class WxCardApiSignature implements Serializable { } public String getCode() { - return code; + return this.code; } public void setCode(String code) { @@ -79,7 +79,7 @@ public class WxCardApiSignature implements Serializable { } public String getOpenId() { - return openId; + return this.openId; } public void setOpenId(String openId) { @@ -87,7 +87,7 @@ public class WxCardApiSignature implements Serializable { } public Long getTimestamp() { - return timestamp; + return this.timestamp; } public void setTimestamp(Long timestamp) { @@ -95,7 +95,7 @@ public class WxCardApiSignature implements Serializable { } public String getNonceStr() { - return nonceStr; + return this.nonceStr; } public void setNonceStr(String nonceStr) { @@ -103,7 +103,7 @@ public class WxCardApiSignature implements Serializable { } public String getSignature() { - return signature; + return this.signature; } public void setSignature(String signature) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxJsapiSignature.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxJsapiSignature.java index 312860df..17799058 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxJsapiSignature.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxJsapiSignature.java @@ -19,7 +19,7 @@ public class WxJsapiSignature implements Serializable { private String signature; public String getSignature() { - return signature; + return this.signature; } public void setSignature(String signature) { @@ -27,7 +27,7 @@ public class WxJsapiSignature implements Serializable { } public String getNoncestr() { - return noncestr; + return this.noncestr; } public void setNoncestr(String noncestr) { @@ -35,7 +35,7 @@ public class WxJsapiSignature implements Serializable { } public long getTimestamp() { - return timestamp; + return this.timestamp; } public void setTimestamp(long timestamp) { @@ -43,7 +43,7 @@ public class WxJsapiSignature implements Serializable { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { @@ -51,7 +51,7 @@ public class WxJsapiSignature implements Serializable { } public String getAppid() { - return appid; + return this.appid; } public void setAppid(String appid) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java index 7989b39a..6b43ed06 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java @@ -19,7 +19,7 @@ public class WxMenu implements Serializable { private static final long serialVersionUID = -7083914585539687746L; - private List buttons = new ArrayList(); + private List buttons = new ArrayList<>(); private WxMenuRule matchRule; @@ -40,7 +40,7 @@ public class WxMenu implements Serializable { } public List getButtons() { - return buttons; + return this.buttons; } public void setButtons(List buttons) { @@ -48,7 +48,7 @@ public class WxMenu implements Serializable { } public WxMenuRule getMatchRule() { - return matchRule; + return this.matchRule; } public void setMatchRule(WxMenuRule matchRule) { @@ -62,7 +62,7 @@ public class WxMenu implements Serializable { @Override public String toString() { return "WxMenu{" + - "buttons=" + buttons + + "buttons=" + this.buttons + '}'; } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java index 88033400..6a5e5426 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java @@ -14,7 +14,7 @@ public class WxMenuButton { private String url; private String mediaId; - private List subButtons = new ArrayList(); + private List subButtons = new ArrayList<>(); @Override public String toString() { @@ -23,7 +23,7 @@ public class WxMenuButton { } public String getType() { - return type; + return this.type; } public void setType(String type) { @@ -31,7 +31,7 @@ public class WxMenuButton { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -39,7 +39,7 @@ public class WxMenuButton { } public String getKey() { - return key; + return this.key; } public void setKey(String key) { @@ -47,7 +47,7 @@ public class WxMenuButton { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { @@ -55,7 +55,7 @@ public class WxMenuButton { } public List getSubButtons() { - return subButtons; + return this.subButtons; } public void setSubButtons(List subButtons) { @@ -63,7 +63,7 @@ public class WxMenuButton { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java index 5cb9d8fe..b3e90886 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java @@ -13,7 +13,7 @@ public class WxMenuRule { private String language; public String getTagId() { - return tagId; + return this.tagId; } public void setTagId(String tagId) { @@ -21,7 +21,7 @@ public class WxMenuRule { } public String getSex() { - return sex; + return this.sex; } public void setSex(String sex) { @@ -29,7 +29,7 @@ public class WxMenuRule { } public String getCountry() { - return country; + return this.country; } public void setCountry(String country) { @@ -37,7 +37,7 @@ public class WxMenuRule { } public String getProvince() { - return province; + return this.province; } public void setProvince(String province) { @@ -45,7 +45,7 @@ public class WxMenuRule { } public String getCity() { - return city; + return this.city; } public void setCity(String city) { @@ -53,7 +53,7 @@ public class WxMenuRule { } public String getClientPlatformType() { - return clientPlatformType; + return this.clientPlatformType; } public void setClientPlatformType(String clientPlatformType) { @@ -61,7 +61,7 @@ public class WxMenuRule { } public String getLanguage() { - return language; + return this.language; } public void setLanguage(String language) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java index 070ec720..54b8b1fd 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java @@ -29,7 +29,7 @@ public class WxError implements Serializable { } public int getErrorCode() { - return errorCode; + return this.errorCode; } public void setErrorCode(int errorCode) { @@ -37,7 +37,7 @@ public class WxError implements Serializable { } public String getErrorMsg() { - return errorMsg; + return this.errorMsg; } public void setErrorMsg(String errorMsg) { @@ -45,7 +45,7 @@ public class WxError implements Serializable { } public String getJson() { - return json; + return this.json; } public void setJson(String json) { @@ -54,10 +54,10 @@ public class WxError implements Serializable { @Override public String toString() { - if (json != null) { - return json; + if (this.json != null) { + return this.json; } - return "错误: Code=" + errorCode + ", Msg=" + errorMsg; + return "错误: Code=" + this.errorCode + ", Msg=" + this.errorMsg; } public static class Builder { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java index 2e4b5fcd..09901c3e 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java @@ -17,7 +17,7 @@ public class WxMediaUploadResult implements Serializable { } public String getType() { - return type; + return this.type; } public void setType(String type) { @@ -25,7 +25,7 @@ public class WxMediaUploadResult implements Serializable { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -33,7 +33,7 @@ public class WxMediaUploadResult implements Serializable { } public long getCreatedAt() { - return createdAt; + return this.createdAt; } public void setCreatedAt(long createdAt) { @@ -41,7 +41,7 @@ public class WxMediaUploadResult implements Serializable { } public String getThumbMediaId() { - return thumbMediaId; + return this.thumbMediaId; } public void setThumbMediaId(String thumbMediaId) { @@ -50,8 +50,8 @@ public class WxMediaUploadResult implements Serializable { @Override public String toString() { - return "WxUploadResult [type=" + type + ", media_id=" + mediaId + ", thumb_media_id=" + thumbMediaId - + ", created_at=" + createdAt + "]"; + return "WxUploadResult [type=" + this.type + ", media_id=" + this.mediaId + ", thumb_media_id=" + this.thumbMediaId + + ", created_at=" + this.createdAt + "]"; } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/exception/WxErrorException.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/exception/WxErrorException.java index 7e2e1941..51219a41 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/exception/WxErrorException.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/exception/WxErrorException.java @@ -14,7 +14,7 @@ public class WxErrorException extends Exception { } public WxError getError() { - return error; + return this.error; } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSession.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSession.java index 9212c619..89d847d7 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSession.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSession.java @@ -18,7 +18,7 @@ public class StandardSession implements WxSession, InternalSession { */ protected static final String EMPTY_ARRAY[] = new String[0]; // ------------------------------ WxSession - protected Map attributes = new ConcurrentHashMap(); + protected Map attributes = new ConcurrentHashMap<>(); /** * The session identifier of this Session. */ @@ -47,7 +47,7 @@ public class StandardSession implements WxSession, InternalSession { /** * The current accessed time for this session. */ - protected volatile long thisAccessedTime = creationTime; + protected volatile long thisAccessedTime = this.creationTime; /** * The default maximum inactive interval for Sessions created by * this Manager. @@ -77,7 +77,7 @@ public class StandardSession implements WxSession, InternalSession { if (name == null) return null; - return (attributes.get(name)); + return (this.attributes.get(name)); } @Override @@ -86,8 +86,8 @@ public class StandardSession implements WxSession, InternalSession { throw new IllegalStateException (sm.getString("sessionImpl.getAttributeNames.ise")); - Set names = new HashSet(); - names.addAll(attributes.keySet()); + Set names = new HashSet<>(); + names.addAll(this.attributes.keySet()); return Collections.enumeration(names); } @@ -109,7 +109,7 @@ public class StandardSession implements WxSession, InternalSession { throw new IllegalStateException(sm.getString( "sessionImpl.setAttribute.ise", getIdInternal())); - attributes.put(name, value); + this.attributes.put(name, value); } @@ -132,10 +132,10 @@ public class StandardSession implements WxSession, InternalSession { @Override public WxSession getSession() { - if (facade == null) { - facade = new StandardSessionFacade(this); + if (this.facade == null) { + this.facade = new StandardSessionFacade(this); } - return (facade); + return (this.facade); } @@ -157,15 +157,15 @@ public class StandardSession implements WxSession, InternalSession { return true; } - if (accessCount.get() > 0) { + if (this.accessCount.get() > 0) { return true; } - if (maxInactiveInterval > 0) { + if (this.maxInactiveInterval > 0) { long timeNow = System.currentTimeMillis(); int timeIdle; - timeIdle = (int) ((timeNow - thisAccessedTime) / 1000L); - if (timeIdle >= maxInactiveInterval) { + timeIdle = (int) ((timeNow - this.thisAccessedTime) / 1000L); + if (timeIdle >= this.maxInactiveInterval) { expire(); } } @@ -193,7 +193,7 @@ public class StandardSession implements WxSession, InternalSession { if (name == null) return; // Remove this attribute from our collection - attributes.remove(name); + this.attributes.remove(name); } @@ -202,7 +202,7 @@ public class StandardSession implements WxSession, InternalSession { // Check to see if session has already been invalidated. // Do not check expiring at this point as expire should not return until // isValid is false - if (!isValid) + if (!this.isValid) return; synchronized (this) { @@ -210,24 +210,24 @@ public class StandardSession implements WxSession, InternalSession { // Double check locking - isValid needs to be volatile // The check of expiring is to ensure that an infinite loop is not // entered as per bug 56339 - if (expiring || !isValid) + if (this.expiring || !this.isValid) return; - if (manager == null) + if (this.manager == null) return; // Mark this session as "being expired" - expiring = true; + this.expiring = true; - accessCount.set(0); + this.accessCount.set(0); // Remove this session from our manager's active sessions - manager.remove(this, true); + this.manager.remove(this, true); // We have completed expire of this session setValid(false); - expiring = false; + this.expiring = false; // Unbind any objects associated with this session String keys[] = keys(); @@ -244,7 +244,7 @@ public class StandardSession implements WxSession, InternalSession { public void access() { this.thisAccessedTime = System.currentTimeMillis(); - accessCount.incrementAndGet(); + this.accessCount.incrementAndGet(); } @@ -253,7 +253,7 @@ public class StandardSession implements WxSession, InternalSession { public void endAccess() { this.thisAccessedTime = System.currentTimeMillis(); - accessCount.decrementAndGet(); + this.accessCount.decrementAndGet(); } @@ -273,13 +273,13 @@ public class StandardSession implements WxSession, InternalSession { @Override public void setId(String id) { - if ((this.id != null) && (manager != null)) - manager.remove(this); + if ((this.id != null) && (this.manager != null)) + this.manager.remove(this); this.id = id; - if (manager != null) - manager.add(this); + if (this.manager != null) + this.manager.add(this); } /** @@ -289,7 +289,7 @@ public class StandardSession implements WxSession, InternalSession { */ protected String[] keys() { - return attributes.keySet().toArray(EMPTY_ARRAY); + return this.attributes.keySet().toArray(EMPTY_ARRAY); } @@ -300,31 +300,31 @@ public class StandardSession implements WxSession, InternalSession { StandardSession session = (StandardSession) o; - if (creationTime != session.creationTime) return false; - if (expiring != session.expiring) return false; - if (isValid != session.isValid) return false; - if (maxInactiveInterval != session.maxInactiveInterval) return false; - if (thisAccessedTime != session.thisAccessedTime) return false; - if (!accessCount.equals(session.accessCount)) return false; - if (!attributes.equals(session.attributes)) return false; - if (!facade.equals(session.facade)) return false; - if (!id.equals(session.id)) return false; - return manager.equals(session.manager); + if (this.creationTime != session.creationTime) return false; + if (this.expiring != session.expiring) return false; + if (this.isValid != session.isValid) return false; + if (this.maxInactiveInterval != session.maxInactiveInterval) return false; + if (this.thisAccessedTime != session.thisAccessedTime) return false; + if (!this.accessCount.equals(session.accessCount)) return false; + if (!this.attributes.equals(session.attributes)) return false; + if (!this.facade.equals(session.facade)) return false; + if (!this.id.equals(session.id)) return false; + return this.manager.equals(session.manager); } @Override public int hashCode() { - int result = attributes.hashCode(); - result = 31 * result + id.hashCode(); - result = 31 * result + (isValid ? 1 : 0); - result = 31 * result + (expiring ? 1 : 0); - result = 31 * result + manager.hashCode(); - result = 31 * result + (int) (creationTime ^ (creationTime >>> 32)); - result = 31 * result + (int) (thisAccessedTime ^ (thisAccessedTime >>> 32)); - result = 31 * result + maxInactiveInterval; - result = 31 * result + facade.hashCode(); - result = 31 * result + accessCount.hashCode(); + int result = this.attributes.hashCode(); + result = 31 * result + this.id.hashCode(); + result = 31 * result + (this.isValid ? 1 : 0); + result = 31 * result + (this.expiring ? 1 : 0); + result = 31 * result + this.manager.hashCode(); + result = 31 * result + (int) (this.creationTime ^ (this.creationTime >>> 32)); + result = 31 * result + (int) (this.thisAccessedTime ^ (this.thisAccessedTime >>> 32)); + result = 31 * result + this.maxInactiveInterval; + result = 31 * result + this.facade.hashCode(); + result = 31 * result + this.accessCount.hashCode(); return result; } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionFacade.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionFacade.java index a9631de6..e4493089 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionFacade.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionFacade.java @@ -14,32 +14,32 @@ public class StandardSessionFacade implements WxSession { } public InternalSession getInternalSession() { - return (InternalSession) session; + return (InternalSession) this.session; } @Override public Object getAttribute(String name) { - return session.getAttribute(name); + return this.session.getAttribute(name); } @Override public Enumeration getAttributeNames() { - return session.getAttributeNames(); + return this.session.getAttributeNames(); } @Override public void setAttribute(String name, Object value) { - session.setAttribute(name, value); + this.session.setAttribute(name, value); } @Override public void removeAttribute(String name) { - session.removeAttribute(name); + this.session.removeAttribute(name); } @Override public void invalidate() { - session.invalidate(); + this.session.invalidate(); } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java index cd14a1fd..7e6c95a2 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java @@ -32,7 +32,7 @@ public class StandardSessionManager implements WxSessionManager, InternalSession * The set of currently active Sessions for this Manager, keyed by * session identifier. */ - protected Map sessions = new ConcurrentHashMap(); + protected Map sessions = new ConcurrentHashMap<>(); /** * The maximum number of active Sessions allowed, or -1 for no limit. */ @@ -117,7 +117,7 @@ public class StandardSessionManager implements WxSessionManager, InternalSession @Override public void remove(InternalSession session, boolean update) { if (session.getIdInternal() != null) { - sessions.remove(session.getIdInternal()); + this.sessions.remove(session.getIdInternal()); } } @@ -127,7 +127,7 @@ public class StandardSessionManager implements WxSessionManager, InternalSession if (id == null) return (null); - return sessions.get(id); + return this.sessions.get(id); } @@ -138,12 +138,12 @@ public class StandardSessionManager implements WxSessionManager, InternalSession (sm.getString("sessionManagerImpl.createSession.ise")); } - if ((maxActiveSessions >= 0) && - (getActiveSessions() >= maxActiveSessions)) { - rejectedSessions++; + if ((this.maxActiveSessions >= 0) && + (getActiveSessions() >= this.maxActiveSessions)) { + this.rejectedSessions++; throw new TooManyActiveSessionsException( sm.getString("sessionManagerImpl.createSession.tmase"), - maxActiveSessions); + this.maxActiveSessions); } // Recycle or create a Session instance @@ -155,7 +155,7 @@ public class StandardSessionManager implements WxSessionManager, InternalSession session.setMaxInactiveInterval(this.maxInactiveInterval); String id = sessionId; session.setId(id); - sessionCounter++; + this.sessionCounter++; return (session); @@ -164,7 +164,7 @@ public class StandardSessionManager implements WxSessionManager, InternalSession @Override public int getActiveSessions() { - return sessions.size(); + return this.sessions.size(); } @@ -185,17 +185,17 @@ public class StandardSessionManager implements WxSessionManager, InternalSession public void add(InternalSession session) { // 当第一次有session创建的时候,开启session清理线程 - if (!backgroundProcessStarted.getAndSet(true)) { + if (!this.backgroundProcessStarted.getAndSet(true)) { Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { try { // 每秒清理一次 - Thread.sleep(backgroundProcessorDelay * 1000l); + Thread.sleep(StandardSessionManager.this.backgroundProcessorDelay * 1000l); backgroundProcess(); } catch (InterruptedException e) { - log.error("SessionManagerImpl.backgroundProcess error", e); + StandardSessionManager.this.log.error("SessionManagerImpl.backgroundProcess error", e); } } } @@ -204,12 +204,12 @@ public class StandardSessionManager implements WxSessionManager, InternalSession t.start(); } - sessions.put(session.getIdInternal(), session); + this.sessions.put(session.getIdInternal(), session); int size = getActiveSessions(); - if (size > maxActive) { - synchronized (maxActiveUpdateLock) { - if (size > maxActive) { - maxActive = size; + if (size > this.maxActive) { + synchronized (this.maxActiveUpdateLock) { + if (size > this.maxActive) { + this.maxActive = size; } } } @@ -223,14 +223,14 @@ public class StandardSessionManager implements WxSessionManager, InternalSession @Override public InternalSession[] findSessions() { - return sessions.values().toArray(new InternalSession[0]); + return this.sessions.values().toArray(new InternalSession[0]); } @Override public void backgroundProcess() { - count = (count + 1) % processExpiresFrequency; - if (count == 0) + this.count = (this.count + 1) % this.processExpiresFrequency; + if (this.count == 0) processExpires(); } @@ -243,17 +243,17 @@ public class StandardSessionManager implements WxSessionManager, InternalSession InternalSession sessions[] = findSessions(); int expireHere = 0; - if (log.isDebugEnabled()) - log.debug("Start expire sessions {} at {} sessioncount {}", getName(), timeNow, sessions.length); + if (this.log.isDebugEnabled()) + this.log.debug("Start expire sessions {} at {} sessioncount {}", getName(), timeNow, sessions.length); for (int i = 0; i < sessions.length; i++) { if (sessions[i] != null && !sessions[i].isValid()) { expireHere++; } } long timeEnd = System.currentTimeMillis(); - if (log.isDebugEnabled()) - log.debug("End expire sessions {} processingTime {} expired sessions: {}", getName(), timeEnd - timeNow, expireHere); - processingTime += (timeEnd - timeNow); + if (this.log.isDebugEnabled()) + this.log.debug("End expire sessions {} processingTime {} expired sessions: {}", getName(), timeEnd - timeNow, expireHere); + this.processingTime += (timeEnd - timeNow); } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java index 69fd89f8..72a2b4c4 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java @@ -40,7 +40,7 @@ public class TooManyActiveSessionsException int maxActive) { super(message); - maxActiveSessions = maxActive; + this.maxActiveSessions = maxActive; } /** @@ -49,6 +49,6 @@ public class TooManyActiveSessionsException * @return The maximum number of sessions allowed by the session manager. */ public int getMaxActiveSessions() { - return maxActiveSessions; + return this.maxActiveSessions; } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/LogExceptionHandler.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/LogExceptionHandler.java index a512e599..7ad976ab 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/LogExceptionHandler.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/LogExceptionHandler.java @@ -13,7 +13,7 @@ public class LogExceptionHandler implements WxErrorExceptionHandler { @Override public void handle(WxErrorException e) { - log.error("Error happens", e); + this.log.error("Error happens", e); } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java index 6cd4a5ef..b12ec655 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java @@ -3,24 +3,24 @@ package me.chanjar.weixin.common.util.crypto; import java.util.ArrayList; public class ByteGroup { - ArrayList byteContainer = new ArrayList(); + ArrayList byteContainer = new ArrayList<>(); public byte[] toBytes() { - byte[] bytes = new byte[byteContainer.size()]; - for (int i = 0; i < byteContainer.size(); i++) { - bytes[i] = byteContainer.get(i); + byte[] bytes = new byte[this.byteContainer.size()]; + for (int i = 0; i < this.byteContainer.size(); i++) { + bytes[i] = this.byteContainer.get(i); } return bytes; } public ByteGroup addBytes(byte[] bytes) { for (byte b : bytes) { - byteContainer.add(b); + this.byteContainer.add(b); } return this; } public int size() { - return byteContainer.size(); + return this.byteContainer.size(); } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java index 2a01aae0..145896a5 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java @@ -47,7 +47,7 @@ public class PKCS7Encoder { * @return 删除补位字符后的明文 */ public static byte[] decode(byte[] decrypted) { - int pad = (int) decrypted[decrypted.length - 1]; + int pad = decrypted[decrypted.length - 1]; if (pad < 1 || pad > 32) { pad = 0; } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java index 4f7503c6..683f2ecf 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java @@ -1,10 +1,9 @@ package me.chanjar.weixin.common.util.crypto; -import org.apache.commons.codec.digest.DigestUtils; - -import java.security.NoSuchAlgorithmException; import java.util.Arrays; +import org.apache.commons.codec.digest.DigestUtils; + /** * Created by Daniel Qian on 14/10/19. */ @@ -13,7 +12,7 @@ public class SHA1 { /** * 串接arr参数,生成sha1 digest */ - public static String gen(String... arr) throws NoSuchAlgorithmException { + public static String gen(String... arr) { Arrays.sort(arr); StringBuilder sb = new StringBuilder(); for (String a : arr) { @@ -25,7 +24,7 @@ public class SHA1 { /** * 用&串接arr参数,生成sha1 digest */ - public static String genWithAmple(String... arr) throws NoSuchAlgorithmException { + public static String genWithAmple(String... arr) { Arrays.sort(arr); StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java index c1341e7b..fead486e 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java @@ -17,11 +17,10 @@ */ package me.chanjar.weixin.common.util.crypto; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.digest.DigestUtils; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.InputSource; +import java.io.StringReader; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Random; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; @@ -29,10 +28,11 @@ import javax.crypto.spec.SecretKeySpec; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import java.io.StringReader; -import java.nio.charset.Charset; -import java.security.NoSuchAlgorithmException; -import java.util.*; + +import org.apache.commons.codec.binary.Base64; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; public class WxCryptUtil { @@ -72,33 +72,6 @@ public class WxCryptUtil { this.aesKey = Base64.decodeBase64(encodingAesKey + "="); } - /** - * 微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3) - * @param packageParams 原始参数 - * @param signKey 加密Key(即 商户Key) - * @return 签名字符串 - */ - public static String createSign(Map packageParams, - String signKey) { - SortedMap sortedMap = new TreeMap(); - sortedMap.putAll(packageParams); - - List keys = new ArrayList(packageParams.keySet()); - Collections.sort(keys); - - StringBuffer toSign = new StringBuffer(); - for (String key : keys) { - String value = packageParams.get(key); - if (null != value && !"".equals(value) && !"sign".equals(key) - && !"key".equals(key)) { - toSign.append(key + "=" + value + "&"); - } - } - toSign.append("key=" + signKey); - String sign = DigestUtils.md5Hex(toSign.toString()).toUpperCase(); - return sign; - } - static String extractEncryptPart(String xml) { try { DocumentBuilder db = builderLocal.get(); @@ -130,13 +103,9 @@ public class WxCryptUtil { String timeStamp = Long.toString(System.currentTimeMillis() / 1000l); String nonce = genRandomStr(); - try { - String signature = SHA1.gen(token, timeStamp, nonce, encryptedXml); - String result = generateXml(encryptedXml, signature, timeStamp, nonce); - return result; - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } + String signature = SHA1.gen(this.token, timeStamp, nonce, encryptedXml); + String result = generateXml(encryptedXml, signature, timeStamp, nonce); + return result; } /** @@ -151,7 +120,7 @@ public class WxCryptUtil { byte[] plainTextBytes = plainText.getBytes(CHARSET); byte[] bytesOfSizeInNetworkOrder = number2BytesInNetworkOrder( plainTextBytes.length); - byte[] appIdBytes = appidOrCorpid.getBytes(CHARSET); + byte[] appIdBytes = this.appidOrCorpid.getBytes(CHARSET); // randomStr + networkBytesOrder + text + appid byteCollector.addBytes(randomStringBytes); @@ -169,8 +138,8 @@ public class WxCryptUtil { try { // 设置加密模式为AES的CBC模式 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); - SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); - IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); + SecretKeySpec keySpec = new SecretKeySpec(this.aesKey, "AES"); + IvParameterSpec iv = new IvParameterSpec(this.aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); // 加密 @@ -205,14 +174,10 @@ public class WxCryptUtil { // 提取密文 String cipherText = extractEncryptPart(encryptedXml); - try { - // 验证安全签名 - String signature = SHA1.gen(token, timeStamp, nonce, cipherText); - if (!signature.equals(msgSignature)) { - throw new RuntimeException("加密消息签名校验失败"); - } - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); + // 验证安全签名 + String signature = SHA1.gen(this.token, timeStamp, nonce, cipherText); + if (!signature.equals(msgSignature)) { + throw new RuntimeException("加密消息签名校验失败"); } // 解密 @@ -231,9 +196,9 @@ public class WxCryptUtil { try { // 设置解密模式为AES的CBC模式 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); - SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES"); + SecretKeySpec key_spec = new SecretKeySpec(this.aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec( - Arrays.copyOfRange(aesKey, 0, 16)); + Arrays.copyOfRange(this.aesKey, 0, 16)); cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); // 使用BASE64对密文进行解码 @@ -264,7 +229,7 @@ public class WxCryptUtil { } // appid不相同的情况 - if (!from_appid.equals(appidOrCorpid)) { + if (!from_appid.equals(this.appidOrCorpid)) { throw new RuntimeException("AppID不正确"); } @@ -277,7 +242,7 @@ public class WxCryptUtil { * * @param number */ - private byte[] number2BytesInNetworkOrder(int number) { + private static byte[] number2BytesInNetworkOrder(int number) { byte[] orderBytes = new byte[4]; orderBytes[3] = (byte) (number & 0xFF); orderBytes[2] = (byte) (number >> 8 & 0xFF); @@ -291,7 +256,7 @@ public class WxCryptUtil { * * @param bytesInNetworkOrder */ - private int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) { + private static int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) { int sourceNumber = 0; for (int i = 0; i < 4; i++) { sourceNumber <<= 8; @@ -303,7 +268,7 @@ public class WxCryptUtil { /** * 随机生成16位字符串 */ - private String genRandomStr() { + private static String genRandomStr() { String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); @@ -323,8 +288,8 @@ public class WxCryptUtil { * @param nonce 随机字符串 * @return 生成的xml字符串 */ - private String generateXml(String encrypt, String signature, String timestamp, - String nonce) { + private static String generateXml(String encrypt, String signature, + String timestamp, String nonce) { String format = "\n" + "\n" + "\n" + "%3$s\n" + "\n" diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java index 706ced39..9ff25ebc 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java @@ -17,37 +17,25 @@ public class FileUtils { * @param tmpDirFile 临时文件夹目录 */ public static File createTmpFile(InputStream inputStream, String name, String ext, File tmpDirFile) throws IOException { - FileOutputStream fos = null; - try { - File tmpFile; - if (tmpDirFile == null) { - tmpFile = File.createTempFile(name, '.' + ext); - } else { - tmpFile = File.createTempFile(name, '.' + ext, tmpDirFile); - } - tmpFile.deleteOnExit(); - fos = new FileOutputStream(tmpFile); + File tmpFile; + if (tmpDirFile == null) { + tmpFile = File.createTempFile(name, '.' + ext); + } else { + tmpFile = File.createTempFile(name, '.' + ext, tmpDirFile); + } + + tmpFile.deleteOnExit(); + + try (FileOutputStream fos = new FileOutputStream(tmpFile)) { int read = 0; byte[] bytes = new byte[1024 * 100]; while ((read = inputStream.read(bytes)) != -1) { fos.write(bytes, 0, read); } + fos.flush(); return tmpFile; - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - } - } - if (fos != null) { - try { - fos.close(); - } catch (IOException e) { - } - } - } + } } /** diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpClientBuilder.java index 4acc7662..f69dcc6c 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpClientBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpClientBuilder.java @@ -103,43 +103,45 @@ public class DefaultApacheHttpClientBuilder implements ApacheHttpClientBuilder { private void prepare() { Registry registry = RegistryBuilder.create() - .register("http", this.plainConnectionSocketFactory) - .register("https", this.sslConnectionSocketFactory) - .build(); + .register("http", this.plainConnectionSocketFactory) + .register("https", this.sslConnectionSocketFactory) + .build(); + @SuppressWarnings("resource") PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(this.maxTotalConn); connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost); connectionManager.setDefaultSocketConfig( - SocketConfig.copy(SocketConfig.DEFAULT) - .setSoTimeout(this.soTimeout) - .build() + SocketConfig.copy(SocketConfig.DEFAULT) + .setSoTimeout(this.soTimeout) + .build() ); this.idleConnectionMonitorThread = new IdleConnectionMonitorThread( - connectionManager, this.idleConnTimeout, this.checkWaitTime); + connectionManager, this.idleConnTimeout, this.checkWaitTime); this.idleConnectionMonitorThread.setDaemon(true); this.idleConnectionMonitorThread.start(); this.httpClientBuilder = HttpClients.custom() - .setConnectionManager(connectionManager) - .setDefaultRequestConfig( - RequestConfig.custom() - .setSocketTimeout(this.soTimeout) - .setConnectTimeout(this.connectionTimeout) - .setConnectionRequestTimeout(this.connectionRequestTimeout) - .build() - ) - .setRetryHandler(this.httpRequestRetryHandler); + .setConnectionManager(connectionManager) + .setConnectionManagerShared(true) + .setDefaultRequestConfig( + RequestConfig.custom() + .setSocketTimeout(this.soTimeout) + .setConnectTimeout(this.connectionTimeout) + .setConnectionRequestTimeout(this.connectionRequestTimeout) + .build() + ) + .setRetryHandler(this.httpRequestRetryHandler); if (StringUtils.isNotBlank(this.httpProxyHost) - && StringUtils.isNotBlank(this.httpProxyUsername)) { + && StringUtils.isNotBlank(this.httpProxyUsername)) { // 使用代理服务器 需要用户认证的代理服务器 CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials( - new AuthScope(this.httpProxyHost, this.httpProxyPort), - new UsernamePasswordCredentials(this.httpProxyUsername, - this.httpProxyPassword)); + new AuthScope(this.httpProxyHost, this.httpProxyPort), + new UsernamePasswordCredentials(this.httpProxyUsername, + this.httpProxyPassword)); this.httpClientBuilder.setDefaultCredentialsProvider(provider); } @@ -180,7 +182,7 @@ public class DefaultApacheHttpClientBuilder implements ApacheHttpClientBuilder { wait(this.checkWaitTime); this.connMgr.closeExpiredConnections(); this.connMgr.closeIdleConnections(this.idleConnTimeout, - TimeUnit.MILLISECONDS); + TimeUnit.MILLISECONDS); } } } catch (InterruptedException ignore) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamResponseHandler.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamResponseHandler.java index 6433c472..0cc1562b 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamResponseHandler.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamResponseHandler.java @@ -14,6 +14,7 @@ public class InputStreamResponseHandler implements ResponseHandler public static final ResponseHandler INSTANCE = new InputStreamResponseHandler(); + @Override public InputStream handleResponse(final HttpResponse response) throws IOException { final StatusLine statusLine = response.getStatusLine(); final HttpEntity entity = response.getEntity(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java index a2ff7a56..34f20779 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java @@ -1,15 +1,14 @@ package me.chanjar.weixin.common.util.http; +import org.apache.http.HttpHost; +import org.apache.http.impl.client.CloseableHttpClient; + import jodd.http.HttpRequest; import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import jodd.http.net.SocketHttpConnectionProvider; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import org.apache.http.HttpHost; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; /** * 简单的GET请求执行器,请求的参数是String, 返回的结果也是String @@ -20,7 +19,7 @@ public class JoddGetRequestExecutor implements RequestExecutor { @Override public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - String queryParam) throws WxErrorException, IOException { + String queryParam) throws WxErrorException { if (queryParam != null) { if (uri.indexOf('?') == -1) { uri += '?'; diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java index 771fb46e..757db665 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java @@ -1,15 +1,14 @@ package me.chanjar.weixin.common.util.http; +import org.apache.http.HttpHost; +import org.apache.http.impl.client.CloseableHttpClient; + import jodd.http.HttpRequest; import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import jodd.http.net.SocketHttpConnectionProvider; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import org.apache.http.HttpHost; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; /** * 简单的POST请求执行器,请求的参数是String, 返回的结果也是String @@ -20,7 +19,7 @@ public class JoddPostRequestExecutor implements RequestExecutor @Override public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - String postEntity) throws WxErrorException, IOException { + String postEntity) throws WxErrorException { SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider(); if (httpProxy != null) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java index 5ffac4bf..c81658e2 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java @@ -20,7 +20,7 @@ import java.util.regex.Pattern; /** * 下载媒体文件请求执行器,请求的参数是String, 返回的结果是File - * + * 视频文件不支持下载 * @author Daniel Qian */ public class MediaDownloadRequestExecutor implements RequestExecutor { @@ -28,15 +28,12 @@ public class MediaDownloadRequestExecutor implements RequestExecutor 0) { - // 下载媒体文件出错 - if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) { + 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)); } } - InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response); - // 视频文件不支持下载 String fileName = getFileName(response); if (StringUtils.isBlank(fileName)) { return null; } - String[] name_ext = fileName.split("\\."); - File localFile = FileUtils.createTmpFile(inputStream, name_ext[0], name_ext[1], tmpDirFile); - return localFile; + + String[] nameAndExt = fileName.split("\\."); + return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], this.tmpDirFile); } finally { httpGet.releaseConnection(); @@ -79,13 +76,18 @@ public class MediaDownloadRequestExecutor implements RequestExecutor { * @param uri uri * @param data 数据 * @throws WxErrorException - * @throws ClientProtocolException * @throws IOException */ T execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, E data) throws WxErrorException, IOException; diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java index ad67bd51..bdea8573 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.common.util.http; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; +import java.io.IOException; + import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -10,7 +10,8 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; -import java.io.IOException; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; /** * 简单的POST请求执行器,请求的参数是String, 返回的结果也是String @@ -34,6 +35,17 @@ public class SimplePostRequestExecutor implements RequestExecutor")) { + //xml格式输出直接返回 + return responseContent; + } + WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/URIUtil.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/URIUtil.java index bb671eb1..9448f2d1 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/URIUtil.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/URIUtil.java @@ -35,7 +35,7 @@ public class URIUtil { private static String getHex(byte buf[]) { StringBuilder o = new StringBuilder(buf.length * 3); for (int i = 0; i < buf.length; i++) { - int n = (int) buf[i] & 0xff; + int n = buf[i] & 0xff; o.append("%"); if (n < 0x10) { o.append("0"); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/Utf8ResponseHandler.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/Utf8ResponseHandler.java index 1d1481b2..148ef965 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/Utf8ResponseHandler.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/Utf8ResponseHandler.java @@ -19,6 +19,7 @@ public class Utf8ResponseHandler implements ResponseHandler { public static final ResponseHandler INSTANCE = new Utf8ResponseHandler(); + @Override public String handleResponse(final HttpResponse response) throws IOException { final StatusLine statusLine = response.getStatusLine(); final HttpEntity entity = response.getEntity(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java index 3c106fbf..ec30c6b0 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java @@ -9,6 +9,10 @@ package me.chanjar.weixin.common.util.json; +import java.util.List; + +import com.google.common.collect.Lists; +import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -112,4 +116,21 @@ public class GsonHelper { return r == null ? 0f : r; } + public static Integer[] getIntArray(JsonObject o, String string) { + JsonArray jsonArray = getAsJsonArray(o.getAsJsonArray(string)); + if (jsonArray == null) { + return null; + } + + List result = Lists.newArrayList(); + for (int i = 0; i < jsonArray.size(); i++) { + result.add(jsonArray.get(i).getAsInt()); + } + + return result.toArray(new Integer[0]); + } + + public static JsonArray getAsJsonArray(JsonElement element) { + return element == null ? null : element.getAsJsonArray(); + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java index 58be83ac..e7d700e9 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java @@ -18,6 +18,7 @@ import java.lang.reflect.Type; */ public class WxAccessTokenAdapter implements JsonDeserializer { + @Override public WxAccessToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxAccessToken accessToken = new WxAccessToken(); JsonObject accessTokenJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java index 30c3708d..cc426bc8 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java @@ -18,6 +18,7 @@ import java.lang.reflect.Type; */ public class WxErrorAdapter implements JsonDeserializer { + @Override public WxError deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxError wxError = new WxError(); JsonObject wxErrorJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java index 16317a40..662b7442 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java @@ -18,6 +18,7 @@ import java.lang.reflect.Type; */ public class WxMediaUploadResultAdapter implements JsonDeserializer { + @Override public WxMediaUploadResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMediaUploadResult uploadResult = new WxMediaUploadResult(); JsonObject uploadResultJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java index 744df7e1..2cfbe252 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java @@ -29,6 +29,7 @@ import me.chanjar.weixin.common.bean.menu.WxMenuRule; */ public class WxMenuGsonAdapter implements JsonSerializer, JsonDeserializer { + @Override public JsonElement serialize(WxMenu menu, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); @@ -75,6 +76,7 @@ public class WxMenuGsonAdapter implements JsonSerializer, JsonDeserializ return matchRule; } + @Override public WxMenu deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { /* * 操蛋的微信 diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java index 94303fec..32f4e42a 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java @@ -47,7 +47,7 @@ import java.util.*; public class StringManager { private static final Map> managers = - new Hashtable>(); + new Hashtable<>(); private static int LOCALE_CACHE_SIZE = 10; /** * The ResourceBundle for this StringManager. @@ -81,10 +81,10 @@ public class StringManager { } } } - bundle = bnd; + this.bundle = bnd; // Get the actual locale, which may be different from the requested one - if (bundle != null) { - Locale bundleLocale = bundle.getLocale(); + if (this.bundle != null) { + Locale bundleLocale = this.bundle.getLocale(); if (bundleLocale.equals(Locale.ROOT)) { this.locale = Locale.ENGLISH; } else { @@ -192,8 +192,8 @@ public class StringManager { try { // Avoid NPE if bundle is null and treat it like an MRE - if (bundle != null) { - str = bundle.getString(key); + if (this.bundle != null) { + str = this.bundle.getString(key); } } catch (MissingResourceException mre) { //bad: shouldn't mask an exception the following way: @@ -227,7 +227,7 @@ public class StringManager { } MessageFormat mf = new MessageFormat(value); - mf.setLocale(locale); + mf.setLocale(this.locale); return mf.format(args, new StringBuffer(), null).toString(); } @@ -235,6 +235,6 @@ public class StringManager { * Identify the Locale this StringManager is associated with */ public Locale getLocale() { - return locale; + return this.locale; } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java index 109acfc0..ba49528a 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java @@ -1,5 +1,7 @@ package me.chanjar.weixin.common.util.xml; +import java.io.Writer; + import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; @@ -8,8 +10,6 @@ import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.security.NullPermission; import com.thoughtworks.xstream.security.PrimitiveTypePermission; -import java.io.Writer; - public class XStreamInitializer { public static XStream getInstance() { @@ -25,15 +25,20 @@ public class XStreamInitializer { @Override protected void writeText(QuickWriter writer, String text) { - if (text.startsWith(PREFIX_CDATA) && text.endsWith(SUFFIX_CDATA)) { + if (text.startsWith(this.PREFIX_CDATA) && text.endsWith(this.SUFFIX_CDATA)) { writer.write(text); - } else if (text.startsWith(PREFIX_MEDIA_ID) && text.endsWith(SUFFIX_MEDIA_ID)) { + } else if (text.startsWith(this.PREFIX_MEDIA_ID) && text.endsWith(this.SUFFIX_MEDIA_ID)) { writer.write(text); } else { super.writeText(writer, text); } } + + @Override + public String encodeNode(String name) { + return name;//防止将_转换成__ + } }; } }); diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java index ce246636..e0248c79 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java @@ -106,7 +106,7 @@ public class SessionTest { } @Test(dataProvider = "getSessionManager") - public void testMaxActive(WxSessionManager sessionManager) throws InterruptedException { + public void testMaxActive(WxSessionManager sessionManager) { InternalSessionManager ism = (InternalSessionManager) sessionManager; ism.setMaxActiveSessions(2); @@ -118,7 +118,7 @@ public class SessionTest { } @Test(dataProvider = "getSessionManager", expectedExceptions = TooManyActiveSessionsException.class) - public void testMaxActive2(WxSessionManager sessionManager) throws InterruptedException { + public void testMaxActive2(WxSessionManager sessionManager) { InternalSessionManager ism = (InternalSessionManager) sessionManager; ism.setMaxActiveSessions(2); diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java index a5fa0c41..e7692165 100755 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java @@ -34,8 +34,8 @@ public class WxCryptUtilTest { String afterAesEncrypt2 = "jn1L23DB+6ELqJ+6bruv23M2GmYfkv0xBh2h+XTBOKVKcgDFHle6gqcZ1cZrk3e1qjPQ1F4RsLWzQRG9udbKWesxlkupqcEcW7ZQweImX9+wLMa0GaUzpkycA8+IamDBxn5loLgZpnS7fVAbExOkK5DYHBmv5tptA9tklE/fTIILHR8HLXa5nQvFb3tYPKAlHF3rtTeayNf0QuM+UW/wM9enGIDIJHF7CLHiDNAYxr+r+OrJCmPQyTy8cVWlu9iSvOHPT/77bZqJucQHQ04sq7KZI27OcqpQNSto2OdHCoTccjggX5Z9Mma0nMJBU+jLKJ38YB1fBIz+vBzsYjrTmFQ44YfeEuZ+xRTQwr92vhA9OxchWVINGC50qE/6lmkwWTwGX9wtQpsJKhP+oS7rvTY8+VdzETdfakjkwQ5/Xka042OlUb1/slTwo4RscuQ+RdxSGvDahxAJ6+EAjLt9d8igHngxIbf6YyqqROxuxqIeIch3CssH/LqRs+iAcILvApYZckqmA7FNERspKA5f8GoJ9sv8xmGvZ9Yrf57cExWtnX8aCMMaBropU/1k+hKP5LVdzbWCG0hGwx/dQudYR/eXp3P0XxjlFiy+9DMlaFExWUZQDajPkdPrEeOwofJb"; public void testNormal() throws ParserConfigurationException, SAXException, IOException { - WxCryptUtil pc = new WxCryptUtil(token, encodingAesKey, appId); - String encryptedXml = pc.encrypt(replyMsg); + WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); + String encryptedXml = pc.encrypt(this.replyMsg); System.out.println(encryptedXml); @@ -56,31 +56,31 @@ public class WxCryptUtilTest { String nonce = root.getElementsByTagName("Nonce").item(0).getTextContent(); System.out.println(nonce); - String messageText = String.format(xmlFormat, cipherText); + String messageText = String.format(this.xmlFormat, cipherText); System.out.println(messageText); // 第三方收到企业号平台发送的消息 String plainMessage = pc.decrypt(cipherText); System.out.println(plainMessage); - assertEquals(plainMessage, replyMsg); + assertEquals(plainMessage, this.replyMsg); } public void testAesEncrypt() { - WxCryptUtil pc = new WxCryptUtil(token, encodingAesKey, appId); - assertEquals(pc.encrypt(randomStr, replyMsg), afterAesEncrypt); + WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); + assertEquals(pc.encrypt(this.randomStr, this.replyMsg), this.afterAesEncrypt); } public void testAesEncrypt2() { - WxCryptUtil pc = new WxCryptUtil(token, encodingAesKey, appId); - assertEquals(pc.encrypt(randomStr, replyMsg2), afterAesEncrypt2); + WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); + assertEquals(pc.encrypt(this.randomStr, this.replyMsg2), this.afterAesEncrypt2); } public void testValidateSignatureError() throws ParserConfigurationException, SAXException, IOException { try { - WxCryptUtil pc = new WxCryptUtil(token, encodingAesKey, appId); - String afterEncrpt = pc.encrypt(replyMsg); + WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); + String afterEncrpt = pc.encrypt(this.replyMsg); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(afterEncrpt); @@ -91,8 +91,8 @@ public class WxCryptUtilTest { NodeList nodelist1 = root.getElementsByTagName("Encrypt"); String encrypt = nodelist1.item(0).getTextContent(); - String fromXML = String.format(xmlFormat, encrypt); - pc.decrypt("12345", timestamp, nonce, fromXML); // 这里签名错误 + String fromXML = String.format(this.xmlFormat, encrypt); + pc.decrypt("12345", this.timestamp, this.nonce, fromXML); // 这里签名错误 } catch (RuntimeException e) { assertEquals(e.getMessage(), "加密消息签名校验失败"); return; diff --git a/weixin-java-cp/pom.xml b/weixin-java-cp/pom.xml index 7b996256..e87e2ea1 100644 --- a/weixin-java-cp/pom.xml +++ b/weixin-java-cp/pom.xml @@ -6,7 +6,7 @@ com.github.binarywang weixin-java-parent - 2.1.0 + 2.2.0 weixin-java-cp diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpConfigStorage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpConfigStorage.java index 4e4ab238..b334b85b 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpConfigStorage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpConfigStorage.java @@ -55,13 +55,13 @@ public interface WxCpConfigStorage { String getOauth2redirectUri(); - String getHttp_proxy_host(); + String getHttpProxyHost(); - int getHttp_proxy_port(); + int getHttpProxyPort(); - String getHttp_proxy_username(); + String getHttpProxyUsername(); - String getHttp_proxy_password(); + String getHttpProxyPassword(); File getTmpDirFile(); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpInMemoryConfigStorage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpInMemoryConfigStorage.java index 52d0c93b..17fda4ca 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpInMemoryConfigStorage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpInMemoryConfigStorage.java @@ -1,10 +1,13 @@ package me.chanjar.weixin.cp.api; +import java.io.File; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + import me.chanjar.weixin.common.bean.WxAccessToken; import me.chanjar.weixin.common.util.http.ApacheHttpClientBuilder; -import java.io.File; - /** * 基于内存的微信配置provider,在实际生产环境中应该将这些配置持久化 * @@ -23,10 +26,10 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { protected volatile String oauth2redirectUri; - protected volatile String http_proxy_host; - protected volatile int http_proxy_port; - protected volatile String http_proxy_username; - protected volatile String http_proxy_password; + protected volatile String httpProxyHost; + protected volatile int httpProxyPort; + protected volatile String httpProxyUsername; + protected volatile String httpProxyPassword; protected volatile String jsapiTicket; protected volatile long jsapiTicketExpiresTime; @@ -35,6 +38,7 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { private volatile ApacheHttpClientBuilder apacheHttpClientBuilder; + @Override public String getAccessToken() { return this.accessToken; } @@ -43,18 +47,22 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { this.accessToken = accessToken; } + @Override public boolean isAccessTokenExpired() { return System.currentTimeMillis() > this.expiresTime; } + @Override public void expireAccessToken() { this.expiresTime = 0; } + @Override public synchronized void updateAccessToken(WxAccessToken accessToken) { updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn()); } + @Override public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) { this.accessToken = accessToken; this.expiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000l; @@ -62,7 +70,7 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { @Override public String getJsapiTicket() { - return jsapiTicket; + return this.jsapiTicket; } public void setJsapiTicket(String jsapiTicket) { @@ -70,27 +78,31 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { } public long getJsapiTicketExpiresTime() { - return jsapiTicketExpiresTime; + return this.jsapiTicketExpiresTime; } public void setJsapiTicketExpiresTime(long jsapiTicketExpiresTime) { this.jsapiTicketExpiresTime = jsapiTicketExpiresTime; } + @Override public boolean isJsapiTicketExpired() { return System.currentTimeMillis() > this.jsapiTicketExpiresTime; } + @Override public synchronized void updateJsapiTicket(String jsapiTicket, int expiresInSeconds) { this.jsapiTicket = jsapiTicket; // 预留200秒的时间 this.jsapiTicketExpiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000l; } + @Override public void expireJsapiTicket() { this.jsapiTicketExpiresTime = 0; } + @Override public String getCorpId() { return this.corpId; } @@ -99,6 +111,7 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { this.corpId = corpId; } + @Override public String getCorpSecret() { return this.corpSecret; } @@ -107,6 +120,7 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { this.corpSecret = corpSecret; } + @Override public String getToken() { return this.token; } @@ -115,6 +129,7 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { this.token = token; } + @Override public long getExpiresTime() { return this.expiresTime; } @@ -123,16 +138,18 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { this.expiresTime = expiresTime; } + @Override public String getAesKey() { - return aesKey; + return this.aesKey; } public void setAesKey(String aesKey) { this.aesKey = aesKey; } + @Override public String getAgentId() { - return agentId; + return this.agentId; } public void setAgentId(String agentId) { @@ -148,60 +165,50 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { this.oauth2redirectUri = oauth2redirectUri; } - public String getHttp_proxy_host() { - return http_proxy_host; + @Override + public String getHttpProxyHost() { + return this.httpProxyHost; } - public void setHttp_proxy_host(String http_proxy_host) { - this.http_proxy_host = http_proxy_host; + public void setHttpProxyHost(String httpProxyHost) { + this.httpProxyHost = httpProxyHost; } - public int getHttp_proxy_port() { - return http_proxy_port; + @Override + public int getHttpProxyPort() { + return this.httpProxyPort; } - public void setHttp_proxy_port(int http_proxy_port) { - this.http_proxy_port = http_proxy_port; + public void setHttpProxyPort(int httpProxyPort) { + this.httpProxyPort = httpProxyPort; } - public String getHttp_proxy_username() { - return http_proxy_username; + @Override + public String getHttpProxyUsername() { + return this.httpProxyUsername; } - public void setHttp_proxy_username(String http_proxy_username) { - this.http_proxy_username = http_proxy_username; + public void setHttpProxyUsername(String httpProxyUsername) { + this.httpProxyUsername = httpProxyUsername; } - public String getHttp_proxy_password() { - return http_proxy_password; + @Override + public String getHttpProxyPassword() { + return this.httpProxyPassword; } - public void setHttp_proxy_password(String http_proxy_password) { - this.http_proxy_password = http_proxy_password; + public void setHttpProxyPassword(String httpProxyPassword) { + this.httpProxyPassword = httpProxyPassword; } @Override public String toString() { - return "WxCpInMemoryConfigStorage{" + - "corpId='" + corpId + '\'' + - ", corpSecret='" + corpSecret + '\'' + - ", token='" + token + '\'' + - ", accessToken='" + accessToken + '\'' + - ", aesKey='" + aesKey + '\'' + - ", agentId='" + agentId + '\'' + - ", expiresTime=" + expiresTime + - ", http_proxy_host='" + http_proxy_host + '\'' + - ", http_proxy_port=" + http_proxy_port + - ", http_proxy_username='" + http_proxy_username + '\'' + - ", http_proxy_password='" + http_proxy_password + '\'' + - ", jsapiTicket='" + jsapiTicket + '\'' + - ", jsapiTicketExpiresTime='" + jsapiTicketExpiresTime + '\'' + - ", tmpDirFile='" + tmpDirFile + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } + @Override public File getTmpDirFile() { - return tmpDirFile; + return this.tmpDirFile; } public void setTmpDirFile(File tmpDirFile) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java index 8d3b6bbd..5209479f 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java @@ -29,10 +29,10 @@ public class WxCpJedisConfigStorage implements WxCpConfigStorage { private volatile String oauth2redirectUri; - private volatile String http_proxy_host; - private volatile int http_proxy_port; - private volatile String http_proxy_username; - private volatile String http_proxy_password; + private volatile String httpProxyHost; + private volatile int httpProxyPort; + private volatile String httpProxyUsername; + private volatile String httpProxyPassword; private volatile File tmpDirFile; @@ -185,23 +185,23 @@ public class WxCpJedisConfigStorage implements WxCpConfigStorage { } @Override - public String getHttp_proxy_host() { - return this.http_proxy_host; + public String getHttpProxyHost() { + return this.httpProxyHost; } @Override - public int getHttp_proxy_port() { - return this.http_proxy_port; + public int getHttpProxyPort() { + return this.httpProxyPort; } @Override - public String getHttp_proxy_username() { - return this.http_proxy_username; + public String getHttpProxyUsername() { + return this.httpProxyUsername; } @Override - public String getHttp_proxy_password() { - return this.http_proxy_password; + public String getHttpProxyPassword() { + return this.httpProxyPassword; } @Override @@ -240,20 +240,20 @@ public class WxCpJedisConfigStorage implements WxCpConfigStorage { this.oauth2redirectUri = oauth2redirectUri; } - public void setHttp_proxy_host(String http_proxy_host) { - this.http_proxy_host = http_proxy_host; + public void setHttpProxyHost(String httpProxyHost) { + this.httpProxyHost = httpProxyHost; } - public void setHttp_proxy_port(int http_proxy_port) { - this.http_proxy_port = http_proxy_port; + public void setHttpProxyPort(int httpProxyPort) { + this.httpProxyPort = httpProxyPort; } - public void setHttp_proxy_username(String http_proxy_username) { - this.http_proxy_username = http_proxy_username; + public void setHttpProxyUsername(String httpProxyUsername) { + this.httpProxyUsername = httpProxyUsername; } - public void setHttp_proxy_password(String http_proxy_password) { - this.http_proxy_password = http_proxy_password; + public void setHttpProxyPassword(String httpProxyPassword) { + this.httpProxyPassword = httpProxyPassword; } public void setTmpDirFile(File tmpDirFile) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouter.java index bdda1886..6d4a8a97 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouter.java @@ -52,7 +52,7 @@ public class WxCpMessageRouter { private static final int DEFAULT_THREAD_POOL_SIZE = 100; protected final Logger log = LoggerFactory.getLogger(WxCpMessageRouter.class); - private final List rules = new ArrayList(); + private final List rules = new ArrayList<>(); private final WxCpService wxCpService; @@ -142,9 +142,9 @@ public class WxCpMessageRouter { return null; } - final List matchRules = new ArrayList(); + final List matchRules = new ArrayList<>(); // 收集匹配的规则 - for (final WxCpMessageRouterRule rule : rules) { + for (final WxCpMessageRouterRule rule : this.rules) { if (rule.test(wxMessage)) { matchRules.add(rule); if (!rule.isReEnter()) { @@ -158,39 +158,40 @@ public class WxCpMessageRouter { } WxCpXmlOutMessage res = null; - final List futures = new ArrayList(); + final List futures = new ArrayList<>(); for (final WxCpMessageRouterRule rule : matchRules) { // 返回最后一个非异步的rule的执行结果 if (rule.isAsync()) { futures.add( - executorService.submit(new Runnable() { + this.executorService.submit(new Runnable() { + @Override public void run() { - rule.service(wxMessage, wxCpService, sessionManager, exceptionHandler); + rule.service(wxMessage, WxCpMessageRouter.this.wxCpService, WxCpMessageRouter.this.sessionManager, WxCpMessageRouter.this.exceptionHandler); } }) ); } else { - res = rule.service(wxMessage, wxCpService, sessionManager, exceptionHandler); + res = rule.service(wxMessage, this.wxCpService, this.sessionManager, this.exceptionHandler); // 在同步操作结束,session访问结束 - log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUserName()); + this.log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUserName()); sessionEndAccess(wxMessage); } } if (futures.size() > 0) { - executorService.submit(new Runnable() { + this.executorService.submit(new Runnable() { @Override public void run() { for (Future future : futures) { try { future.get(); - log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUserName()); + WxCpMessageRouter.this.log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUserName()); // 异步操作结束,session访问结束 sessionEndAccess(wxMessage); } catch (InterruptedException e) { - log.error("Error happened when wait task finish", e); + WxCpMessageRouter.this.log.error("Error happened when wait task finish", e); } catch (ExecutionException e) { - log.error("Error happened when wait task finish", e); + WxCpMessageRouter.this.log.error("Error happened when wait task finish", e); } } } @@ -213,7 +214,7 @@ public class WxCpMessageRouter { messageId = String.valueOf(wxMessage.getMsgId()); } - return messageDuplicateChecker.isDuplicate(messageId); + return this.messageDuplicateChecker.isDuplicate(messageId); } @@ -224,7 +225,7 @@ public class WxCpMessageRouter { */ protected void sessionEndAccess(WxCpXmlMessage wxMessage) { - InternalSession session = ((InternalSessionManager) sessionManager).findSession(wxMessage.getFromUserName()); + InternalSession session = ((InternalSessionManager) this.sessionManager).findSession(wxMessage.getFromUserName()); if (session != null) { session.endAccess(); } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouterRule.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouterRule.java index a987841c..c81f045f 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouterRule.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouterRule.java @@ -36,9 +36,9 @@ public class WxCpMessageRouterRule { private Integer agentId; - private List handlers = new ArrayList(); + private List handlers = new ArrayList<>(); - private List interceptors = new ArrayList(); + private List interceptors = new ArrayList<>(); protected WxCpMessageRouterRule(WxCpMessageRouter routerBuilder) { this.routerBuilder = routerBuilder; @@ -235,7 +235,7 @@ public class WxCpMessageRouterRule { try { - Map context = new HashMap(); + Map context = new HashMap<>(); // 如果拦截器不通过 for (WxCpMessageInterceptor interceptor : this.interceptors) { if (!interceptor.intercept(wxMessage, context, wxCpService, sessionManager)) { @@ -300,7 +300,7 @@ public class WxCpMessageRouterRule { } public boolean isAsync() { - return async; + return this.async; } public void setAsync(boolean async) { @@ -308,7 +308,7 @@ public class WxCpMessageRouterRule { } public boolean isReEnter() { - return reEnter; + return this.reEnter; } public void setReEnter(boolean reEnter) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java index 278fe6c8..e3723a71 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java @@ -1,12 +1,28 @@ package me.chanjar.weixin.cp.api; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.UUID; + +import org.apache.http.HttpHost; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; -import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; + import me.chanjar.weixin.common.bean.WxAccessToken; import me.chanjar.weixin.common.bean.WxJsapiSignature; import me.chanjar.weixin.common.bean.menu.WxMenu; @@ -20,30 +36,20 @@ import me.chanjar.weixin.common.util.RandomUtils; import me.chanjar.weixin.common.util.StringUtils; import me.chanjar.weixin.common.util.crypto.SHA1; import me.chanjar.weixin.common.util.fs.FileUtils; -import me.chanjar.weixin.common.util.http.*; +import me.chanjar.weixin.common.util.http.ApacheHttpClientBuilder; +import me.chanjar.weixin.common.util.http.DefaultApacheHttpClientBuilder; +import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor; +import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; +import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; +import me.chanjar.weixin.common.util.http.URIUtil; import me.chanjar.weixin.common.util.json.GsonHelper; import me.chanjar.weixin.cp.bean.WxCpDepart; import me.chanjar.weixin.cp.bean.WxCpMessage; import me.chanjar.weixin.cp.bean.WxCpTag; import me.chanjar.weixin.cp.bean.WxCpUser; import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; -import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.BasicResponseHandler; -import org.apache.http.impl.client.CloseableHttpClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.UUID; public class WxCpServiceImpl implements WxCpService { @@ -59,7 +65,7 @@ public class WxCpServiceImpl implements WxCpService { */ protected final Object globalJsapiTicketRefreshLock = new Object(); - protected WxCpConfigStorage wxCpConfigStorage; + protected WxCpConfigStorage configStorage; protected CloseableHttpClient httpClient; @@ -72,42 +78,48 @@ public class WxCpServiceImpl implements WxCpService { private int retrySleepMillis = 1000; private int maxRetryTimes = 5; + @Override public boolean checkSignature(String msgSignature, String timestamp, String nonce, String data) { try { - return SHA1.gen(wxCpConfigStorage.getToken(), timestamp, nonce, data).equals(msgSignature); + return SHA1.gen(this.configStorage.getToken(), timestamp, nonce, data) + .equals(msgSignature); } catch (Exception e) { return false; } } + @Override public void userAuthenticated(String userId) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?userid=" + userId; get(url, null); } + @Override public String getAccessToken() throws WxErrorException { return getAccessToken(false); } + @Override public String getAccessToken(boolean forceRefresh) throws WxErrorException { if (forceRefresh) { - wxCpConfigStorage.expireAccessToken(); + this.configStorage.expireAccessToken(); } - if (wxCpConfigStorage.isAccessTokenExpired()) { - synchronized (globalAccessTokenRefreshLock) { - if (wxCpConfigStorage.isAccessTokenExpired()) { + if (this.configStorage.isAccessTokenExpired()) { + synchronized (this.globalAccessTokenRefreshLock) { + if (this.configStorage.isAccessTokenExpired()) { String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?" - + "&corpid=" + wxCpConfigStorage.getCorpId() - + "&corpsecret=" + wxCpConfigStorage.getCorpSecret(); + + "&corpid=" + this.configStorage.getCorpId() + + "&corpsecret=" + this.configStorage.getCorpSecret(); try { HttpGet httpGet = new HttpGet(url); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); + if (this.httpProxy != null) { + RequestConfig config = RequestConfig.custom() + .setProxy(this.httpProxy).build(); httpGet.setConfig(config); } - CloseableHttpClient httpclient = getHttpclient(); String resultContent = null; - try (CloseableHttpResponse response = httpclient.execute(httpGet)) { + try (CloseableHttpClient httpclient = getHttpclient(); + CloseableHttpResponse response = httpclient.execute(httpGet)) { resultContent = new BasicResponseHandler().handleResponse(response); } finally { httpGet.releaseConnection(); @@ -117,7 +129,8 @@ public class WxCpServiceImpl implements WxCpService { throw new WxErrorException(error); } WxAccessToken accessToken = WxAccessToken.fromJson(resultContent); - wxCpConfigStorage.updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn()); + this.configStorage.updateAccessToken( + accessToken.getAccessToken(), accessToken.getExpiresIn()); } catch (ClientProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { @@ -126,59 +139,60 @@ public class WxCpServiceImpl implements WxCpService { } } } - return wxCpConfigStorage.getAccessToken(); + return this.configStorage.getAccessToken(); } + @Override public String getJsapiTicket() throws WxErrorException { return getJsapiTicket(false); } + @Override public String getJsapiTicket(boolean forceRefresh) throws WxErrorException { if (forceRefresh) { - wxCpConfigStorage.expireJsapiTicket(); + this.configStorage.expireJsapiTicket(); } - if (wxCpConfigStorage.isJsapiTicketExpired()) { - synchronized (globalJsapiTicketRefreshLock) { - if (wxCpConfigStorage.isJsapiTicketExpired()) { + if (this.configStorage.isJsapiTicketExpired()) { + synchronized (this.globalJsapiTicketRefreshLock) { + if (this.configStorage.isJsapiTicketExpired()) { String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket"; String responseContent = execute(new SimpleGetRequestExecutor(), url, null); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String jsapiTicket = tmpJsonObject.get("ticket").getAsString(); int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt(); - wxCpConfigStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds); + this.configStorage.updateJsapiTicket(jsapiTicket, + expiresInSeconds); } } } - return wxCpConfigStorage.getJsapiTicket(); + return this.configStorage.getJsapiTicket(); } + @Override public WxJsapiSignature createJsapiSignature(String url) throws WxErrorException { long timestamp = System.currentTimeMillis() / 1000; String noncestr = RandomUtils.getRandomStr(); String jsapiTicket = getJsapiTicket(false); - try { - String signature = SHA1.genWithAmple( - "jsapi_ticket=" + jsapiTicket, - "noncestr=" + noncestr, - "timestamp=" + timestamp, - "url=" + url - ); - WxJsapiSignature jsapiSignature = new WxJsapiSignature(); - jsapiSignature.setTimestamp(timestamp); - jsapiSignature.setNoncestr(noncestr); - jsapiSignature.setUrl(url); - jsapiSignature.setSignature(signature); - - // Fixed bug - jsapiSignature.setAppid(this.wxCpConfigStorage.getCorpId()); - - return jsapiSignature; - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } + String signature = SHA1.genWithAmple( + "jsapi_ticket=" + jsapiTicket, + "noncestr=" + noncestr, + "timestamp=" + timestamp, + "url=" + url + ); + WxJsapiSignature jsapiSignature = new WxJsapiSignature(); + jsapiSignature.setTimestamp(timestamp); + jsapiSignature.setNoncestr(noncestr); + jsapiSignature.setUrl(url); + jsapiSignature.setSignature(signature); + + // Fixed bug + jsapiSignature.setAppid(this.configStorage.getCorpId()); + + return jsapiSignature; } + @Override public void messageSend(WxCpMessage message) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"; post(url, message.toJson()); @@ -186,18 +200,19 @@ public class WxCpServiceImpl implements WxCpService { @Override public void menuCreate(WxMenu menu) throws WxErrorException { - menuCreate(wxCpConfigStorage.getAgentId(), menu); + menuCreate(this.configStorage.getAgentId(), menu); } @Override public void menuCreate(String agentId, WxMenu menu) throws WxErrorException { - String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?agentid=" + wxCpConfigStorage.getAgentId(); + String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?agentid=" + + this.configStorage.getAgentId(); post(url, menu.toJson()); } @Override public void menuDelete() throws WxErrorException { - menuDelete(wxCpConfigStorage.getAgentId()); + menuDelete(this.configStorage.getAgentId()); } @Override @@ -208,7 +223,7 @@ public class WxCpServiceImpl implements WxCpService { @Override public WxMenu menuGet() throws WxErrorException { - return menuGet(wxCpConfigStorage.getAgentId()); + return menuGet(this.configStorage.getAgentId()); } @Override @@ -226,42 +241,52 @@ public class WxCpServiceImpl implements WxCpService { } } + @Override public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream) throws WxErrorException, IOException { return mediaUpload(mediaType, FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType)); } + @Override public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType; return execute(new MediaUploadRequestExecutor(), url, file); } + @Override public File mediaDownload(String media_id) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/media/get"; - return execute(new MediaDownloadRequestExecutor(wxCpConfigStorage.getTmpDirFile()), url, "media_id=" + media_id); + return execute( + new MediaDownloadRequestExecutor( +this.configStorage.getTmpDirFile()), + url, "media_id=" + media_id); } + @Override public Integer departCreate(WxCpDepart depart) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create"; String responseContent = execute( new SimplePostRequestExecutor(), url, depart.toJson()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return GsonHelper.getAsInteger(tmpJsonElement.getAsJsonObject().get("id")); } + @Override public void departUpdate(WxCpDepart group) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/department/update"; post(url, group.toJson()); } + @Override public void departDelete(Integer departId) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?id=" + departId; get(url, null); } + @Override public List departGet() throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list"; String responseContent = get(url, null); @@ -269,7 +294,7 @@ public class WxCpServiceImpl implements WxCpService { * 操蛋的微信API,创建时返回的是 { group : { id : ..., name : ...} } * 查询时返回的是 { groups : [ { id : ..., name : ..., count : ... }, ... ] } */ - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("department"), @@ -329,7 +354,7 @@ public class WxCpServiceImpl implements WxCpService { } String responseContent = get(url, params); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("userlist"), @@ -352,7 +377,7 @@ public class WxCpServiceImpl implements WxCpService { } String responseContent = get(url, params); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("userlist"), @@ -367,7 +392,7 @@ public class WxCpServiceImpl implements WxCpService { JsonObject o = new JsonObject(); o.addProperty("tagname", tagName); String responseContent = post(url, o.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return tmpJsonElement.getAsJsonObject().get("tagid").getAsString(); } @@ -390,7 +415,7 @@ public class WxCpServiceImpl implements WxCpService { public List tagGet() throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list"; String responseContent = get(url, null); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("taglist"), @@ -403,7 +428,7 @@ public class WxCpServiceImpl implements WxCpService { public List tagGetUsers(String tagId) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/get?tagid=" + tagId; String responseContent = get(url, null); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxCpGsonBuilder.INSTANCE.create() .fromJson( tmpJsonElement.getAsJsonObject().get("userlist"), @@ -450,7 +475,7 @@ public class WxCpServiceImpl implements WxCpService { @Override public String oauth2buildAuthorizationUrl(String state) { return this.oauth2buildAuthorizationUrl( - this.wxCpConfigStorage.getOauth2redirectUri(), +this.configStorage.getOauth2redirectUri(), state ); } @@ -458,7 +483,7 @@ public class WxCpServiceImpl implements WxCpService { @Override public String oauth2buildAuthorizationUrl(String redirectUri, String state) { String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"; - url += "appid=" + wxCpConfigStorage.getCorpId(); + url += "appid=" + this.configStorage.getCorpId(); url += "&redirect_uri=" + URIUtil.encodeURIComponent(redirectUri); url += "&response_type=code"; url += "&scope=snsapi_base"; @@ -471,7 +496,7 @@ public class WxCpServiceImpl implements WxCpService { @Override public String[] oauth2getUserInfo(String code) throws WxErrorException { - return oauth2getUserInfo(wxCpConfigStorage.getAgentId(), code); + return oauth2getUserInfo(this.configStorage.getAgentId(), code); } @Override @@ -480,7 +505,7 @@ public class WxCpServiceImpl implements WxCpService { + "code=" + code + "&agendid=" + agentId; String responseText = get(url, null); - JsonElement je = Streams.parse(new JsonReader(new StringReader(responseText))); + JsonElement je = new JsonParser().parse(responseText); JsonObject jo = je.getAsJsonObject(); return new String[]{GsonHelper.getString(jo, "UserId"), GsonHelper.getString(jo, "DeviceId")}; } @@ -494,7 +519,7 @@ public class WxCpServiceImpl implements WxCpService { jsonObject.addProperty("invite_tips", inviteTips); } String responseContent = post(url, jsonObject.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return tmpJsonElement.getAsJsonObject().get("type").getAsInt(); } @@ -502,7 +527,7 @@ public class WxCpServiceImpl implements WxCpService { public String[] getCallbackIp() throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/getcallbackip"; String responseContent = get(url, null); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); JsonArray jsonArray = tmpJsonElement.getAsJsonObject().get("ip_list").getAsJsonArray(); String[] ips = new String[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { @@ -511,10 +536,12 @@ public class WxCpServiceImpl implements WxCpService { return ips; } + @Override public String get(String url, String queryParam) throws WxErrorException { return execute(new SimpleGetRequestExecutor(), url, queryParam); } + @Override public String post(String url, String postData) throws WxErrorException { return execute(new SimplePostRequestExecutor(), url, postData); } @@ -522,6 +549,7 @@ public class WxCpServiceImpl implements WxCpService { /** * 向微信端发送请求,在这里执行的策略是当发生access_token过期时才去刷新,然后重新执行请求,而不是全局定时请求 */ + @Override public T execute(RequestExecutor executor, String uri, E data) throws WxErrorException { int retryTimes = 0; do { @@ -533,9 +561,10 @@ public class WxCpServiceImpl implements WxCpService { * -1 系统繁忙, 1000ms后重试 */ if (error.getErrorCode() == -1) { - int sleepMillis = retrySleepMillis * (1 << retryTimes); + int sleepMillis = this.retrySleepMillis * (1 << retryTimes); try { - log.debug("微信系统繁忙,{}ms 后重试(第{}次)", sleepMillis, retryTimes + 1); + this.log.debug("微信系统繁忙,{}ms 后重试(第{}次)", sleepMillis, + retryTimes + 1); Thread.sleep(sleepMillis); } catch (InterruptedException e1) { throw new RuntimeException(e1); @@ -544,7 +573,7 @@ public class WxCpServiceImpl implements WxCpService { throw e; } } - } while (++retryTimes < maxRetryTimes); + } while (++retryTimes < this.maxRetryTimes); throw new RuntimeException("微信服务端异常,超出重试次数"); } @@ -559,7 +588,8 @@ public class WxCpServiceImpl implements WxCpService { uriWithAccessToken += uri.indexOf('?') == -1 ? "?access_token=" + accessToken : "&access_token=" + accessToken; try { - return executor.execute(getHttpclient(), httpProxy, uriWithAccessToken, data); + return executor.execute(getHttpclient(), this.httpProxy, + uriWithAccessToken, data); } catch (WxErrorException e) { WxError error = e.getError(); /* @@ -569,7 +599,7 @@ public class WxCpServiceImpl implements WxCpService { */ if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001) { // 强制设置wxCpConfigStorage它的access token过期了,这样在下一次请求里就会刷新access token - wxCpConfigStorage.expireAccessToken(); + this.configStorage.expireAccessToken(); return execute(executor, uri, data); } if (error.getErrorCode() != 0) { @@ -584,21 +614,28 @@ public class WxCpServiceImpl implements WxCpService { } protected CloseableHttpClient getHttpclient() { - return httpClient; + return this.httpClient; } + @Override public void setWxCpConfigStorage(WxCpConfigStorage wxConfigProvider) { - this.wxCpConfigStorage = wxConfigProvider; - ApacheHttpClientBuilder apacheHttpClientBuilder = wxCpConfigStorage.getApacheHttpClientBuilder(); + this.configStorage = wxConfigProvider; + ApacheHttpClientBuilder apacheHttpClientBuilder = this.configStorage + .getApacheHttpClientBuilder(); if (null == apacheHttpClientBuilder) { apacheHttpClientBuilder = DefaultApacheHttpClientBuilder.get(); } - apacheHttpClientBuilder.httpProxyHost(wxCpConfigStorage.getHttp_proxy_host()) - .httpProxyPort(wxCpConfigStorage.getHttp_proxy_port()) - .httpProxyUsername(wxCpConfigStorage.getHttp_proxy_username()) - .httpProxyPassword(wxCpConfigStorage.getHttp_proxy_password()); - httpClient = apacheHttpClientBuilder.build(); + apacheHttpClientBuilder.httpProxyHost(this.configStorage.getHttpProxyHost()) + .httpProxyPort(this.configStorage.getHttpProxyPort()) + .httpProxyUsername(this.configStorage.getHttpProxyUsername()) + .httpProxyPassword(this.configStorage.getHttpProxyPassword()); + + if (this.configStorage.getHttpProxyHost() != null && this.configStorage.getHttpProxyPort() > 0) { + this.httpProxy = new HttpHost(this.configStorage.getHttpProxyHost(), this.configStorage.getHttpProxyPort()); + } + + this.httpClient = apacheHttpClientBuilder.build(); } @Override @@ -614,18 +651,18 @@ public class WxCpServiceImpl implements WxCpService { @Override public WxSession getSession(String id) { - if (sessionManager == null) { + if (this.sessionManager == null) { return null; } - return sessionManager.getSession(id); + return this.sessionManager.getSession(id); } @Override public WxSession getSession(String id, boolean create) { - if (sessionManager == null) { + if (this.sessionManager == null) { return null; } - return sessionManager.getSession(id, create); + return this.sessionManager.getSession(id, create); } @@ -657,7 +694,7 @@ public class WxCpServiceImpl implements WxCpService { } public File getTmpDirFile() { - return tmpDirFile; + return this.tmpDirFile; } public void setTmpDirFile(File tmpDirFile) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java index e2bfbd39..c8735086 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java @@ -11,6 +11,10 @@ import java.io.Serializable; */ public class WxCpDepart implements Serializable { + /** + * + */ + private static final long serialVersionUID = -5028321625140879571L; private Integer id; private String name; private Integer parentId; @@ -21,7 +25,7 @@ public class WxCpDepart implements Serializable { } public Integer getId() { - return id; + return this.id; } public void setId(Integer id) { @@ -29,7 +33,7 @@ public class WxCpDepart implements Serializable { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -37,7 +41,7 @@ public class WxCpDepart implements Serializable { } public Integer getParentId() { - return parentId; + return this.parentId; } public void setParentId(Integer parentId) { @@ -45,7 +49,7 @@ public class WxCpDepart implements Serializable { } public Integer getOrder() { - return order; + return this.order; } public void setOrder(Integer order) { @@ -59,10 +63,10 @@ public class WxCpDepart implements Serializable { @Override public String toString() { return "WxCpDepart{" + - "id=" + id + - ", name='" + name + '\'' + - ", parentId=" + parentId + - ", order=" + order + + "id=" + this.id + + ", name='" + this.name + '\'' + + ", parentId=" + this.parentId + + ", order=" + this.order + '}'; } } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java index 89611525..6dba9091 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java @@ -14,6 +14,10 @@ import java.util.List; */ public class WxCpMessage implements Serializable { + /** + * + */ + private static final long serialVersionUID = -2082278303476631708L; private String toUser; private String toParty; private String toTag; @@ -27,7 +31,7 @@ public class WxCpMessage implements Serializable { private String musicUrl; private String hqMusicUrl; private String safe; - private List articles = new ArrayList(); + private List articles = new ArrayList<>(); /** * 获得文本消息builder @@ -72,7 +76,7 @@ public class WxCpMessage implements Serializable { } public String getToUser() { - return toUser; + return this.toUser; } public void setToUser(String toUser) { @@ -80,7 +84,7 @@ public class WxCpMessage implements Serializable { } public String getToParty() { - return toParty; + return this.toParty; } public void setToParty(String toParty) { @@ -88,7 +92,7 @@ public class WxCpMessage implements Serializable { } public String getToTag() { - return toTag; + return this.toTag; } public void setToTag(String toTag) { @@ -96,7 +100,7 @@ public class WxCpMessage implements Serializable { } public String getAgentId() { - return agentId; + return this.agentId; } public void setAgentId(String agentId) { @@ -104,7 +108,7 @@ public class WxCpMessage implements Serializable { } public String getMsgType() { - return msgType; + return this.msgType; } /** @@ -125,7 +129,7 @@ public class WxCpMessage implements Serializable { } public String getSafe() { - return safe; + return this.safe; } public void setSafe(String safe) { @@ -133,7 +137,7 @@ public class WxCpMessage implements Serializable { } public String getContent() { - return content; + return this.content; } public void setContent(String content) { @@ -141,7 +145,7 @@ public class WxCpMessage implements Serializable { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -149,7 +153,7 @@ public class WxCpMessage implements Serializable { } public String getThumbMediaId() { - return thumbMediaId; + return this.thumbMediaId; } public void setThumbMediaId(String thumbMediaId) { @@ -157,7 +161,7 @@ public class WxCpMessage implements Serializable { } public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -165,7 +169,7 @@ public class WxCpMessage implements Serializable { } public String getDescription() { - return description; + return this.description; } public void setDescription(String description) { @@ -173,7 +177,7 @@ public class WxCpMessage implements Serializable { } public String getMusicUrl() { - return musicUrl; + return this.musicUrl; } public void setMusicUrl(String musicUrl) { @@ -181,7 +185,7 @@ public class WxCpMessage implements Serializable { } public String getHqMusicUrl() { - return hqMusicUrl; + return this.hqMusicUrl; } public void setHqMusicUrl(String hqMusicUrl) { @@ -189,7 +193,7 @@ public class WxCpMessage implements Serializable { } public List getArticles() { - return articles; + return this.articles; } public void setArticles(List articles) { @@ -208,7 +212,7 @@ public class WxCpMessage implements Serializable { private String picUrl; public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -216,7 +220,7 @@ public class WxCpMessage implements Serializable { } public String getDescription() { - return description; + return this.description; } public void setDescription(String description) { @@ -224,7 +228,7 @@ public class WxCpMessage implements Serializable { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { @@ -232,7 +236,7 @@ public class WxCpMessage implements Serializable { } public String getPicUrl() { - return picUrl; + return this.picUrl; } public void setPicUrl(String picUrl) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java index 72fd6628..ca11cb1f 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java @@ -9,6 +9,11 @@ import java.io.Serializable; */ public class WxCpTag implements Serializable { + /** + * + */ + private static final long serialVersionUID = -7243320279646928402L; + private String id; private String name; @@ -28,7 +33,7 @@ public class WxCpTag implements Serializable { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -36,7 +41,7 @@ public class WxCpTag implements Serializable { } public String getId() { - return id; + return this.id; } public void setId(String id) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java index e96206eb..d1737d5d 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java @@ -13,7 +13,11 @@ import java.util.List; */ public class WxCpUser implements Serializable { - private final List extAttrs = new ArrayList(); + /** + * + */ + private static final long serialVersionUID = -5696099236344075582L; + private final List extAttrs = new ArrayList<>(); private String userId; private String name; private Integer[] departIds; @@ -32,7 +36,7 @@ public class WxCpUser implements Serializable { } public String getUserId() { - return userId; + return this.userId; } public void setUserId(String userId) { @@ -40,7 +44,7 @@ public class WxCpUser implements Serializable { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -48,7 +52,7 @@ public class WxCpUser implements Serializable { } public Integer[] getDepartIds() { - return departIds; + return this.departIds; } public void setDepartIds(Integer[] departIds) { @@ -56,7 +60,7 @@ public class WxCpUser implements Serializable { } public String getGender() { - return gender; + return this.gender; } public void setGender(String gender) { @@ -64,7 +68,7 @@ public class WxCpUser implements Serializable { } public String getPosition() { - return position; + return this.position; } public void setPosition(String position) { @@ -72,7 +76,7 @@ public class WxCpUser implements Serializable { } public String getMobile() { - return mobile; + return this.mobile; } public void setMobile(String mobile) { @@ -80,7 +84,7 @@ public class WxCpUser implements Serializable { } public String getTel() { - return tel; + return this.tel; } public void setTel(String tel) { @@ -88,7 +92,7 @@ public class WxCpUser implements Serializable { } public String getEmail() { - return email; + return this.email; } public void setEmail(String email) { @@ -96,7 +100,7 @@ public class WxCpUser implements Serializable { } public String getWeiXinId() { - return weiXinId; + return this.weiXinId; } public void setWeiXinId(String weiXinId) { @@ -104,7 +108,7 @@ public class WxCpUser implements Serializable { } public String getAvatar() { - return avatar; + return this.avatar; } public void setAvatar(String avatar) { @@ -112,7 +116,7 @@ public class WxCpUser implements Serializable { } public Integer getStatus() { - return status; + return this.status; } public void setStatus(Integer status) { @@ -120,7 +124,7 @@ public class WxCpUser implements Serializable { } public Integer getEnable() { - return enable; + return this.enable; } public void setEnable(Integer enable) { @@ -132,7 +136,7 @@ public class WxCpUser implements Serializable { } public List getExtAttrs() { - return extAttrs; + return this.extAttrs; } public String toJson() { @@ -150,7 +154,7 @@ public class WxCpUser implements Serializable { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -158,7 +162,7 @@ public class WxCpUser implements Serializable { } public String getValue() { - return value; + return this.value; } public void setValue(String value) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java index 0b833e06..352fa2e6 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java @@ -32,6 +32,11 @@ public class WxCpXmlMessage implements Serializable { // 以下都是微信推送过来的消息的xml的element所对应的属性 /////////////////////// + /** + * + */ + private static final long serialVersionUID = -1042994982179476410L; + @XStreamAlias("AgentID") private Integer agentId; @@ -200,7 +205,7 @@ public class WxCpXmlMessage implements Serializable { } public Integer getAgentId() { - return agentId; + return this.agentId; } public void setAgentId(Integer agentId) { @@ -208,7 +213,7 @@ public class WxCpXmlMessage implements Serializable { } public String getToUserName() { - return toUserName; + return this.toUserName; } public void setToUserName(String toUserName) { @@ -216,7 +221,7 @@ public class WxCpXmlMessage implements Serializable { } public Long getCreateTime() { - return createTime; + return this.createTime; } public void setCreateTime(Long createTime) { @@ -236,7 +241,7 @@ public class WxCpXmlMessage implements Serializable { * */ public String getMsgType() { - return msgType; + return this.msgType; } /** @@ -256,7 +261,7 @@ public class WxCpXmlMessage implements Serializable { } public String getContent() { - return content; + return this.content; } public void setContent(String content) { @@ -264,7 +269,7 @@ public class WxCpXmlMessage implements Serializable { } public Long getMsgId() { - return msgId; + return this.msgId; } public void setMsgId(Long msgId) { @@ -272,7 +277,7 @@ public class WxCpXmlMessage implements Serializable { } public String getPicUrl() { - return picUrl; + return this.picUrl; } public void setPicUrl(String picUrl) { @@ -280,7 +285,7 @@ public class WxCpXmlMessage implements Serializable { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -288,7 +293,7 @@ public class WxCpXmlMessage implements Serializable { } public String getFormat() { - return format; + return this.format; } public void setFormat(String format) { @@ -296,7 +301,7 @@ public class WxCpXmlMessage implements Serializable { } public String getThumbMediaId() { - return thumbMediaId; + return this.thumbMediaId; } public void setThumbMediaId(String thumbMediaId) { @@ -304,7 +309,7 @@ public class WxCpXmlMessage implements Serializable { } public Double getLocationX() { - return locationX; + return this.locationX; } public void setLocationX(Double locationX) { @@ -312,7 +317,7 @@ public class WxCpXmlMessage implements Serializable { } public Double getLocationY() { - return locationY; + return this.locationY; } public void setLocationY(Double locationY) { @@ -320,7 +325,7 @@ public class WxCpXmlMessage implements Serializable { } public Double getScale() { - return scale; + return this.scale; } public void setScale(Double scale) { @@ -328,7 +333,7 @@ public class WxCpXmlMessage implements Serializable { } public String getLabel() { - return label; + return this.label; } public void setLabel(String label) { @@ -336,7 +341,7 @@ public class WxCpXmlMessage implements Serializable { } public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -344,7 +349,7 @@ public class WxCpXmlMessage implements Serializable { } public String getDescription() { - return description; + return this.description; } public void setDescription(String description) { @@ -352,7 +357,7 @@ public class WxCpXmlMessage implements Serializable { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { @@ -360,7 +365,7 @@ public class WxCpXmlMessage implements Serializable { } public String getEvent() { - return event; + return this.event; } public void setEvent(String event) { @@ -368,7 +373,7 @@ public class WxCpXmlMessage implements Serializable { } public String getEventKey() { - return eventKey; + return this.eventKey; } public void setEventKey(String eventKey) { @@ -376,7 +381,7 @@ public class WxCpXmlMessage implements Serializable { } public String getTicket() { - return ticket; + return this.ticket; } public void setTicket(String ticket) { @@ -384,7 +389,7 @@ public class WxCpXmlMessage implements Serializable { } public Double getLatitude() { - return latitude; + return this.latitude; } public void setLatitude(Double latitude) { @@ -392,7 +397,7 @@ public class WxCpXmlMessage implements Serializable { } public Double getLongitude() { - return longitude; + return this.longitude; } public void setLongitude(Double longitude) { @@ -400,7 +405,7 @@ public class WxCpXmlMessage implements Serializable { } public Double getPrecision() { - return precision; + return this.precision; } public void setPrecision(Double precision) { @@ -408,7 +413,7 @@ public class WxCpXmlMessage implements Serializable { } public String getRecognition() { - return recognition; + return this.recognition; } public void setRecognition(String recognition) { @@ -416,7 +421,7 @@ public class WxCpXmlMessage implements Serializable { } public String getFromUserName() { - return fromUserName; + return this.fromUserName; } public void setFromUserName(String fromUserName) { @@ -424,7 +429,7 @@ public class WxCpXmlMessage implements Serializable { } public String getStatus() { - return status; + return this.status; } public void setStatus(String status) { @@ -432,7 +437,7 @@ public class WxCpXmlMessage implements Serializable { } public Integer getTotalCount() { - return totalCount; + return this.totalCount; } public void setTotalCount(Integer totalCount) { @@ -440,7 +445,7 @@ public class WxCpXmlMessage implements Serializable { } public Integer getFilterCount() { - return filterCount; + return this.filterCount; } public void setFilterCount(Integer filterCount) { @@ -448,7 +453,7 @@ public class WxCpXmlMessage implements Serializable { } public Integer getSentCount() { - return sentCount; + return this.sentCount; } public void setSentCount(Integer sentCount) { @@ -456,7 +461,7 @@ public class WxCpXmlMessage implements Serializable { } public Integer getErrorCount() { - return errorCount; + return this.errorCount; } public void setErrorCount(Integer errorCount) { @@ -464,7 +469,7 @@ public class WxCpXmlMessage implements Serializable { } public WxCpXmlMessage.ScanCodeInfo getScanCodeInfo() { - return scanCodeInfo; + return this.scanCodeInfo; } public void setScanCodeInfo(WxCpXmlMessage.ScanCodeInfo scanCodeInfo) { @@ -472,7 +477,7 @@ public class WxCpXmlMessage implements Serializable { } public WxCpXmlMessage.SendPicsInfo getSendPicsInfo() { - return sendPicsInfo; + return this.sendPicsInfo; } public void setSendPicsInfo(WxCpXmlMessage.SendPicsInfo sendPicsInfo) { @@ -480,7 +485,7 @@ public class WxCpXmlMessage implements Serializable { } public WxCpXmlMessage.SendLocationInfo getSendLocationInfo() { - return sendLocationInfo; + return this.sendLocationInfo; } public void setSendLocationInfo(WxCpXmlMessage.SendLocationInfo sendLocationInfo) { @@ -490,39 +495,39 @@ public class WxCpXmlMessage implements Serializable { @Override public String toString() { return "WxCpXmlMessage{" + - "agentId=" + agentId + - ", toUserName='" + toUserName + '\'' + - ", fromUserName='" + fromUserName + '\'' + - ", createTime=" + createTime + - ", msgType='" + msgType + '\'' + - ", content='" + content + '\'' + - ", msgId=" + msgId + - ", picUrl='" + picUrl + '\'' + - ", mediaId='" + mediaId + '\'' + - ", format='" + format + '\'' + - ", thumbMediaId='" + thumbMediaId + '\'' + - ", locationX=" + locationX + - ", locationY=" + locationY + - ", scale=" + scale + - ", label='" + label + '\'' + - ", title='" + title + '\'' + - ", description='" + description + '\'' + - ", url='" + url + '\'' + - ", event='" + event + '\'' + - ", eventKey='" + eventKey + '\'' + - ", ticket='" + ticket + '\'' + - ", latitude=" + latitude + - ", longitude=" + longitude + - ", precision=" + precision + - ", recognition='" + recognition + '\'' + - ", status='" + status + '\'' + - ", totalCount=" + totalCount + - ", filterCount=" + filterCount + - ", sentCount=" + sentCount + - ", errorCount=" + errorCount + - ", scanCodeInfo=" + scanCodeInfo + - ", sendPicsInfo=" + sendPicsInfo + - ", sendLocationInfo=" + sendLocationInfo + + "agentId=" + this.agentId + + ", toUserName='" + this.toUserName + '\'' + + ", fromUserName='" + this.fromUserName + '\'' + + ", createTime=" + this.createTime + + ", msgType='" + this.msgType + '\'' + + ", content='" + this.content + '\'' + + ", msgId=" + this.msgId + + ", picUrl='" + this.picUrl + '\'' + + ", mediaId='" + this.mediaId + '\'' + + ", format='" + this.format + '\'' + + ", thumbMediaId='" + this.thumbMediaId + '\'' + + ", locationX=" + this.locationX + + ", locationY=" + this.locationY + + ", scale=" + this.scale + + ", label='" + this.label + '\'' + + ", title='" + this.title + '\'' + + ", description='" + this.description + '\'' + + ", url='" + this.url + '\'' + + ", event='" + this.event + '\'' + + ", eventKey='" + this.eventKey + '\'' + + ", ticket='" + this.ticket + '\'' + + ", latitude=" + this.latitude + + ", longitude=" + this.longitude + + ", precision=" + this.precision + + ", recognition='" + this.recognition + '\'' + + ", status='" + this.status + '\'' + + ", totalCount=" + this.totalCount + + ", filterCount=" + this.filterCount + + ", sentCount=" + this.sentCount + + ", errorCount=" + this.errorCount + + ", scanCodeInfo=" + this.scanCodeInfo + + ", sendPicsInfo=" + this.sendPicsInfo + + ", sendLocationInfo=" + this.sendLocationInfo + '}'; } @@ -542,7 +547,7 @@ public class WxCpXmlMessage implements Serializable { */ public String getScanType() { - return scanType; + return this.scanType; } public void setScanType(String scanType) { @@ -553,7 +558,7 @@ public class WxCpXmlMessage implements Serializable { * 扫描结果,即二维码对应的字符串信息 */ public String getScanResult() { - return scanResult; + return this.scanResult; } public void setScanResult(String scanResult) { @@ -566,12 +571,12 @@ public class WxCpXmlMessage implements Serializable { public static class SendPicsInfo { @XStreamAlias("PicList") - protected final List picList = new ArrayList(); + protected final List picList = new ArrayList<>(); @XStreamAlias("Count") private Long count; public Long getCount() { - return count; + return this.count; } public void setCount(Long count) { @@ -579,7 +584,7 @@ public class WxCpXmlMessage implements Serializable { } public List getPicList() { - return picList; + return this.picList; } @XStreamAlias("item") @@ -590,11 +595,11 @@ public class WxCpXmlMessage implements Serializable { private String PicMd5Sum; public String getPicMd5Sum() { - return PicMd5Sum; + return this.PicMd5Sum; } public void setPicMd5Sum(String picMd5Sum) { - PicMd5Sum = picMd5Sum; + this.PicMd5Sum = picMd5Sum; } } } @@ -623,7 +628,7 @@ public class WxCpXmlMessage implements Serializable { private String poiname; public String getLocationX() { - return locationX; + return this.locationX; } public void setLocationX(String locationX) { @@ -631,7 +636,7 @@ public class WxCpXmlMessage implements Serializable { } public String getLocationY() { - return locationY; + return this.locationY; } public void setLocationY(String locationY) { @@ -639,7 +644,7 @@ public class WxCpXmlMessage implements Serializable { } public String getScale() { - return scale; + return this.scale; } public void setScale(String scale) { @@ -647,7 +652,7 @@ public class WxCpXmlMessage implements Serializable { } public String getLabel() { - return label; + return this.label; } public void setLabel(String label) { @@ -655,7 +660,7 @@ public class WxCpXmlMessage implements Serializable { } public String getPoiname() { - return poiname; + return this.poiname; } public void setPoiname(String poiname) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java index 1bf4a33f..44de8811 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java @@ -17,7 +17,7 @@ public class WxCpXmlOutImageMessage extends WxCpXmlOutMessage { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutMessage.java index 257778bf..332b5e24 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutMessage.java @@ -62,7 +62,7 @@ public abstract class WxCpXmlOutMessage { } public String getToUserName() { - return toUserName; + return this.toUserName; } public void setToUserName(String toUserName) { @@ -70,7 +70,7 @@ public abstract class WxCpXmlOutMessage { } public String getFromUserName() { - return fromUserName; + return this.fromUserName; } public void setFromUserName(String fromUserName) { @@ -78,7 +78,7 @@ public abstract class WxCpXmlOutMessage { } public Long getCreateTime() { - return createTime; + return this.createTime; } public void setCreateTime(Long createTime) { @@ -86,7 +86,7 @@ public abstract class WxCpXmlOutMessage { } public String getMsgType() { - return msgType; + return this.msgType; } public void setMsgType(String msgType) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java index 3b7ae3af..5906a324 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java @@ -12,7 +12,7 @@ import java.util.List; public class WxCpXmlOutNewsMessage extends WxCpXmlOutMessage { @XStreamAlias("Articles") - protected final List articles = new ArrayList(); + protected final List articles = new ArrayList<>(); @XStreamAlias("ArticleCount") protected int articleCount; @@ -21,7 +21,7 @@ public class WxCpXmlOutNewsMessage extends WxCpXmlOutMessage { } public int getArticleCount() { - return articleCount; + return this.articleCount; } public void addArticle(Item item) { @@ -30,7 +30,7 @@ public class WxCpXmlOutNewsMessage extends WxCpXmlOutMessage { } public List getArticles() { - return articles; + return this.articles; } @@ -54,35 +54,35 @@ public class WxCpXmlOutNewsMessage extends WxCpXmlOutMessage { private String Url; public String getTitle() { - return Title; + return this.Title; } public void setTitle(String title) { - Title = title; + this.Title = title; } public String getDescription() { - return Description; + return this.Description; } public void setDescription(String description) { - Description = description; + this.Description = description; } public String getPicUrl() { - return PicUrl; + return this.PicUrl; } public void setPicUrl(String picUrl) { - PicUrl = picUrl; + this.PicUrl = picUrl; } public String getUrl() { - return Url; + return this.Url; } public void setUrl(String url) { - Url = url; + this.Url = url; } } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java index e9dd7183..3c59edf9 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java @@ -17,7 +17,7 @@ public class WxCpXmlOutTextMessage extends WxCpXmlOutMessage { } public String getContent() { - return content; + return this.content; } public void setContent(String content) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java index b5e15801..6e2f268f 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java @@ -16,27 +16,27 @@ public class WxCpXmlOutVideoMessage extends WxCpXmlOutMessage { } public String getMediaId() { - return video.getMediaId(); + return this.video.getMediaId(); } public void setMediaId(String mediaId) { - video.setMediaId(mediaId); + this.video.setMediaId(mediaId); } public String getTitle() { - return video.getTitle(); + return this.video.getTitle(); } public void setTitle(String title) { - video.setTitle(title); + this.video.setTitle(title); } public String getDescription() { - return video.getDescription(); + return this.video.getDescription(); } public void setDescription(String description) { - video.setDescription(description); + this.video.setDescription(description); } @@ -56,7 +56,7 @@ public class WxCpXmlOutVideoMessage extends WxCpXmlOutMessage { private String description; public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -64,7 +64,7 @@ public class WxCpXmlOutVideoMessage extends WxCpXmlOutMessage { } public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -72,7 +72,7 @@ public class WxCpXmlOutVideoMessage extends WxCpXmlOutMessage { } public String getDescription() { - return description; + return this.description; } public void setDescription(String description) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java index 1730a0cf..1fd6d4ce 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java @@ -17,7 +17,7 @@ public class WxCpXmlOutVoiceMessage extends WxCpXmlOutMessage { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/FileBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/FileBuilder.java index d8295454..1da78169 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/FileBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/FileBuilder.java @@ -23,6 +23,7 @@ public final class FileBuilder extends BaseBuilder { return this; } + @Override public WxCpMessage build() { WxCpMessage m = super.build(); m.setMediaId(this.mediaId); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/ImageBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/ImageBuilder.java index 99195c26..a74f5016 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/ImageBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/ImageBuilder.java @@ -23,6 +23,7 @@ public final class ImageBuilder extends BaseBuilder { return this; } + @Override public WxCpMessage build() { WxCpMessage m = super.build(); m.setMediaId(this.mediaId); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/NewsBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/NewsBuilder.java index e2d2086a..8ea90872 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/NewsBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/NewsBuilder.java @@ -17,7 +17,7 @@ import java.util.List; */ public final class NewsBuilder extends BaseBuilder { - private List articles = new ArrayList(); + private List articles = new ArrayList<>(); public NewsBuilder() { this.msgType = WxConsts.CUSTOM_MSG_NEWS; @@ -28,6 +28,7 @@ public final class NewsBuilder extends BaseBuilder { return this; } + @Override public WxCpMessage build() { WxCpMessage m = super.build(); m.setArticles(this.articles); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/TextBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/TextBuilder.java index 076db2f1..8c1ee1d0 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/TextBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/TextBuilder.java @@ -23,6 +23,7 @@ public final class TextBuilder extends BaseBuilder { return this; } + @Override public WxCpMessage build() { WxCpMessage m = super.build(); m.setContent(this.content); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VideoBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VideoBuilder.java index 66dfc553..52cba287 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VideoBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VideoBuilder.java @@ -47,12 +47,13 @@ public final class VideoBuilder extends BaseBuilder { return this; } + @Override public WxCpMessage build() { WxCpMessage m = super.build(); m.setMediaId(this.mediaId); - m.setTitle(title); - m.setDescription(description); - m.setThumbMediaId(thumbMediaId); + m.setTitle(this.title); + m.setDescription(this.description); + m.setThumbMediaId(this.thumbMediaId); return m; } } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VoiceBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VoiceBuilder.java index 10b2b0fe..0960fe8f 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VoiceBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VoiceBuilder.java @@ -23,6 +23,7 @@ public final class VoiceBuilder extends BaseBuilder { return this; } + @Override public WxCpMessage build() { WxCpMessage m = super.build(); m.setMediaId(this.mediaId); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/ImageBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/ImageBuilder.java index ae774e40..f8cd25f4 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/ImageBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/ImageBuilder.java @@ -16,6 +16,7 @@ public final class ImageBuilder extends BaseBuilder { - protected final List articles = new ArrayList(); + protected final List articles = new ArrayList<>(); public NewsBuilder addArticle(Item item) { this.articles.add(item); return this; } + @Override public WxCpXmlOutNewsMessage build() { WxCpXmlOutNewsMessage m = new WxCpXmlOutNewsMessage(); - for (Item item : articles) { + for (Item item : this.articles) { m.addArticle(item); } setCommon(m); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/TextBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/TextBuilder.java index 909a0ec9..dcdb58ca 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/TextBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/TextBuilder.java @@ -15,6 +15,7 @@ public final class TextBuilder extends BaseBuilder, JsonDeserializer { + @Override public JsonElement serialize(WxCpDepart group, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); if (group.getId() != null) { @@ -36,6 +37,7 @@ public class WxCpDepartGsonAdapter implements JsonSerializer, JsonDe return json; } + @Override public WxCpDepart deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxCpDepart depart = new WxCpDepart(); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java index 45df80b3..322658c2 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java @@ -20,6 +20,7 @@ import java.lang.reflect.Type; */ public class WxCpMessageGsonAdapter implements JsonSerializer { + @Override public JsonElement serialize(WxCpMessage message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); messageJson.addProperty("agentid", message.getAgentId()); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java index b8599a1c..43e84a00 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java @@ -19,6 +19,7 @@ import java.lang.reflect.Type; */ public class WxCpTagGsonAdapter implements JsonSerializer, JsonDeserializer { + @Override public JsonElement serialize(WxCpTag tag, Type typeOfSrc, JsonSerializationContext context) { JsonObject o = new JsonObject(); o.addProperty("tagid", tag.getId()); @@ -26,6 +27,7 @@ public class WxCpTagGsonAdapter implements JsonSerializer, JsonDeserial return o; } + @Override public WxCpTag deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java index 7a88f47e..bbabf054 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java @@ -19,6 +19,7 @@ import java.lang.reflect.Type; */ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSerializer { + @Override public WxCpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java index ae46d8f2..6b580630 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java @@ -45,7 +45,7 @@ public class XStreamTransformer { } private static Map configXStreamInstance() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(WxCpXmlMessage.class, config_WxCpXmlMessage()); map.put(WxCpXmlOutNewsMessage.class, config_WxCpXmlOutNewsMessage()); map.put(WxCpXmlOutTextMessage.class, config_WxCpXmlOutTextMessage()); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java index 5235486b..2a694ff3 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java @@ -1,12 +1,14 @@ package me.chanjar.weixin.cp.api; +import java.io.IOException; +import java.io.InputStream; + import com.google.inject.Binder; import com.google.inject.Module; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; -import me.chanjar.weixin.common.util.xml.XStreamInitializer; -import java.io.InputStream; +import me.chanjar.weixin.common.util.xml.XStreamInitializer; public class ApiTestModule implements Module { @@ -19,13 +21,18 @@ public class ApiTestModule implements Module { @Override public void configure(Binder binder) { - 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); + 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 (IOException e) { + e.printStackTrace(); + } } @XStreamAlias("xml") @@ -38,7 +45,7 @@ public class ApiTestModule implements Module { protected String tagId; public String getUserId() { - return userId; + return this.userId; } public void setUserId(String userId) { @@ -46,7 +53,7 @@ public class ApiTestModule implements Module { } public String getDepartmentId() { - return departmentId; + return this.departmentId; } public void setDepartmentId(String departmentId) { @@ -54,7 +61,7 @@ public class ApiTestModule implements Module { } public String getTagId() { - return tagId; + return this.tagId; } public void setTagId(String tagId) { @@ -64,9 +71,9 @@ public class ApiTestModule implements Module { @Override public String toString() { return super.toString() + " > WxXmlCpConfigStorage{" + - "userId='" + userId + '\'' + - ", departmentId='" + departmentId + '\'' + - ", tagId='" + tagId + '\'' + + "userId='" + this.userId + '\'' + + ", departmentId='" + this.departmentId + '\'' + + ", tagId='" + this.tagId + '\'' + '}'; } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java index 9f2b60f8..d2eb2ec6 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java @@ -1,12 +1,14 @@ package me.chanjar.weixin.cp.api; -import com.google.inject.Inject; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.StringUtils; import org.testng.Assert; import org.testng.annotations.Guice; import org.testng.annotations.Test; +import com.google.inject.Inject; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.StringUtils; + /** * 基础API测试 * @@ -20,9 +22,9 @@ public class WxCpBaseAPITest { protected WxCpServiceImpl wxService; public void testRefreshAccessToken() throws WxErrorException { - WxCpConfigStorage configStorage = wxService.wxCpConfigStorage; + WxCpConfigStorage configStorage = this.wxService.configStorage; String before = configStorage.getAccessToken(); - wxService.getAccessToken(false); + this.wxService.getAccessToken(false); String after = configStorage.getAccessToken(); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java index 989a69e6..b3f96b1b 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java @@ -1,16 +1,17 @@ package me.chanjar.weixin.cp.api; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestExecutor; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; + @Test public class WxCpBusyRetryTest { @@ -19,7 +20,9 @@ public class WxCpBusyRetryTest { WxCpService service = new WxCpServiceImpl() { @Override - protected T executeInternal(RequestExecutor executor, String uri, E data) throws WxErrorException { + protected synchronized T executeInternal( + RequestExecutor executor, String uri, E data) + throws WxErrorException { WxError error = new WxError(); error.setErrorCode(-1); throw new WxErrorException(error); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java index cb8db0d5..c0cc3251 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java @@ -1,13 +1,15 @@ package me.chanjar.weixin.cp.api; -import com.google.inject.Inject; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.cp.bean.WxCpDepart; +import java.util.List; + import org.testng.Assert; import org.testng.annotations.Guice; import org.testng.annotations.Test; -import java.util.List; +import com.google.inject.Inject; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.cp.bean.WxCpDepart; /** * 测试部门接口 @@ -24,22 +26,23 @@ public class WxCpDepartAPITest { protected WxCpDepart depart; public void testDepartCreate() throws WxErrorException { - WxCpDepart depart = new WxCpDepart(); - depart.setName("子部门" + System.currentTimeMillis()); - depart.setParentId(1); - depart.setOrder(1); - Integer departId = wxCpService.departCreate(depart); + WxCpDepart cpDepart = new WxCpDepart(); + cpDepart.setName("子部门" + System.currentTimeMillis()); + cpDepart.setParentId(1); + cpDepart.setOrder(1); + Integer departId = this.wxCpService.departCreate(cpDepart); + System.out.println(departId); } @Test(dependsOnMethods = "testDepartCreate") public void testDepartGet() throws WxErrorException { System.out.println("=================获取部门"); - List departList = wxCpService.departGet(); + List departList = this.wxCpService.departGet(); Assert.assertNotNull(departList); Assert.assertTrue(departList.size() > 0); for (WxCpDepart g : departList) { - depart = g; - System.out.println(depart.getId() + ":" + depart.getName()); + this.depart = g; + System.out.println(this.depart.getId() + ":" + this.depart.getName()); Assert.assertNotNull(g.getName()); } } @@ -47,15 +50,15 @@ public class WxCpDepartAPITest { @Test(dependsOnMethods = {"testDepartGet", "testDepartCreate"}) public void testDepartUpdate() throws WxErrorException { System.out.println("=================更新部门"); - depart.setName("子部门改名" + System.currentTimeMillis()); - wxCpService.departUpdate(depart); + this.depart.setName("子部门改名" + System.currentTimeMillis()); + this.wxCpService.departUpdate(this.depart); } @Test(dependsOnMethods = "testDepartUpdate") public void testDepartDelete() throws WxErrorException { System.out.println("=================删除部门"); - System.out.println(depart.getId() + ":" + depart.getName()); - wxCpService.departDelete(depart.getId()); + System.out.println(this.depart.getId() + ":" + this.depart.getName()); + this.wxCpService.departDelete(this.depart.getId()); } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java index e880ad07..fe379226 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java @@ -1,18 +1,20 @@ package me.chanjar.weixin.cp.api; -import com.google.inject.Inject; -import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; -import me.chanjar.weixin.common.exception.WxErrorException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Guice; import org.testng.annotations.Test; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; +import com.google.inject.Inject; + +import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; +import me.chanjar.weixin.common.exception.WxErrorException; /** * 测试多媒体文件上传下载 @@ -27,21 +29,25 @@ public class WxCpMediaAPITest { @Inject protected WxCpServiceImpl wxService; - private List media_ids = new ArrayList(); + private List media_ids = new ArrayList<>(); @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); + try (InputStream inputStream = ClassLoader + .getSystemResourceAsStream(fileName);) { + WxMediaUploadResult res = this.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()); + if (res.getMediaId() != null) { + this.media_ids.add(res.getMediaId()); + } + if (res.getThumbMediaId() != null) { + this.media_ids.add(res.getThumbMediaId()); + } } } @@ -57,7 +63,7 @@ public class WxCpMediaAPITest { @Test(dependsOnMethods = {"testUploadMedia"}, dataProvider = "downloadMedia") public void testDownloadMedia(String media_id) throws WxErrorException { - wxService.mediaDownload(media_id); + this.wxService.mediaDownload(media_id); } @DataProvider diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageAPITest.java index 9810435e..b7bcf7a3 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageAPITest.java @@ -1,11 +1,13 @@ package me.chanjar.weixin.cp.api; +import org.testng.annotations.Guice; +import org.testng.annotations.Test; + import com.google.inject.Inject; + import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.cp.bean.WxCpMessage; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; /*** * 测试发送消息 @@ -20,21 +22,21 @@ public class WxCpMessageAPITest { protected WxCpServiceImpl wxService; public void testSendCustomMessage() throws WxErrorException { - ApiTestModule.WxXmlCpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlCpInMemoryConfigStorage) wxService.wxCpConfigStorage; + ApiTestModule.WxXmlCpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlCpInMemoryConfigStorage) this.wxService.configStorage; WxCpMessage message1 = new WxCpMessage(); message1.setAgentId(configStorage.getAgentId()); message1.setMsgType(WxConsts.CUSTOM_MSG_TEXT); message1.setToUser(configStorage.getUserId()); message1.setContent("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World"); - wxService.messageSend(message1); + this.wxService.messageSend(message1); WxCpMessage message2 = WxCpMessage .TEXT() .agentId(configStorage.getAgentId()) .toUser(configStorage.getUserId()) - .content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World") + .content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World") .build(); - wxService.messageSend(message2); + this.wxService.messageSend(message2); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java index a5e40968..4b0fc56a 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java @@ -286,7 +286,7 @@ public class WxCpMessageRouterTest { @Override public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, WxCpService wxCpService, WxSessionManager sessionManager) { - sb.append(this.echoStr).append(','); + this.sb.append(this.echoStr).append(','); return null; } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java index 130b0722..aa26e962 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java @@ -23,44 +23,44 @@ public class WxCpTagAPITest { protected String tagId; public void testTagCreate() throws Exception { - tagId = wxService.tagCreate("测试标签4"); - System.out.println(tagId); + this.tagId = this.wxService.tagCreate("测试标签4"); + System.out.println(this.tagId); } @Test(dependsOnMethods = "testTagCreate") public void testTagUpdate() throws Exception { - wxService.tagUpdate(tagId, "测试标签-改名"); + this.wxService.tagUpdate(this.tagId, "测试标签-改名"); } @Test(dependsOnMethods = "testTagUpdate") public void testTagGet() throws Exception { - List tags = wxService.tagGet(); + List tags = this.wxService.tagGet(); Assert.assertNotEquals(tags.size(), 0); } @Test(dependsOnMethods = "testTagGet") public void testTagAddUsers() throws Exception { - List userIds = new ArrayList(); - userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage) configStorage).getUserId()); - wxService.tagAddUsers(tagId, userIds, null); + List userIds = new ArrayList<>(); + userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage) this.configStorage).getUserId()); + this.wxService.tagAddUsers(this.tagId, userIds, null); } @Test(dependsOnMethods = "testTagAddUsers") public void testTagGetUsers() throws Exception { - List users = wxService.tagGetUsers(tagId); + List users = this.wxService.tagGetUsers(this.tagId); Assert.assertNotEquals(users.size(), 0); } @Test(dependsOnMethods = "testTagGetUsers") public void testTagRemoveUsers() throws Exception { - List userIds = new ArrayList(); - userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage) configStorage).getUserId()); - wxService.tagRemoveUsers(tagId, userIds); + List userIds = new ArrayList<>(); + userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage) this.configStorage).getUserId()); + this.wxService.tagRemoveUsers(this.tagId, userIds); } @Test(dependsOnMethods = "testTagRemoveUsers") public void testTagDelete() throws Exception { - wxService.tagDelete(tagId); + this.wxService.tagDelete(this.tagId); } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java index 8c5d2064..4d5a7a91 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java @@ -35,7 +35,7 @@ public class WxCpUserAPITest { user.setPosition("woman"); user.setTel("3300393"); user.addExtAttr("爱好", "table"); - wxCpService.userCreate(user); + this.wxCpService.userCreate(user); } @Test(dependsOnMethods = "testUserCreate") @@ -44,23 +44,23 @@ public class WxCpUserAPITest { user.setUserId("some.woman"); user.setName("Some Woman"); user.addExtAttr("爱好", "table2"); - wxCpService.userUpdate(user); + this.wxCpService.userUpdate(user); } @Test(dependsOnMethods = "testUserUpdate") public void testUserGet() throws WxErrorException { - WxCpUser user = wxCpService.userGet("some.woman"); + WxCpUser user = this.wxCpService.userGet("some.woman"); Assert.assertNotNull(user); } @Test(dependsOnMethods = "testUserGet") public void testDepartGetUsers() throws WxErrorException { - List users = wxCpService.departGetUsers(1, true, 0); + List users = this.wxCpService.departGetUsers(1, true, 0); Assert.assertNotEquals(users.size(), 0); } @Test(dependsOnMethods = "testDepartGetUsers") public void testUserDelete() throws WxErrorException { - wxCpService.userDelete("some.woman"); + this.wxCpService.userDelete("some.woman"); } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java index 8fe136b9..c837e51e 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java @@ -24,17 +24,17 @@ public class WxMenuAPITest { @Test(dataProvider = "menu") public void testCreateMenu(WxMenu wxMenu) throws WxErrorException { - wxService.menuCreate(wxMenu); + this.wxService.menuCreate(wxMenu); } @Test(dependsOnMethods = {"testCreateMenu"}) public void testGetMenu() throws WxErrorException { - Assert.assertNotNull(wxService.menuGet()); + Assert.assertNotNull(this.wxService.menuGet()); } @Test(dependsOnMethods = {"testGetMenu"}) public void testDeleteMenu() throws WxErrorException { - wxService.menuDelete(); + this.wxService.menuDelete(); } @DataProvider(name = "menu") diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java index f883e311..9a97b6cd 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java @@ -21,8 +21,8 @@ class WxCpDemoInMemoryConfigStorage extends WxCpInMemoryConfigStorage { @Override public String toString() { - return "SimpleWxConfigProvider [appidOrCorpid=" + corpId + ", corpSecret=" + corpSecret + ", accessToken=" + accessToken - + ", expiresTime=" + expiresTime + ", token=" + token + ", aesKey=" + aesKey + "]"; + return "SimpleWxConfigProvider [appidOrCorpid=" + this.corpId + ", corpSecret=" + this.corpSecret + ", accessToken=" + this.accessToken + + ", expiresTime=" + this.expiresTime + ", token=" + this.token + ", aesKey=" + this.aesKey + "]"; } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java index 10af3c57..dc667d88 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java @@ -1,16 +1,22 @@ package me.chanjar.weixin.cp.demo; -import me.chanjar.weixin.common.session.WxSessionManager; -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 java.io.IOException; +import java.io.InputStream; +import java.util.Map; + import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; -import java.io.InputStream; -import java.util.Map; +import me.chanjar.weixin.common.session.WxSessionManager; +import me.chanjar.weixin.cp.api.WxCpConfigStorage; +import me.chanjar.weixin.cp.api.WxCpMessageHandler; +import me.chanjar.weixin.cp.api.WxCpMessageRouter; +import me.chanjar.weixin.cp.api.WxCpService; +import me.chanjar.weixin.cp.api.WxCpServiceImpl; +import me.chanjar.weixin.cp.bean.WxCpXmlMessage; +import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage; +import me.chanjar.weixin.cp.bean.WxCpXmlOutTextMessage; public class WxCpDemoServer { @@ -36,55 +42,48 @@ public class WxCpDemoServer { server.join(); } - private static void initWeixin() { - 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 context, - WxCpService wxCpService, WxSessionManager sessionManager) { - WxCpXmlOutTextMessage m = WxCpXmlOutMessage - .TEXT() - .content("测试加密消息") - .fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()) - .build(); - return m; - } - }; - - WxCpMessageHandler oauth2handler = new WxCpMessageHandler() { - @Override - public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, - WxCpService wxCpService, WxSessionManager sessionManager) { - String href = "测试oauth2"; - return WxCpXmlOutMessage - .TEXT() - .content(href) - .fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()).build(); - } - }; - - wxCpMessageRouter = new WxCpMessageRouter(wxCpService); - wxCpMessageRouter - .rule() - .async(false) - .content("哈哈") // 拦截内容为“哈哈”的消息 - .handler(handler) - .end() - .rule() - .async(false) - .content("oauth") - .handler(oauth2handler) - .end() - ; - + private static void initWeixin() throws IOException { + 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 context, WxCpService wxService, + WxSessionManager sessionManager) { + WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("测试加密消息") + .fromUser(wxMessage.getToUserName()) + .toUser(wxMessage.getFromUserName()).build(); + return m; + } + }; + + WxCpMessageHandler oauth2handler = new WxCpMessageHandler() { + @Override + public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, + Map context, WxCpService wxService, + WxSessionManager sessionManager) { + String href = "测试oauth2"; + return WxCpXmlOutMessage.TEXT().content(href) + .fromUser(wxMessage.getToUserName()) + .toUser(wxMessage.getFromUserName()).build(); + } + }; + + wxCpMessageRouter = new WxCpMessageRouter(wxCpService); + wxCpMessageRouter.rule().async(false).content("哈哈") // 拦截内容为“哈哈”的消息 + .handler(handler).end().rule().async(false).content("oauth") + .handler(oauth2handler).end(); + + } } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java index 67738d2b..d59eb3f3 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java @@ -1,5 +1,11 @@ package me.chanjar.weixin.cp.demo; +import java.io.IOException; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import me.chanjar.weixin.common.util.StringUtils; import me.chanjar.weixin.cp.api.WxCpConfigStorage; import me.chanjar.weixin.cp.api.WxCpMessageRouter; @@ -8,17 +14,11 @@ import me.chanjar.weixin.cp.bean.WxCpXmlMessage; import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage; import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - /** * @author Daniel Qian */ public class WxCpEndpointServlet extends HttpServlet { - + private static final long serialVersionUID = 1L; protected WxCpConfigStorage wxCpConfigStorage; protected WxCpService wxCpService; protected WxCpMessageRouter wxCpMessageRouter; @@ -32,7 +32,7 @@ public class WxCpEndpointServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); @@ -43,12 +43,12 @@ public class WxCpEndpointServlet extends HttpServlet { String echostr = request.getParameter("echostr"); if (StringUtils.isNotBlank(echostr)) { - if (!wxCpService.checkSignature(msgSignature, timestamp, nonce, echostr)) { + if (!this.wxCpService.checkSignature(msgSignature, timestamp, nonce, echostr)) { // 消息签名不正确,说明不是公众平台发过来的消息 response.getWriter().println("非法请求"); return; } - WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage); + WxCpCryptUtil cryptUtil = new WxCpCryptUtil(this.wxCpConfigStorage); String plainText = cryptUtil.decrypt(echostr); // 说明是一个仅仅用来验证的请求,回显echostr response.getWriter().println(plainText); @@ -56,10 +56,10 @@ public class WxCpEndpointServlet extends HttpServlet { } WxCpXmlMessage inMessage = WxCpXmlMessage - .fromEncryptedXml(request.getInputStream(), wxCpConfigStorage, timestamp, nonce, msgSignature); - WxCpXmlOutMessage outMessage = wxCpMessageRouter.route(inMessage); + .fromEncryptedXml(request.getInputStream(), this.wxCpConfigStorage, timestamp, nonce, msgSignature); + WxCpXmlOutMessage outMessage = this.wxCpMessageRouter.route(inMessage); if (outMessage != null) { - response.getWriter().write(outMessage.toEncryptedXml(wxCpConfigStorage)); + response.getWriter().write(outMessage.toEncryptedXml(this.wxCpConfigStorage)); } return; diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java index 80dc565d..edab8966 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java @@ -1,16 +1,17 @@ package me.chanjar.weixin.cp.demo; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.cp.api.WxCpService; +import java.io.IOException; +import java.util.Arrays; -import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Arrays; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.cp.api.WxCpService; public class WxCpOAuth2Servlet extends HttpServlet { + private static final long serialVersionUID = 1L; protected WxCpService wxCpService; @@ -20,7 +21,7 @@ public class WxCpOAuth2Servlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); @@ -30,7 +31,7 @@ public class WxCpOAuth2Servlet extends HttpServlet { response.getWriter().println("

code

"); response.getWriter().println(code); - String[] res = wxCpService.oauth2getUserInfo(code); + String[] res = this.wxCpService.oauth2getUserInfo(code); response.getWriter().println("

result

"); response.getWriter().println(Arrays.toString(res)); } catch (WxErrorException e) { diff --git a/weixin-java-mp/pom.xml b/weixin-java-mp/pom.xml index 2ed00145..6fc42ee6 100644 --- a/weixin-java-mp/pom.xml +++ b/weixin-java-mp/pom.xml @@ -1,12 +1,12 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 com.github.binarywang weixin-java-parent - 2.1.0 + 2.2.0 weixin-java-mp WeiXin Java Tools - MP @@ -47,7 +47,7 @@ org.eclipse.jetty jetty-servlet test - + joda-time joda-time diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java index 80bf38a6..d4a36c65 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java @@ -6,8 +6,7 @@ import me.chanjar.weixin.mp.bean.result.WxMpCardResult; /** * 卡券相关接口 - * Created by Binary Wang on 2016/7/27. - * @author binarywang(https://github.com/binarywang) + * @author YuJian(mgcnrx11@hotmail.com) on 01/11/2016 */ public interface WxMpCardService { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpGroupService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpGroupService.java deleted file mode 100644 index 80bcf524..00000000 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpGroupService.java +++ /dev/null @@ -1,69 +0,0 @@ -package me.chanjar.weixin.mp.api; - -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.bean.WxMpGroup; - -import java.util.List; - -/** - * 用户分组相关操作接口 - * @author Binary Wang - * - */ -public interface WxMpGroupService { - - - /** - *
-   * 分组管理接口 - 创建分组
-   * 最多支持创建500个分组
-   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
-   * 
- * - * @param name 分组名字(30个字符以内) - */ - WxMpGroup groupCreate(String name) throws WxErrorException; - - /** - *
-   * 分组管理接口 - 查询所有分组
-   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
-   * 
- */ - List groupGet() throws WxErrorException; - - /** - *
-   * 分组管理接口 - 查询用户所在分组
-   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
-   * 
- * - * @param openid 微信用户的openid - */ - long userGetGroup(String openid) throws WxErrorException; - - /** - *
-   * 分组管理接口 - 修改分组名
-   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
-   *
-   * 如果id为0(未分组),1(黑名单),2(星标组),或者不存在的id,微信会返回系统繁忙的错误
-   * 
- * - * @param group 要更新的group,group的id,name必须设置 - */ - void groupUpdate(WxMpGroup group) throws WxErrorException; - - /** - *
-   * 分组管理接口 - 移动用户分组
-   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
-   *
-   * 如果to_groupid为0(未分组),1(黑名单),2(星标组),或者不存在的id,微信会返回系统繁忙的错误
-   * 
- * - * @param openid 用户openid - * @param to_groupid 移动到的分组id - */ - void userUpdateGroup(String openid, long to_groupid) throws WxErrorException; -} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpKefuService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpKefuService.java index c4731cb5..fc678b42 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpKefuService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpKefuService.java @@ -1,12 +1,18 @@ package me.chanjar.weixin.mp.api; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfAccountRequest; -import me.chanjar.weixin.mp.bean.kefu.result.*; - import java.io.File; import java.util.Date; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.bean.WxMpCustomMessage; +import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfAccountRequest; +import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfList; +import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfMsgList; +import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfOnlineList; +import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionGetResult; +import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionList; +import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionWaitCaseList; + /** * 客服接口 , * 命名采用kefu拼音的原因是: @@ -17,6 +23,14 @@ import java.util.Date; */ public interface WxMpKefuService { + /** + *
+   * 发送客服消息
+   * 详情请见: 发送客服消息
+   * 
+ */ + boolean customMessageSend(WxMpCustomMessage message) throws WxErrorException; + //*******************客服管理接口***********************// /** diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java index 2325ccac..48a6f610 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java @@ -10,10 +10,12 @@ import java.io.IOException; import java.io.InputStream; /** + *
  * Created by Binary Wang on 2016/7/21.
  * 素材管理的相关接口,包括媒体管理的接口,
  * 即以https://api.weixin.qq.com/cgi-bin/material
  * 和 https://api.weixin.qq.com/cgi-bin/media开头的接口
+ * 
*/ public interface WxMpMaterialService { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java index b72cc45a..7db50e79 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java @@ -1,24 +1,25 @@ package me.chanjar.weixin.mp.api; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import me.chanjar.weixin.common.api.WxErrorExceptionHandler; +import me.chanjar.weixin.common.api.WxMessageDuplicateChecker; +import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker; import me.chanjar.weixin.common.session.InternalSession; import me.chanjar.weixin.common.session.InternalSessionManager; import me.chanjar.weixin.common.session.StandardSessionManager; import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.common.util.LogExceptionHandler; -import me.chanjar.weixin.common.api.WxErrorExceptionHandler; -import me.chanjar.weixin.common.api.WxMessageDuplicateChecker; -import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker; import me.chanjar.weixin.mp.bean.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; /** *
@@ -155,7 +156,7 @@ public class WxMpMessageRouter {
     }
 
     WxMpXmlOutMessage res = null;
-    final List futures = new ArrayList<>();
+    final List> futures = new ArrayList<>();
     for (final WxMpMessageRouterRule rule : matchRules) {
       // 返回最后一个非异步的rule的执行结果
       if(rule.isAsync()) {
@@ -170,7 +171,7 @@ public class WxMpMessageRouter {
       } else {
         res = rule.service(wxMessage, this.wxMpService, this.sessionManager, this.exceptionHandler);
         // 在同步操作结束,session访问结束
-        this.log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUserName());
+        this.log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUser());
         sessionEndAccess(wxMessage);
       }
     }
@@ -179,10 +180,10 @@ public class WxMpMessageRouter {
       this.executorService.submit(new Runnable() {
         @Override
         public void run() {
-          for (Future future : futures) {
+          for (Future future : futures) {
             try {
               future.get();
-              WxMpMessageRouter.this.log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUserName());
+              WxMpMessageRouter.this.log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUser());
               // 异步操作结束,session访问结束
               sessionEndAccess(wxMessage);
             } catch (InterruptedException e) {
@@ -202,7 +203,7 @@ public class WxMpMessageRouter {
     StringBuffer messageId = new StringBuffer();
     if (wxMessage.getMsgId() == null) {
       messageId.append(wxMessage.getCreateTime())
-        .append("-").append(wxMessage.getFromUserName())
+        .append("-").append(wxMessage.getFromUser())
         .append("-").append(wxMessage.getEventKey() == null ? "" : wxMessage.getEventKey())
         .append("-").append(wxMessage.getEvent() == null ? "" : wxMessage.getEvent())
       ;
@@ -220,7 +221,7 @@ public class WxMpMessageRouter {
    */
   protected void sessionEndAccess(WxMpXmlMessage wxMessage) {
 
-    InternalSession session = ((InternalSessionManager)this.sessionManager).findSession(wxMessage.getFromUserName());
+    InternalSession session = ((InternalSessionManager)this.sessionManager).findSession(wxMessage.getFromUser());
     if (session != null) {
       session.endAccess();
     }
diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouterRule.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouterRule.java
index eb02c641..317303b8 100644
--- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouterRule.java
+++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouterRule.java
@@ -168,7 +168,7 @@ public class WxMpMessageRouterRule {
    */
   protected boolean test(WxMpXmlMessage wxMessage) {
     return
-        (this.fromUser == null || this.fromUser.equals(wxMessage.getFromUserName()))
+        (this.fromUser == null || this.fromUser.equals(wxMessage.getFromUser()))
             &&
             (this.msgType == null || this.msgType.toLowerCase().equals((wxMessage.getMsgType()==null?null:wxMessage.getMsgType().toLowerCase())))
             &&
diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java
index 0db67cb7..72eabd08 100644
--- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java
+++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java
@@ -1,10 +1,17 @@
 package me.chanjar.weixin.mp.api;
 
-import me.chanjar.weixin.common.exception.WxErrorException;
-import me.chanjar.weixin.mp.bean.result.*;
-
 import java.util.Map;
 
+import me.chanjar.weixin.common.exception.WxErrorException;
+import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback;
+import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult;
+import me.chanjar.weixin.mp.bean.pay.WxMpPayResult;
+import me.chanjar.weixin.mp.bean.pay.WxMpPrepayIdResult;
+import me.chanjar.weixin.mp.bean.pay.WxRedpackResult;
+import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest;
+import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest;
+import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderResult;
+
 /**
  *  微信支付相关接口
  *  Created by Binary Wang on 2016/7/28.
@@ -12,77 +19,32 @@ import java.util.Map;
  */
 public interface WxMpPayService {
 
-
-  /**
-   * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
-   * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"
-   *
-   * @param openId     支付人openId
-   * @param outTradeNo 商户端对应订单号
-   * @param amt        金额(单位元)
-   * @param body       商品描述
-   * @param tradeType  交易类型 JSAPI,NATIVE,APP,WAP
-   * @param ip         发起支付的客户端IP
-   * @param notifyUrl  通知地址
-   * @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPrepayId(Map) instead
-   */
-  @Deprecated
-  WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String notifyUrl);
-
   /**
    * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
    * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"
+   * 接口地址:https://api.mch.weixin.qq.com/pay/unifiedorder
+   * @throws WxErrorException 
    *
-   * @param parameters All required/optional parameters for weixin payment
    */
-  WxMpPrepayIdResult getPrepayId(Map parameters);
+  WxUnifiedOrderResult unifiedOrder(WxUnifiedOrderRequest request)
+      throws WxErrorException;
 
   /**
    * 该接口调用“统一下单”接口,并拼装发起支付请求需要的参数
-   * 详见http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E5.8F.91.E8.B5.B7.E4.B8.80.E4.B8.AA.E5.BE.AE.E4.BF.A1.E6.94.AF.E4.BB.98.E8.AF.B7.E6.B1.82
+   * 详见http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN
    *
-   * @param parameters the required or optional parameters
    */
-  Map getPayInfo(Map parameters) throws WxErrorException;
+  Map getPayInfo(WxUnifiedOrderRequest request) throws WxErrorException;
 
-  /**
-   * 该接口调用“统一下单”接口,并拼装NATIVE发起支付请求需要的参数
-   * 详见http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E5.8F.91.E8.B5.B7.E4.B8.80.E4.B8.AA.E5.BE.AE.E4.BF.A1.E6.94.AF.E4.BB.98.E8.AF.B7.E6.B1.82
-   * tradeType 交易类型 NATIVE (其他交易类型JSAPI,APP,WAP)
-   *
-   * @param productId  商户商品ID
-   * @param outTradeNo 商户端对应订单号
-   * @param amt        金额(单位元)
-   * @param body       商品描述
-   * @param ip         发起支付的客户端IP
-   * @param notifyUrl  通知地址
-   * @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPayInfo(Map) instead
-   */
-  @Deprecated
-  Map getNativePayInfo(String productId, String outTradeNo, double amt, String body, String ip, String notifyUrl) throws WxErrorException;
-
-  /**
-   * 该接口调用“统一下单”接口,并拼装JSAPI发起支付请求需要的参数
-   * 详见http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E5.8F.91.E8.B5.B7.E4.B8.80.E4.B8.AA.E5.BE.AE.E4.BF.A1.E6.94.AF.E4.BB.98.E8.AF.B7.E6.B1.82
-   * tradeType 交易类型 JSAPI(其他交易类型NATIVE,APP,WAP)
-   *
-   * @param openId     支付人openId
-   * @param outTradeNo 商户端对应订单号
-   * @param amt        金额(单位元)
-   * @param body       商品描述
-   * @param ip         发起支付的客户端IP
-   * @param notifyUrl  通知地址
-   * @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPayInfo(Map) instead
-   */
-  @Deprecated
-  Map getJsapiPayInfo(String openId, String outTradeNo, double amt, String body, String ip, String notifyUrl) throws WxErrorException;
 
   /**
    * 该接口提供所有微信支付订单的查询,当支付通知处理异常戒丢失的情冴,商户可以通过该接口查询订单支付状态。
    * 详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2
+   * @throws WxErrorException 
    *
    */
-  WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo);
+  WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo)
+      throws WxErrorException;
 
   /**
    * 读取支付结果通知
@@ -116,23 +78,12 @@ public interface WxMpPayService {
 
   /**
    * 发送微信红包给个人用户
-   * 

- * 需要传入的必填参数如下: - * mch_billno//商户订单号 - * send_name//商户名称 - * re_openid//用户openid - * total_amount//红包总额 - * total_num//红包发放总人数 - * wishing//红包祝福语 - * client_ip//服务器Ip地址 - * act_name//活动名称 - * remark //备注 - * 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5 - *

- * 使用现金红包功能需要在xml配置文件中额外设置: - * 微信商户平台ID - * 商户平台设置的API密钥 - * + *

 
+   * 文档详见:
+   * 发送普通红包 https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
+   * 发送裂变红包 https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5&index=4
+   * 
*/ - WxRedpackResult sendRedpack(Map parameters) throws WxErrorException; + WxRedpackResult sendRedpack(WxSendRedpackRequest request) throws WxErrorException; + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java index ab205a03..292c5645 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java @@ -3,18 +3,25 @@ package me.chanjar.weixin.mp.api; import me.chanjar.weixin.common.bean.WxJsapiSignature; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestExecutor; -import me.chanjar.weixin.mp.bean.*; -import me.chanjar.weixin.mp.bean.result.*; - -import java.text.SimpleDateFormat; +import me.chanjar.weixin.mp.bean.WxMpIndustry; +import me.chanjar.weixin.mp.bean.WxMpMassTagMessage; +import me.chanjar.weixin.mp.bean.WxMpMassNews; +import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage; +import me.chanjar.weixin.mp.bean.WxMpMassPreviewMessage; +import me.chanjar.weixin.mp.bean.WxMpMassVideo; +import me.chanjar.weixin.mp.bean.WxMpSemanticQuery; +import me.chanjar.weixin.mp.bean.WxMpTemplateMessage; +import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult; +import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult; +import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; +import me.chanjar.weixin.mp.bean.result.WxMpSemanticQueryResult; +import me.chanjar.weixin.mp.bean.result.WxMpUser; /** * 微信API的Service */ public interface WxMpService { - SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); - /** *
    * 验证推送过来的消息的正确性
@@ -74,14 +81,6 @@ public interface WxMpService {
    */
   WxJsapiSignature createJsapiSignature(String url) throws WxErrorException;
 
-  /**
-   * 
-   * 发送客服消息
-   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=发送客服消息
-   * 
- */ - void customMessageSend(WxMpCustomMessage message) throws WxErrorException; - /** *
    * 上传群发用的图文消息,上传后才能群发图文消息
@@ -89,7 +88,7 @@ public interface WxMpService {
    * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=高级群发接口
    * 
* - * @see #massGroupMessageSend(me.chanjar.weixin.mp.bean.WxMpMassGroupMessage) + * @see #massGroupMessageSend(me.chanjar.weixin.mp.bean.WxMpMassTagMessage) * @see #massOpenIdsMessageSend(me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage) */ WxMpMassUploadResult massNewsUpload(WxMpMassNews news) throws WxErrorException; @@ -100,7 +99,7 @@ public interface WxMpService { * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=高级群发接口 *
* - * @see #massGroupMessageSend(me.chanjar.weixin.mp.bean.WxMpMassGroupMessage) + * @see #massGroupMessageSend(me.chanjar.weixin.mp.bean.WxMpMassTagMessage) * @see #massOpenIdsMessageSend(me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage) */ WxMpMassUploadResult massVideoUpload(WxMpMassVideo video) throws WxErrorException; @@ -113,7 +112,7 @@ public interface WxMpService { * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=高级群发接口 *
*/ - WxMpMassSendResult massGroupMessageSend(WxMpMassGroupMessage message) throws WxErrorException; + WxMpMassSendResult massGroupMessageSend(WxMpMassTagMessage message) throws WxErrorException; /** *
@@ -303,58 +302,72 @@ public interface WxMpService {
   WxMpKefuService getKefuService();
 
   /**
-   * 返回素材相关接口的方法实现类,以方便调用个其各种接口
+   * 返回素材相关接口方法的实现类对象,以方便调用个其各种接口
    *
    * @return WxMpMaterialService
    */
   WxMpMaterialService getMaterialService();
 
   /**
-   * 返回菜单相关接口的方法实现类,以方便调用个其各种接口
+   * 返回菜单相关接口方法的实现类对象,以方便调用个其各种接口
    *
    * @return WxMpMenuService
    */
   WxMpMenuService getMenuService();
 
   /**
-   * 返回用户相关接口的方法实现类,以方便调用个其各种接口
+   * 返回用户相关接口方法的实现类对象,以方便调用个其各种接口
    *
    * @return WxMpUserService
    */
   WxMpUserService getUserService();
 
   /**
-   * 返回用户分组相关接口的方法实现类,以方便调用个其各种接口
+   * 返回用户标签相关接口方法的实现类对象,以方便调用个其各种接口
    *
-   * @return WxMpGroupService
+   * @return WxMpUserTagService
    */
-  WxMpGroupService getGroupService();
+  WxMpUserTagService getUserTagService();
 
   /**
-   * 返回二维码相关接口的方法实现类,以方便调用个其各种接口
+   * 返回二维码相关接口方法的实现类对象,以方便调用个其各种接口
    *
    * @return WxMpQrcodeService
    */
   WxMpQrcodeService getQrcodeService();
 
   /**
-   * 返回卡券相关接口的方法实现类,以方便调用个其各种接口
+   * 返回卡券相关接口方法的实现类对象,以方便调用个其各种接口
    *
    * @return WxMpCardService
    */
   WxMpCardService getCardService();
 
   /**
-   * 返回微信支付相关接口的方法实现类,以方便调用个其各种接口
+   * 返回微信支付相关接口方法的实现类对象,以方便调用个其各种接口
    *
    * @return WxMpPayService
    */
   WxMpPayService getPayService();
 
   /**
-   * 返回数据分析统计相关接口的方法实现类,以方便调用个其各种接口
+   * 返回数据分析统计相关接口方法的实现类对象,以方便调用个其各种接口
    *
    * @return WxMpDataCubeService
    */
   WxMpDataCubeService getDataCubeService();
+
+  /**
+   * 返回用户黑名单管理相关接口方法的实现类对象,以方便调用其各种接口
+   *
+   * @return WxMpUserBlacklistService
+   */
+  WxMpUserBlacklistService getBlackListService();
+
+  /**
+   * 返回门店管理相关接口方法的实现类对象,以方便调用其各种接口
+   *
+   * @return WxMpStoreService
+   */
+  WxMpStoreService getStoreService();
 }
diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java
new file mode 100644
index 00000000..0ce7cc03
--- /dev/null
+++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java
@@ -0,0 +1,103 @@
+package me.chanjar.weixin.mp.api;
+
+import me.chanjar.weixin.common.exception.WxErrorException;
+import me.chanjar.weixin.mp.bean.store.WxMpStoreBaseInfo;
+import me.chanjar.weixin.mp.bean.store.WxMpStoreInfo;
+import me.chanjar.weixin.mp.bean.store.WxMpStoreListResult;
+
+import java.util.List;
+
+/**
+ * 门店管理的相关接口代码
+ * @author binarywang(https://github.com/binarywang)
+ *         Created by Binary Wang on 2016-09-23.
+ */
+public interface WxMpStoreService {
+  /**
+   * 
+   * 创建门店
+   * 接口说明
+   * 创建门店接口是为商户提供创建自己门店数据的接口,门店数据字段越完整,商户页面展示越丰富,越能够吸引更多用户,并提高曝光度。
+   * 创建门店接口调用成功后会返回errcode 0、errmsg ok,但不会实时返回poi_id。
+   * 成功创建后,会生成poi_id,但该id不一定为最终id。门店信息会经过审核,审核通过后方可获取最终poi_id,该id为门店的唯一id,强烈建议自行存储审核通过后的最终poi_id,并为后续调用使用。
+   * 详情请见: 微信门店接口
+   * 接口格式: http://api.weixin.qq.com/cgi-bin/poi/addpoi?access_token=TOKEN
+   * 
+ * + */ + void add(WxMpStoreBaseInfo request) throws WxErrorException; + + /** + *
+   * 查询门店信息
+   * 创建门店后获取poi_id 后,商户可以利用poi_id,查询具体某条门店的信息。
+   * 若在查询时,update_status 字段为1,表明在5 个工作日内曾用update 接口修改过门店扩展字段,该扩展字段为最新的修改字段,尚未经过审核采纳,因此不是最终结果。
+   * 最终结果会在5 个工作日内,最终确认是否采纳,并前端生效(但该扩展字段的采纳过程不影响门店的可用性,即available_state仍为审核通过状态)
+   * 注:扩展字段为公共编辑信息(大家都可修改),修改将会审核,并决定是否对修改建议进行采纳,但不会影响该门店的生效可用状态。
+   * 详情请见: 微信门店接口
+   * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/getpoi?access_token=TOKEN
+   * 
+ * @param poiId 门店Id + * @throws WxErrorException + */ + WxMpStoreBaseInfo get(String poiId) throws WxErrorException; + + /** + *
+   * 删除门店
+   * 商户可以通过该接口,删除已经成功创建的门店。请商户慎重调用该接口。
+   * 详情请见: 微信门店接口
+   * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/delpoi?access_token=TOKEN
+   * 
+ * @param poiId 门店Id + * @throws WxErrorException + */ + void delete(String poiId) throws WxErrorException; + + /** + *
+   * 查询门店列表(指定查询起始位置和个数)
+   * 商户可以通过该接口,批量查询自己名下的门店list,并获取已审核通过的poi_id(所有状态均会返回poi_id,但该poi_id不一定为最终id)、商户自身sid 用于对应、商户名、分店名、地址字段。
+   * 详情请见: 微信门店接口
+   * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=TOKEN
+   * 
+ * @param begin 开始位置,0 即为从第一条开始查询 + * @param limit 返回数据条数,最大允许50,默认为20 + * @throws WxErrorException + */ + WxMpStoreListResult list(int begin, int limit) throws WxErrorException; + + /** + *
+   * 查询门店列表(所有)
+   * 商户可以通过该接口,批量查询自己名下的门店list,并获取已审核通过的poi_id(所有状态均会返回poi_id,但该poi_id不一定为最终id)、商户自身sid 用于对应、商户名、分店名、地址字段。
+   * 详情请见: 微信门店接口
+   * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=TOKEN
+   * 
+ * @throws WxErrorException + */ + List listAll() throws WxErrorException; + + /** + *
+   * 修改门店服务信息
+   * 商户可以通过该接口,修改门店的服务信息,包括:sid、图片列表、营业时间、推荐、特色服务、简介、人均价格、电话8个字段(名称、坐标、地址等不可修改)修改后需要人工审核。
+   * 详情请见: 微信门店接口
+   * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/updatepoi?access_token=TOKEN
+   * 
+ * @throws WxErrorException + */ + void update(WxMpStoreBaseInfo info) throws WxErrorException; + + /** + *
+   * 门店类目表
+   * 类目名称接口是为商户提供自己门店类型信息的接口。门店类目定位的越规范,能够精准的吸引更多用户,提高曝光率。
+   * 详情请见: 微信门店接口
+   * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/getwxcategory?access_token=TOKEN
+   * 
+ * @throws WxErrorException + */ + List listCategories() throws WxErrorException; + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserBlacklistService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserBlacklistService.java new file mode 100644 index 00000000..d93384f0 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserBlacklistService.java @@ -0,0 +1,35 @@ +package me.chanjar.weixin.mp.api; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.bean.result.WxMpUserBlacklistGetResult; + +import java.util.List; + +/** + * @author miller + */ +public interface WxMpUserBlacklistService { + /** + *
+   * 获取公众号的黑名单列表
+   * 详情请见http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN
+   * 
+ */ + WxMpUserBlacklistGetResult getBlacklist(String nextOpenid) throws WxErrorException; + + /** + *
+   *   拉黑用户
+   *   详情请见http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN
+   * 
+ */ + void pushToBlacklist(List openidList) throws WxErrorException; + + /** + *
+   *   取消拉黑用户
+   *   详情请见http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN
+   * 
+ */ + void pullFromBlacklist(List openidList) throws WxErrorException; +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java index deaf85ab..f46ca634 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java @@ -1,14 +1,14 @@ package me.chanjar.weixin.mp.api; +import java.util.List; + import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.bean.WxMpUserQuery; import me.chanjar.weixin.mp.bean.result.WxMpUser; import me.chanjar.weixin.mp.bean.result.WxMpUserList; -import java.util.List; - /** - * 用户管理和统计相关操作接口 + * 用户管理相关操作接口 * * @author Binary Wang */ @@ -42,9 +42,9 @@ public interface WxMpUserService { * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=批量获取用户基本信息 *
* - * @param openidList 用户openid列表 + * @param openids 用户openid列表 */ - List userInfoList(List openidList) throws WxErrorException; + List userInfoList(List openids) throws WxErrorException; /** *
diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java
new file mode 100644
index 00000000..0fcfb40f
--- /dev/null
+++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java
@@ -0,0 +1,101 @@
+package me.chanjar.weixin.mp.api;
+
+import java.util.List;
+
+import me.chanjar.weixin.common.exception.WxErrorException;
+import me.chanjar.weixin.mp.bean.tag.WxTagListUser;
+import me.chanjar.weixin.mp.bean.tag.WxUserTag;
+
+/**
+ * 用户标签管理相关接口
+ * Created by Binary Wang on 2016/9/2.
+ * @author binarywang(https://github.com/binarywang)
+ *
+ */
+public interface WxMpUserTagService {
+
+  /**
+   * 
+   * 创建标签
+   * 一个公众号,最多可以创建100个标签。
+   * 详情请见:用户标签管理
+   * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/create?access_token=ACCESS_TOKEN
+   * 
+ * + * @param name 标签名字(30个字符以内) + */ + WxUserTag tagCreate(String name) throws WxErrorException; + + /** + *
+   * 获取公众号已创建的标签
+   * 详情请见:用户标签管理
+   * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/get?access_token=ACCESS_TOKEN
+   * 
+ * + */ + List tagGet() throws WxErrorException; + + /** + *
+   * 编辑标签
+   * 详情请见:用户标签管理
+   * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/update?access_token=ACCESS_TOKEN
+   * 
+ * + */ + Boolean tagUpdate(Long tagId, String name) throws WxErrorException; + + /** + *
+   * 删除标签
+   * 详情请见:用户标签管理
+   * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=ACCESS_TOKEN
+   * 
+ * + */ + Boolean tagDelete(Long tagId) throws WxErrorException; + + /** + *
+   * 获取标签下粉丝列表
+   * 详情请见:用户标签管理
+   * 接口url格式: https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=ACCESS_TOKEN
+   * 
+ * + */ + WxTagListUser tagListUser(Long tagId, String nextOpenid) + throws WxErrorException; + + /** + *
+   * 批量为用户打标签
+   * 详情请见:用户标签管理
+   * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=ACCESS_TOKEN
+   * 
+ * + */ + boolean batchTagging(Long tagId, String[] openids) throws WxErrorException; + + /** + *
+   * 批量为用户取消标签
+   * 详情请见:用户标签管理
+   * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=ACCESS_TOKEN
+   * 
+ * + */ + boolean batchUntagging(Long tagId, String[] openids) throws WxErrorException; + + + /** + *
+   * 获取用户身上的标签列表
+   * 详情请见:用户标签管理
+   * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=ACCESS_TOKEN
+   * 
+ * + */ + List userTagList(String openid) throws WxErrorException; + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java index b65d1ff4..63e13809 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java @@ -1,6 +1,5 @@ package me.chanjar.weixin.mp.api.impl; -import java.security.NoSuchAlgorithmException; import java.util.Arrays; import org.slf4j.Logger; @@ -111,16 +110,12 @@ public class WxMpCardServiceImpl implements WxMpCardService { signParam[optionalSignParam.length] = String.valueOf(timestamp); signParam[optionalSignParam.length + 1] = nonceStr; signParam[optionalSignParam.length + 2] = cardApiTicket; - try { - String signature = SHA1.gen(signParam); - WxCardApiSignature cardApiSignature = new WxCardApiSignature(); - cardApiSignature.setTimestamp(timestamp); - cardApiSignature.setNonceStr(nonceStr); - cardApiSignature.setSignature(signature); - return cardApiSignature; - } catch (NoSuchAlgorithmException e) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg(e.getMessage()).build()); - } + String signature = SHA1.gen(signParam); + WxCardApiSignature cardApiSignature = new WxCardApiSignature(); + cardApiSignature.setTimestamp(timestamp); + cardApiSignature.setNonceStr(nonceStr); + cardApiSignature.setSignature(signature); + return cardApiSignature; } /** diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java index 092d6af1..2dbee076 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java @@ -1,21 +1,13 @@ package me.chanjar.weixin.mp.api.impl; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.WxMpDataCubeService; import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleResult; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleTotal; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeInterfaceResult; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeMsgResult; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import me.chanjar.weixin.mp.bean.datacube.*; +import org.apache.commons.lang3.time.FastDateFormat; +import java.text.Format; import java.util.Date; import java.util.List; @@ -24,9 +16,10 @@ import java.util.List; * @author binarywang (https://github.com/binarywang) */ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { - protected final Logger log = LoggerFactory.getLogger(WxMpDataCubeServiceImpl.class); - private static final String API_URL_PREFIX = "https://api.weixin.qq.com/datacube"; + + private final Format dateFormat = FastDateFormat.getInstance("yyyy-MM-dd"); + private WxMpService wxMpService; public WxMpDataCubeServiceImpl(WxMpService wxMpService) { @@ -37,104 +30,80 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { public List getUserSummary(Date beginDate, Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getusersummary"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeUserSummary.fromJson(responseContent); } @Override public List getUserCumulate(Date beginDate, Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getusercumulate"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeUserCumulate.fromJson(responseContent); } @Override public List getArticleSummary(Date beginDate, Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getarticlesummary"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeArticleResult.fromJson(responseContent); } @Override public List getArticleTotal(Date beginDate, Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getarticletotal"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeArticleTotal.fromJson(responseContent); } @Override public List getUserRead(Date beginDate, Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getuserread"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeArticleResult.fromJson(responseContent); } @Override public List getUserReadHour(Date beginDate, Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getuserreadhour"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeArticleResult.fromJson(responseContent); } @Override public List getUserShare(Date beginDate, Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getusershare"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeArticleResult.fromJson(responseContent); } @Override public List getUserShareHour(Date beginDate, Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getusersharehour"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeArticleResult.fromJson(responseContent); } @Override @@ -142,13 +111,10 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsg"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeMsgResult.fromJson(responseContent); } @Override @@ -156,13 +122,10 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsghour"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeMsgResult.fromJson(responseContent); } @Override @@ -170,13 +133,10 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgweek"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeMsgResult.fromJson(responseContent); } @Override @@ -184,13 +144,10 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgmonth"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeMsgResult.fromJson(responseContent); } @Override @@ -198,13 +155,10 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgdist"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeMsgResult.fromJson(responseContent); } @Override @@ -212,13 +166,10 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgdistweek"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeMsgResult.fromJson(responseContent); } @Override @@ -226,13 +177,10 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgdistmonth"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeMsgResult.fromJson(responseContent); } @Override @@ -240,13 +188,10 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getinterfacesummary"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeInterfaceResult.fromJson(responseContent); } @Override @@ -254,12 +199,9 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getinterfacesummaryhour"; JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + param.addProperty("begin_date", this.dateFormat.format(beginDate)); + param.addProperty("end_date", this.dateFormat.format(endDate)); String responseContent = this.wxMpService.post(url, param.toString()); - this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + return WxDataCubeInterfaceResult.fromJson(responseContent); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImpl.java deleted file mode 100644 index 5f97a83a..00000000 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImpl.java +++ /dev/null @@ -1,84 +0,0 @@ -package me.chanjar.weixin.mp.api.impl; - -import java.util.List; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; - -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; -import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; -import me.chanjar.weixin.common.util.json.GsonHelper; -import me.chanjar.weixin.mp.api.WxMpGroupService; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.WxMpGroup; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - -/** - * Created by Binary Wang on 2016/7/21. - */ -public class WxMpGroupServiceImpl implements WxMpGroupService { - private static final String API_URL_PREFIX = "https://api.weixin.qq.com/cgi-bin/groups"; - private WxMpService wxMpService; - - public WxMpGroupServiceImpl(WxMpService wxMpService) { - this.wxMpService = wxMpService; - } - - @Override - public WxMpGroup groupCreate(String name) throws WxErrorException { - String url = API_URL_PREFIX + "/create"; - JsonObject json = new JsonObject(); - JsonObject groupJson = new JsonObject(); - json.add("group", groupJson); - groupJson.addProperty("name", name); - - String responseContent = this.wxMpService.execute( - new SimplePostRequestExecutor(), - url, - json.toString()); - return WxMpGroup.fromJson(responseContent); - } - - @Override - public List groupGet() throws WxErrorException { - String url = API_URL_PREFIX + "/get"; - String responseContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, null); - /* - * 操蛋的微信API,创建时返回的是 { group : { id : ..., name : ...} } - * 查询时返回的是 { groups : [ { id : ..., name : ..., count : ... }, ... ] } - */ - JsonElement tmpJsonElement = new JsonParser().parse(responseContent); - return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("groups"), - new TypeToken>() { - }.getType()); - } - - @Override - public long userGetGroup(String openid) throws WxErrorException { - String url = API_URL_PREFIX + "/getid"; - JsonObject o = new JsonObject(); - o.addProperty("openid", openid); - String responseContent = this.wxMpService.execute(new SimplePostRequestExecutor(), url, o.toString()); - JsonElement tmpJsonElement = new JsonParser().parse(responseContent); - return GsonHelper.getAsLong(tmpJsonElement.getAsJsonObject().get("groupid")); - } - - @Override - public void groupUpdate(WxMpGroup group) throws WxErrorException { - String url = API_URL_PREFIX + "/update"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, group.toJson()); - } - - @Override - public void userUpdateGroup(String openid, long to_groupid) throws WxErrorException { - String url = API_URL_PREFIX + "/members/update"; - JsonObject json = new JsonObject(); - json.addProperty("openid", openid); - json.addProperty("to_groupid", to_groupid); - this.wxMpService.execute(new SimplePostRequestExecutor(), url, json.toString()); - } - -} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImpl.java index 6d6cf14c..99428348 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImpl.java @@ -1,52 +1,57 @@ package me.chanjar.weixin.mp.api.impl; -import java.io.File; -import java.util.Date; - import com.google.gson.JsonObject; - import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; -import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; -import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; import me.chanjar.weixin.mp.api.WxMpKefuService; import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.bean.WxMpCustomMessage; import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfAccountRequest; import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfSessionRequest; -import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfList; -import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfMsgList; -import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfOnlineList; -import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionGetResult; -import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionList; -import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionWaitCaseList; +import me.chanjar.weixin.mp.bean.kefu.result.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Date; /** - * + * * @author Binary Wang * */ public class WxMpKefuServiceImpl implements WxMpKefuService { + protected final Logger log = LoggerFactory + .getLogger(WxMpKefuServiceImpl.class); private static final String API_URL_PREFIX = "https://api.weixin.qq.com/customservice"; + private static final String API_URL_PREFIX_WITH_CGI_BIN = "https://api.weixin.qq.com/cgi-bin/customservice"; private WxMpService wxMpService; public WxMpKefuServiceImpl(WxMpService wxMpService) { this.wxMpService = wxMpService; } + @Override + public boolean customMessageSend(WxMpCustomMessage message) + throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"; + String responseContent = this.wxMpService.post(url, message.toJson()); + return true; + } + @Override public WxMpKfList kfList() throws WxErrorException { - String url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist"; - String responseContent = this.wxMpService - .execute(new SimpleGetRequestExecutor(), url, null); + String url = API_URL_PREFIX_WITH_CGI_BIN + "/getkflist"; + String responseContent = this.wxMpService.get(url, null); return WxMpKfList.fromJson(responseContent); } @Override public WxMpKfOnlineList kfOnlineList() throws WxErrorException { - String url = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist"; - String responseContent = this.wxMpService - .execute(new SimpleGetRequestExecutor(), url, null); + String url = API_URL_PREFIX_WITH_CGI_BIN + "/getonlinekflist"; + String responseContent = this.wxMpService.get(url, null); return WxMpKfOnlineList.fromJson(responseContent); } @@ -54,8 +59,7 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { public boolean kfAccountAdd(WxMpKfAccountRequest request) throws WxErrorException { String url = API_URL_PREFIX + "/kfaccount/add"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, - request.toJson()); + String responseContent = this.wxMpService.post(url, request.toJson()); return true; } @@ -63,16 +67,14 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { public boolean kfAccountUpdate(WxMpKfAccountRequest request) throws WxErrorException { String url = API_URL_PREFIX + "/kfaccount/update"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, - request.toJson()); + String responseContent = this.wxMpService.post(url, request.toJson()); return true; } @Override public boolean kfAccountInviteWorker(WxMpKfAccountRequest request) throws WxErrorException { String url = API_URL_PREFIX + "/kfaccount/inviteworker"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, - request.toJson()); + String responseContent = this.wxMpService.post(url, request.toJson()); return true; } @@ -80,14 +82,15 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { public boolean kfAccountUploadHeadImg(String kfAccount, File imgFile) throws WxErrorException { String url = API_URL_PREFIX + "/kfaccount/uploadheadimg?kf_account=" + kfAccount; - this.wxMpService.execute(new MediaUploadRequestExecutor(), url, imgFile); + WxMediaUploadResult responseContent = this.wxMpService + .execute(new MediaUploadRequestExecutor(), url, imgFile); return true; } @Override public boolean kfAccountDel(String kfAccount) throws WxErrorException { String url = API_URL_PREFIX + "/kfaccount/del?kf_account=" + kfAccount; - this.wxMpService.execute(new SimpleGetRequestExecutor(), url, null); + String responseContent = this.wxMpService.get(url, null); return true; } @@ -96,8 +99,7 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { throws WxErrorException { WxMpKfSessionRequest request = new WxMpKfSessionRequest(kfAccount, openid); String url = API_URL_PREFIX + "/kfsession/create"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, - request.toJson()); + String responseContent = this.wxMpService.post(url, request.toJson()); return true; } @@ -106,8 +108,7 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { throws WxErrorException { WxMpKfSessionRequest request = new WxMpKfSessionRequest(kfAccount, openid); String url = API_URL_PREFIX + "/kfsession/close"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, - request.toJson()); + String responseContent = this.wxMpService.post(url, request.toJson()); return true; } @@ -115,8 +116,7 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { public WxMpKfSessionGetResult kfSessionGet(String openid) throws WxErrorException { String url = API_URL_PREFIX + "/kfsession/getsession?openid=" + openid; - String responseContent = this.wxMpService - .execute(new SimpleGetRequestExecutor(), url, null); + String responseContent = this.wxMpService.get(url, null); return WxMpKfSessionGetResult.fromJson(responseContent); } @@ -124,8 +124,7 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { public WxMpKfSessionList kfSessionList(String kfAccount) throws WxErrorException { String url = API_URL_PREFIX + "/kfsession/getsessionlist?kf_account=" + kfAccount; - String responseContent = this.wxMpService - .execute(new SimpleGetRequestExecutor(), url, null); + String responseContent = this.wxMpService.get(url, null); return WxMpKfSessionList.fromJson(responseContent); } @@ -133,8 +132,7 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { public WxMpKfSessionWaitCaseList kfSessionGetWaitCase() throws WxErrorException { String url = API_URL_PREFIX + "/kfsession/getwaitcase"; - String responseContent = this.wxMpService - .execute(new SimpleGetRequestExecutor(), url, null); + String responseContent = this.wxMpService.get(url, null); return WxMpKfSessionWaitCaseList.fromJson(responseContent); } @@ -156,7 +154,8 @@ public class WxMpKefuServiceImpl implements WxMpKefuService { param.addProperty("msgid", msgId); //msgid 消息id顺序从小到大,从1开始 param.addProperty("number", number); //number 每次获取条数,最多10000条 - String responseContent = this.wxMpService.execute(new SimplePostRequestExecutor(), url, param.toString()); + String responseContent = this.wxMpService.post(url, param.toString()); + return WxMpKfMsgList.fromJson(responseContent); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java index c6825815..310bbe78 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java @@ -50,7 +50,10 @@ public class WxMpMaterialServiceImpl implements WxMpMaterialService { @Override public File mediaDownload(String media_id) throws WxErrorException { String url = MEDIA_API_URL_PREFIX + "/get"; - return this.wxMpService.execute(new MediaDownloadRequestExecutor(this.wxMpService.getWxMpConfigStorage().getTmpDirFile()), url, "media_id=" + media_id); + return this.wxMpService.execute( + new MediaDownloadRequestExecutor(this.wxMpService.getWxMpConfigStorage().getTmpDirFile()), + url, + "media_id=" + media_id); } @Override diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java index 28dbff91..2f40f709 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java @@ -1,9 +1,10 @@ package me.chanjar.weixin.mp.api.impl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; -import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; import me.chanjar.weixin.mp.api.WxMpMenuService; import me.chanjar.weixin.mp.api.WxMpService; @@ -12,6 +13,8 @@ import me.chanjar.weixin.mp.api.WxMpService; */ public class WxMpMenuServiceImpl implements WxMpMenuService { private static final String API_URL_PREFIX = "https://api.weixin.qq.com/cgi-bin/menu"; + private static Logger log = LoggerFactory + .getLogger(WxMpMenuServiceImpl.class); private WxMpService wxMpService; @@ -21,32 +24,37 @@ public class WxMpMenuServiceImpl implements WxMpMenuService { @Override public void menuCreate(WxMenu menu) throws WxErrorException { + String menuJson = menu.toJson(); + String url = API_URL_PREFIX + "/create"; if (menu.getMatchRule() != null) { - String url = API_URL_PREFIX + "/addconditional"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, menu.toJson()); - } else { - String url = API_URL_PREFIX + "/create"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, menu.toJson()); + url = API_URL_PREFIX + "/addconditional"; } + + log.debug("开始创建菜单:{}", menuJson); + + String result = this.wxMpService.post(url, menuJson); + log.debug("创建菜单:{},结果:{}", menuJson, result); } @Override public void menuDelete() throws WxErrorException { String url = API_URL_PREFIX + "/delete"; - this.wxMpService.execute(new SimpleGetRequestExecutor(), url, null); + String result = this.wxMpService.get(url, null); + log.debug("删除菜单结果:{}", result); } @Override public void menuDelete(String menuid) throws WxErrorException { String url = API_URL_PREFIX + "/delconditional"; - this.wxMpService.execute(new SimpleGetRequestExecutor(), url, "menuid=" + menuid); + String result = this.wxMpService.get(url, "menuid=" + menuid); + log.debug("根据MeunId({})删除菜单结果:{}", menuid, result); } @Override public WxMenu menuGet() throws WxErrorException { String url = API_URL_PREFIX + "/get"; try { - String resultContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, null); + String resultContent = this.wxMpService.get(url, null); return WxMenu.fromJson(resultContent); } catch (WxErrorException e) { // 46003 不存在的菜单数据 @@ -61,11 +69,12 @@ public class WxMpMenuServiceImpl implements WxMpMenuService { public WxMenu menuTryMatch(String userid) throws WxErrorException { String url = API_URL_PREFIX + "/trymatch"; try { - String resultContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, "user_id=" + userid); + String resultContent = this.wxMpService.get(url, "user_id=" + userid); return WxMenu.fromJson(resultContent); } catch (WxErrorException e) { // 46003 不存在的菜单数据 46002 不存在的菜单版本 - if (e.getError().getErrorCode() == 46003 || e.getError().getErrorCode() == 46002) { + if (e.getError().getErrorCode() == 46003 + || e.getError().getErrorCode() == 46002) { return null; } throw e; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index ce7f9517..dcb1e89f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -1,28 +1,37 @@ package me.chanjar.weixin.mp.api.impl; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.StringUtils; +import org.joor.Reflect; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import me.chanjar.weixin.common.annotation.Required; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.crypto.WxCryptUtil; -import me.chanjar.weixin.common.util.http.Utf8ResponseHandler; import me.chanjar.weixin.common.util.xml.XStreamInitializer; import me.chanjar.weixin.mp.api.WxMpPayService; -import me.chanjar.weixin.mp.bean.result.*; -import org.apache.http.Consts; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.helpers.MessageFormatter; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback; +import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; +import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; +import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; +import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderResult; /** * Created by Binary Wang on 2016/7/28. @@ -31,198 +40,25 @@ import java.util.TreeMap; */ public class WxMpPayServiceImpl implements WxMpPayService { + private static final List TRADE_TYPES = Lists.newArrayList("JSAPI", + "NATIVE", "APP"); private final Logger log = LoggerFactory.getLogger(WxMpPayServiceImpl.class); - private final String[] REQUIRED_ORDER_PARAMETERS = new String[]{"appid", - "mch_id", "body", "out_trade_no", "total_fee", "spbill_create_ip", - "notify_url", "trade_type"}; - private HttpHost httpProxy; - private WxMpServiceImpl wxMpService; + private WxMpService wxMpService; - public WxMpPayServiceImpl(WxMpServiceImpl wxMpService) { + public WxMpPayServiceImpl(WxMpService wxMpService) { this.wxMpService = wxMpService; - this.httpProxy = wxMpService.getHttpProxy(); - } - - @Override - public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, - double amt, String body, String tradeType, String ip, - String callbackUrl) { - Map packageParams = new HashMap<>(); - packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("body", body); - packageParams.put("out_trade_no", outTradeNo); - packageParams.put("total_fee", (int) (amt * 100) + ""); - packageParams.put("spbill_create_ip", ip); - packageParams.put("notify_url", callbackUrl); - packageParams.put("trade_type", tradeType); - packageParams.put("openid", openId); - - return getPrepayId(packageParams); - } - - @Override - public WxMpPrepayIdResult getPrepayId(final Map parameters) { - final SortedMap packageParams = new TreeMap<>(parameters); - packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("nonce_str", System.currentTimeMillis() + ""); - checkParameters(packageParams); - - String sign = WxCryptUtil.createSign(packageParams, - this.wxMpService.getWxMpConfigStorage().getPartnerKey()); - packageParams.put("sign", sign); - - StringBuilder request = new StringBuilder(""); - for (Map.Entry para : packageParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), - para.getValue(), para.getKey())); - } - - request.append(""); - - HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/pay/unifiedorder"); - if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); - httpPost.setConfig(config); - } - - StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); - httpPost.setEntity(entity); - try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); - XStream xstream = XStreamInitializer.getInstance(); - xstream.alias("xml", WxMpPrepayIdResult.class); - return (WxMpPrepayIdResult) xstream.fromXML(responseContent); - } catch (IOException e) { - throw new RuntimeException("Failed to get prepay id due to IO exception.", - e); - } finally { - httpPost.releaseConnection(); - } - } - - private void checkParameters(Map parameters) { - for (String para : this.REQUIRED_ORDER_PARAMETERS) { - if (!parameters.containsKey(para)) { - throw new IllegalArgumentException( - "Reqiured argument '" + para + "' is missing."); - } - } - - if ("JSAPI".equals(parameters.get("trade_type")) - && !parameters.containsKey("openid")) { - throw new IllegalArgumentException( - "Reqiured argument 'openid' is missing when trade_type is 'JSAPI'."); - } - - if ("NATIVE".equals(parameters.get("trade_type")) - && !parameters.containsKey("product_id")) { - throw new IllegalArgumentException( - "Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'."); - } - } - - @Override - public Map getJsapiPayInfo(String openId, String outTradeNo, - double amt, String body, String ip, String callbackUrl) - throws WxErrorException { - Map packageParams = new HashMap<>(); - packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("body", body); - packageParams.put("out_trade_no", outTradeNo); - packageParams.put("total_fee", (int) (amt * 100) + ""); - packageParams.put("spbill_create_ip", ip); - packageParams.put("notify_url", callbackUrl); - packageParams.put("trade_type", "JSAPI"); - packageParams.put("openid", openId); - - return getPayInfo(packageParams); - } - - @Override - public Map getNativePayInfo(String productId, - String outTradeNo, double amt, String body, String ip, String callbackUrl) - throws WxErrorException { - Map packageParams = new HashMap<>(); - packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("body", body); - packageParams.put("out_trade_no", outTradeNo); - packageParams.put("total_fee", (int) (amt * 100) + ""); - packageParams.put("spbill_create_ip", ip); - packageParams.put("notify_url", callbackUrl); - packageParams.put("trade_type", "NATIVE"); - packageParams.put("product_id", productId); - - return getPayInfo(packageParams); - } - - @Override - public Map getPayInfo(Map parameters) - throws WxErrorException { - WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(parameters); - - if (!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getReturn_code()) - || !"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { - WxError error = new WxError(); - error.setErrorCode(-1); - error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code() - + ";return_msg:" + wxMpPrepayIdResult.getReturn_msg() - + ";result_code:" + wxMpPrepayIdResult.getResult_code() + ";err_code" - + wxMpPrepayIdResult.getErr_code() + ";err_code_des" - + wxMpPrepayIdResult.getErr_code_des()); - throw new WxErrorException(error); - } - - String prepayId = wxMpPrepayIdResult.getPrepay_id(); - if (prepayId == null || prepayId.equals("")) { - throw new RuntimeException( - String.format("Failed to get prepay id due to error code '%s'(%s).", - wxMpPrepayIdResult.getErr_code(), - wxMpPrepayIdResult.getErr_code_des())); - } - - Map payInfo = new HashMap<>(); - payInfo.put("appId", this.wxMpService.getWxMpConfigStorage().getAppId()); - // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符 - payInfo.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000)); - payInfo.put("nonceStr", System.currentTimeMillis() + ""); - payInfo.put("package", "prepay_id=" + prepayId); - payInfo.put("signType", "MD5"); - if ("NATIVE".equals(parameters.get("trade_type"))) { - payInfo.put("codeUrl", wxMpPrepayIdResult.getCode_url()); - } - - String finalSign = WxCryptUtil.createSign(payInfo, - this.wxMpService.getWxMpConfigStorage().getPartnerKey()); - payInfo.put("paySign", finalSign); - return payInfo; } @Override public WxMpPayResult getJSSDKPayResult(String transactionId, - String outTradeNo) { + String outTradeNo) throws WxErrorException { String nonce_str = System.currentTimeMillis() + ""; SortedMap packageParams = new TreeMap<>(); packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); if (transactionId != null && !"".equals(transactionId.trim())) { packageParams.put("transaction_id", transactionId); @@ -230,41 +66,25 @@ public class WxMpPayServiceImpl implements WxMpPayService { packageParams.put("out_trade_no", outTradeNo); } else { throw new IllegalArgumentException( - "Either 'transactionId' or 'outTradeNo' must be given."); + "Either 'transactionId' or 'outTradeNo' must be given."); } packageParams.put("nonce_str", nonce_str); - packageParams.put("sign", WxCryptUtil.createSign(packageParams, - this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + packageParams.put("sign", this.createSign(packageParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey())); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { request.append(String.format("<%s>%s", para.getKey(), - para.getValue(), para.getKey())); + para.getValue(), para.getKey())); } request.append(""); - HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/pay/orderquery"); - if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); - httpPost.setConfig(config); - } - - StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); - httpPost.setEntity(entity); - try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); - XStream xstream = XStreamInitializer.getInstance(); - xstream.alias("xml", WxMpPayResult.class); - return (WxMpPayResult) xstream.fromXML(responseContent); - } catch (IOException e) { - throw new RuntimeException("Failed to query order due to IO exception.", - e); - } + String url = "https://api.mch.weixin.qq.com/pay/orderquery"; + String responseContent = this.wxMpService.post(url, request.toString()); + XStream xstream = XStreamInitializer.getInstance(); + xstream.alias("xml", WxMpPayResult.class); + return (WxMpPayResult) xstream.fromXML(responseContent); } @Override @@ -282,127 +102,237 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public WxMpPayRefundResult refundPay(Map parameters) - throws WxErrorException { + throws WxErrorException { SortedMap refundParams = new TreeMap<>(parameters); refundParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); refundParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); refundParams.put("nonce_str", System.currentTimeMillis() + ""); refundParams.put("op_user_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); - String sign = WxCryptUtil.createSign(refundParams, - this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + String sign = this.createSign(refundParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); refundParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : refundParams.entrySet()) { request.append(String.format("<%s>%s", para.getKey(), - para.getValue(), para.getKey())); + para.getValue(), para.getKey())); } request.append(""); - HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/secapi/pay/refund"); - if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); - httpPost.setConfig(config); + String url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; + String responseContent = this.wxMpService.post(url, request.toString()); + XStream xstream = XStreamInitializer.getInstance(); + xstream.processAnnotations(WxMpPayRefundResult.class); + WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream + .fromXML(responseContent); + + if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) + || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { + WxError error = new WxError(); + error.setErrorCode(-1); + error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() + + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() + + ";result_code:" + wxMpPayRefundResult.getResultCode() + ";err_code" + + wxMpPayRefundResult.getErrCode() + ";err_code_des" + + wxMpPayRefundResult.getErrCodeDes()); + throw new WxErrorException(error); } - StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); - httpPost.setEntity(entity); - try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); - XStream xstream = XStreamInitializer.getInstance(); - xstream.processAnnotations(WxMpPayRefundResult.class); - WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream - .fromXML(responseContent); - - if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) - || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { - WxError error = new WxError(); - error.setErrorCode(-1); - error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() - + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() - + ";result_code:" + wxMpPayRefundResult.getResultCode() - + ";err_code" + wxMpPayRefundResult.getErrCode() + ";err_code_des" - + wxMpPayRefundResult.getErrCodeDes()); - throw new WxErrorException(error); + return wxMpPayRefundResult; + } + + @Override + public boolean checkJSSDKCallbackDataSignature(Map kvm, + String signature) { + return signature.equals(this.createSign(kvm, + this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + } + + @Override + public WxRedpackResult sendRedpack(WxSendRedpackRequest request) + throws WxErrorException { + XStream xstream = XStreamInitializer.getInstance(); + xstream.processAnnotations(WxSendRedpackRequest.class); + xstream.processAnnotations(WxRedpackResult.class); + + request.setWxAppid(this.wxMpService.getWxMpConfigStorage().getAppId()); + request.setMchId(this.wxMpService.getWxMpConfigStorage().getPartnerId()); + request.setNonceStr(System.currentTimeMillis() + ""); + + String sign = this.createSign(xmlBean2Map(request), + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + request.setSign(sign); + + String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; + if (request.getAmtType() != null) { + //裂变红包 + url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack"; + } + + String responseContent = this.wxMpService.post(url, xstream.toXML(request)); + WxRedpackResult redpackResult = (WxRedpackResult) xstream + .fromXML(responseContent); + if ("FAIL".equals(redpackResult.getResultCode())) { + throw new WxErrorException(WxError.newBuilder() + .setErrorMsg( + redpackResult.getErrCode() + ":" + redpackResult.getErrCodeDes()) + .build()); + } + + return redpackResult; + } + + private Map xmlBean2Map(Object bean) { + Map result = Maps.newHashMap(); + for (Entry entry : Reflect.on(bean).fields().entrySet()) { + Reflect reflect = entry.getValue(); + if (reflect.get() == null) { + continue; + } + + try { + Field field = bean.getClass().getDeclaredField(entry.getKey()); + if (field.isAnnotationPresent(XStreamAlias.class)) { + result.put(field.getAnnotation(XStreamAlias.class).value(), + reflect.get().toString()); + } + } catch (NoSuchFieldException | SecurityException e) { + e.printStackTrace(); } - return wxMpPayRefundResult; - } catch (IOException e) { - String message = MessageFormatter - .format("Exception happened when sending refund '{}'.", - request.toString()) - .getMessage(); - this.log.error(message, e); - throw new WxErrorException( - WxError.newBuilder().setErrorMsg(message).build()); - } finally { - httpPost.releaseConnection(); } + + return result; } - @Override - public boolean checkJSSDKCallbackDataSignature(Map kvm, - String signature) { - return signature.equals(WxCryptUtil.createSign(kvm, - this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + /** + * 微信公众号支付签名算法(详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3) + * @param packageParams 原始参数 + * @param signKey 加密Key(即 商户Key) + * @return 签名字符串 + */ + private String createSign(Map packageParams, String signKey) { + SortedMap sortedMap = new TreeMap<>(packageParams); + + StringBuffer toSign = new StringBuffer(); + for (String key : sortedMap.keySet()) { + String value = packageParams.get(key); + if (null != value && !"".equals(value) && !"sign".equals(key) + && !"key".equals(key)) { + toSign.append(key + "=" + value + "&"); + } + } + + toSign.append("key=" + signKey); + + return DigestUtils.md5Hex(toSign.toString()).toUpperCase(); } @Override - public WxRedpackResult sendRedpack(Map parameters) - throws WxErrorException { - SortedMap packageParams = new TreeMap<>(parameters); - packageParams.put("wxappid", - this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("nonce_str", System.currentTimeMillis() + ""); + public WxUnifiedOrderResult unifiedOrder(WxUnifiedOrderRequest request) + throws WxErrorException { + checkParameters(request); + + XStream xstream = XStreamInitializer.getInstance(); + xstream.processAnnotations(WxUnifiedOrderRequest.class); + xstream.processAnnotations(WxUnifiedOrderResult.class); + + request.setAppid(this.wxMpService.getWxMpConfigStorage().getAppId()); + request.setMchId(this.wxMpService.getWxMpConfigStorage().getPartnerId()); + request.setNonceStr(System.currentTimeMillis() + ""); + + String sign = this.createSign(xmlBean2Map(request), + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + request.setSign(sign); + + String url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; + + String responseContent = this.wxMpService.post(url, xstream.toXML(request)); + WxUnifiedOrderResult result = (WxUnifiedOrderResult) xstream + .fromXML(responseContent); + if ("FAIL".equals(result.getResultCode())) { + throw new WxErrorException(WxError.newBuilder() + .setErrorMsg(result.getErrCode() + ":" + result.getErrCodeDes()) + .build()); + } - String sign = WxCryptUtil.createSign(packageParams, - this.wxMpService.getWxMpConfigStorage().getPartnerKey()); - packageParams.put("sign", sign); + return result; - StringBuilder request = new StringBuilder(""); - for (Map.Entry para : packageParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), - para.getValue(), para.getKey())); + } + + private void checkParameters(WxUnifiedOrderRequest request) { + + List nullFields = Lists.newArrayList(); + for (Entry entry : Reflect.on(request).fields() + .entrySet()) { + Reflect reflect = entry.getValue(); + try { + Field field = request.getClass().getDeclaredField(entry.getKey()); + if (field.isAnnotationPresent(Required.class) + && reflect.get() == null) { + nullFields.add(entry.getKey()); + } + } catch (NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } } - request.append(""); + if (!nullFields.isEmpty()) { + throw new IllegalArgumentException("必填字段[" + nullFields + "]必须提供值"); + } + + if (!TRADE_TYPES.contains(request.getTradeType())) { + throw new IllegalArgumentException( + "trade_type目前必须为" + TRADE_TYPES + "其中之一"); - HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); - if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); - httpPost.setConfig(config); } - StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); - httpPost.setEntity(entity); - try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); - XStream xstream = XStreamInitializer.getInstance(); - xstream.processAnnotations(WxRedpackResult.class); - return (WxRedpackResult) xstream.fromXML(responseContent); - } catch (IOException e) { - String message = MessageFormatter - .format("Exception occured when sending redpack '{}'.", - request.toString()) - .getMessage(); - this.log.error(message, e); - throw new WxErrorException(WxError.newBuilder().setErrorMsg(message).build()); - } finally { - httpPost.releaseConnection(); + if ("JSAPI".equals(request.getTradeType()) && request.getOpenid() == null) { + throw new IllegalArgumentException("当 trade_type是'JSAPI'时未指定openid"); + } + + if ("NATIVE".equals(request.getTradeType()) + && request.getProductId() == null) { + throw new IllegalArgumentException("当 trade_type是'NATIVE'时未指定product_id"); } } + @Override + public Map getPayInfo(WxUnifiedOrderRequest request) throws WxErrorException { + WxUnifiedOrderResult unifiedOrderResult = this.unifiedOrder(request); + + if (!"SUCCESS".equalsIgnoreCase(unifiedOrderResult.getReturnCode()) + || !"SUCCESS".equalsIgnoreCase(unifiedOrderResult.getResultCode())) { + throw new WxErrorException(WxError.newBuilder().setErrorCode(-1) + .setErrorMsg("return_code:" + unifiedOrderResult.getReturnCode() + ";return_msg:" + + unifiedOrderResult.getReturnMsg() + ";result_code:" + unifiedOrderResult.getResultCode() + ";err_code" + + unifiedOrderResult.getErrCode() + ";err_code_des" + unifiedOrderResult.getErrCodeDes()) + .build()); + } + + String prepayId = unifiedOrderResult.getPrepayId(); + if (StringUtils.isBlank(prepayId)) { + throw new RuntimeException(String.format("Failed to get prepay id due to error code '%s'(%s).", + unifiedOrderResult.getErrCode(), unifiedOrderResult.getErrCodeDes())); + } + + Map payInfo = new HashMap<>(); + payInfo.put("appId", this.wxMpService.getWxMpConfigStorage().getAppId()); + // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符 + payInfo.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000)); + payInfo.put("nonceStr", System.currentTimeMillis() + ""); + payInfo.put("package", "prepay_id=" + prepayId); + payInfo.put("signType", "MD5"); + if ("NATIVE".equals(request.getTradeType())) { + payInfo.put("codeUrl", unifiedOrderResult.getCodeURL()); + } + + String finalSign = this.createSign(payInfo, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + payInfo.put("paySign", finalSign); + return payInfo; + } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java index b3f52ed8..1a7ffe84 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java @@ -1,9 +1,23 @@ package me.chanjar.weixin.mp.api.impl; +import java.io.IOException; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.DefaultHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; + import me.chanjar.weixin.common.bean.WxAccessToken; import me.chanjar.weixin.common.bean.WxJsapiSignature; import me.chanjar.weixin.common.bean.result.WxError; @@ -12,23 +26,38 @@ import me.chanjar.weixin.common.session.StandardSessionManager; import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.common.util.RandomUtils; import me.chanjar.weixin.common.util.crypto.SHA1; -import me.chanjar.weixin.common.util.http.*; -import me.chanjar.weixin.mp.api.*; -import me.chanjar.weixin.mp.bean.*; -import me.chanjar.weixin.mp.bean.result.*; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.conn.ssl.DefaultHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.client.BasicResponseHandler; -import org.apache.http.impl.client.CloseableHttpClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; +import me.chanjar.weixin.common.util.http.ApacheHttpClientBuilder; +import me.chanjar.weixin.common.util.http.DefaultApacheHttpClientBuilder; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; +import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; +import me.chanjar.weixin.common.util.http.URIUtil; +import me.chanjar.weixin.mp.api.WxMpCardService; +import me.chanjar.weixin.mp.api.WxMpConfigStorage; +import me.chanjar.weixin.mp.api.WxMpDataCubeService; +import me.chanjar.weixin.mp.api.WxMpKefuService; +import me.chanjar.weixin.mp.api.WxMpMaterialService; +import me.chanjar.weixin.mp.api.WxMpMenuService; +import me.chanjar.weixin.mp.api.WxMpPayService; +import me.chanjar.weixin.mp.api.WxMpQrcodeService; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.WxMpStoreService; +import me.chanjar.weixin.mp.api.WxMpUserBlacklistService; +import me.chanjar.weixin.mp.api.WxMpUserService; +import me.chanjar.weixin.mp.api.WxMpUserTagService; +import me.chanjar.weixin.mp.bean.WxMpIndustry; +import me.chanjar.weixin.mp.bean.WxMpMassNews; +import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage; +import me.chanjar.weixin.mp.bean.WxMpMassPreviewMessage; +import me.chanjar.weixin.mp.bean.WxMpMassTagMessage; +import me.chanjar.weixin.mp.bean.WxMpMassVideo; +import me.chanjar.weixin.mp.bean.WxMpSemanticQuery; +import me.chanjar.weixin.mp.bean.WxMpTemplateMessage; +import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult; +import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult; +import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; +import me.chanjar.weixin.mp.bean.result.WxMpSemanticQueryResult; +import me.chanjar.weixin.mp.bean.result.WxMpUser; public class WxMpServiceImpl implements WxMpService { @@ -46,8 +75,8 @@ public class WxMpServiceImpl implements WxMpService { */ private final Object globalJsapiTicketRefreshLock = new Object(); - private WxMpConfigStorage wxMpConfigStorage; - + private WxMpConfigStorage configStorage; + private WxMpKefuService kefuService = new WxMpKefuServiceImpl(this); private WxMpMaterialService materialService = new WxMpMaterialServiceImpl(this); @@ -56,7 +85,7 @@ public class WxMpServiceImpl implements WxMpService { private WxMpUserService userService = new WxMpUserServiceImpl(this); - private WxMpGroupService groupService = new WxMpGroupServiceImpl(this); + private WxMpUserTagService tagService = new WxMpUserTagServiceImpl(this); private WxMpQrcodeService qrCodeService = new WxMpQrcodeServiceImpl(this); @@ -64,8 +93,12 @@ public class WxMpServiceImpl implements WxMpService { private WxMpPayService payService = new WxMpPayServiceImpl(this); + private WxMpStoreService storeService = new WxMpStoreServiceImpl(this); + private WxMpDataCubeService dataCubeService = new WxMpDataCubeServiceImpl(this); + private WxMpUserBlacklistService blackListService = new WxMpUserBlacklistServiceImpl(this); + private CloseableHttpClient httpClient; private HttpHost httpProxy; @@ -79,7 +112,8 @@ public class WxMpServiceImpl implements WxMpService { @Override public boolean checkSignature(String timestamp, String nonce, String signature) { try { - return SHA1.gen(this.wxMpConfigStorage.getToken(), timestamp, nonce).equals(signature); + return SHA1.gen(this.configStorage.getToken(), timestamp, nonce) + .equals(signature); } catch (Exception e) { return false; } @@ -93,14 +127,14 @@ public class WxMpServiceImpl implements WxMpService { @Override public String getAccessToken(boolean forceRefresh) throws WxErrorException { if (forceRefresh) { - this.wxMpConfigStorage.expireAccessToken(); + this.configStorage.expireAccessToken(); } - if (this.wxMpConfigStorage.isAccessTokenExpired()) { + if (this.configStorage.isAccessTokenExpired()) { synchronized (this.globalAccessTokenRefreshLock) { - if (this.wxMpConfigStorage.isAccessTokenExpired()) { + if (this.configStorage.isAccessTokenExpired()) { String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + - "&appid=" + this.wxMpConfigStorage.getAppId() + - "&secret=" + this.wxMpConfigStorage.getSecret(); + "&appid=" + this.configStorage.getAppId() + "&secret=" + + this.configStorage.getSecret(); try { HttpGet httpGet = new HttpGet(url); if (this.httpProxy != null) { @@ -114,7 +148,8 @@ public class WxMpServiceImpl implements WxMpService { throw new WxErrorException(error); } WxAccessToken accessToken = WxAccessToken.fromJson(resultContent); - this.wxMpConfigStorage.updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn()); + this.configStorage.updateAccessToken(accessToken.getAccessToken(), + accessToken.getExpiresIn()); }finally { httpGet.releaseConnection(); } @@ -124,7 +159,7 @@ public class WxMpServiceImpl implements WxMpService { } } } - return this.wxMpConfigStorage.getAccessToken(); + return this.configStorage.getAccessToken(); } @Override @@ -135,23 +170,23 @@ public class WxMpServiceImpl implements WxMpService { @Override public String getJsapiTicket(boolean forceRefresh) throws WxErrorException { if (forceRefresh) { - this.wxMpConfigStorage.expireJsapiTicket(); + this.configStorage.expireJsapiTicket(); } - if (this.wxMpConfigStorage.isJsapiTicketExpired()) { + if (this.configStorage.isJsapiTicketExpired()) { synchronized (this.globalJsapiTicketRefreshLock) { - if (this.wxMpConfigStorage.isJsapiTicketExpired()) { + if (this.configStorage.isJsapiTicketExpired()) { String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi"; String responseContent = execute(new SimpleGetRequestExecutor(), url, null); JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String jsapiTicket = tmpJsonObject.get("ticket").getAsString(); int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt(); - this.wxMpConfigStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds); + this.configStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds); } } } - return this.wxMpConfigStorage.getJsapiTicket(); + return this.configStorage.getJsapiTicket(); } @Override @@ -159,63 +194,49 @@ public class WxMpServiceImpl implements WxMpService { long timestamp = System.currentTimeMillis() / 1000; String noncestr = RandomUtils.getRandomStr(); String jsapiTicket = getJsapiTicket(false); - try { - String signature = SHA1.genWithAmple( - "jsapi_ticket=" + jsapiTicket, - "noncestr=" + noncestr, - "timestamp=" + timestamp, - "url=" + url - ); - WxJsapiSignature jsapiSignature = new WxJsapiSignature(); - jsapiSignature.setAppid(this.wxMpConfigStorage.getAppId()); - jsapiSignature.setTimestamp(timestamp); - jsapiSignature.setNoncestr(noncestr); - jsapiSignature.setUrl(url); - jsapiSignature.setSignature(signature); - return jsapiSignature; - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - @Override - public void customMessageSend(WxMpCustomMessage message) throws WxErrorException { - String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"; - execute(new SimplePostRequestExecutor(), url, message.toJson()); + String signature = SHA1.genWithAmple("jsapi_ticket=" + jsapiTicket, + "noncestr=" + noncestr, "timestamp=" + timestamp, "url=" + url); + WxJsapiSignature jsapiSignature = new WxJsapiSignature(); + jsapiSignature.setAppid(this.configStorage.getAppId()); + jsapiSignature.setTimestamp(timestamp); + jsapiSignature.setNoncestr(noncestr); + jsapiSignature.setUrl(url); + jsapiSignature.setSignature(signature); + return jsapiSignature; } @Override public WxMpMassUploadResult massNewsUpload(WxMpMassNews news) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews"; - String responseContent = execute(new SimplePostRequestExecutor(), url, news.toJson()); + String responseContent = this.post(url, news.toJson()); return WxMpMassUploadResult.fromJson(responseContent); } @Override public WxMpMassUploadResult massVideoUpload(WxMpMassVideo video) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/media/uploadvideo"; - String responseContent = execute(new SimplePostRequestExecutor(), url, video.toJson()); + String responseContent = this.post(url, video.toJson()); return WxMpMassUploadResult.fromJson(responseContent); } @Override - public WxMpMassSendResult massGroupMessageSend(WxMpMassGroupMessage message) throws WxErrorException { + public WxMpMassSendResult massGroupMessageSend(WxMpMassTagMessage message) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall"; - String responseContent = execute(new SimplePostRequestExecutor(), url, message.toJson()); + String responseContent = this.post(url, message.toJson()); return WxMpMassSendResult.fromJson(responseContent); } @Override public WxMpMassSendResult massOpenIdsMessageSend(WxMpMassOpenIdsMessage message) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send"; - String responseContent = execute(new SimplePostRequestExecutor(), url, message.toJson()); + String responseContent = this.post(url, message.toJson()); return WxMpMassSendResult.fromJson(responseContent); } @Override public WxMpMassSendResult massMessagePreview(WxMpMassPreviewMessage wxMpMassPreviewMessage) throws Exception { String url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview"; - String responseContent = execute(new SimplePostRequestExecutor(), url, wxMpMassPreviewMessage.toJson()); + String responseContent = this.post(url, wxMpMassPreviewMessage.toJson()); return WxMpMassSendResult.fromJson(responseContent); } @@ -225,7 +246,7 @@ public class WxMpServiceImpl implements WxMpService { JsonObject o = new JsonObject(); o.addProperty("action", "long2short"); o.addProperty("long_url", long_url); - String responseContent = execute(new SimplePostRequestExecutor(), url, o.toString()); + String responseContent = this.post(url, o.toString()); JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); return tmpJsonElement.getAsJsonObject().get("short_url").getAsString(); } @@ -233,9 +254,8 @@ public class WxMpServiceImpl implements WxMpService { @Override public String templateSend(WxMpTemplateMessage templateMessage) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/message/template/send"; - String responseContent = execute(new SimplePostRequestExecutor(), url, templateMessage.toJson()); - JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); - final JsonObject jsonObject = tmpJsonElement.getAsJsonObject(); + String responseContent = this.post(url, templateMessage.toJson()); + final JsonObject jsonObject = JSON_PARSER.parse(responseContent).getAsJsonObject(); if (jsonObject.get("errcode").getAsInt() == 0){ return jsonObject.get("msgid").getAsString(); } @@ -250,20 +270,20 @@ public class WxMpServiceImpl implements WxMpService { throw new IllegalArgumentException("industry id is empty"); } String url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry"; - return execute(new SimplePostRequestExecutor(), url, wxMpIndustry.toJson()); + return this.post(url, wxMpIndustry.toJson()); } @Override public WxMpIndustry getIndustry() throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/template/get_industry"; - String responseContent = execute(new SimpleGetRequestExecutor(), url, null); + String responseContent = this.get(url, null); return WxMpIndustry.fromJson(responseContent); } @Override public WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) throws WxErrorException { String url = "https://api.weixin.qq.com/semantic/semproxy/search"; - String responseContent = execute(new SimplePostRequestExecutor(), url, semanticQuery.toJson()); + String responseContent = this.post(url, semanticQuery.toJson()); return WxMpSemanticQueryResult.fromJson(responseContent); } @@ -271,7 +291,7 @@ public class WxMpServiceImpl implements WxMpService { public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state) { StringBuilder url = new StringBuilder(); url.append("https://open.weixin.qq.com/connect/oauth2/authorize?"); - url.append("appid=").append(this.wxMpConfigStorage.getAppId()); + url.append("appid=").append(this.configStorage.getAppId()); url.append("&redirect_uri=").append(URIUtil.encodeURIComponent(redirectURI)); url.append("&response_type=code"); url.append("&scope=").append(scope); @@ -287,14 +307,14 @@ public class WxMpServiceImpl implements WxMpService { String state) { StringBuilder url = new StringBuilder(); url.append("https://open.weixin.qq.com/connect/qrconnect?"); - url.append("appid=").append(this.wxMpConfigStorage.getAppId()); + url.append("appid=").append(this.configStorage.getAppId()); url.append("&redirect_uri=").append(URIUtil.encodeURIComponent(redirectURI)); url.append("&response_type=code"); url.append("&scope=").append(scope); if (state != null) { url.append("&state=").append(state); } - + url.append("#wechat_redirect"); return url.toString(); } @@ -313,8 +333,8 @@ public class WxMpServiceImpl implements WxMpService { public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException { StringBuilder url = new StringBuilder(); url.append("https://api.weixin.qq.com/sns/oauth2/access_token?"); - url.append("appid=").append(this.wxMpConfigStorage.getAppId()); - url.append("&secret=").append(this.wxMpConfigStorage.getSecret()); + url.append("appid=").append(this.configStorage.getAppId()); + url.append("&secret=").append(this.configStorage.getSecret()); url.append("&code=").append(code); url.append("&grant_type=authorization_code"); @@ -325,7 +345,7 @@ public class WxMpServiceImpl implements WxMpService { public WxMpOAuth2AccessToken oauth2refreshAccessToken(String refreshToken) throws WxErrorException { StringBuilder url = new StringBuilder(); url.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?"); - url.append("appid=").append(this.wxMpConfigStorage.getAppId()); + url.append("appid=").append(this.configStorage.getAppId()); url.append("&grant_type=refresh_token"); url.append("&refresh_token=").append(refreshToken); @@ -402,7 +422,9 @@ public class WxMpServiceImpl implements WxMpService { int retryTimes = 0; do { try { - return executeInternal(executor, uri, data); + T result = executeInternal(executor, uri, data); + this.log.debug("\n[URL]: {}\n[PARAMS]: {}\n[RESPONSE]: {}",uri, data, result); + return result; } catch (WxErrorException e) { WxError error = e.getError(); /** @@ -445,10 +467,12 @@ public class WxMpServiceImpl implements WxMpService { */ if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001) { // 强制设置wxMpConfigStorage它的access token过期了,这样在下一次请求里就会刷新access token - this.wxMpConfigStorage.expireAccessToken(); - return execute(executor, uri, data); + this.configStorage.expireAccessToken(); + return this.execute(executor, uri, data); } if (error.getErrorCode() != 0) { + this.log.error("\n[URL]: {}\n[PARAMS]: {}\n[RESPONSE]: {}", uri, data, + error); throw new WxErrorException(error); } return null; @@ -456,7 +480,7 @@ public class WxMpServiceImpl implements WxMpService { throw new RuntimeException(e); } } - + public HttpHost getHttpProxy() { return this.httpProxy; } @@ -467,33 +491,39 @@ public class WxMpServiceImpl implements WxMpService { @Override public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) { - this.wxMpConfigStorage = wxConfigProvider; + this.configStorage = wxConfigProvider; this.initHttpClient(); } private void initHttpClient() { - ApacheHttpClientBuilder apacheHttpClientBuilder = this.wxMpConfigStorage.getApacheHttpClientBuilder(); + ApacheHttpClientBuilder apacheHttpClientBuilder = this.configStorage + .getApacheHttpClientBuilder(); if (null == apacheHttpClientBuilder) { apacheHttpClientBuilder = DefaultApacheHttpClientBuilder.get(); } - - apacheHttpClientBuilder.httpProxyHost(this.wxMpConfigStorage.getHttpProxyHost()) - .httpProxyPort(this.wxMpConfigStorage.getHttpProxyPort()) - .httpProxyUsername(this.wxMpConfigStorage.getHttpProxyUsername()) - .httpProxyPassword(this.wxMpConfigStorage.getHttpProxyPassword()); - if (this.wxMpConfigStorage.getSSLContext() != null){ + apacheHttpClientBuilder.httpProxyHost(this.configStorage.getHttpProxyHost()) + .httpProxyPort(this.configStorage.getHttpProxyPort()) + .httpProxyUsername(this.configStorage.getHttpProxyUsername()) + .httpProxyPassword(this.configStorage.getHttpProxyPassword()); + + if (this.configStorage.getSSLContext() != null) { SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( - this.wxMpConfigStorage.getSSLContext(), new String[] { "TLSv1" }, null, new DefaultHostnameVerifier()); + this.configStorage.getSSLContext(), new String[] { "TLSv1" }, null, + new DefaultHostnameVerifier()); apacheHttpClientBuilder.sslConnectionSocketFactory(sslsf); } + if (this.configStorage.getHttpProxyHost() != null && this.configStorage.getHttpProxyPort() > 0) { + this.httpProxy = new HttpHost(this.configStorage.getHttpProxyHost(), this.configStorage.getHttpProxyPort()); + } + this.httpClient = apacheHttpClientBuilder.build(); } @Override public WxMpConfigStorage getWxMpConfigStorage() { - return this.wxMpConfigStorage; + return this.configStorage; } @Override @@ -527,8 +557,8 @@ public class WxMpServiceImpl implements WxMpService { } @Override - public WxMpGroupService getGroupService() { - return this.groupService; + public WxMpUserTagService getUserTagService() { + return this.tagService; } @Override @@ -551,4 +581,14 @@ public class WxMpServiceImpl implements WxMpService { return this.dataCubeService; } + @Override + public WxMpUserBlacklistService getBlackListService() { + return this.blackListService; + } + + @Override + public WxMpStoreService getStoreService() { + return this.storeService; + } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java new file mode 100644 index 00000000..39c7f729 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java @@ -0,0 +1,158 @@ +package me.chanjar.weixin.mp.api.impl; + +import com.google.common.collect.Lists; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; +import me.chanjar.weixin.common.annotation.Required; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.WxMpStoreService; +import me.chanjar.weixin.mp.bean.store.WxMpStoreBaseInfo; +import me.chanjar.weixin.mp.bean.store.WxMpStoreInfo; +import me.chanjar.weixin.mp.bean.store.WxMpStoreListResult; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import org.joor.Reflect; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.Map.Entry; + +/** + * Created by Binary Wang on 2016/9/26. + * @author binarywang (https://github.com/binarywang) + * + */ +public class WxMpStoreServiceImpl implements WxMpStoreService { + private static final String API_BASE_URL = "http://api.weixin.qq.com/cgi-bin/poi"; + + private WxMpService wxMpService; + + public WxMpStoreServiceImpl(WxMpService wxMpService) { + this.wxMpService = wxMpService; + } + + @Override + public void add(WxMpStoreBaseInfo request) throws WxErrorException { + checkParameters(request); + + String url = API_BASE_URL + "/addpoi"; + String response = this.wxMpService.post(url, request.toJson()); + WxError wxError = WxError.fromJson(response); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + } + + @Override + public WxMpStoreBaseInfo get(String poiId) throws WxErrorException { + String url = API_BASE_URL + "/getpoi"; + JsonObject paramObject = new JsonObject(); + paramObject.addProperty("poi_id",poiId); + String response = this.wxMpService.post(url, paramObject.toString()); + WxError wxError = WxError.fromJson(response); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + return WxMpStoreBaseInfo.fromJson(new JsonParser().parse(response).getAsJsonObject() + .get("business").getAsJsonObject().get("base_info").toString()); + } + + @Override + public void delete(String poiId) throws WxErrorException { + String url = API_BASE_URL + "/delpoi"; + JsonObject paramObject = new JsonObject(); + paramObject.addProperty("poi_id",poiId); + String response = this.wxMpService.post(url, paramObject.toString()); + WxError wxError = WxError.fromJson(response); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + } + + private void checkParameters(WxMpStoreBaseInfo request) { + List nullFields = Lists.newArrayList(); + for (Entry entry : Reflect.on(request).fields() + .entrySet()) { + Reflect reflect = entry.getValue(); + try { + Field field = request.getClass().getDeclaredField(entry.getKey()); + if (field.isAnnotationPresent(Required.class) + && reflect.get() == null) { + nullFields.add(entry.getKey()); + } + } catch (NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } + } + + if (!nullFields.isEmpty()) { + throw new IllegalArgumentException("必填字段[" + nullFields + "]必须提供值"); + } + + } + + @Override + public WxMpStoreListResult list(int begin, int limit) + throws WxErrorException { + String url = API_BASE_URL + "/getpoilist"; + JsonObject params = new JsonObject(); + params.addProperty("begin", begin); + params.addProperty("limit", limit); + String response = this.wxMpService.post(url, params.toString()); + + WxError wxError = WxError.fromJson(response); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + + return WxMpStoreListResult.fromJson(response); + } + + @Override + public List listAll() throws WxErrorException { + int limit = 50; + WxMpStoreListResult list = this.list(0, limit); + List 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; + } + + @Override + public void update(WxMpStoreBaseInfo request) throws WxErrorException { + String url = API_BASE_URL + "/updatepoi"; + String response = this.wxMpService.post(url, request.toJson()); + WxError wxError = WxError.fromJson(response); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + } + + @Override + public List listCategories() throws WxErrorException { + String url = API_BASE_URL + "/getwxcategory"; + String response = this.wxMpService.get(url, null); + WxError wxError = WxError.fromJson(response); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + + return WxMpGsonBuilder.create().fromJson( + new JsonParser().parse(response).getAsJsonObject().get("category_list"), + new TypeToken>(){}.getType()); + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserBlacklistServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserBlacklistServiceImpl.java new file mode 100644 index 00000000..b0b35343 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserBlacklistServiceImpl.java @@ -0,0 +1,50 @@ +package me.chanjar.weixin.mp.api.impl; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.WxMpUserBlacklistService; +import me.chanjar.weixin.mp.bean.result.WxMpUserBlacklistGetResult; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author miller + */ +public class WxMpUserBlacklistServiceImpl implements WxMpUserBlacklistService { + private static final String API_BLACKLIST_PREFIX = "https://api.weixin.qq.com/cgi-bin/tags/members"; + private WxMpService wxMpService; + + public WxMpUserBlacklistServiceImpl(WxMpService wxMpService) { + this.wxMpService = wxMpService; + } + + @Override + public WxMpUserBlacklistGetResult getBlacklist(String nextOpenid) throws WxErrorException { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("begin_openid", nextOpenid); + String url = API_BLACKLIST_PREFIX + "/getblacklist"; + String responseContent = this.wxMpService.execute(new SimplePostRequestExecutor(), url, jsonObject.toString()); + return WxMpUserBlacklistGetResult.fromJson(responseContent); + } + + @Override + public void pushToBlacklist(List openidList) throws WxErrorException { + Map map = new HashMap<>(); + map.put("openid_list", openidList); + String url = API_BLACKLIST_PREFIX + "/batchblacklist"; + this.wxMpService.execute(new SimplePostRequestExecutor(), url, new Gson().toJson(map)); + } + + @Override + public void pullFromBlacklist(List openidList) throws WxErrorException { + Map map = new HashMap<>(); + map.put("openid_list", openidList); + String url = API_BLACKLIST_PREFIX + "/batchunblacklist"; + this.wxMpService.execute(new SimplePostRequestExecutor(), url, new Gson().toJson(map)); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java index 995eb58a..9267407c 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java @@ -5,8 +5,6 @@ import java.util.List; import com.google.gson.JsonObject; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; -import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.bean.WxMpUserQuery; @@ -30,33 +28,37 @@ public class WxMpUserServiceImpl implements WxMpUserService { JsonObject json = new JsonObject(); json.addProperty("openid", openid); json.addProperty("remark", remark); - this.wxMpService.execute(new SimplePostRequestExecutor(), url, json.toString()); + this.wxMpService.post(url, json.toString()); } @Override public WxMpUser userInfo(String openid, String lang) throws WxErrorException { String url = API_URL_PREFIX + "/info"; lang = lang == null ? "zh_CN" : lang; - String responseContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, "openid=" + openid + "&lang=" + lang); + String responseContent = this.wxMpService.get(url, + "openid=" + openid + "&lang=" + lang); return WxMpUser.fromJson(responseContent); } @Override public WxMpUserList userList(String next_openid) throws WxErrorException { String url = API_URL_PREFIX + "/get"; - String responseContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, next_openid == null ? null : "next_openid=" + next_openid); + String responseContent = this.wxMpService.get(url, + next_openid == null ? null : "next_openid=" + next_openid); return WxMpUserList.fromJson(responseContent); } @Override - public List userInfoList(List openidList) throws WxErrorException { - return userInfoList(new WxMpUserQuery(openidList)); + public List userInfoList(List openids) + throws WxErrorException { + return this.userInfoList(new WxMpUserQuery(openids)); } @Override public List userInfoList(WxMpUserQuery userQuery) throws WxErrorException { String url = API_URL_PREFIX + "/info/batchget"; - String responseContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, userQuery.toJsonString()); + String responseContent = this.wxMpService.post(url, + userQuery.toJsonString()); return WxMpUser.fromJsonList(responseContent); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java new file mode 100644 index 00000000..4d3639c8 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java @@ -0,0 +1,160 @@ +package me.chanjar.weixin.mp.api.impl; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.WxMpUserTagService; +import me.chanjar.weixin.mp.bean.tag.WxTagListUser; +import me.chanjar.weixin.mp.bean.tag.WxUserTag; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import org.apache.commons.lang3.StringUtils; + +import java.util.List; + +/** + * + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/9/2. + */ +public class WxMpUserTagServiceImpl implements WxMpUserTagService { + private static final String API_URL_PREFIX = "https://api.weixin.qq.com/cgi-bin/tags"; + + private WxMpService wxMpService; + + public WxMpUserTagServiceImpl(WxMpService wxMpService) { + this.wxMpService = wxMpService; + } + + @Override + public WxUserTag tagCreate(String name) throws WxErrorException { + String url = API_URL_PREFIX + "/create"; + JsonObject json = new JsonObject(); + JsonObject tagJson = new JsonObject(); + tagJson.addProperty("name", name); + json.add("tag", tagJson); + + String responseContent = this.wxMpService.post(url, json.toString()); + return WxUserTag.fromJson(responseContent); + } + + @Override + public List tagGet() throws WxErrorException { + String url = API_URL_PREFIX + "/get"; + + String responseContent = this.wxMpService.get(url, null); + return WxUserTag.listFromJson(responseContent); + } + + @Override + public Boolean tagUpdate(Long id, String name) throws WxErrorException { + String url = API_URL_PREFIX + "/update"; + + JsonObject json = new JsonObject(); + JsonObject tagJson = new JsonObject(); + tagJson.addProperty("id", id); + tagJson.addProperty("name", name); + json.add("tag", tagJson); + + String responseContent = this.wxMpService.post(url, json.toString()); + WxError wxError = WxError.fromJson(responseContent); + if (wxError.getErrorCode() == 0) { + return true; + } + + throw new WxErrorException(wxError); + } + + @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); + if (wxError.getErrorCode() == 0) { + return true; + } + + throw new WxErrorException(wxError); + } + + @Override + public WxTagListUser tagListUser(Long tagId, String nextOpenid) + throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/user/tag/get"; + + JsonObject json = new JsonObject(); + json.addProperty("tagid", tagId); + json.addProperty("next_openid", StringUtils.trimToEmpty(nextOpenid)); + + String responseContent = this.wxMpService.post(url, json.toString()); + return WxTagListUser.fromJson(responseContent); + } + + @Override + public boolean batchTagging(Long tagId, String[] openids) + throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging"; + + JsonObject json = new JsonObject(); + json.addProperty("tagid", tagId); + JsonArray openidArrayJson = new JsonArray(); + for (String openid : openids) { + openidArrayJson.add(openid); + } + json.add("openid_list", openidArrayJson); + + String responseContent = this.wxMpService.post(url, json.toString()); + WxError wxError = WxError.fromJson(responseContent); + if (wxError.getErrorCode() == 0) { + return true; + } + + throw new WxErrorException(wxError); + } + + @Override + public boolean batchUntagging(Long tagId, String[] openids) + throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging"; + + JsonObject json = new JsonObject(); + json.addProperty("tagid", tagId); + JsonArray openidArrayJson = new JsonArray(); + for (String openid : openids) { + openidArrayJson.add(openid); + } + json.add("openid_list", openidArrayJson); + + String responseContent = this.wxMpService.post(url, json.toString()); + WxError wxError = WxError.fromJson(responseContent); + if (wxError.getErrorCode() == 0) { + return true; + } + + throw new WxErrorException(wxError); + } + + @Override + public List userTagList(String openid) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/tags/getidlist"; + + JsonObject json = new JsonObject(); + json.addProperty("openid", openid); + + String responseContent = this.wxMpService.post(url, json.toString()); + + return WxMpGsonBuilder.create().fromJson( + new JsonParser().parse(responseContent).getAsJsonObject().get("tagid_list"), + new TypeToken>() { + }.getType()); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java index 04eee332..a7f1670f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java @@ -1,12 +1,18 @@ package me.chanjar.weixin.mp.bean; -import me.chanjar.weixin.mp.bean.custombuilder.*; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import me.chanjar.weixin.mp.bean.custombuilder.ImageBuilder; +import me.chanjar.weixin.mp.bean.custombuilder.MusicBuilder; +import me.chanjar.weixin.mp.bean.custombuilder.NewsBuilder; +import me.chanjar.weixin.mp.bean.custombuilder.TextBuilder; +import me.chanjar.weixin.mp.bean.custombuilder.VideoBuilder; +import me.chanjar.weixin.mp.bean.custombuilder.VoiceBuilder; +import me.chanjar.weixin.mp.bean.custombuilder.WxCardBuilder; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + /** * 客服消息 * @author chanjarster @@ -14,7 +20,7 @@ import java.util.List; */ public class WxMpCustomMessage implements Serializable { private static final long serialVersionUID = -9196732086954365246L; - + private String toUser; private String msgType; private String content; @@ -25,8 +31,9 @@ public class WxMpCustomMessage implements Serializable { private String musicUrl; private String hqMusicUrl; private String kfAccount; + private String cardId; private List articles = new ArrayList<>(); - + public String getToUser() { return this.toUser; } @@ -36,7 +43,7 @@ public class WxMpCustomMessage implements Serializable { public String getMsgType() { return this.msgType; } - + /** *
    * 请使用
@@ -46,6 +53,7 @@ public class WxMpCustomMessage implements Serializable {
    * {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_MUSIC}
    * {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_VIDEO}
    * {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_NEWS}
+   * {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_WXCARD}
    * 
* @param msgType */ @@ -94,24 +102,33 @@ public class WxMpCustomMessage implements Serializable { public void setHqMusicUrl(String hqMusicUrl) { this.hqMusicUrl = hqMusicUrl; } + + public String getCardId() { + return this.cardId; + } + + public void setCardId(String cardId) { + this.cardId = cardId; + } + public List getArticles() { return this.articles; } public void setArticles(List articles) { this.articles = articles; } - + public String toJson() { return WxMpGsonBuilder.INSTANCE.create().toJson(this); } - + public static class WxArticle { - + private String title; private String description; private String url; private String picUrl; - + public String getTitle() { return this.title; } @@ -136,9 +153,9 @@ public class WxMpCustomMessage implements Serializable { public void setPicUrl(String picUrl) { this.picUrl = picUrl; } - + } - + /** * 获得文本消息builder */ @@ -159,34 +176,41 @@ public class WxMpCustomMessage implements Serializable { public static VoiceBuilder VOICE() { return new VoiceBuilder(); } - + /** * 获得视频消息builder */ public static VideoBuilder VIDEO() { return new VideoBuilder(); } - + /** * 获得音乐消息builder */ public static MusicBuilder MUSIC() { return new MusicBuilder(); } - + /** * 获得图文消息builder */ public static NewsBuilder NEWS() { return new NewsBuilder(); } - + + + /** + * 获得卡券消息builder + */ + public static WxCardBuilder WXCARD() { + return new WxCardBuilder(); + } + public String getKfAccount() { return this.kfAccount; } - + public void setKfAccount(String kfAccount) { this.kfAccount = kfAccount; } - } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpGroup.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpGroup.java deleted file mode 100644 index 7dfd4ccc..00000000 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpGroup.java +++ /dev/null @@ -1,52 +0,0 @@ -package me.chanjar.weixin.mp.bean; - -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - -import java.io.Serializable; - -/** - * 微信用户分组 - * @author chanjarster - * - */ -public class WxMpGroup implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1554709708638735270L; - private long id = -1; - private String name; - private long count; - public long getId() { - return this.id; - } - public void setId(long id) { - this.id = id; - } - public String getName() { - return this.name; - } - public void setName(String name) { - this.name = name; - } - public long getCount() { - return this.count; - } - public void setCount(long count) { - this.count = count; - } - - public static WxMpGroup fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json, WxMpGroup.class); - } - - public String toJson() { - return WxMpGsonBuilder.create().toJson(this); - } - @Override - public String toString() { - return "WxMpGroup [id=" + this.id + ", name=" + this.name + ", count=" + this.count + "]"; - } - -} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassGroupMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassTagMessage.java similarity index 82% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassGroupMessage.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassTagMessage.java index d77605a6..300b4f90 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassGroupMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassTagMessage.java @@ -1,26 +1,23 @@ package me.chanjar.weixin.mp.bean; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - import java.io.Serializable; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + /** - * 分组群发的消息 + * 按标签群发的消息 * * @author chanjarster */ -public class WxMpMassGroupMessage implements Serializable { +public class WxMpMassTagMessage implements Serializable { - /** - * - */ private static final long serialVersionUID = -6625914040986749286L; - private Long groupId; + private Long tagId; private String msgtype; private String content; private String mediaId; - public WxMpMassGroupMessage() { + public WxMpMassTagMessage() { super(); } @@ -64,16 +61,16 @@ public class WxMpMassGroupMessage implements Serializable { return WxMpGsonBuilder.INSTANCE.create().toJson(this); } - public Long getGroupId() { - return this.groupId; + public Long getTagId() { + return this.tagId; } /** * 如果不设置则就意味着发给所有用户 - * @param groupId + * @param tagId */ - public void setGroupId(Long groupId) { - this.groupId = groupId; + public void setTagId(Long tagId) { + this.tagId = tagId; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java index ff83baa9..d46ae24b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java @@ -7,9 +7,6 @@ import java.io.Serializable; */ public class WxMpTemplateData implements Serializable { - /** - * - */ private static final long serialVersionUID = 6301835292940277870L; private String name; private String value; @@ -48,6 +45,7 @@ public class WxMpTemplateData implements Serializable { public String getColor() { return this.color; } + public void setColor(String color) { this.color = color; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java index eec25eda..408abb50 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java @@ -1,17 +1,14 @@ package me.chanjar.weixin.mp.bean; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - import java.io.Serializable; import java.util.ArrayList; import java.util.List; -public class WxMpTemplateMessage implements Serializable { +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - /** - * - */ +public class WxMpTemplateMessage implements Serializable { private static final long serialVersionUID = 5063374783759519418L; + private String toUser; private String templateId; private String url; @@ -65,4 +62,61 @@ public class WxMpTemplateMessage implements Serializable { public String toJson() { return WxMpGsonBuilder.INSTANCE.create().toJson(this); } + + public static WxMpTemplateMessageBuilder builder() { + return new WxMpTemplateMessageBuilder(); + } + + public static class WxMpTemplateMessageBuilder { + private String toUser; + private String templateId; + private String url; + private String topColor; + private List data = new ArrayList<>(); + + public WxMpTemplateMessageBuilder toUser(String toUser) { + this.toUser = toUser; + return this; + } + + public WxMpTemplateMessageBuilder templateId(String templateId) { + this.templateId = templateId; + return this; + } + + public WxMpTemplateMessageBuilder url(String url) { + this.url = url; + return this; + } + + public WxMpTemplateMessageBuilder topColor(String topColor) { + this.topColor = topColor; + return this; + } + + public WxMpTemplateMessageBuilder data(List data) { + this.data = data; + return this; + } + + public WxMpTemplateMessageBuilder from(WxMpTemplateMessage origin) { + this.toUser(origin.toUser); + this.templateId(origin.templateId); + this.url(origin.url); + this.topColor(origin.topColor); + this.data(origin.data); + return this; + } + + public WxMpTemplateMessage build() { + WxMpTemplateMessage m = new WxMpTemplateMessage(); + m.toUser = this.toUser; + m.templateId = this.templateId; + m.url = this.url; + m.topColor = this.topColor; + m.data = this.data; + return m; + } + } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java index f16c004c..e97389b8 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java @@ -24,22 +24,22 @@ public class WxMpUserQuery { /** * 语言使用默认(zh_CN) * - * @param openIdList + * @param openids */ - public WxMpUserQuery(List openIdList) { + public WxMpUserQuery(List openids) { super(); - add(openIdList); + add(openids); } /** * 添加OpenId列表,语言使用默认(zh_CN) * - * @param openIdList + * @param openids * @return {@link WxMpUserQuery} */ - public WxMpUserQuery add(List openIdList) { - for (String openId : openIdList) { - this.add(openId); + public WxMpUserQuery add(List openids) { + for (String openid : openids) { + this.add(openid); } return this; } @@ -47,12 +47,12 @@ public class WxMpUserQuery { /** * 添加一个OpenId * - * @param openId + * @param openid * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 * @return {@link WxMpUserQuery} */ - public WxMpUserQuery add(String openId, String lang) { - this.queryParamList.add(new WxMpUserQueryParam(openId, lang)); + public WxMpUserQuery add(String openid, String lang) { + this.queryParamList.add(new WxMpUserQueryParam(openid, lang)); return this; } @@ -63,34 +63,34 @@ public class WxMpUserQuery { * 该方法默认lang = zh_CN *
* - * @param openId + * @param openid * @return {@link WxMpUserQuery} */ - public WxMpUserQuery add(String openId) { - this.queryParamList.add(new WxMpUserQueryParam(openId)); + public WxMpUserQuery add(String openid) { + this.queryParamList.add(new WxMpUserQueryParam(openid)); return this; } /** * 删除指定的OpenId,语言使用默认(zh_CN) * - * @param openId + * @param openid * @return {@link WxMpUserQuery} */ - public WxMpUserQuery remove(String openId) { - this.queryParamList.remove(new WxMpUserQueryParam(openId)); + public WxMpUserQuery remove(String openid) { + this.queryParamList.remove(new WxMpUserQueryParam(openid)); return this; } /** * 删除指定的OpenId * - * @param openId + * @param openid * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 * @return {@link WxMpUserQuery} */ - public WxMpUserQuery remove(String openId, String lang) { - this.queryParamList.remove(new WxMpUserQueryParam(openId, lang)); + public WxMpUserQuery remove(String openid, String lang) { + this.queryParamList.remove(new WxMpUserQueryParam(openid, lang)); return this; } @@ -110,9 +110,6 @@ public class WxMpUserQuery { // 查询参数封装 public class WxMpUserQueryParam implements Serializable { - /** - * @fields serialVersionUID - */ private static final long serialVersionUID = -6863571795702385319L; private String openid; private String lang; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlMessage.java index 823558fe..9adcb54d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlMessage.java @@ -6,8 +6,6 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import me.chanjar.weixin.mp.util.json.WxLongTimeJsonSerializer; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -22,11 +20,10 @@ import me.chanjar.weixin.mp.util.xml.XStreamTransformer; /** *
- * 微信推送过来的消息,也是同步回复给用户的消息,xml格式
- * 相关字段的解释看微信开发者文档:
- * http://mp.weixin.qq.com/wiki/index.php?title=接收普通消息
- * http://mp.weixin.qq.com/wiki/index.php?title=接收事件推送
- * http://mp.weixin.qq.com/wiki/index.php?title=接收语音识别结果
+ * 微信推送过来的消息,xml格式
+ * 部分未注释的字段的解释请查阅相关微信开发文档:
+ * 接收普通消息
+ * 接收事件推送
  * 
* * @author chanjarster @@ -42,14 +39,13 @@ public class WxMpXmlMessage implements Serializable { @XStreamAlias("ToUserName") @XStreamConverter(value = XStreamCDataConverter.class) - private String toUserName; + private String toUser; @XStreamAlias("FromUserName") @XStreamConverter(value = XStreamCDataConverter.class) - private String fromUserName; + private String fromUser; @XStreamAlias("CreateTime") - @JsonSerialize(using = WxLongTimeJsonSerializer.class) private Long createTime; @XStreamAlias("MsgType") @@ -212,12 +208,75 @@ public class WxMpXmlMessage implements Serializable { @XStreamAlias("SendLocationInfo") private SendLocationInfo sendLocationInfo = new SendLocationInfo(); - public String getToUserName() { - return this.toUserName; + /////////////////////////////////////// + // 门店审核事件推送 + /////////////////////////////////////// + /** + * UniqId + * 商户自己内部ID,即字段中的sid + */ + @XStreamAlias("UniqId") + private String storeUniqId; + + /** + * PoiId + * 微信的门店ID,微信内门店唯一标示ID + */ + @XStreamAlias("PoiId") + private String poiId; + + /** + * Result + * 审核结果,成功succ 或失败fail + */ + @XStreamAlias("Result") + private String result; + + /** + * msg + * 成功的通知信息,或审核失败的驳回理由 + */ + @XStreamAlias("msg") + private String msg; + + public String getStoreUniqId() { + return this.storeUniqId; + } + + public void setStoreUniqId(String storeUniqId) { + this.storeUniqId = storeUniqId; + } + + public String getPoiId() { + return this.poiId; + } + + public void setPoiId(String poiId) { + this.poiId = poiId; + } + + public String getResult() { + return this.result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getMsg() { + return this.msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getToUser() { + return this.toUser; } - public void setToUserName(String toUserName) { - this.toUserName = toUserName; + public void setToUser(String toUser) { + this.toUser = toUser; } public Long getCreateTime() { @@ -422,12 +481,12 @@ public class WxMpXmlMessage implements Serializable { this.recognition = recognition; } - public String getFromUserName() { - return this.fromUserName; + public String getFromUser() { + return this.fromUser; } - public void setFromUserName(String fromUserName) { - this.fromUserName = fromUserName; + public void setFromUser(String fromUser) { + this.fromUser = fromUser; } public static WxMpXmlMessage fromXml(String xml) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java new file mode 100644 index 00000000..8620cd84 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java @@ -0,0 +1,32 @@ +package me.chanjar.weixin.mp.bean.custombuilder; + +import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.mp.bean.WxMpCustomMessage; + +/** + * 卡券消息builder + *
+ * 用法: WxMpCustomMessage m = WxMpCustomMessage.WXCARD().cardId(...).toUser(...).build();
+ * 
+ * @author mgcnrx11 + * + */ +public final class WxCardBuilder extends BaseBuilder { + private String cardId; + + public WxCardBuilder() { + this.msgType = WxConsts.CUSTOM_MSG_WXCARD; + } + + public WxCardBuilder cardId(String cardId) { + this.cardId = cardId; + return this; + } + + @Override + public WxMpCustomMessage build() { + WxMpCustomMessage m = super.build(); + m.setCardId(this.cardId); + return m; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java index ce1f4269..3dd28459 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java @@ -1,6 +1,12 @@ package me.chanjar.weixin.mp.bean.datacube; +import java.util.List; + +import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * 图文分析数据接口返回结果对象 @@ -9,6 +15,8 @@ import com.google.gson.annotations.SerializedName; */ public class WxDataCubeArticleResult extends WxDataCubeBaseResult { + private static final JsonParser JSON_PARSER = new JsonParser(); + /** * ref_hour * 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 @@ -203,5 +211,11 @@ public class WxDataCubeArticleResult extends WxDataCubeBaseResult { public void setUserSource(Integer userSource) { this.userSource = userSource; } - + + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java index 1832f734..37401cf8 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java @@ -1,8 +1,12 @@ package me.chanjar.weixin.mp.bean.datacube; +import java.util.List; + +import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; -import java.util.List; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * 图文分析数据接口返回结果对象 @@ -11,6 +15,8 @@ import java.util.List; */ public class WxDataCubeArticleTotal extends WxDataCubeBaseResult { + private static final JsonParser JSON_PARSER = new JsonParser(); + /** * msgid * 请注意:这里的msgid实际上是由msgid(图文消息id,这也就是群发接口调用后返回的msg_data_id)和index(消息次序索引)组成, 例如12003_3, 其中12003是msgid,即一次群发的消息的id; 3为index,假设该次群发的图文消息共5个文章(因为可能为多图文),3表示5个中的第3个 @@ -55,5 +61,11 @@ public class WxDataCubeArticleTotal extends WxDataCubeBaseResult { public void setDetails(List details) { this.details = details; } - + + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java index 4abbe277..82a45dcf 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java @@ -1,6 +1,12 @@ package me.chanjar.weixin.mp.bean.datacube; +import java.util.List; + +import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * 接口分析数据接口返回结果对象 @@ -9,6 +15,8 @@ import com.google.gson.annotations.SerializedName; */ public class WxDataCubeInterfaceResult extends WxDataCubeBaseResult { + private static final JsonParser JSON_PARSER = new JsonParser(); + /** * ref_hour * 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 @@ -83,5 +91,12 @@ public class WxDataCubeInterfaceResult extends WxDataCubeBaseResult { public void setMaxTimeCost(Integer maxTimeCost) { this.maxTimeCost = maxTimeCost; } + + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java index bbeb3b36..908dfca8 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java @@ -1,6 +1,12 @@ package me.chanjar.weixin.mp.bean.datacube; +import java.util.List; + +import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * 消息分析数据接口返回结果对象 @@ -9,6 +15,8 @@ import com.google.gson.annotations.SerializedName; */ public class WxDataCubeMsgResult extends WxDataCubeBaseResult { + private static final JsonParser JSON_PARSER = new JsonParser(); + /** * ref_hour * 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 @@ -114,4 +122,11 @@ public class WxDataCubeMsgResult extends WxDataCubeBaseResult { this.oriPageReadUser = oriPageReadUser; } + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java index 7192cfb4..039bd189 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java @@ -1,19 +1,27 @@ package me.chanjar.weixin.mp.bean.datacube; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import java.io.Serializable; -import java.util.Date; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** *
  * 累计用户数据接口的返回JSON数据包
- * http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html
+ * 详情查看文档:用户分析数据接口
  * 
*/ public class WxDataCubeUserCumulate implements Serializable { + private static final JsonParser JSON_PARSER = new JsonParser(); + private static final long serialVersionUID = -3570981300225093657L; private Date refDate; @@ -40,4 +48,11 @@ public class WxDataCubeUserCumulate implements Serializable { public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } + + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java index cfb41842..4802027e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java @@ -1,20 +1,28 @@ package me.chanjar.weixin.mp.bean.datacube; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -import java.io.Serializable; -import java.util.Date; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** *
  * 用户增减数据接口的返回JSON数据包
- * http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html
+ * 详情查看文档:用户分析数据接口
  * 
*/ public class WxDataCubeUserSummary implements Serializable { private static final long serialVersionUID = -2336654489906694173L; + private static final JsonParser JSON_PARSER = new JsonParser(); + private Date refDate; private Integer userSource; @@ -59,4 +67,11 @@ public class WxDataCubeUserSummary implements Serializable { public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } + + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java index 3fe2002c..7f326ac1 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java @@ -1,11 +1,10 @@ package me.chanjar.weixin.mp.bean.kefu.result; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.google.gson.annotations.SerializedName; -import me.chanjar.weixin.mp.util.json.WxLongTimeJsonSerializer; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import com.google.gson.annotations.SerializedName; + /** * Created by Binary Wang on 2016/7/18. */ @@ -38,7 +37,6 @@ public class WxMpKfMsgRecord { * time 操作时间,unix时间戳 */ @SerializedName("time") - @JsonSerialize(using = WxLongTimeJsonSerializer.class) private Long time; @Override diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayCallback.java similarity index 99% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayCallback.java index 6e96f5e2..e32e721e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayCallback.java @@ -1,4 +1,4 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayRefundResult.java similarity index 99% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayRefundResult.java index 4d51e8f4..3f917fe0 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayRefundResult.java @@ -1,4 +1,4 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayResult.java similarity index 78% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayResult.java index 1ea8fd65..2978ba17 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayResult.java @@ -1,7 +1,10 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + /** *
  * 查询订单支付状态返回的结果
@@ -13,9 +16,11 @@ import java.io.Serializable;
  * @author ukid
  */
 public class WxMpPayResult implements Serializable {
-  /**
-   * 
-   */
+  @Override
+  public String toString() {
+    return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
+  }
+
   private static final long serialVersionUID = -570934170727777190L;
   
   private String return_code;
@@ -41,6 +46,16 @@ public class WxMpPayResult implements Serializable {
   private String out_trade_no;
   private String attach;
   private String time_end;
+ /**
+  *  现金支付金额	cash_fee	是	Int	100	现金支付金额订单现金支付金额,详见支付金额
+  */
+  private String cash_fee;
+  
+  /**
+   * 现金支付货币类型	cash_fee_type	否
+   * 
+   */
+  private String cash_fee_type;
 
   public String getReturn_code() {
     return this.return_code;
@@ -226,32 +241,19 @@ public class WxMpPayResult implements Serializable {
     this.trade_state_desc = trade_state_desc;
   }
 
-  @Override
-  public String toString() {
-    return "WxMpPayResult{" +
-        "return_code=" + this.return_code +
-        ", return_msg='" + this.return_msg + '\'' +
-        ", appid='" + this.appid + '\'' +
-        ", mch_id='" + this.mch_id + '\'' +
-        ", nonce_str='" + this.nonce_str + '\'' +
-        ", sign='" + this.sign + '\'' +
-        ", result_code='" + this.result_code + '\'' +
-        ", err_code='" + this.err_code + '\'' +
-        ", err_code_des='" + this.err_code_des + '\'' +
-        ", trade_state=" + this.trade_state +
-        ", trade_state_desc=" + this.trade_state_desc +
-        ", device_info='" + this.device_info + '\'' +
-        ", openid='" + this.openid + '\'' +
-        ", is_subscribe='" + this.is_subscribe + '\'' +
-        ", trade_type='" + this.trade_type + '\'' +
-        ", bank_type='" + this.bank_type + '\'' +
-        ", total_fee='" + this.total_fee + '\'' +
-        ", coupon_fee='" + this.coupon_fee + '\'' +
-        ", fee_type='" + this.fee_type + '\'' +
-        ", transaction_id='" + this.transaction_id + '\'' +
-        ", out_trade_no='" + this.out_trade_no + '\'' +
-        ", attach='" + this.attach + '\'' +
-        ", time_end='" + this.time_end + '\'' +
-        '}';
+  public String getCash_fee() {
+    return this.cash_fee;
+  }
+
+  public void setCash_fee(String cash_fee) {
+    this.cash_fee = cash_fee;
+  }
+
+  public String getCash_fee_type() {
+    return this.cash_fee_type;
+  }
+
+  public void setCash_fee_type(String cash_fee_type) {
+    this.cash_fee_type = cash_fee_type;
   }
 }
diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java
new file mode 100644
index 00000000..cff9d787
--- /dev/null
+++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java
@@ -0,0 +1,124 @@
+package me.chanjar.weixin.mp.bean.pay;
+
+import java.io.Serializable;
+
+/**
+ * 
+ * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
+ * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
+ * 
+ * + * @author chanjarster + */ +@Deprecated +public class WxMpPrepayIdResult implements Serializable { + private static final long serialVersionUID = -8970574397788396143L; + private String return_code; + private String return_msg; + private String appid; + private String mch_id; + private String nonce_str; + private String sign; + private String result_code; + private String prepay_id; + private String trade_type; + private String err_code; + private String err_code_des; + private String code_url; + + public String getReturn_code() { + return this.return_code; + } + + public void setReturn_code(String return_code) { + this.return_code = return_code; + } + + public String getReturn_msg() { + return this.return_msg; + } + + public void setReturn_msg(String return_msg) { + this.return_msg = return_msg; + } + + public String getAppid() { + return this.appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getMch_id() { + return this.mch_id; + } + + public void setMch_id(String mch_id) { + this.mch_id = mch_id; + } + + public String getNonce_str() { + return this.nonce_str; + } + + public void setNonce_str(String nonce_str) { + this.nonce_str = nonce_str; + } + + public String getSign() { + return this.sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getResult_code() { + return this.result_code; + } + + public void setResult_code(String result_code) { + this.result_code = result_code; + } + + public String getPrepay_id() { + return this.prepay_id; + } + + public void setPrepay_id(String prepay_id) { + this.prepay_id = prepay_id; + } + + public String getTrade_type() { + return this.trade_type; + } + + public void setTrade_type(String trade_type) { + this.trade_type = trade_type; + } + + public String getErr_code() { + return this.err_code; + } + + public void setErr_code(String err_code) { + this.err_code = err_code; + } + + public String getErr_code_des() { + return this.err_code_des; + } + + public void setErr_code_des(String err_code_des) { + this.err_code_des = err_code_des; + } + + public String getCode_url() { + return this.code_url; + } + + public void setCode_url(String code_url) { + this.code_url = code_url; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java similarity index 66% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java index be328668..297e07d7 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java @@ -1,7 +1,10 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + import com.thoughtworks.xstream.annotations.XStreamAlias; /** @@ -13,38 +16,35 @@ import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("xml") public class WxRedpackResult implements Serializable { - /** - * - */ private static final long serialVersionUID = -4837415036337132073L; @XStreamAlias("return_code") - String returnCode; + private String returnCode; @XStreamAlias("return_msg") - String returnMsg; + private String returnMsg; @XStreamAlias("sign") - String sign; + private String sign; @XStreamAlias("result_code") - String resultCode; + private String resultCode; @XStreamAlias("err_code") - String errCode; + private String errCode; @XStreamAlias("err_code_des") - String errCodeDes; + private String errCodeDes; @XStreamAlias("mch_billno") - String mchBillno; + private String mchBillno; @XStreamAlias("mch_id") - String mchId; + private String mchId; @XStreamAlias("wxappid") - String wxappid; + private String wxappid; @XStreamAlias("re_openid") - String reOpenid; + private String reOpenid; @XStreamAlias("total_amount") - int totalAmount; + private int totalAmount; @XStreamAlias("send_time") - String sendTime; + private String sendTime; @XStreamAlias("send_listid") - String sendListid; + private String sendListid; public String getErrCode() { return this.errCode; @@ -100,19 +100,6 @@ public class WxRedpackResult implements Serializable { @Override public String toString() { - return "WxRedpackResult{" + - "returnCode=" + this.returnCode + - ", returnMsg=" + this.returnMsg + - ", sign=" + this.sign + - ", errCode=" + this.errCode + - ", errCodeDes=" + this.errCodeDes + - ", mchBillno=" + this.mchBillno + - ", mchId=" + this.mchId + - ", wxappid=" + this.wxappid + - ", reOpenid=" + this.reOpenid + - ", totalAmount=" + this.totalAmount + - ", sendTime=" + this.sendTime + - ", sendListid=" + this.sendListid + - '}'; + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java new file mode 100644 index 00000000..abe0d68f --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java @@ -0,0 +1,296 @@ +package me.chanjar.weixin.mp.bean.pay; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +/** + * 发送红包请求参数对象 + * Created by Binary Wang on 2016/9/24. + * @author binarywang (https://github.com/binarywang) + */ +@XStreamAlias("xml") +public class WxSendRedpackRequest { + /** + * mch_billno + * 商户订单号(每个订单号必须唯一) 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。 接口根据商户订单号支持重入,如出现超时可再调用。 + */ + @XStreamAlias("mch_billno") + private String mchBillno; + + /** + * send_name + * 商户名称 + * 红包发送者名称 + */ + @XStreamAlias("send_name") + private String sendName; + + /** + * re_openid + * 接受红包的用户 用户在wxappid下的openid + */ + @XStreamAlias("re_openid") + private String reOpenid; + + /** + * total_amount + * 红包总额 + */ + @XStreamAlias("total_amount") + private Integer totalAmount; + + /** + * total_num + * 红包发放总人数 + */ + @XStreamAlias("total_num") + private Integer totalNum; + + /** + * amt_type + * 红包金额设置方式 + * ALL_RAND—全部随机,商户指定总金额和红包发放总人数,由微信支付随机计算出各红包金额 + * 裂变红包必填 + */ + @XStreamAlias("amt_type") + private String amtType; + + /** + * wishing + * 红包祝福语 + */ + @XStreamAlias("wishing") + private String wishing; + + /** + * client_ip + * 服务器Ip地址 + * 调用接口的机器Ip地址 + */ + @XStreamAlias("client_ip") + private String clientIp; + + /** + * act_name + * 活动名称 + */ + @XStreamAlias("act_name") + private String actName; + + /** + * remark + * 备注 + */ + @XStreamAlias("remark") + private String remark; + + /** + * wxappid + * 微信分配的公众账号ID(企业号corpid即为此appId)。接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的) + */ + @XStreamAlias("wxappid") + private String wxAppid; + + /** + * mch_id + * 微信支付分配的商户号 + */ + @XStreamAlias("mch_id") + private String mchId; + + /** + * nonce_str + * 随机字符串,不长于32位 + */ + @XStreamAlias("nonce_str") + private String nonceStr; + + /** + * sign + * 详见签名生成算法 + */ + @XStreamAlias("sign") + private String sign; + + /** + *
+   * scene_id
+   * 场景id
+   * PRODUCT_1:商品促销
+   * PRODUCT_2:抽奖
+   * PRODUCT_3:虚拟物品兑奖 
+   * PRODUCT_4:企业内部福利
+   * PRODUCT_5:渠道分润
+   * PRODUCT_6:保险回馈
+   * PRODUCT_7:彩票派奖
+   * PRODUCT_8:税务刮奖
+   * 非必填字段
+   * 
+ */ + @XStreamAlias("scene_id") + private String sceneId; + + /** + *
+   * risk_info
+   * 活动信息
+   * posttime:用户操作的时间戳
+   * mobile:业务系统账号的手机号,国家代码-手机号。不需要+号
+   * deviceid :mac 地址或者设备唯一标识 
+   * clientversion :用户操作的客户端版本
+   * 把值为非空的信息用key=value进行拼接,再进行urlencode
+   * urlencode(posttime=xx&mobile=xx&deviceid=xx)
+   *  非必填字段
+   * 
+ */ + @XStreamAlias("risk_info") + private String riskInfo; + + /** + *
+   * consume_mch_id
+   * 资金授权商户号
+   * 资金授权商户号
+   * 服务商替特约商户发放时使用  
+   * 非必填字段
+   * 
+ */ + @XStreamAlias("consume_mch_id") + private String consumeMchId; + + public String getMchBillno() { + return this.mchBillno; + } + + public void setMchBillno(String mchBillno) { + this.mchBillno = mchBillno; + } + + public String getSendName() { + return this.sendName; + } + + public void setSendName(String sendName) { + this.sendName = sendName; + } + + public String getReOpenid() { + return this.reOpenid; + } + + public void setReOpenid(String reOpenid) { + this.reOpenid = reOpenid; + } + + public Integer getTotalAmount() { + return this.totalAmount; + } + + public void setTotalAmount(Integer totalAmount) { + this.totalAmount = totalAmount; + } + + public Integer getTotalNum() { + return this.totalNum; + } + + public void setTotalNum(Integer totalNum) { + this.totalNum = totalNum; + } + + public String getAmtType() { + return this.amtType; + } + + public void setAmtType(String amtType) { + this.amtType = amtType; + } + + public String getWishing() { + return this.wishing; + } + + public void setWishing(String wishing) { + this.wishing = wishing; + } + + public String getClientIp() { + return this.clientIp; + } + + public void setClientIp(String clientIp) { + this.clientIp = clientIp; + } + + public String getActName() { + return this.actName; + } + + public void setActName(String actName) { + this.actName = actName; + } + + public String getRemark() { + return this.remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public String getWxAppid() { + return this.wxAppid; + } + + public void setWxAppid(String wxAppid) { + this.wxAppid = wxAppid; + } + + public String getMchId() { + return this.mchId; + } + + public void setMchId(String mchId) { + this.mchId = mchId; + } + + public String getNonceStr() { + return this.nonceStr; + } + + public void setNonceStr(String nonceStr) { + this.nonceStr = nonceStr; + } + + public String getSign() { + return this.sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getSceneId() { + return this.sceneId; + } + + public void setSceneId(String sceneId) { + this.sceneId = sceneId; + } + + public String getRiskInfo() { + return this.riskInfo; + } + + public void setRiskInfo(String riskInfo) { + this.riskInfo = riskInfo; + } + + public String getConsumeMchId() { + return this.consumeMchId; + } + + public void setConsumeMchId(String consumeMchId) { + this.consumeMchId = consumeMchId; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java new file mode 100644 index 00000000..ccdfff90 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java @@ -0,0 +1,666 @@ +package me.chanjar.weixin.mp.bean.pay; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import me.chanjar.weixin.common.annotation.Required; + +/** + *
+ * 统一下单请求参数对象
+ * 参考文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
+ * 每个字段描述对应如下:
+ * 
  • 字段名 + *
  • 变量名 + *
  • 是否必填 + *
  • 类型 + *
  • 示例值 + *
  • 描述 + *
  • + * Created by Binary Wang on 2016/9/25. + * @author binarywang (https://github.com/binarywang) + */ +@XStreamAlias("xml") +public class WxUnifiedOrderRequest { + + /** + *
    +   * 公众账号ID
    +   * appid
    +   * 是
    +   * String(32)
    +   * wxd678efh567hg6787
    +   * 微信分配的公众账号ID(企业号corpid即为此appId)
    +   * 
    + */ + @XStreamAlias("appid") + private String appid; + + /** + *
    +   * 商户号
    +   * mch_id
    +   * 是
    +   * String(32)
    +   * 1230000109
    +   * 微信支付分配的商户号
    +   * 
    + */ + @XStreamAlias("mch_id") + private String mchId; + + /** + *
    +   * 设备号
    +   * device_info
    +   * 否
    +   * String(32)
    +   * 013467007045764
    +   * 终端设备号(门店号或收银设备Id),注意:PC网页或公众号内支付请传"WEB"
    +   * 
    + */ + @XStreamAlias("device_info") + private String deviceInfo; + + /** + *
    +   * 随机字符串
    +   * nonce_str
    +   * 是
    +   * String(32)
    +   * 5K8264ILTKCH16CQ2502SI8ZNMTM67VS
    +   * 随机字符串,不长于32位。推荐随机数生成算法
    +   * 
    + */ + @XStreamAlias("nonce_str") + private String nonceStr; + + /** + *
    +   * 签名
    +   * sign
    +   * 是
    +   * String(32)
    +   * C380BEC2BFD727A4B6845133519F3AD6
    +   * 签名,详见签名生成算法
    +   * 
    + */ + @XStreamAlias("sign") + private String sign; + + /** + *
    +   * 商品描述
    +   * body
    +   * 是
    +   * String(128)
    +   * 腾讯充值中心-QQ会员充值
    +   * 商品简单描述,该字段须严格按照规范传递,具体请见参数规定
    +   * 
    + */ + @Required + @XStreamAlias("body") + private String body; + + /** + *
    +   * 商品详情
    +   * detail
    +   * 否
    +   * String(6000)
    +   *  {  "goods_detail":[
    +    {
    +    "goods_id":"iphone6s_16G",
    +    "wxpay_goods_id":"1001",
    +    "goods_name":"iPhone6s 16G",
    +    "goods_num":1,
    +    "price":528800,
    +    "goods_category":"123456",
    +    "body":"苹果手机"
    +    },
    +    {
    +    "goods_id":"iphone6s_32G",
    +    "wxpay_goods_id":"1002",
    +    "goods_name":"iPhone6s 32G",
    +    "quantity":1,
    +    "price":608800,
    +    "goods_category":"123789",
    +    "body":"苹果手机"
    +    }
    +    ]
    +    }
    +            商品详细列表,使用Json格式,传输签名前请务必使用CDATA标签将JSON文本串保护起来。
    +      goods_detail []:
    +      └ goods_id String 必填 32 商品的编号
    +      └ wxpay_goods_id String 可选 32 微信支付定义的统一商品编号
    +      └ goods_name String 必填 256 商品名称
    +      └ goods_num Int 必填 商品数量
    +      └ price Int 必填 商品单价,单位为分
    +      └ goods_category String 可选 32 商品类目Id
    +      └ body String 可选 1000 商品描述信息
    +   * 
    + */ + @XStreamAlias("detail") + private String detail; + + /** + *
    +   * 附加数据
    +   * attach
    +   * 否
    +   * String(127)
    +   * 深圳分店
    +   *  附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
    +   * 
    + */ + @XStreamAlias("attach") + private String attach; + + /** + *
    +   * 商户订单号
    +   * out_trade_no
    +   * 是
    +   * String(32)
    +   * 20150806125346
    +   * 商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
    +   * 
    + */ + @Required + @XStreamAlias("out_trade_no") + private String outTradeNo; + + /** + *
    +   * 货币类型
    +   * fee_type
    +   * 否
    +   * String(16)
    +   * CNY
    +   * 符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
    +   * 
    + */ + @XStreamAlias("fee_type") + private String feeType; + + /** + *
    +   * 总金额
    +   * total_fee
    +   * 是
    +   * Int
    +   * 888
    +   * 订单总金额,单位为分,详见支付金额
    +   * 
    + */ + @Required + @XStreamAlias("total_fee") + private Integer totalFee; + + /** + *
    +   * 终端IP
    +   * spbill_create_ip
    +   * 是
    +   * String(16)
    +   * 123.12.12.123
    +   * APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
    +   * 
    + */ + @Required + @XStreamAlias("spbill_create_ip") + private String spbillCreateIp; + + /** + *
    +   * 交易起始时间
    +   * time_start
    +   * 否
    +   * String(14)
    +   * 20091225091010
    +   * 订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
    +   * 
    + */ + @XStreamAlias("time_start") + private String timeStart; + + /** + *
    +   * 交易结束时间
    +   * time_expire
    +   * 否
    +   * String(14)
    +   * 20091227091010
    +   * 订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则
    +   *   注意:最短失效时间间隔必须大于5分钟
    +   * 
    + */ + @XStreamAlias("time_expire") + private String timeExpire; + + /** + *
    +   * 商品标记
    +   * goods_tag
    +   * 否
    +   * String(32)
    +   * WXG
    +   * 商品标记,代金券或立减优惠功能的参数,说明详见代金券或立减优惠
    +   * 
    + */ + @XStreamAlias("goods_tag") + private String goodsTag; + + /** + *
    +   * 通知地址
    +   * notify_url
    +   * 是
    +   * String(256)
    +   * http://www.weixin.qq.com/wxpay/pay.php
    +   * 接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
    +   * 
    + */ + @Required + @XStreamAlias("notify_url") + private String notifyURL; + + /** + *
    +   * 交易类型
    +   * trade_type
    +   * 是
    +   * String(16)
    +   * JSAPI
    +   * 取值如下:JSAPI,NATIVE,APP,详细说明见参数规定:
    +   * JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里
    +   * 
    + */ + @Required + @XStreamAlias("trade_type") + private String tradeType; + + /** + *
    +   * 商品Id
    +   * product_id
    +   * 否
    +   * String(32)
    +   * 12235413214070356458058
    +   * trade_type=NATIVE,此参数必传。此id为二维码中包含的商品Id,商户自行定义。
    +   * 
    + */ + @XStreamAlias("product_id") + private String productId; + + /** + *
    +   * 指定支付方式
    +   * limit_pay
    +   * 否
    +   * String(32)
    +   * no_credit no_credit--指定不能使用信用卡支付
    +   * 
    + */ + @XStreamAlias("limit_pay") + private String limitPay; + + /** + *
    +   * 用户标识
    +   * openid
    +   * 否
    +   * String(128)
    +   * oUpF8uMuAJO_M2pxb1Q9zNjWeS6o
    +   * trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。
    +   * openid如何获取,可参考【获取openid】。
    +   * 企业号请使用【企业号OAuth2.0接口】获取企业号内成员userid,再调用【企业号userid转openid接口】进行转换
    +   * 
    + */ + @XStreamAlias("openid") + private String openid; + + public String getAppid() { + return this.appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getMchId() { + return this.mchId; + } + + public void setMchId(String mchId) { + this.mchId = mchId; + } + + public String getDeviceInfo() { + return this.deviceInfo; + } + + public void setDeviceInfo(String deviceInfo) { + this.deviceInfo = deviceInfo; + } + + public String getNonceStr() { + return this.nonceStr; + } + + public void setNonceStr(String nonceStr) { + this.nonceStr = nonceStr; + } + + public String getSign() { + return this.sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getBody() { + return this.body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getDetail() { + return this.detail; + } + + public void setDetail(String detail) { + this.detail = detail; + } + + public String getAttach() { + return this.attach; + } + + public void setAttach(String attach) { + this.attach = attach; + } + + public String getOutTradeNo() { + return this.outTradeNo; + } + + public void setOutTradeNo(String outTradeNo) { + this.outTradeNo = outTradeNo; + } + + public String getFeeType() { + return this.feeType; + } + + public void setFeeType(String feeType) { + this.feeType = feeType; + } + + public Integer getTotalFee() { + return this.totalFee; + } + + public void setTotalFee(Integer totalFee) { + this.totalFee = totalFee; + } + + public String getSpbillCreateIp() { + return this.spbillCreateIp; + } + + public void setSpbillCreateIp(String spbillCreateIp) { + this.spbillCreateIp = spbillCreateIp; + } + + public String getTimeStart() { + return this.timeStart; + } + + public void setTimeStart(String timeStart) { + this.timeStart = timeStart; + } + + public String getTimeExpire() { + return this.timeExpire; + } + + public void setTimeExpire(String timeExpire) { + this.timeExpire = timeExpire; + } + + public String getGoodsTag() { + return this.goodsTag; + } + + public void setGoodsTag(String goodsTag) { + this.goodsTag = goodsTag; + } + + public String getNotifyURL() { + return this.notifyURL; + } + + public void setNotifyURL(String notifyURL) { + this.notifyURL = notifyURL; + } + + public String getTradeType() { + return this.tradeType; + } + + public void setTradeType(String tradeType) { + this.tradeType = tradeType; + } + + public String getProductId() { + return this.productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getLimitPay() { + return this.limitPay; + } + + public void setLimitPay(String limitPay) { + this.limitPay = limitPay; + } + + public String getOpenid() { + return this.openid; + } + + public void setOpenid(String openid) { + this.openid = openid; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } + + public static WxUnifiedOrderRequestBuilder builder() { + return new WxUnifiedOrderRequestBuilder(); + } + + public static class WxUnifiedOrderRequestBuilder { + private String appid; + private String mchId; + private String deviceInfo; + private String nonceStr; + private String sign; + private String body; + private String detail; + private String attach; + private String outTradeNo; + private String feeType; + private Integer totalFee; + private String spbillCreateIp; + private String timeStart; + private String timeExpire; + private String goodsTag; + private String notifyURL; + private String tradeType; + private String productId; + private String limitPay; + private String openid; + + public WxUnifiedOrderRequestBuilder appid(String appid) { + this.appid = appid; + return this; + } + + public WxUnifiedOrderRequestBuilder mchId(String mchId) { + this.mchId = mchId; + return this; + } + + public WxUnifiedOrderRequestBuilder deviceInfo(String deviceInfo) { + this.deviceInfo = deviceInfo; + return this; + } + + public WxUnifiedOrderRequestBuilder nonceStr(String nonceStr) { + this.nonceStr = nonceStr; + return this; + } + + public WxUnifiedOrderRequestBuilder sign(String sign) { + this.sign = sign; + return this; + } + + public WxUnifiedOrderRequestBuilder body(String body) { + this.body = body; + return this; + } + + public WxUnifiedOrderRequestBuilder detail(String detail) { + this.detail = detail; + return this; + } + + public WxUnifiedOrderRequestBuilder attach(String attach) { + this.attach = attach; + return this; + } + + public WxUnifiedOrderRequestBuilder outTradeNo(String outTradeNo) { + this.outTradeNo = outTradeNo; + return this; + } + + public WxUnifiedOrderRequestBuilder feeType(String feeType) { + this.feeType = feeType; + return this; + } + + public WxUnifiedOrderRequestBuilder totalFee(Integer totalFee) { + this.totalFee = totalFee; + return this; + } + + public WxUnifiedOrderRequestBuilder spbillCreateIp(String spbillCreateIp) { + this.spbillCreateIp = spbillCreateIp; + return this; + } + + public WxUnifiedOrderRequestBuilder timeStart(String timeStart) { + this.timeStart = timeStart; + return this; + } + + public WxUnifiedOrderRequestBuilder timeExpire(String timeExpire) { + this.timeExpire = timeExpire; + return this; + } + + public WxUnifiedOrderRequestBuilder goodsTag(String goodsTag) { + this.goodsTag = goodsTag; + return this; + } + + public WxUnifiedOrderRequestBuilder notifyURL(String notifyURL) { + this.notifyURL = notifyURL; + return this; + } + + public WxUnifiedOrderRequestBuilder tradeType(String tradeType) { + this.tradeType = tradeType; + return this; + } + + public WxUnifiedOrderRequestBuilder productId(String productId) { + this.productId = productId; + return this; + } + + public WxUnifiedOrderRequestBuilder limitPay(String limitPay) { + this.limitPay = limitPay; + return this; + } + + public WxUnifiedOrderRequestBuilder openid(String openid) { + this.openid = openid; + return this; + } + + public WxUnifiedOrderRequestBuilder from(WxUnifiedOrderRequest origin) { + this.appid(origin.appid); + this.mchId(origin.mchId); + this.deviceInfo(origin.deviceInfo); + this.nonceStr(origin.nonceStr); + this.sign(origin.sign); + this.body(origin.body); + this.detail(origin.detail); + this.attach(origin.attach); + this.outTradeNo(origin.outTradeNo); + this.feeType(origin.feeType); + this.totalFee(origin.totalFee); + this.spbillCreateIp(origin.spbillCreateIp); + this.timeStart(origin.timeStart); + this.timeExpire(origin.timeExpire); + this.goodsTag(origin.goodsTag); + this.notifyURL(origin.notifyURL); + this.tradeType(origin.tradeType); + this.productId(origin.productId); + this.limitPay(origin.limitPay); + this.openid(origin.openid); + return this; + } + + public WxUnifiedOrderRequest build() { + WxUnifiedOrderRequest m = new WxUnifiedOrderRequest(); + m.appid = this.appid; + m.mchId = this.mchId; + m.deviceInfo = this.deviceInfo; + m.nonceStr = this.nonceStr; + m.sign = this.sign; + m.body = this.body; + m.detail = this.detail; + m.attach = this.attach; + m.outTradeNo = this.outTradeNo; + m.feeType = this.feeType; + m.totalFee = this.totalFee; + m.spbillCreateIp = this.spbillCreateIp; + m.timeStart = this.timeStart; + m.timeExpire = this.timeExpire; + m.goodsTag = this.goodsTag; + m.notifyURL = this.notifyURL; + m.tradeType = this.tradeType; + m.productId = this.productId; + m.limitPay = this.limitPay; + m.openid = this.openid; + return m; + } + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java new file mode 100644 index 00000000..18817461 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java @@ -0,0 +1,155 @@ +package me.chanjar.weixin.mp.bean.pay; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +/** + *
    + * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
    + * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
    + * 
    + * + * @author chanjarster + */ +@XStreamAlias("xml") +public class WxUnifiedOrderResult { + + @XStreamAlias("return_code") + private String returnCode; + + @XStreamAlias("return_msg") + private String returnMsg; + + @XStreamAlias("appid") + private String appid; + + @XStreamAlias("mch_id") + private String mchId; + + @XStreamAlias("nonce_str") + private String nonceStr; + + @XStreamAlias("sign") + private String sign; + + @XStreamAlias("result_code") + private String resultCode; + + @XStreamAlias("prepay_id") + private String prepayId; + + @XStreamAlias("trade_type") + private String tradeType; + + @XStreamAlias("err_code") + private String errCode; + + @XStreamAlias("err_code_des") + private String errCodeDes; + + @XStreamAlias("code_url") + private String codeURL; + + public String getReturnCode() { + return this.returnCode; + } + + public void setReturnCode(String returnCode) { + this.returnCode = returnCode; + } + + public String getReturnMsg() { + return this.returnMsg; + } + + public void setReturnMsg(String returnMsg) { + this.returnMsg = returnMsg; + } + + public String getAppid() { + return this.appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getMchId() { + return this.mchId; + } + + public void setMchId(String mchId) { + this.mchId = mchId; + } + + public String getNonceStr() { + return this.nonceStr; + } + + public void setNonceStr(String nonceStr) { + this.nonceStr = nonceStr; + } + + public String getSign() { + return this.sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getResultCode() { + return this.resultCode; + } + + public void setResultCode(String resultCode) { + this.resultCode = resultCode; + } + + public String getPrepayId() { + return this.prepayId; + } + + public void setPrepayId(String prepayId) { + this.prepayId = prepayId; + } + + public String getTradeType() { + return this.tradeType; + } + + public void setTradeType(String tradeType) { + this.tradeType = tradeType; + } + + public String getErrCode() { + return this.errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrCodeDes() { + return this.errCodeDes; + } + + public void setErrCodeDes(String errCodeDes) { + this.errCodeDes = errCodeDes; + } + + public String getCodeURL() { + return this.codeURL; + } + + public void setCodeURL(String codeURL) { + this.codeURL = codeURL; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java deleted file mode 100644 index e930fc13..00000000 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java +++ /dev/null @@ -1,128 +0,0 @@ -package me.chanjar.weixin.mp.bean.result; - -import java.io.Serializable; - -/** - *
    - * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
    - *
    - * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
    - *
    - * 
    - * - * @author chanjarster - */ -public class WxMpPrepayIdResult implements Serializable { - /** - * - */ - private static final long serialVersionUID = -8970574397788396143L; - private String return_code; - private String return_msg; - private String appid; - private String mch_id; - private String nonce_str; - private String sign; - private String result_code; - private String prepay_id; - private String trade_type; - private String err_code; - private String err_code_des; - private String code_url; - - public String getReturn_code() { - return this.return_code; - } - - public void setReturn_code(String return_code) { - this.return_code = return_code; - } - - public String getReturn_msg() { - return this.return_msg; - } - - public void setReturn_msg(String return_msg) { - this.return_msg = return_msg; - } - - public String getAppid() { - return this.appid; - } - - public void setAppid(String appid) { - this.appid = appid; - } - - public String getMch_id() { - return this.mch_id; - } - - public void setMch_id(String mch_id) { - this.mch_id = mch_id; - } - - public String getNonce_str() { - return this.nonce_str; - } - - public void setNonce_str(String nonce_str) { - this.nonce_str = nonce_str; - } - - public String getSign() { - return this.sign; - } - - public void setSign(String sign) { - this.sign = sign; - } - - public String getResult_code() { - return this.result_code; - } - - public void setResult_code(String result_code) { - this.result_code = result_code; - } - - public String getPrepay_id() { - return this.prepay_id; - } - - public void setPrepay_id(String prepay_id) { - this.prepay_id = prepay_id; - } - - public String getTrade_type() { - return this.trade_type; - } - - public void setTrade_type(String trade_type) { - this.trade_type = trade_type; - } - - public String getErr_code() { - return this.err_code; - } - - public void setErr_code(String err_code) { - this.err_code = err_code; - } - - public String getErr_code_des() { - return this.err_code_des; - } - - public void setErr_code_des(String err_code_des) { - this.err_code_des = err_code_des; - } - - public String getCode_url() { - return this.code_url; - } - - public void setCode_url(String code_url) { - this.code_url = code_url; - } -} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java index 76670f02..19d03abf 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java @@ -4,6 +4,9 @@ import java.io.Serializable; import java.lang.reflect.Type; import java.util.List; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; @@ -17,91 +20,111 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; */ public class WxMpUser implements Serializable { - /** - * @fields serialVersionUID - */ private static final long serialVersionUID = 5788154322646488738L; - protected Boolean subscribe; - protected String openId; - protected String nickname; - protected String sex; - protected String language; - protected String city; - protected String province; - protected String country; - protected String headImgUrl; - protected Long subscribeTime; - protected String unionId; - protected Integer sexId; - protected String remark; - protected Integer groupId; + private Boolean subscribe; + private String openId; + private String nickname; + private String sex; + private String language; + private String city; + private String province; + private String country; + private String headImgUrl; + private Long subscribeTime; + private String unionId; + private Integer sexId; + private String remark; + private Integer groupId; + private Integer[] tagIds; public Boolean getSubscribe() { return this.subscribe; } + public Boolean isSubscribe() { return this.subscribe; } + public void setSubscribe(Boolean subscribe) { this.subscribe = subscribe; } + public String getOpenId() { return this.openId; } + public void setOpenId(String openId) { this.openId = openId; } + public String getNickname() { return this.nickname; } + public void setNickname(String nickname) { this.nickname = nickname; } + public String getSex() { return this.sex; } + public void setSex(String sex) { this.sex = sex; } + public String getLanguage() { return this.language; } + public void setLanguage(String language) { this.language = language; } + public String getCity() { return this.city; } + public void setCity(String city) { this.city = city; } + public String getProvince() { return this.province; } + public void setProvince(String province) { this.province = province; } + public String getCountry() { return this.country; } + public void setCountry(String country) { this.country = country; } + public String getHeadImgUrl() { return this.headImgUrl; } + public void setHeadImgUrl(String headImgUrl) { this.headImgUrl = headImgUrl; } + public Long getSubscribeTime() { return this.subscribeTime; } + public void setSubscribeTime(Long subscribeTime) { this.subscribeTime = subscribeTime; } + public String getUnionId() { return this.unionId; } + public void setUnionId(String unionId) { this.unionId = unionId; } @@ -118,22 +141,34 @@ public class WxMpUser implements Serializable { public String getRemark() { return this.remark; } + public void setRemark(String remark) { this.remark = remark; } + public Integer getGroupId() { return this.groupId; } + public void setGroupId(Integer groupId) { this.groupId = groupId; } + public Integer[] getTagIds() { + return this.tagIds; + } + + public void setTagIds(Integer[] tagIds) { + this.tagIds = tagIds; + } + public static WxMpUser fromJson(String json) { return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUser.class); } public static List fromJsonList(String json) { - Type collectionType = new TypeToken>() {}.getType(); + Type collectionType = new TypeToken>() { + }.getType(); Gson gson = WxMpGsonBuilder.INSTANCE.create(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); return gson.fromJson(jsonObject.get("user_info_list"), collectionType); @@ -141,20 +176,7 @@ public class WxMpUser implements Serializable { @Override public String toString() { - return "WxMpUser{" + - "subscribe=" + this.subscribe + - ", openId='" + this.openId + '\'' + - ", nickname='" + this.nickname + '\'' + - ", sex='" + this.sex + '\'' + - ", language='" + this.language + '\'' + - ", city='" + this.city + '\'' + - ", province='" + this.province + '\'' + - ", country='" + this.country + '\'' + - ", headImgUrl='" + this.headImgUrl + '\'' + - ", subscribeTime=" + this.subscribeTime + - ", unionId='" + this.unionId + '\'' + - ", remark='" + this.remark + '\'' + - ", groupId='" + this.groupId + '\'' + - '}'; + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserBlacklistGetResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserBlacklistGetResult.java new file mode 100644 index 00000000..3cfbc009 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserBlacklistGetResult.java @@ -0,0 +1,57 @@ +package me.chanjar.weixin.mp.bean.result; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author miller + */ +public class WxMpUserBlacklistGetResult { + protected int total = -1; + protected int count = -1; + protected List openidList = new ArrayList<>(); + protected String nextOpenid; + + public static WxMpUserBlacklistGetResult fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUserBlacklistGetResult.class); + } + + public int getTotal() { + return this.total; + } + + public void setTotal(int total) { + this.total = total; + } + + public int getCount() { + return this.count; + } + + public void setCount(int count) { + this.count = count; + } + + public List getOpenidList() { + return this.openidList; + } + + public void setOpenidList(List openidList) { + this.openidList = openidList; + } + + public String getNextOpenid() { + return this.nextOpenid; + } + + public void setNextOpenid(String nextOpenid) { + this.nextOpenid = nextOpenid; + } + + @Override + public String toString() { + return WxMpGsonBuilder.INSTANCE.create().toJson(this); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java new file mode 100644 index 00000000..dcfd3153 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java @@ -0,0 +1,562 @@ +package me.chanjar.weixin.mp.bean.store; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.annotations.SerializedName; +import me.chanjar.weixin.common.annotation.Required; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import java.math.BigDecimal; +import java.util.List; + +/** + * 门店基础信息 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016-09-23. + */ +public class WxMpStoreBaseInfo { + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } + + public static WxMpStoreBaseInfo fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpStoreBaseInfo.class); + } + + public String toJson() { + JsonElement base_info = WxMpGsonBuilder.create().toJsonTree(this); + JsonObject jsonObject = new JsonObject(); + jsonObject.add("base_info", base_info); + JsonObject business = new JsonObject(); + business.add("business", jsonObject); + return business.toString(); + } + + public static class WxMpStorePhoto { + /** + * 照片url + */ + @SerializedName("photo_url") + private String photoUrl; + } + + /** + * sid + * 商户自己的id,用于后续审核通过收到poi_id 的通知时,做对应关系。请商户自己保证唯一识别性 + */ + @SerializedName("sid") + private String sid; + + /** + * business_name + * 门店名称(仅为商户名,如:国美、麦当劳,不应包含地区、地址、分店名等信息,错误示例:北京国美) + * 不能为空,15个汉字或30个英文字符内 + */ + @Required + @SerializedName("business_name") + private String businessName; + + /** + * branch_name + * 分店名称(不应包含地区信息,不应与门店名有重复,错误示例:北京王府井店) + * 10个字以内 + */ + @Required + @SerializedName("branch_name") + private String branchName; + + /** + * province + * 门店所在的省份(直辖市填城市名,如:北京市) + * 10个字以内 + */ + @Required + @SerializedName("province") + private String province; + + /** + * city + * 门店所在的城市 + * 10个字以内 + */ + @Required + @SerializedName("city") + private String city; + + /** + * district + * 门店所在地区 + * 10个字以内 + */ + @Required + @SerializedName("district") + private String district; + + /** + * address + * 门店所在的详细街道地址(不要填写省市信息) + * (东莞等没有“区”行政区划的城市,该字段可不必填写。其余城市必填。) + */ + @Required + @SerializedName("address") + private String address; + + /** + * telephone + * 门店的电话(纯数字,区号、分机号均由“-”隔开) + */ + @Required + @SerializedName("telephone") + private String telephone; + + /** + * categories + * 门店的类型(不同级分类用“,”隔开,如:美食,川菜,火锅。详细分类参见附件:微信门店类目表) + */ + @Required + @SerializedName("categories") + private String[] categories; + + /** + * offsetType + * 坐标类型,1 为火星坐标(目前只能选1) + */ + @Required + @SerializedName("offset_type") + private Integer offsetType = 1; + + /** + * longitude + * 门店所在地理位置的经度 + */ + @Required + @SerializedName("longitude") + private BigDecimal longitude; + + /** + * latitude + * 门店所在地理位置的纬度(经纬度均为火星坐标,最好选用腾讯地图标记的坐标) + */ + @Required + @SerializedName("latitude") + private BigDecimal latitude; + + /** + * photo_list + * 图片列表,url 形式,可以有多张图片,尺寸为 640*340px。必须为上一接口生成的url。 + * 图片内容不允许与门店不相关,不允许为二维码、员工合照(或模特肖像)、营业执照、无门店正门的街景、地图截图、公交地铁站牌、菜单截图等 + */ + @SerializedName("photo_list") + private List photos; + + /** + * recommend + * 推荐品,餐厅可为推荐菜;酒店为推荐套房;景点为推荐游玩景点等,针对自己行业的推荐内容 + * 200字以内 + */ + @SerializedName("recommend") + private String recommend; + + /** + * special + * 特色服务,如免费wifi,免费停车,送货上门等商户能提供的特色功能或服务 + */ + @SerializedName("special") + private String special; + + /** + * introduction + * 商户简介,主要介绍商户信息等 + * 300字以内 + */ + @SerializedName("introduction") + private String introduction; + + /** + * open_time + * 营业时间,24 小时制表示,用“-”连接,如 8:00-20:00 + */ + @SerializedName("open_time") + private String openTime; + + /** + * avg_price + * 人均价格,大于0 的整数 + */ + @SerializedName("avg_price") + private Integer avgPrice; + + /** + * 门店是否可用状态。1 表示系统错误、2 表示审核中、3 审核通过、4 审核驳回。当该字段为1、2、4 状态时,poi_id 为空 + */ + @SerializedName("available_state") + private Integer availableState; + + /** + * 扩展字段是否正在更新中。1 表示扩展字段正在更新中,尚未生效,不允许再次更新; 0 表示扩展字段没有在更新中或更新已生效,可以再次更新 + */ + @SerializedName("update_status") + private Integer updateStatus; + + /** + * 门店poi id + */ + @SerializedName("poi_id") + private String poiId; + + public String getSid() { + return this.sid; + } + + public void setSid(String sid) { + this.sid = sid; + } + + public String getBusinessName() { + return this.businessName; + } + + public void setBusinessName(String businessName) { + this.businessName = businessName; + } + + public String getBranchName() { + return this.branchName; + } + + public void setBranchName(String branchName) { + this.branchName = branchName; + } + + public String getProvince() { + return this.province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getCity() { + return this.city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getDistrict() { + return this.district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getAddress() { + return this.address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getTelephone() { + return this.telephone; + } + + public void setTelephone(String telephone) { + this.telephone = telephone; + } + + public String[] getCategories() { + return this.categories; + } + + public void setCategories(String[] categories) { + this.categories = categories; + } + + public Integer getOffsetType() { + return this.offsetType; + } + + public void setOffsetType(Integer offsetType) { + this.offsetType = offsetType; + } + + public BigDecimal getLongitude() { + return this.longitude; + } + + public void setLongitude(BigDecimal longitude) { + this.longitude = longitude; + } + + public BigDecimal getLatitude() { + return this.latitude; + } + + public void setLatitude(BigDecimal latitude) { + this.latitude = latitude; + } + + public List getPhotos() { + return this.photos; + } + + public void setPhotos(List photos) { + this.photos = photos; + } + + public String getRecommend() { + return this.recommend; + } + + public void setRecommend(String recommend) { + this.recommend = recommend; + } + + public String getSpecial() { + return this.special; + } + + public void setSpecial(String special) { + this.special = special; + } + + public String getIntroduction() { + return this.introduction; + } + + public void setIntroduction(String introduction) { + this.introduction = introduction; + } + + public String getOpenTime() { + return this.openTime; + } + + public void setOpenTime(String openTime) { + this.openTime = openTime; + } + + public Integer getAvgPrice() { + return this.avgPrice; + } + + public void setAvgPrice(Integer avgPrice) { + this.avgPrice = avgPrice; + } + + public Integer getAvailableState() { + return this.availableState; + } + + public void setAvailableState(Integer availableState) { + this.availableState = availableState; + } + + public Integer getUpdateStatus() { + return this.updateStatus; + } + + public void setUpdateStatus(Integer updateStatus) { + this.updateStatus = updateStatus; + } + + public String getPoiId() { + return this.poiId; + } + + public void setPoiId(String poiId) { + this.poiId = poiId; + } + + public static WxMpStoreBaseInfoBuilder builder() { + return new WxMpStoreBaseInfoBuilder(); + } + + public static class WxMpStoreBaseInfoBuilder { + private String sid; + private String businessName; + private String branchName; + private String province; + private String city; + private String district; + private String address; + private String telephone; + private String[] categories; + private Integer offsetType; + private BigDecimal longitude; + private BigDecimal latitude; + private List photos; + private String recommend; + private String special; + private String introduction; + private String openTime; + private Integer avgPrice; + private Integer availableState; + private Integer updateStatus; + private String poiId; + + public WxMpStoreBaseInfoBuilder sid(String sid) { + this.sid = sid; + return this; + } + + public WxMpStoreBaseInfoBuilder businessName(String businessName) { + this.businessName = businessName; + return this; + } + + public WxMpStoreBaseInfoBuilder branchName(String branchName) { + this.branchName = branchName; + return this; + } + + public WxMpStoreBaseInfoBuilder province(String province) { + this.province = province; + return this; + } + + public WxMpStoreBaseInfoBuilder city(String city) { + this.city = city; + return this; + } + + public WxMpStoreBaseInfoBuilder district(String district) { + this.district = district; + return this; + } + + public WxMpStoreBaseInfoBuilder address(String address) { + this.address = address; + return this; + } + + public WxMpStoreBaseInfoBuilder telephone(String telephone) { + this.telephone = telephone; + return this; + } + + public WxMpStoreBaseInfoBuilder categories(String[] categories) { + this.categories = categories; + return this; + } + + public WxMpStoreBaseInfoBuilder offsetType(Integer offsetType) { + this.offsetType = offsetType; + return this; + } + + public WxMpStoreBaseInfoBuilder longitude(BigDecimal longitude) { + this.longitude = longitude; + return this; + } + + public WxMpStoreBaseInfoBuilder latitude(BigDecimal latitude) { + this.latitude = latitude; + return this; + } + + public WxMpStoreBaseInfoBuilder photos(List photos) { + this.photos = photos; + return this; + } + + public WxMpStoreBaseInfoBuilder recommend(String recommend) { + this.recommend = recommend; + return this; + } + + public WxMpStoreBaseInfoBuilder special(String special) { + this.special = special; + return this; + } + + public WxMpStoreBaseInfoBuilder introduction(String introduction) { + this.introduction = introduction; + return this; + } + + public WxMpStoreBaseInfoBuilder openTime(String openTime) { + this.openTime = openTime; + return this; + } + + public WxMpStoreBaseInfoBuilder avgPrice(Integer avgPrice) { + this.avgPrice = avgPrice; + return this; + } + + public WxMpStoreBaseInfoBuilder availableState(Integer availableState) { + this.availableState = availableState; + return this; + } + + public WxMpStoreBaseInfoBuilder updateStatus(Integer updateStatus) { + this.updateStatus = updateStatus; + return this; + } + + public WxMpStoreBaseInfoBuilder poiId(String poiId) { + this.poiId = poiId; + return this; + } + + public WxMpStoreBaseInfoBuilder from(WxMpStoreBaseInfo origin) { + this.sid(origin.sid); + this.businessName(origin.businessName); + this.branchName(origin.branchName); + this.province(origin.province); + this.city(origin.city); + this.district(origin.district); + this.address(origin.address); + this.telephone(origin.telephone); + this.categories(origin.categories); + this.offsetType(origin.offsetType); + this.longitude(origin.longitude); + this.latitude(origin.latitude); + this.photos(origin.photos); + this.recommend(origin.recommend); + this.special(origin.special); + this.introduction(origin.introduction); + this.openTime(origin.openTime); + this.avgPrice(origin.avgPrice); + this.availableState(origin.availableState); + this.updateStatus(origin.updateStatus); + this.poiId(origin.poiId); + return this; + } + + public WxMpStoreBaseInfo build() { + WxMpStoreBaseInfo m = new WxMpStoreBaseInfo(); + m.sid = this.sid; + m.businessName = this.businessName; + m.branchName = this.branchName; + m.province = this.province; + m.city = this.city; + m.district = this.district; + m.address = this.address; + m.telephone = this.telephone; + m.categories = this.categories; + m.offsetType = this.offsetType; + m.longitude = this.longitude; + m.latitude = this.latitude; + m.photos = this.photos; + m.recommend = this.recommend; + m.special = this.special; + m.introduction = this.introduction; + m.openTime = this.openTime; + m.avgPrice = this.avgPrice; + m.availableState = this.availableState; + m.updateStatus = this.updateStatus; + m.poiId = this.poiId; + return m; + } + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java new file mode 100644 index 00000000..5b44b860 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java @@ -0,0 +1,26 @@ +package me.chanjar.weixin.mp.bean.store; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.google.gson.annotations.SerializedName; + +public class WxMpStoreInfo { + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } + + @SerializedName("base_info") + private WxMpStoreBaseInfo baseInfo; + + public WxMpStoreBaseInfo getBaseInfo() { + return this.baseInfo; + } + + public void setBaseInfo(WxMpStoreBaseInfo baseInfo) { + this.baseInfo = baseInfo; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java new file mode 100644 index 00000000..2bc514ed --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java @@ -0,0 +1,84 @@ +package me.chanjar.weixin.mp.bean.store; + +import java.util.List; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.google.gson.annotations.SerializedName; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +/** + * 门店列表结果类 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016-09-27. + * + */ +public class WxMpStoreListResult { + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } + + public static WxMpStoreListResult fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpStoreListResult.class); + } + + /** + * 错误码,0为正常 + */ + @SerializedName("errcode") + private Integer errCode; + + /** + * 错误信息 + */ + @SerializedName("errmsg") + private String errMsg; + + /** + * 门店信息列表 + */ + @SerializedName("business_list") + private List businessList; + + /** + * 门店信息总数 + */ + @SerializedName("total_count") + private Integer totalCount; + + public Integer getTotalCount() { + return this.totalCount; + } + + public void setTotalCount(Integer totalCount) { + this.totalCount = totalCount; + } + + public Integer getErrCode() { + return this.errCode; + } + + public void setErrCode(Integer errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return this.errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + public List getBusinessList() { + return this.businessList; + } + + public void setBusinessList(List businessList) { + this.businessList = businessList; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java new file mode 100644 index 00000000..b07314ba --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java @@ -0,0 +1,94 @@ +package me.chanjar.weixin.mp.bean.tag; + +import java.util.List; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.google.gson.annotations.SerializedName; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +/** + * 获取标签下粉丝列表的结果对象 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016-09-19. + */ +public class WxTagListUser { + + public static WxTagListUser fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json,WxTagListUser.class); + } + + public String toJson() { + return WxMpGsonBuilder.create().toJson(this); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } + + /** + *"count":2,这次获取的粉丝数量 + */ + @SerializedName("count") + private Integer count; + + /** + *"data" 粉丝列表 + */ + @SerializedName("data") + private WxTagListUserData data; + + /** + *"next_openid" 拉取列表最后一个用户的openid + */ + @SerializedName("next_openid") + private String nextOpenid; + + public Integer getCount() { + return this.count; + } + + public void setCount(Integer count) { + this.count = count; + } + + public WxTagListUserData getData() { + return this.data; + } + + public void setData(WxTagListUserData data) { + this.data = data; + } + + public String getNextOpenid() { + return this.nextOpenid; + } + + public void setNextOpenid(String nextOpenid) { + this.nextOpenid = nextOpenid; + } + + public static class WxTagListUserData { + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } + + /** + * openid 列表 + */ + @SerializedName("openid") + private List openidList; + + public List getOpenidList() { + return this.openidList; + } + + public void setOpenidList(List openidList) { + this.openidList = openidList; + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxUserTag.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxUserTag.java new file mode 100644 index 00000000..53e247a7 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxUserTag.java @@ -0,0 +1,78 @@ +package me.chanjar.weixin.mp.bean.tag; + +import java.util.List; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +/** + * 用户标签对象 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/9/2. + */ +public class WxUserTag { + /** + * id 标签id,由微信分配 + */ + private Long id; + + /** + * name 标签名,UTF8编码 + */ + private String name; + + /** + * count 此标签下粉丝数 + */ + private Integer count; + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getCount() { + return this.count; + } + + public void setCount(Integer count) { + this.count = count; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public static WxUserTag fromJson(String json) { + return WxMpGsonBuilder.create().fromJson( + new JsonParser().parse(json).getAsJsonObject().get("tag"), + WxUserTag.class); + } + + public static List listFromJson(String json) { + return WxMpGsonBuilder.create().fromJson( + new JsonParser().parse(json).getAsJsonObject().get("tags"), + new TypeToken>(){}.getType()); + } + + public String toJson() { + return WxMpGsonBuilder.create().toJson(this); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java index 81bc2253..c40366ca 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java @@ -1,10 +1,12 @@ package me.chanjar.weixin.mp.util.http; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.InputStreamResponseHandler; -import me.chanjar.weixin.common.util.http.RequestExecutor; -import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -13,12 +15,11 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.InputStreamResponseHandler; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; public class MaterialVoiceAndImageDownloadRequestExecutor implements RequestExecutor { @@ -44,9 +45,9 @@ public class MaterialVoiceAndImageDownloadRequestExecutor implements RequestExec Map params = new HashMap<>(); params.put("media_id", materialId); httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); - try(CloseableHttpResponse response = httpclient.execute(httpPost)){ + try (CloseableHttpResponse response = httpclient.execute(httpPost); + InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);){ // 下载媒体文件出错 - InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response); byte[] responseContent = IOUtils.toByteArray(inputStream); String responseContentString = new String(responseContent, "UTF-8"); if (responseContentString.length() < 100) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java index 49606031..9b87b5af 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java @@ -24,27 +24,32 @@ import java.io.IOException; public class MediaImgUploadRequestExecutor implements RequestExecutor { @Override public WxMediaImgUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File data) throws WxErrorException, IOException { + if (data == null) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build()); + } + HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); httpPost.setConfig(config); } - if (data != null) { - HttpEntity entity = MultipartEntityBuilder - .create() - .addBinaryBody("media", data) - .setMode(HttpMultipartMode.RFC6532) - .build(); - httpPost.setEntity(entity); - httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); - } + + 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 = httpclient.execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } + return WxMediaImgUploadResult.fromJson(responseContent); } } -} \ No newline at end of file +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxLongTimeJsonSerializer.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxLongTimeJsonSerializer.java deleted file mode 100644 index 388139f2..00000000 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxLongTimeJsonSerializer.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.chanjar.weixin.mp.util.json; - -import java.io.IOException; -import java.text.SimpleDateFormat; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -/** - * Created by Binary Wang on 2016/7/13. - */ -public class WxLongTimeJsonSerializer extends JsonSerializer { - private static SimpleDateFormat DF = new SimpleDateFormat( - "yyyy-MM-dd HH:mm:ss"); - - @Override - public void serialize(Long value, JsonGenerator gen, - SerializerProvider serializers) - throws IOException { - gen.writeString(DF.format(value * 1000)); - } -} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java index 74a2acfe..973966db 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java @@ -75,6 +75,12 @@ public class WxMpCustomMessageGsonAdapter implements JsonSerializer, JsonDeserializer { - - @Override - public JsonElement serialize(WxMpGroup group, Type typeOfSrc, JsonSerializationContext context) { - JsonObject json = new JsonObject(); - JsonObject groupJson = new JsonObject(); - groupJson.addProperty("name", group.getName()); - groupJson.addProperty("id", group.getId()); - groupJson.addProperty("count", group.getCount()); - json.add("group", groupJson); - return json; - } - - @Override - public WxMpGroup deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - WxMpGroup group = new WxMpGroup(); - JsonObject groupJson = json.getAsJsonObject(); - if (json.getAsJsonObject().get("group") != null) { - groupJson = json.getAsJsonObject().get("group").getAsJsonObject(); - } - if (groupJson.get("name") != null && !groupJson.get("name").isJsonNull()) { - group.setName(GsonHelper.getAsString(groupJson.get("name"))); - } - if (groupJson.get("id") != null && !groupJson.get("id").isJsonNull()) { - group.setId(GsonHelper.getAsPrimitiveLong(groupJson.get("id"))); - } - if (groupJson.get("count") != null && !groupJson.get("count").isJsonNull()) { - group.setCount(GsonHelper.getAsPrimitiveLong(groupJson.get("count"))); - } - return group; - } - -} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java index bf920fff..df63ac64 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java @@ -2,10 +2,35 @@ package me.chanjar.weixin.mp.util.json; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import me.chanjar.weixin.mp.bean.*; + +import me.chanjar.weixin.mp.bean.WxMpCard; +import me.chanjar.weixin.mp.bean.WxMpCustomMessage; +import me.chanjar.weixin.mp.bean.WxMpIndustry; +import me.chanjar.weixin.mp.bean.WxMpMassNews; +import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage; +import me.chanjar.weixin.mp.bean.WxMpMassPreviewMessage; +import me.chanjar.weixin.mp.bean.WxMpMassTagMessage; +import me.chanjar.weixin.mp.bean.WxMpMassVideo; +import me.chanjar.weixin.mp.bean.WxMpMaterialArticleUpdate; +import me.chanjar.weixin.mp.bean.WxMpMaterialNews; +import me.chanjar.weixin.mp.bean.WxMpTemplateMessage; import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; -import me.chanjar.weixin.mp.bean.result.*; +import me.chanjar.weixin.mp.bean.result.WxMediaImgUploadResult; +import me.chanjar.weixin.mp.bean.result.WxMpCardResult; +import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult; +import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialCountResult; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialFileBatchGetResult; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialNewsBatchGetResult; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialUploadResult; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialVideoInfoResult; +import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; +import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; +import me.chanjar.weixin.mp.bean.result.WxMpSemanticQueryResult; +import me.chanjar.weixin.mp.bean.result.WxMpUser; +import me.chanjar.weixin.mp.bean.result.WxMpUserBlacklistGetResult; +import me.chanjar.weixin.mp.bean.result.WxMpUserList; public class WxMpGsonBuilder { @@ -15,9 +40,8 @@ public class WxMpGsonBuilder { INSTANCE.disableHtmlEscaping(); INSTANCE.registerTypeAdapter(WxMpCustomMessage.class, new WxMpCustomMessageGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpMassNews.class, new WxMpMassNewsGsonAdapter()); - INSTANCE.registerTypeAdapter(WxMpMassGroupMessage.class, new WxMpMassGroupMessageGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpMassTagMessage.class, new WxMpMassTagMessageGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpMassOpenIdsMessage.class, new WxMpMassOpenIdsMessageGsonAdapter()); - INSTANCE.registerTypeAdapter(WxMpGroup.class, new WxMpGroupGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpUser.class, new WxMpUserGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpUserList.class, new WxUserListGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpMassVideo.class, new WxMpMassVideoAdapter()); @@ -45,6 +69,7 @@ public class WxMpGsonBuilder { INSTANCE.registerTypeAdapter(WxMpMassPreviewMessage.class, new WxMpMassPreviewMessageGsonAdapter()); INSTANCE.registerTypeAdapter(WxMediaImgUploadResult.class, new WxMediaImgUploadResultGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpIndustry.class, new WxMpIndustryGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpUserBlacklistGetResult.class, new WxUserBlacklistGetResultGsonAdapter()); } public static Gson create() { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpIndustryGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpIndustryGsonAdapter.java index 79fb5f0b..60361249 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpIndustryGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpIndustryGsonAdapter.java @@ -1,5 +1,7 @@ package me.chanjar.weixin.mp.util.json; +import java.lang.reflect.Type; + import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; @@ -7,38 +9,43 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; + import me.chanjar.weixin.common.util.json.GsonHelper; import me.chanjar.weixin.mp.bean.Industry; import me.chanjar.weixin.mp.bean.WxMpIndustry; -import java.lang.reflect.Type; - /** * @author miller */ -public class WxMpIndustryGsonAdapter implements JsonSerializer, JsonDeserializer { - @Override - public JsonElement serialize(WxMpIndustry wxMpIndustry, Type type, JsonSerializationContext jsonSerializationContext) { - JsonObject json = new JsonObject(); - json.addProperty("industry_id1", wxMpIndustry.getPrimaryIndustry().getId()); - json.addProperty("industry_id2", wxMpIndustry.getSecondIndustry().getId()); - return json; - } +public class WxMpIndustryGsonAdapter + implements JsonSerializer, JsonDeserializer { + @Override + public JsonElement serialize(WxMpIndustry wxMpIndustry, Type type, + JsonSerializationContext jsonSerializationContext) { + JsonObject json = new JsonObject(); + json.addProperty("industry_id1", wxMpIndustry.getPrimaryIndustry().getId()); + json.addProperty("industry_id2", wxMpIndustry.getSecondIndustry().getId()); + return json; + } - @Override - public WxMpIndustry deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { - WxMpIndustry wxMpIndustry = new WxMpIndustry(); - JsonObject primaryIndustry = jsonElement.getAsJsonObject().get("primary_industry").getAsJsonObject(); - wxMpIndustry.setPrimaryIndustry(convertFromJson(primaryIndustry)); - JsonObject secondaryIndustry = jsonElement.getAsJsonObject().get("secondary_industry").getAsJsonObject(); - wxMpIndustry.setSecondIndustry(convertFromJson(secondaryIndustry)); - return wxMpIndustry; - } + @Override + public WxMpIndustry deserialize(JsonElement jsonElement, Type type, + JsonDeserializationContext jsonDeserializationContext) + throws JsonParseException { + WxMpIndustry wxMpIndustry = new WxMpIndustry(); + JsonObject primaryIndustry = jsonElement.getAsJsonObject() + .get("primary_industry").getAsJsonObject(); + wxMpIndustry.setPrimaryIndustry(convertFromJson(primaryIndustry)); + JsonObject secondaryIndustry = jsonElement.getAsJsonObject() + .get("secondary_industry").getAsJsonObject(); + wxMpIndustry.setSecondIndustry(convertFromJson(secondaryIndustry)); + return wxMpIndustry; + } - private Industry convertFromJson(JsonObject json) { - Industry industry = new Industry(); - industry.setFirstClass(GsonHelper.getString(json, "first_class")); - industry.setSecondClass(GsonHelper.getString(json, "second_class")); - return industry; - } + private static Industry convertFromJson(JsonObject json) { + Industry industry = new Industry(); + industry.setFirstClass(GsonHelper.getString(json, "first_class")); + industry.setSecondClass(GsonHelper.getString(json, "second_class")); + return industry; + } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassGroupMessageGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassTagMessageGsonAdapter.java similarity index 85% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassGroupMessageGsonAdapter.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassTagMessageGsonAdapter.java index 4ad45848..6514ed59 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassGroupMessageGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassTagMessageGsonAdapter.java @@ -8,27 +8,28 @@ */ package me.chanjar.weixin.mp.util.json; +import java.lang.reflect.Type; + import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; -import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.mp.bean.WxMpMassGroupMessage; -import java.lang.reflect.Type; +import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.mp.bean.WxMpMassTagMessage; -public class WxMpMassGroupMessageGsonAdapter implements JsonSerializer { +public class WxMpMassTagMessageGsonAdapter implements JsonSerializer { @Override - public JsonElement serialize(WxMpMassGroupMessage message, Type typeOfSrc, JsonSerializationContext context) { + public JsonElement serialize(WxMpMassTagMessage message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); JsonObject filter = new JsonObject(); - if(null == message.getGroupId()) { + if(null == message.getTagId()) { filter.addProperty("is_to_all", true); } else { filter.addProperty("is_to_all", false); - filter.addProperty("group_id", message.getGroupId()); + filter.addProperty("tag_id", message.getTagId()); } messageJson.add("filter", filter); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserCumulateGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserCumulateGsonAdapter.java index fcf1d403..74ccd154 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserCumulateGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserCumulateGsonAdapter.java @@ -8,13 +8,19 @@ */ package me.chanjar.weixin.mp.util.json; -import com.google.gson.*; -import me.chanjar.weixin.common.util.json.GsonHelper; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; - import java.lang.reflect.Type; import java.text.ParseException; -import java.text.SimpleDateFormat; + +import org.apache.commons.lang3.time.FastDateFormat; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; /** * @@ -23,7 +29,8 @@ import java.text.SimpleDateFormat; */ public class WxMpUserCumulateGsonAdapter implements JsonDeserializer { - private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + private static final FastDateFormat DATE_FORMAT = FastDateFormat + .getInstance("yyyy-MM-dd"); @Override public WxDataCubeUserCumulate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { @@ -33,7 +40,7 @@ public class WxMpUserCumulateGsonAdapter implements JsonDeserializer { @Override @@ -36,6 +41,7 @@ public class WxMpUserGsonAdapter implements JsonDeserializer { Integer sexId = GsonHelper.getInteger(o, "sex"); wxMpUser.setRemark(GsonHelper.getString(o, "remark")); wxMpUser.setGroupId(GsonHelper.getInteger(o, "groupid")); + wxMpUser.setTagIds(GsonHelper.getIntArray(o, "tagid_list")); wxMpUser.setSexId(sexId); if(new Integer(1).equals(sexId)) { wxMpUser.setSex("男"); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserSummaryGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserSummaryGsonAdapter.java index 848b82ce..2e0791f8 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserSummaryGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserSummaryGsonAdapter.java @@ -8,20 +8,27 @@ */ package me.chanjar.weixin.mp.util.json; -import com.google.gson.*; -import me.chanjar.weixin.common.util.json.GsonHelper; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; - import java.lang.reflect.Type; import java.text.ParseException; -import java.text.SimpleDateFormat; + +import org.apache.commons.lang3.time.FastDateFormat; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; /** * @author Daniel Qian */ public class WxMpUserSummaryGsonAdapter implements JsonDeserializer { - private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + private static final FastDateFormat DATE_FORMAT = FastDateFormat + .getInstance("yyyy-MM-dd"); @Override public WxDataCubeUserSummary deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) @@ -32,7 +39,7 @@ public class WxMpUserSummaryGsonAdapter implements JsonDeserializer { + @Override + public WxMpUserBlacklistGetResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject o = json.getAsJsonObject(); + WxMpUserBlacklistGetResult wxMpUserBlacklistGetResult = new WxMpUserBlacklistGetResult(); + wxMpUserBlacklistGetResult.setTotal(GsonHelper.getInteger(o, "total")); + wxMpUserBlacklistGetResult.setCount(GsonHelper.getInteger(o, "count")); + wxMpUserBlacklistGetResult.setNextOpenid(GsonHelper.getString(o, "next_openid")); + if (o.get("data") != null && !o.get("data").isJsonNull() && !o.get("data").getAsJsonObject().get("openid").isJsonNull()) { + JsonArray data = o.get("data").getAsJsonObject().get("openid").getAsJsonArray(); + for (int i = 0; i < data.size(); i++) { + wxMpUserBlacklistGetResult.getOpenidList().add(GsonHelper.getAsString(data.get(i))); + } + } + return wxMpUserBlacklistGetResult; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java index 61ecac41..39e3d1dc 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java @@ -1,16 +1,25 @@ package me.chanjar.weixin.mp.util.xml; -import com.thoughtworks.xstream.XStream; -import me.chanjar.weixin.common.util.xml.XStreamInitializer; -import me.chanjar.weixin.mp.bean.*; - import java.io.InputStream; import java.util.HashMap; import java.util.Map; +import com.thoughtworks.xstream.XStream; + +import me.chanjar.weixin.common.util.xml.XStreamInitializer; +import me.chanjar.weixin.mp.bean.WxMpXmlMessage; +import me.chanjar.weixin.mp.bean.WxMpXmlOutImageMessage; +import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage; +import me.chanjar.weixin.mp.bean.WxMpXmlOutMusicMessage; +import me.chanjar.weixin.mp.bean.WxMpXmlOutNewsMessage; +import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage; +import me.chanjar.weixin.mp.bean.WxMpXmlOutTransferCustomerServiceMessage; +import me.chanjar.weixin.mp.bean.WxMpXmlOutVideoMessage; +import me.chanjar.weixin.mp.bean.WxMpXmlOutVoiceMessage; + public class XStreamTransformer { - protected static final Map CLASS_2_XSTREAM_INSTANCE = configXStreamInstance(); + protected static final Map, XStream> CLASS_2_XSTREAM_INSTANCE = configXStreamInstance(); /** * xml -> pojo @@ -32,7 +41,7 @@ public class XStreamTransformer { * @param clz 类型 * @param xStream xml解析器 */ - public static void register(Class clz,XStream xStream){ + public static void register(Class clz, XStream xStream) { CLASS_2_XSTREAM_INSTANCE.put(clz,xStream); } @@ -44,8 +53,8 @@ public class XStreamTransformer { return CLASS_2_XSTREAM_INSTANCE.get(clazz).toXML(object); } - private static Map configXStreamInstance() { - Map map = new HashMap<>(); + private static Map, XStream> configXStreamInstance() { + Map, XStream> map = new HashMap<>(); map.put(WxMpXmlMessage.class, config_WxMpXmlMessage()); map.put(WxMpXmlOutMusicMessage.class, config_WxMpXmlOutMusicMessage()); map.put(WxMpXmlOutNewsMessage.class, config_WxMpXmlOutNewsMessage()); diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/ApiTestModule.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/ApiTestModule.java index 3955f87d..4ec12cbd 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/ApiTestModule.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/ApiTestModule.java @@ -3,15 +3,12 @@ package me.chanjar.weixin.mp.api; import java.io.IOException; import java.io.InputStream; -import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; -import org.apache.commons.lang3.builder.ToStringBuilder; - import com.google.inject.Binder; import com.google.inject.Module; import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.annotations.XStreamAlias; import me.chanjar.weixin.common.util.xml.XStreamInitializer; +import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; public class ApiTestModule implements Module { @@ -19,8 +16,8 @@ public class ApiTestModule implements Module { public void configure(Binder binder) { try (InputStream is1 = ClassLoader .getSystemResourceAsStream("test-config.xml")) { - WxXmlMpInMemoryConfigStorage config = fromXml( - WxXmlMpInMemoryConfigStorage.class, is1); + WxXmlMpInMemoryConfigStorage config = this + .fromXml(WxXmlMpInMemoryConfigStorage.class, is1); WxMpServiceImpl wxService = new WxMpServiceImpl(); wxService.setWxMpConfigStorage(config); @@ -32,50 +29,11 @@ public class ApiTestModule implements Module { } @SuppressWarnings("unchecked") - public static T fromXml(Class clazz, InputStream is) { + private T fromXml(Class clazz, InputStream is) { XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", clazz); xstream.processAnnotations(clazz); return (T) xstream.fromXML(is); } - @XStreamAlias("xml") - public static class WxXmlMpInMemoryConfigStorage - extends WxMpInMemoryConfigStorage { - - private String openId; - private String kfAccount; - private String qrconnectRedirectUrl; - - public String getOpenId() { - return this.openId; - } - - public void setOpenId(String openId) { - this.openId = openId; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - public String getKfAccount() { - return this.kfAccount; - } - - public void setKfAccount(String kfAccount) { - this.kfAccount = kfAccount; - } - - public String getQrconnectRedirectUrl() { - return this.qrconnectRedirectUrl; - } - - public void setQrconnectRedirectUrl(String qrconnectRedirectUrl) { - this.qrconnectRedirectUrl = qrconnectRedirectUrl; - } - - } - } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBusyRetryTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBusyRetryTest.java index c9edbdc5..a302cc2f 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBusyRetryTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBusyRetryTest.java @@ -1,17 +1,18 @@ package me.chanjar.weixin.mp.api; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestExecutor; -import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; + @Test public class WxMpBusyRetryTest { @@ -20,7 +21,9 @@ public class WxMpBusyRetryTest { WxMpService service = new WxMpServiceImpl() { @Override - protected T executeInternal(RequestExecutor executor, String uri, E data) throws WxErrorException { + protected synchronized T executeInternal( + RequestExecutor executor, String uri, E data) + throws WxErrorException { WxError error = new WxError(); error.setErrorCode(-1); throw new WxErrorException(error); diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpCustomMessageAPITest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpCustomMessageAPITest.java deleted file mode 100644 index 4cca2e3c..00000000 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpCustomMessageAPITest.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.chanjar.weixin.mp.api; - -import com.google.inject.Inject; -import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; -import me.chanjar.weixin.mp.bean.WxMpCustomMessage; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; - -/*** - * 测试发送客服消息 - * @author chanjarster - * - */ -@Test(groups="customMessageAPI") -@Guice(modules = ApiTestModule.class) -public class WxMpCustomMessageAPITest { - - @Inject - protected WxMpServiceImpl wxService; - - public void testSendCustomMessage() throws WxErrorException { - ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) wxService.getWxMpConfigStorage(); - WxMpCustomMessage message = new WxMpCustomMessage(); - message.setMsgType(WxConsts.CUSTOM_MSG_TEXT); - message.setToUser(configStorage.getOpenId()); - message.setContent("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World"); - - this.wxService.customMessageSend(message); - } - - public void testSendCustomMessageWithKfAccount() throws WxErrorException { - ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) wxService.getWxMpConfigStorage(); - WxMpCustomMessage message = new WxMpCustomMessage(); - message.setMsgType(WxConsts.CUSTOM_MSG_TEXT); - message.setToUser(configStorage.getOpenId()); - message.setKfAccount(configStorage.getKfAccount()); - message.setContent("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World"); - - this.wxService.customMessageSend(message); - } - -} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpJsAPITest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpJsAPITest.java index dacc2ab8..d4c49a0b 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpJsAPITest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpJsAPITest.java @@ -1,14 +1,14 @@ package me.chanjar.weixin.mp.api; -import com.google.inject.Inject; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.crypto.SHA1; -import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; import org.testng.Assert; import org.testng.annotations.Guice; import org.testng.annotations.Test; -import java.security.NoSuchAlgorithmException; +import com.google.inject.Inject; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.crypto.SHA1; +import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; /** * 测试jsapi ticket接口 @@ -24,12 +24,12 @@ public class WxMpJsAPITest { public void testJsapiTicket() throws WxErrorException { - String jsapiTicket = wxService.getJsapiTicket(false); + String jsapiTicket = this.wxService.getJsapiTicket(false); System.out.println(jsapiTicket); Assert.assertNotNull(jsapiTicket); } - public void test() throws NoSuchAlgorithmException { + public void test() { long timestamp = 1419835025l; String url = "http://omstest.vmall.com:23568/thirdparty/wechat/vcode/gotoshare?quantity=1&batchName=MATE7"; String noncestr = "82693e11-b9bc-448e-892f-f5289f46cd0f"; diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMassMessageAPITest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMassMessageAPITest.java index 5b50b5a4..e093d575 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMassMessageAPITest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMassMessageAPITest.java @@ -1,23 +1,25 @@ package me.chanjar.weixin.mp.api; +import java.io.IOException; +import java.io.InputStream; + +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.api.WxConsts; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; -import me.chanjar.weixin.mp.bean.WxMpMassGroupMessage; import me.chanjar.weixin.mp.bean.WxMpMassNews; import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage; +import me.chanjar.weixin.mp.bean.WxMpMassTagMessage; import me.chanjar.weixin.mp.bean.WxMpMassVideo; import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult; import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.io.InputStream; /** * 测试群发消息 @@ -34,108 +36,126 @@ public class WxMpMassMessageAPITest { @Test public void testTextMassOpenIdsMessageSend() throws WxErrorException { // 发送群发消息 - ApiTestModule.WxXmlMpInMemoryConfigStorage configProvider = (ApiTestModule.WxXmlMpInMemoryConfigStorage) wxService.getWxMpConfigStorage(); + WxXmlMpInMemoryConfigStorage configProvider = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage(); massMessage.setMsgType(WxConsts.MASS_MSG_TEXT); massMessage.setContent("测试群发消息\n欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World"); - massMessage.getToUsers().add(configProvider.getOpenId()); + massMessage.getToUsers().add(configProvider.getOpenid()); - WxMpMassSendResult massResult = wxService.massOpenIdsMessageSend(massMessage); + WxMpMassSendResult massResult = this.wxService + .massOpenIdsMessageSend(massMessage); Assert.assertNotNull(massResult); Assert.assertNotNull(massResult.getMsgId()); } @Test(dataProvider="massMessages") - public void testMediaMassOpenIdsMessageSend(String massMsgType, String mediaId) throws WxErrorException, IOException { + public void testMediaMassOpenIdsMessageSend(String massMsgType, + String mediaId) throws WxErrorException { // 发送群发消息 - ApiTestModule.WxXmlMpInMemoryConfigStorage configProvider = (ApiTestModule.WxXmlMpInMemoryConfigStorage) wxService.getWxMpConfigStorage(); + WxXmlMpInMemoryConfigStorage configProvider = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage(); massMessage.setMsgType(massMsgType); massMessage.setMediaId(mediaId); - massMessage.getToUsers().add(configProvider.getOpenId()); + massMessage.getToUsers().add(configProvider.getOpenid()); - WxMpMassSendResult massResult = wxService.massOpenIdsMessageSend(massMessage); + WxMpMassSendResult massResult = this.wxService + .massOpenIdsMessageSend(massMessage); Assert.assertNotNull(massResult); Assert.assertNotNull(massResult.getMsgId()); } @Test public void testTextMassGroupMessageSend() throws WxErrorException { - WxMpMassGroupMessage massMessage = new WxMpMassGroupMessage(); + WxMpMassTagMessage massMessage = new WxMpMassTagMessage(); massMessage.setMsgtype(WxConsts.MASS_MSG_TEXT); massMessage.setContent("测试群发消息\n欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World"); - massMessage.setGroupId(wxService.getGroupService().groupGet().get(0).getId()); - - WxMpMassSendResult massResult = wxService.massGroupMessageSend(massMessage); + massMessage + .setTagId(this.wxService.getUserTagService().tagGet().get(0).getId()); + + WxMpMassSendResult massResult = this.wxService + .massGroupMessageSend(massMessage); Assert.assertNotNull(massResult); Assert.assertNotNull(massResult.getMsgId()); } - + @Test(dataProvider="massMessages") - public void testMediaMassGroupMessageSend(String massMsgType, String mediaId) throws WxErrorException, IOException { - WxMpMassGroupMessage massMessage = new WxMpMassGroupMessage(); + public void testMediaMassGroupMessageSend(String massMsgType, String mediaId) + throws WxErrorException { + WxMpMassTagMessage massMessage = new WxMpMassTagMessage(); massMessage.setMsgtype(massMsgType); massMessage.setMediaId(mediaId); - massMessage.setGroupId(wxService.getGroupService().groupGet().get(0).getId()); + massMessage + .setTagId(this.wxService.getUserTagService().tagGet().get(0).getId()); - WxMpMassSendResult massResult = wxService.massGroupMessageSend(massMessage); + WxMpMassSendResult massResult = this.wxService + .massGroupMessageSend(massMessage); Assert.assertNotNull(massResult); Assert.assertNotNull(massResult.getMsgId()); } - + @DataProvider public Object[][] massMessages() throws WxErrorException, IOException { Object[][] messages = new Object[4][]; + /* * 视频素材 */ - { + try (InputStream inputStream = ClassLoader + .getSystemResourceAsStream("mm.mp4")) { // 上传视频到媒体库 - InputStream inputStream = ClassLoader.getSystemResourceAsStream("mm.mp4"); - WxMediaUploadResult uploadMediaRes = wxService.getMaterialService().mediaUpload(WxConsts.MEDIA_VIDEO, WxConsts.FILE_MP4, inputStream); + WxMediaUploadResult uploadMediaRes = this.wxService.getMaterialService() + .mediaUpload(WxConsts.MEDIA_VIDEO, WxConsts.FILE_MP4, inputStream); Assert.assertNotNull(uploadMediaRes); Assert.assertNotNull(uploadMediaRes.getMediaId()); - + // 把视频变成可被群发的媒体 WxMpMassVideo video = new WxMpMassVideo(); video.setTitle("测试标题"); video.setDescription("测试描述"); video.setMediaId(uploadMediaRes.getMediaId()); - WxMpMassUploadResult uploadResult = wxService.massVideoUpload(video); + WxMpMassUploadResult uploadResult = this.wxService.massVideoUpload(video); Assert.assertNotNull(uploadResult); Assert.assertNotNull(uploadResult.getMediaId()); messages[0] = new Object[] { WxConsts.MASS_MSG_VIDEO, uploadResult.getMediaId() }; } + /** * 图片素材 */ - { - InputStream inputStream = ClassLoader.getSystemResourceAsStream("mm.jpeg"); - WxMediaUploadResult uploadMediaRes = wxService.getMaterialService().mediaUpload(WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, inputStream); + try (InputStream inputStream = ClassLoader + .getSystemResourceAsStream("mm.jpeg")) { + WxMediaUploadResult uploadMediaRes = this.wxService.getMaterialService() + .mediaUpload(WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, inputStream); Assert.assertNotNull(uploadMediaRes); Assert.assertNotNull(uploadMediaRes.getMediaId()); messages[1] = new Object[] { WxConsts.MASS_MSG_IMAGE, uploadMediaRes.getMediaId() }; } + /** * 语音素材 */ - { - InputStream inputStream = ClassLoader.getSystemResourceAsStream("mm.mp3"); - WxMediaUploadResult uploadMediaRes = wxService.getMaterialService().mediaUpload(WxConsts.MEDIA_VOICE, WxConsts.FILE_MP3, inputStream); + try (InputStream inputStream = ClassLoader + .getSystemResourceAsStream("mm.mp3")) { + WxMediaUploadResult uploadMediaRes = this.wxService.getMaterialService() + .mediaUpload(WxConsts.MEDIA_VOICE, WxConsts.FILE_MP3, inputStream); Assert.assertNotNull(uploadMediaRes); Assert.assertNotNull(uploadMediaRes.getMediaId()); messages[2] = new Object[] { WxConsts.MASS_MSG_VOICE, uploadMediaRes.getMediaId() }; } + /** * 图文素材 */ - { + try (InputStream inputStream = ClassLoader + .getSystemResourceAsStream("mm.jpeg")) { // 上传照片到媒体库 - InputStream inputStream = ClassLoader.getSystemResourceAsStream("mm.jpeg"); - WxMediaUploadResult uploadMediaRes = wxService.getMaterialService().mediaUpload(WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, inputStream); + WxMediaUploadResult uploadMediaRes = this.wxService.getMaterialService() + .mediaUpload(WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, inputStream); Assert.assertNotNull(uploadMediaRes); Assert.assertNotNull(uploadMediaRes.getMediaId()); - + // 上传图文消息 WxMpMassNews news = new WxMpMassNews(); WxMpMassNews.WxMpMassNewsArticle article1 = new WxMpMassNews.WxMpMassNewsArticle(); @@ -143,7 +163,7 @@ public class WxMpMassMessageAPITest { article1.setContent("内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1内容1"); article1.setThumbMediaId(uploadMediaRes.getMediaId()); news.addArticle(article1); - + WxMpMassNews.WxMpMassNewsArticle article2 = new WxMpMassNews.WxMpMassNewsArticle(); article2.setTitle("标题2"); article2.setContent("内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2内容2"); @@ -153,13 +173,15 @@ public class WxMpMassMessageAPITest { article2.setContentSourceUrl("www.baidu.com"); article2.setDigest("摘要2"); news.addArticle(article2); - - WxMpMassUploadResult massUploadResult = wxService.massNewsUpload(news); + + WxMpMassUploadResult massUploadResult = this.wxService + .massNewsUpload(news); Assert.assertNotNull(massUploadResult); Assert.assertNotNull(uploadMediaRes.getMediaId()); messages[3] = new Object[] { WxConsts.MASS_MSG_NEWS, massUploadResult.getMediaId() }; } + return messages; } - + } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMessageRouterTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMessageRouterTest.java index a6cb0a63..fdc90744 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMessageRouterTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMessageRouterTest.java @@ -163,7 +163,7 @@ public class WxMpMessageRouterTest { @Override public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, WxSessionManager sessionManager) { - sb.append(this.echoStr).append(','); + this.sb.append(this.echoStr).append(','); return null; } @@ -195,7 +195,7 @@ public class WxMpMessageRouterTest { .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxMpXmlMessage msg = new WxMpXmlMessage(); - msg.setFromUserName("abc"); + msg.setFromUser("abc"); router.route(msg); Thread.sleep(2000l); @@ -215,7 +215,7 @@ public class WxMpMessageRouterTest { .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxMpXmlMessage msg = new WxMpXmlMessage(); - msg.setFromUserName("abc"); + msg.setFromUser("abc"); router.route(msg); Thread.sleep(2000l); @@ -229,7 +229,7 @@ public class WxMpMessageRouterTest { .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxMpXmlMessage msg = new WxMpXmlMessage(); - msg.setFromUserName("abc"); + msg.setFromUser("abc"); router.route(msg); Thread.sleep(2000l); @@ -249,7 +249,7 @@ public class WxMpMessageRouterTest { .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxMpXmlMessage msg = new WxMpXmlMessage(); - msg.setFromUserName("abc"); + msg.setFromUser("abc"); router.route(msg); Thread.sleep(2000l); @@ -268,7 +268,7 @@ public class WxMpMessageRouterTest { .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxMpXmlMessage msg = new WxMpXmlMessage(); - msg.setFromUserName("abc"); + msg.setFromUser("abc"); router.route(msg); Thread.sleep(2000l); @@ -282,7 +282,7 @@ public class WxMpMessageRouterTest { .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxMpXmlMessage msg = new WxMpXmlMessage(); - msg.setFromUserName("abc"); + msg.setFromUser("abc"); router.route(msg); Thread.sleep(2000l); @@ -295,7 +295,7 @@ public class WxMpMessageRouterTest { @Override public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, WxSessionManager sessionManager) { - sessionManager.getSession(wxMessage.getFromUserName()); + sessionManager.getSession(wxMessage.getFromUser()); return null; } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpShortUrlAPITest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpShortUrlAPITest.java index 091f62ee..d392d1f5 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpShortUrlAPITest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpShortUrlAPITest.java @@ -20,7 +20,7 @@ public class WxMpShortUrlAPITest { protected WxMpServiceImpl wxService; public void testShortUrl() throws WxErrorException { - String shortUrl = wxService.shortUrl("www.baidu.com"); + String shortUrl = this.wxService.shortUrl("www.baidu.com"); Assert.assertNotNull(shortUrl); } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxXmlMpInMemoryConfigStorage.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxXmlMpInMemoryConfigStorage.java new file mode 100644 index 00000000..c9835a0a --- /dev/null +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxXmlMpInMemoryConfigStorage.java @@ -0,0 +1,53 @@ +package me.chanjar.weixin.mp.api; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("xml") +public class WxXmlMpInMemoryConfigStorage + extends WxMpInMemoryConfigStorage { + + private String openid; + private String kfAccount; + private String qrconnectRedirectUrl; + private String templateId; + + public String getOpenid() { + return this.openid; + } + + public void setOpenid(String openid) { + this.openid = openid; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getKfAccount() { + return this.kfAccount; + } + + public void setKfAccount(String kfAccount) { + this.kfAccount = kfAccount; + } + + public String getQrconnectRedirectUrl() { + return this.qrconnectRedirectUrl; + } + + public void setQrconnectRedirectUrl(String qrconnectRedirectUrl) { + this.qrconnectRedirectUrl = qrconnectRedirectUrl; + } + + public String getTemplateId() { + return this.templateId; + } + + public void setTemplateId(String templateId) { + this.templateId = templateId; + } + +} \ No newline at end of file diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImplTest.java index a28723c5..b7981dbd 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImplTest.java @@ -42,7 +42,7 @@ public class WxMpCardServiceImplTest { public void testCreateCardApiSignature() throws Exception { //app_id, card_id, card_type, code, openid, location_id - String[] param = {"123", cardId, "", code, openid, ""}; + String[] param = {"123", this.cardId, "", this.code, this.openid, ""}; WxCardApiSignature cardApiSignature = this.wxService.getCardService().createCardApiSignature(param); assertNotNull(cardApiSignature); System.out.println(cardApiSignature); @@ -58,34 +58,34 @@ public class WxMpCardServiceImplTest { @Test public void testQueryCardCode() throws Exception { - WxMpCardResult wxMpCardResult = this.wxService.getCardService().queryCardCode(cardId, code, false); + WxMpCardResult wxMpCardResult = this.wxService.getCardService().queryCardCode(this.cardId, this.code, false); assertNotNull(wxMpCardResult); System.out.println(wxMpCardResult); } @Test public void testConsumeCardCode() throws Exception { - String result = this.wxService.getCardService().consumeCardCode(code); + String result = this.wxService.getCardService().consumeCardCode(this.code); assertNotNull(result); System.out.println(result); } @Test public void testConsumeCardCodeWithCardId() throws Exception { - String result = this.wxService.getCardService().consumeCardCode(code, cardId); + String result = this.wxService.getCardService().consumeCardCode(this.code, this.cardId); assertNotNull(result); System.out.println(result); } @Test public void testMarkCardCode() throws Exception { - this.wxService.getCardService().markCardCode(code, cardId, openid, true); + this.wxService.getCardService().markCardCode(this.code, this.cardId, this.openid, true); System.out.println("done"); } @Test public void testGetCardDetail() throws Exception { - String result = this.wxService.getCardService().getCardDetail(cardId); + String result = this.wxService.getCardService().getCardDetail(this.cardId); assertNotNull(result); System.out.println(result); } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImplTest.java index bfb8cf58..1111f96a 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImplTest.java @@ -1,10 +1,10 @@ package me.chanjar.weixin.mp.api.impl; import java.text.ParseException; -import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import org.apache.commons.lang3.time.FastDateFormat; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Guice; @@ -28,39 +28,39 @@ import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; */ @Guice(modules = ApiTestModule.class) public class WxMpDataCubeServiceImplTest { - private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat( - "yyyy-MM-dd"); + private FastDateFormat simpleDateFormat = FastDateFormat + .getInstance("yyyy-MM-dd"); @Inject protected WxMpServiceImpl wxService; @DataProvider public Object[][] oneDay() throws ParseException { - return new Object[][] { { simpleDateFormat.parse("2016-08-22") } }; + return new Object[][] { { this.simpleDateFormat.parse("2016-08-22") } }; } @DataProvider public Object[][] threeDays() throws ParseException { - return new Object[][] { { simpleDateFormat.parse("2016-08-20"), - simpleDateFormat.parse("2016-08-22") } }; + return new Object[][] { { this.simpleDateFormat.parse("2016-08-20"), + this.simpleDateFormat.parse("2016-08-22") } }; } @DataProvider public Object[][] sevenDays() throws ParseException { - return new Object[][] { { simpleDateFormat.parse("2016-08-16"), - simpleDateFormat.parse("2016-08-22") } }; + return new Object[][] { { this.simpleDateFormat.parse("2016-08-16"), + this.simpleDateFormat.parse("2016-08-22") } }; } @DataProvider public Object[][] fifteenDays() throws ParseException { - return new Object[][] { { simpleDateFormat.parse("2016-08-14"), - simpleDateFormat.parse("2016-08-27") } }; + return new Object[][] { { this.simpleDateFormat.parse("2016-08-14"), + this.simpleDateFormat.parse("2016-08-27") } }; } @DataProvider public Object[][] thirtyDays() throws ParseException { - return new Object[][] { { simpleDateFormat.parse("2016-07-30"), - simpleDateFormat.parse("2016-08-27") } }; + return new Object[][] { { this.simpleDateFormat.parse("2016-07-30"), + this.simpleDateFormat.parse("2016-08-27") } }; } @Test(dataProvider = "sevenDays") diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImplTest.java deleted file mode 100644 index f2dd8f64..00000000 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImplTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package me.chanjar.weixin.mp.api.impl; - -import com.google.inject.Inject; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.api.ApiTestModule; -import me.chanjar.weixin.mp.bean.WxMpGroup; -import org.testng.Assert; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; - -import java.util.List; - -/** - * 测试分组接口 - * - * @author chanjarster - */ -@Test(groups = "groupAPI") -@Guice(modules = ApiTestModule.class) -public class WxMpGroupServiceImplTest { - - @Inject - protected WxMpServiceImpl wxService; - - protected WxMpGroup group; - - public void testGroupCreate() throws WxErrorException { - WxMpGroup res = this.wxService.getGroupService().groupCreate("测试分组1"); - Assert.assertEquals(res.getName(), "测试分组1"); - } - - @Test(dependsOnMethods="testGroupCreate") - public void testGroupGet() throws WxErrorException { - List groupList = this.wxService.getGroupService().groupGet(); - Assert.assertNotNull(groupList); - Assert.assertTrue(groupList.size() > 0); - for (WxMpGroup g : groupList) { - group = g; - Assert.assertNotNull(g.getName()); - } - } - - @Test(dependsOnMethods={"testGroupGet", "testGroupCreate"}) - public void getGroupUpdate() throws WxErrorException { - group.setName("分组改名"); - this.wxService.getGroupService().groupUpdate(group); - } - -} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImplTest.java index c1812ab0..32a0118f 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImplTest.java @@ -9,13 +9,13 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Guice; import org.testng.annotations.Test; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; +import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.ApiTestModule; -import me.chanjar.weixin.mp.api.ApiTestModule.WxXmlMpInMemoryConfigStorage; +import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage; +import me.chanjar.weixin.mp.bean.WxMpCustomMessage; import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfAccountRequest; import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfInfo; import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfList; @@ -37,6 +37,31 @@ public class WxMpKefuServiceImplTest { @Inject protected WxMpServiceImpl wxService; + public void testSendCustomMessage() throws WxErrorException { + WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); + WxMpCustomMessage message = new WxMpCustomMessage(); + message.setMsgType(WxConsts.CUSTOM_MSG_TEXT); + message.setToUser(configStorage.getOpenid()); + message.setContent( + "欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World"); + + this.wxService.getKefuService().customMessageSend(message); + } + + public void testSendCustomMessageWithKfAccount() throws WxErrorException { + WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); + WxMpCustomMessage message = new WxMpCustomMessage(); + message.setMsgType(WxConsts.CUSTOM_MSG_TEXT); + message.setToUser(configStorage.getOpenid()); + message.setKfAccount(configStorage.getKfAccount()); + message.setContent( + "欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World"); + + this.wxService.getKefuService().customMessageSend(message); + } + public void testKfList() throws WxErrorException { WxMpKfList kfList = this.wxService.getKefuService().kfList(); Assert.assertNotNull(kfList); @@ -80,7 +105,7 @@ public class WxMpKefuServiceImplTest { "testKfAccountAdd" }, dataProvider = "getKfAccount") public void testKfAccountInviteWorker(String kfAccount) throws WxErrorException { WxMpKfAccountRequest request = WxMpKfAccountRequest.builder() - .kfAccount(kfAccount).inviteWx("www_ucredit_com").build(); + .kfAccount(kfAccount).inviteWx(" ").build(); Assert.assertTrue(this.wxService.getKefuService().kfAccountInviteWorker(request)); } @@ -105,7 +130,7 @@ public class WxMpKefuServiceImplTest { WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService .getWxMpConfigStorage(); return new Object[][] { - { configStorage.getKfAccount(), configStorage.getOpenId() } }; + { configStorage.getKfAccount(), configStorage.getOpenid() } }; } @Test(dataProvider = "getKfAccountAndOpenid") @@ -125,7 +150,7 @@ public class WxMpKefuServiceImplTest { } @Test(dataProvider = "getKfAccountAndOpenid") - public void testKfSessionGet(String kfAccount, + public void testKfSessionGet(@SuppressWarnings("unused") String kfAccount, String openid) throws WxErrorException { WxMpKfSessionGetResult result = this.wxService.getKefuService() .kfSessionGet(openid); @@ -150,20 +175,20 @@ public class WxMpKefuServiceImplTest { } @Test - public void testKfMsgList() throws WxErrorException, JsonProcessingException { + public void testKfMsgList() throws WxErrorException { Date startTime = DateTime.now().minusDays(1).toDate(); Date endTime = DateTime.now().minusDays(0).toDate(); WxMpKfMsgList result = this.wxService.getKefuService().kfMsgList(startTime,endTime, 1L, 50); Assert.assertNotNull(result); - System.err.println(new ObjectMapper().writeValueAsString(result)); + System.err.println(result); } @Test - public void testKfMsgListAll() throws WxErrorException, JsonProcessingException { + public void testKfMsgListAll() throws WxErrorException { Date startTime = DateTime.now().minusDays(1).toDate(); Date endTime = DateTime.now().minusDays(0).toDate(); WxMpKfMsgList result = this.wxService.getKefuService().kfMsgList(startTime,endTime); Assert.assertNotNull(result); - System.err.println(new ObjectMapper().writeValueAsString(result)); + System.err.println(result); } } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImplTest.java index 73349626..5cde8adc 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImplTest.java @@ -1,24 +1,6 @@ package me.chanjar.weixin.mp.api.impl; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.io.IOUtils; -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.api.WxConsts; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; @@ -27,11 +9,17 @@ import me.chanjar.weixin.mp.api.ApiTestModule; import me.chanjar.weixin.mp.bean.WxMpMaterial; import me.chanjar.weixin.mp.bean.WxMpMaterialArticleUpdate; import me.chanjar.weixin.mp.bean.WxMpMaterialNews; -import me.chanjar.weixin.mp.bean.result.WxMpMaterialCountResult; -import me.chanjar.weixin.mp.bean.result.WxMpMaterialFileBatchGetResult; -import me.chanjar.weixin.mp.bean.result.WxMpMaterialNewsBatchGetResult; -import me.chanjar.weixin.mp.bean.result.WxMpMaterialUploadResult; -import me.chanjar.weixin.mp.bean.result.WxMpMaterialVideoInfoResult; +import me.chanjar.weixin.mp.bean.result.*; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Guice; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +import static org.junit.Assert.*; /** * 素材管理相关接口的测试 @@ -46,7 +34,7 @@ public class WxMpMaterialServiceImplTest { @Inject protected WxMpServiceImpl wxService; - private Map> media_ids = new LinkedHashMap<>(); + private Map> mediaIds = new LinkedHashMap<>(); // 缩略图的id,测试上传图文使用 private String thumbMediaId = ""; // 单图文消息media_id @@ -57,7 +45,7 @@ public class WxMpMaterialServiceImplTest { private WxMpMaterialCountResult wxMaterialCountResultBeforeTest; @DataProvider - public Object[][] uploadMedia() { + public Object[][] mediaFiles() { return new Object[][] { new Object[] { WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, "mm.jpeg" }, new Object[] { WxConsts.MEDIA_VOICE, WxConsts.FILE_MP3, "mm.mp3" }, @@ -66,36 +54,46 @@ public class WxMpMaterialServiceImplTest { }; } - @Test(dataProvider = "uploadMedia") + @Test(dataProvider = "mediaFiles") public void testUploadMaterial(String mediaType, String fileType, String fileName) throws WxErrorException, IOException { - if (wxMaterialCountResultBeforeTest == null) { - wxMaterialCountResultBeforeTest = this.wxService.getMaterialService().materialCount(); - } - InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName); - File tempFile = FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType); - WxMpMaterial wxMaterial = new WxMpMaterial(); - wxMaterial.setFile(tempFile); - wxMaterial.setName(fileName); - if (WxConsts.MEDIA_VIDEO.equals(mediaType)) { - wxMaterial.setVideoTitle("title"); - wxMaterial.setVideoIntroduction("test video description"); - } - WxMpMaterialUploadResult res = this.wxService.getMaterialService().materialFileUpload(mediaType, wxMaterial); - Assert.assertNotNull(res.getMediaId()); - if (WxConsts.MEDIA_IMAGE.equals(mediaType) || WxConsts.MEDIA_THUMB.equals(mediaType)) { - Assert.assertNotNull(res.getUrl()); - } - if (WxConsts.MEDIA_THUMB.equals(mediaType)) { - thumbMediaId = res.getMediaId(); + if (this.wxMaterialCountResultBeforeTest == null) { + this.wxMaterialCountResultBeforeTest = this.wxService.getMaterialService() + .materialCount(); } - Map materialInfo = new HashMap<>(); - materialInfo.put("media_id", res.getMediaId()); - materialInfo.put("length", tempFile.length()); - materialInfo.put("filename", tempFile.getName()); - media_ids.put(res.getMediaId(), materialInfo); + try (InputStream inputStream = ClassLoader + .getSystemResourceAsStream(fileName)) { + File tempFile = FileUtils.createTmpFile(inputStream, + UUID.randomUUID().toString(), fileType); + WxMpMaterial wxMaterial = new WxMpMaterial(); + wxMaterial.setFile(tempFile); + wxMaterial.setName(fileName); + if (WxConsts.MEDIA_VIDEO.equals(mediaType)) { + wxMaterial.setVideoTitle("title"); + wxMaterial.setVideoIntroduction("test video description"); + } + + WxMpMaterialUploadResult res = this.wxService.getMaterialService() + .materialFileUpload(mediaType, wxMaterial); + assertNotNull(res.getMediaId()); - System.out.println(res); + if (WxConsts.MEDIA_IMAGE.equals(mediaType) + || WxConsts.MEDIA_THUMB.equals(mediaType)) { + assertNotNull(res.getUrl()); + } + + if (WxConsts.MEDIA_THUMB.equals(mediaType)) { + this.thumbMediaId = res.getMediaId(); + } + + Map materialInfo = new HashMap<>(); + materialInfo.put("media_id", res.getMediaId()); + materialInfo.put("length", tempFile.length()); + materialInfo.put("filename", tempFile.getName()); + this.mediaIds.put(res.getMediaId(), materialInfo); + + System.out.println(res); + } } @Test(dependsOnMethods = {"testUploadMaterial"}) @@ -105,7 +103,7 @@ public class WxMpMaterialServiceImplTest { WxMpMaterialNews wxMpMaterialNewsSingle = new WxMpMaterialNews(); WxMpMaterialNews.WxMpMaterialNewsArticle mpMaterialNewsArticleSingle = new WxMpMaterialNews.WxMpMaterialNewsArticle(); mpMaterialNewsArticleSingle.setAuthor("author"); - mpMaterialNewsArticleSingle.setThumbMediaId(thumbMediaId); + mpMaterialNewsArticleSingle.setThumbMediaId(this.thumbMediaId); mpMaterialNewsArticleSingle.setTitle("single title"); mpMaterialNewsArticleSingle.setContent("single content"); mpMaterialNewsArticleSingle.setContentSourceUrl("content url"); @@ -117,7 +115,7 @@ public class WxMpMaterialServiceImplTest { WxMpMaterialNews wxMpMaterialNewsMultiple = new WxMpMaterialNews(); WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticleMultiple1 = new WxMpMaterialNews.WxMpMaterialNewsArticle(); wxMpMaterialNewsArticleMultiple1.setAuthor("author1"); - wxMpMaterialNewsArticleMultiple1.setThumbMediaId(thumbMediaId); + wxMpMaterialNewsArticleMultiple1.setThumbMediaId(this.thumbMediaId); wxMpMaterialNewsArticleMultiple1.setTitle("multi title1"); wxMpMaterialNewsArticleMultiple1.setContent("content 1"); wxMpMaterialNewsArticleMultiple1.setContentSourceUrl("content url"); @@ -126,7 +124,7 @@ public class WxMpMaterialServiceImplTest { WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticleMultiple2 = new WxMpMaterialNews.WxMpMaterialNewsArticle(); wxMpMaterialNewsArticleMultiple2.setAuthor("author2"); - wxMpMaterialNewsArticleMultiple2.setThumbMediaId(thumbMediaId); + wxMpMaterialNewsArticleMultiple2.setThumbMediaId(this.thumbMediaId); wxMpMaterialNewsArticleMultiple2.setTitle("multi title2"); wxMpMaterialNewsArticleMultiple2.setContent("content 2"); wxMpMaterialNewsArticleMultiple2.setContentSourceUrl("content url"); @@ -137,82 +135,97 @@ public class WxMpMaterialServiceImplTest { wxMpMaterialNewsMultiple.addArticle(wxMpMaterialNewsArticleMultiple2); WxMpMaterialUploadResult resSingle = this.wxService.getMaterialService().materialNewsUpload(wxMpMaterialNewsSingle); - singleNewsMediaId = resSingle.getMediaId(); + this.singleNewsMediaId = resSingle.getMediaId(); WxMpMaterialUploadResult resMulti = this.wxService.getMaterialService().materialNewsUpload(wxMpMaterialNewsMultiple); - multiNewsMediaId = resMulti.getMediaId(); + this.multiNewsMediaId = resMulti.getMediaId(); } @Test(dependsOnMethods = {"testAddNews"}) public void testMaterialCount() throws WxErrorException { WxMpMaterialCountResult wxMaterialCountResult = this.wxService.getMaterialService().materialCount(); // 测试上传过程中添加了一个音频,一个视频,两个图片,两个图文消息 - Assert.assertEquals(wxMaterialCountResultBeforeTest.getVoiceCount() + 1, wxMaterialCountResult.getVoiceCount()); - Assert.assertEquals(wxMaterialCountResultBeforeTest.getVideoCount() + 1, wxMaterialCountResult.getVideoCount()); - Assert.assertEquals(wxMaterialCountResultBeforeTest.getImageCount() + 2, wxMaterialCountResult.getImageCount()); - Assert.assertEquals(wxMaterialCountResultBeforeTest.getNewsCount() + 2, wxMaterialCountResult.getNewsCount()); + assertEquals( + this.wxMaterialCountResultBeforeTest.getVoiceCount() + 1, + wxMaterialCountResult.getVoiceCount()); + assertEquals( + this.wxMaterialCountResultBeforeTest.getVideoCount() + 1, + wxMaterialCountResult.getVideoCount()); + assertEquals( + this.wxMaterialCountResultBeforeTest.getImageCount() + 2, + wxMaterialCountResult.getImageCount()); + assertEquals(this.wxMaterialCountResultBeforeTest.getNewsCount() + 2, + wxMaterialCountResult.getNewsCount()); } @Test(dependsOnMethods = {"testMaterialCount"}, dataProvider = "downloadMaterial") - public void testDownloadMaterial(String media_id) throws WxErrorException, IOException { - Map materialInfo = media_ids.get(media_id); - Assert.assertNotNull(materialInfo); + public void testDownloadMaterial(String mediaId) throws WxErrorException, IOException { + Map materialInfo = this.mediaIds.get(mediaId); + assertNotNull(materialInfo); String filename = materialInfo.get("filename").toString(); if (filename.endsWith(".mp3") || filename.endsWith(".jpeg")) { - InputStream inputStream = this.wxService.getMaterialService().materialImageOrVoiceDownload(media_id); - Assert.assertNotNull(inputStream); - IOUtils.closeQuietly(inputStream); + try (InputStream inputStream = this.wxService.getMaterialService() + .materialImageOrVoiceDownload(mediaId)) { + assertNotNull(inputStream); + } } if (filename.endsWith("mp4")) { - WxMpMaterialVideoInfoResult wxMaterialVideoInfoResult = this.wxService.getMaterialService().materialVideoInfo(media_id); - Assert.assertNotNull(wxMaterialVideoInfoResult); - Assert.assertNotNull(wxMaterialVideoInfoResult.getDownUrl()); + WxMpMaterialVideoInfoResult wxMaterialVideoInfoResult = this.wxService.getMaterialService().materialVideoInfo(mediaId); + assertNotNull(wxMaterialVideoInfoResult); + assertNotNull(wxMaterialVideoInfoResult.getDownUrl()); } } @Test(dependsOnMethods = {"testAddNews"}) public void testGetNewsInfo() throws WxErrorException { - WxMpMaterialNews wxMpMaterialNewsSingle = this.wxService.getMaterialService().materialNewsInfo(singleNewsMediaId); - WxMpMaterialNews wxMpMaterialNewsMultiple = this.wxService.getMaterialService().materialNewsInfo(multiNewsMediaId); - Assert.assertNotNull(wxMpMaterialNewsSingle); - Assert.assertNotNull(wxMpMaterialNewsMultiple); + WxMpMaterialNews wxMpMaterialNewsSingle = this.wxService + .getMaterialService().materialNewsInfo(this.singleNewsMediaId); + WxMpMaterialNews wxMpMaterialNewsMultiple = this.wxService + .getMaterialService().materialNewsInfo(this.multiNewsMediaId); + assertNotNull(wxMpMaterialNewsSingle); + assertNotNull(wxMpMaterialNewsMultiple); } @Test(dependsOnMethods = {"testGetNewsInfo"}) public void testUpdateNewsInfo() throws WxErrorException { - WxMpMaterialNews wxMpMaterialNewsSingle = this.wxService.getMaterialService().materialNewsInfo(singleNewsMediaId); - Assert.assertNotNull(wxMpMaterialNewsSingle); + WxMpMaterialNews wxMpMaterialNewsSingle = this.wxService + .getMaterialService().materialNewsInfo(this.singleNewsMediaId); + assertNotNull(wxMpMaterialNewsSingle); WxMpMaterialArticleUpdate wxMpMaterialArticleUpdateSingle = new WxMpMaterialArticleUpdate(); WxMpMaterialNews.WxMpMaterialNewsArticle articleSingle = wxMpMaterialNewsSingle.getArticles().get(0); articleSingle.setContent("content single update"); - wxMpMaterialArticleUpdateSingle.setMediaId(singleNewsMediaId); + wxMpMaterialArticleUpdateSingle.setMediaId(this.singleNewsMediaId); wxMpMaterialArticleUpdateSingle.setArticles(articleSingle); wxMpMaterialArticleUpdateSingle.setIndex(0); boolean resultSingle = this.wxService.getMaterialService().materialNewsUpdate(wxMpMaterialArticleUpdateSingle); - Assert.assertTrue(resultSingle); - wxMpMaterialNewsSingle = this.wxService.getMaterialService().materialNewsInfo(singleNewsMediaId); - Assert.assertNotNull(wxMpMaterialNewsSingle); - Assert.assertEquals("content single update", wxMpMaterialNewsSingle.getArticles().get(0).getContent()); - - WxMpMaterialNews wxMpMaterialNewsMultiple = this.wxService.getMaterialService().materialNewsInfo(multiNewsMediaId); - Assert.assertNotNull(wxMpMaterialNewsMultiple); + assertTrue(resultSingle); + wxMpMaterialNewsSingle = this.wxService.getMaterialService() + .materialNewsInfo(this.singleNewsMediaId); + assertNotNull(wxMpMaterialNewsSingle); + assertEquals("content single update", + wxMpMaterialNewsSingle.getArticles().get(0).getContent()); + + WxMpMaterialNews wxMpMaterialNewsMultiple = this.wxService + .getMaterialService().materialNewsInfo(this.multiNewsMediaId); + assertNotNull(wxMpMaterialNewsMultiple); WxMpMaterialArticleUpdate wxMpMaterialArticleUpdateMulti = new WxMpMaterialArticleUpdate(); WxMpMaterialNews.WxMpMaterialNewsArticle articleMulti = wxMpMaterialNewsMultiple.getArticles().get(1); articleMulti.setContent("content 2 update"); - wxMpMaterialArticleUpdateMulti.setMediaId(multiNewsMediaId); + wxMpMaterialArticleUpdateMulti.setMediaId(this.multiNewsMediaId); wxMpMaterialArticleUpdateMulti.setArticles(articleMulti); wxMpMaterialArticleUpdateMulti.setIndex(1); boolean resultMulti = this.wxService.getMaterialService().materialNewsUpdate(wxMpMaterialArticleUpdateMulti); - Assert.assertTrue(resultMulti); - wxMpMaterialNewsMultiple = this.wxService.getMaterialService().materialNewsInfo(multiNewsMediaId); - Assert.assertNotNull(wxMpMaterialNewsMultiple); - Assert.assertEquals("content 2 update", wxMpMaterialNewsMultiple.getArticles().get(1).getContent()); + assertTrue(resultMulti); + wxMpMaterialNewsMultiple = this.wxService.getMaterialService() + .materialNewsInfo(this.multiNewsMediaId); + assertNotNull(wxMpMaterialNewsMultiple); + assertEquals("content 2 update", + wxMpMaterialNewsMultiple.getArticles().get(1).getContent()); } @Test(dependsOnMethods = {"testUpdateNewsInfo"}) public void testMaterialNewsList() throws WxErrorException { WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = this.wxService.getMaterialService().materialNewsBatchGet(0, 20); - Assert.assertNotNull(wxMpMaterialNewsBatchGetResult); - return; + assertNotNull(wxMpMaterialNewsBatchGetResult); } @Test(dependsOnMethods = {"testMaterialNewsList"}) @@ -220,24 +233,22 @@ public class WxMpMaterialServiceImplTest { WxMpMaterialFileBatchGetResult wxMpMaterialVoiceBatchGetResult = this.wxService.getMaterialService().materialFileBatchGet(WxConsts.MATERIAL_VOICE, 0, 20); WxMpMaterialFileBatchGetResult wxMpMaterialVideoBatchGetResult = this.wxService.getMaterialService().materialFileBatchGet(WxConsts.MATERIAL_VIDEO, 0, 20); WxMpMaterialFileBatchGetResult wxMpMaterialImageBatchGetResult = this.wxService.getMaterialService().materialFileBatchGet(WxConsts.MATERIAL_IMAGE, 0, 20); - - Assert.assertNotNull(wxMpMaterialVoiceBatchGetResult); - Assert.assertNotNull(wxMpMaterialVideoBatchGetResult); - Assert.assertNotNull(wxMpMaterialImageBatchGetResult); - return; + assertNotNull(wxMpMaterialVoiceBatchGetResult); + assertNotNull(wxMpMaterialVideoBatchGetResult); + assertNotNull(wxMpMaterialImageBatchGetResult); } @Test(dependsOnMethods = {"testMaterialFileList"}, dataProvider = "allTestMaterial") public void testDeleteMaterial(String mediaId) throws WxErrorException { boolean result = this.wxService.getMaterialService().materialDelete(mediaId); - Assert.assertTrue(result); + assertTrue(result); } @DataProvider public Object[][] downloadMaterial() { - Object[][] params = new Object[this.media_ids.size()][]; + Object[][] params = new Object[this.mediaIds.size()][]; int index = 0; - for (String mediaId : this.media_ids.keySet()) { + for (String mediaId : this.mediaIds.keySet()) { params[index] = new Object[]{mediaId}; index++; } @@ -247,7 +258,7 @@ public class WxMpMaterialServiceImplTest { @DataProvider public Iterator allTestMaterial() { List params = new ArrayList<>(); - for (String mediaId : this.media_ids.keySet()) { + for (String mediaId : this.mediaIds.keySet()) { params.add(new Object[]{mediaId}); } params.add(new Object[]{this.singleNewsMediaId}); @@ -256,40 +267,41 @@ public class WxMpMaterialServiceImplTest { } // 以下为media接口的测试 - private List mediaIds = new ArrayList<>(); - @Test(dataProvider="uploadMedia") + private List mediaIdsToDownload = new ArrayList<>(); + @Test(dataProvider="mediaFiles") public void testUploadMedia(String mediaType, String fileType, String fileName) throws WxErrorException, IOException { try(InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName)){ WxMediaUploadResult res = this.wxService.getMaterialService().mediaUpload(mediaType, fileType, inputStream); - Assert.assertNotNull(res.getType()); - Assert.assertNotNull(res.getCreatedAt()); - Assert.assertTrue(res.getMediaId() != null || res.getThumbMediaId() != null); + assertNotNull(res.getType()); + assertNotNull(res.getCreatedAt()); + assertTrue(res.getMediaId() != null || res.getThumbMediaId() != null); - if (res.getMediaId() != null) { - this.mediaIds.add(res.getMediaId()); + if (res.getMediaId() != null && !mediaType.equals(WxConsts.MEDIA_VIDEO)) { + //video 不支持下载,所以不加入 + this.mediaIdsToDownload.add(res.getMediaId()); } if (res.getThumbMediaId() != null) { - this.mediaIds.add(res.getThumbMediaId()); + this.mediaIdsToDownload.add(res.getThumbMediaId()); } System.out.println(res); } } - @Test(dependsOnMethods = { "testUploadMedia" }, dataProvider="downloadMedia") - public void testDownloadMedia(String media_id) throws WxErrorException { - File file = this.wxService.getMaterialService().mediaDownload(media_id); - Assert.assertNotNull(file); - System.out.println(file.getAbsolutePath()); - } - @DataProvider public Object[][] downloadMedia() { - Object[][] params = new Object[this.mediaIds.size()][]; - for (int i = 0; i < this.mediaIds.size(); i++) { - params[i] = new Object[] { this.mediaIds.get(i) }; + Object[][] params = new Object[this.mediaIdsToDownload.size()][]; + for (int i = 0; i < this.mediaIdsToDownload.size(); i++) { + params[i] = new Object[] { this.mediaIdsToDownload.get(i) }; } return params; } + + @Test(dependsOnMethods = { "testUploadMedia" }, dataProvider="downloadMedia") + public void testDownloadMedia(String mediaId) throws WxErrorException { + File file = this.wxService.getMaterialService().mediaDownload(mediaId); + assertNotNull(file); + System.out.println(file.getAbsolutePath()); + } } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java index 79a5a631..092be38a 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java @@ -1,31 +1,29 @@ package me.chanjar.weixin.mp.api.impl; +import org.testng.annotations.Guice; import org.testng.annotations.Test; +import com.google.inject.Inject; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.api.ApiTestModule; +import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage; +import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; +import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderResult; + /** + * 测试支付相关接口 * Created by Binary Wang on 2016/7/28. * @author binarywang (https://github.com/binarywang) */ +@Test +@Guice(modules = ApiTestModule.class) public class WxMpPayServiceImplTest { - @Test - public void testGetPrepayId() throws Exception { - - } - @Test - public void testGetPrepayId1() throws Exception { - - } - - @Test - public void testGetJsapiPayInfo() throws Exception { - - } - - @Test - public void testGetNativePayInfo() throws Exception { - - } + @Inject + protected WxMpServiceImpl wxService; @Test public void testGetPayInfo() throws Exception { @@ -54,7 +52,26 @@ public class WxMpPayServiceImplTest { @Test public void testSendRedpack() throws Exception { - + WxSendRedpackRequest request = new WxSendRedpackRequest(); + request.setActName("abc"); + request.setClientIp("aaa"); + request.setMchBillno("aaaa"); + request + .setReOpenid(((WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage()).getOpenid()); + WxRedpackResult redpackResult = this.wxService.getPayService().sendRedpack(request); + System.err.println(redpackResult); } -} \ No newline at end of file + /** + * Test method for {@link me.chanjar.weixin.mp.api.impl.WxMpPayServiceImpl#unifiedOrder(me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest)}. + * @throws WxErrorException + */ + @Test + public void testUnifiedOrder() throws WxErrorException { + WxUnifiedOrderResult result = this.wxService.getPayService() + .unifiedOrder(WxUnifiedOrderRequest.builder().body("1111111") + .totalFee(1).spbillCreateIp("111111").notifyURL("111111") + .tradeType("JSAPI").openid("122").outTradeNo("111111").build()); + System.err.println(result); + } +} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImplTest.java index 33242ba4..c108d575 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImplTest.java @@ -1,5 +1,8 @@ package me.chanjar.weixin.mp.api.impl; +import java.text.SimpleDateFormat; +import java.util.Date; + import org.testng.Assert; import org.testng.annotations.Guice; import org.testng.annotations.Test; @@ -7,8 +10,11 @@ import org.testng.annotations.Test; import com.google.inject.Inject; import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.ApiTestModule; -import me.chanjar.weixin.mp.api.ApiTestModule.WxXmlMpInMemoryConfigStorage; +import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage; +import me.chanjar.weixin.mp.bean.WxMpTemplateData; +import me.chanjar.weixin.mp.bean.WxMpTemplateMessage; @Test @Guice(modules = ApiTestModule.class) @@ -82,9 +88,18 @@ public class WxMpServiceImplTest { Assert.fail("Not yet implemented"); } - @Test - public void testTemplateSend() { - Assert.fail("Not yet implemented"); + @Test(invocationCount = 100, threadPoolSize = 30) + public void testTemplateSend() throws WxErrorException { + SimpleDateFormat dateFormat = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss.SSS"); + WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); + WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder() + .toUser(configStorage.getOpenid()) + .templateId(configStorage.getTemplateId()).build(); + templateMessage.addWxMpTemplateData( + new WxMpTemplateData("first", dateFormat.format(new Date()))); + this.wxService.templateSend(templateMessage); } @Test diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImplTest.java new file mode 100644 index 00000000..76685470 --- /dev/null +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImplTest.java @@ -0,0 +1,78 @@ +package me.chanjar.weixin.mp.api.impl; + +import com.google.inject.Inject; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.api.ApiTestModule; +import me.chanjar.weixin.mp.bean.store.WxMpStoreBaseInfo; +import me.chanjar.weixin.mp.bean.store.WxMpStoreInfo; +import me.chanjar.weixin.mp.bean.store.WxMpStoreListResult; +import org.testng.annotations.Guice; +import org.testng.annotations.Test; + +import java.math.BigDecimal; +import java.util.List; + +import static org.junit.Assert.assertNotNull; + +/** + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016-09-23. + * + */ +@Test +@Guice(modules = ApiTestModule.class) +public class WxMpStoreServiceImplTest { + @Inject + private WxMpServiceImpl wxMpService; + + /** + * Test method for {@link me.chanjar.weixin.mp.api.impl.WxMpStoreServiceImpl#add(me.chanjar.weixin.mp.bean.store.WxMpStoreBaseInfo)}. + * @throws WxErrorException + */ + public void testAdd() throws WxErrorException { + this.wxMpService.getStoreService() + .add(WxMpStoreBaseInfo.builder().businessName("haha").branchName("abc") + .province("aaa").district("aaa").telephone("122").address("abc").categories(new String[] { "美食,江浙菜" }) + .longitude(new BigDecimal("115.32375")) + .latitude(new BigDecimal("25.097486")).city("aaa").offsetType(1) + .build()); + } + + public void testUpdate() throws WxErrorException { + this.wxMpService.getStoreService() + .update(WxMpStoreBaseInfo.builder().poiId("291503654").telephone("020-12345678") + .sid("aaa").avgPrice(35).openTime("8:00-20:00").special("免费wifi,外卖服务") + .introduction("麦当劳是全球大型跨国连锁餐厅,1940 年创立于美国,在世界上大约拥有3 万间分店。主要售卖汉堡包,以及薯条、炸鸡、汽水、冰品、沙拉、水果等快餐食品").offsetType(1) + .build()); + } + + public void testGet() throws WxErrorException { + WxMpStoreBaseInfo result = this.wxMpService.getStoreService().get("291503654"); + assertNotNull(result); + System.err.println(result); + } + + public void testDelete() throws WxErrorException { + this.wxMpService.getStoreService().delete("463558057"); + } + + public void testListCategories() throws WxErrorException { + List result = this.wxMpService.getStoreService().listCategories(); + assertNotNull(result); + System.err.println(result); + } + + public void testList() throws WxErrorException { + WxMpStoreListResult result = this.wxMpService.getStoreService().list(0, 10); + assertNotNull(result); + System.err.println(result); + } + + public void testListAll() throws WxErrorException { + List list = this.wxMpService.getStoreService().listAll(); + assertNotNull(list); + System.err.println(list.size()); + System.err.println(list); + } + +} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserBlacklistServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserBlacklistServiceImplTest.java new file mode 100644 index 00000000..aebf6926 --- /dev/null +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserBlacklistServiceImplTest.java @@ -0,0 +1,53 @@ +package me.chanjar.weixin.mp.api.impl; + +import me.chanjar.weixin.mp.api.ApiTestModule; +import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage; +import me.chanjar.weixin.mp.bean.result.WxMpUserBlacklistGetResult; +import org.testng.Assert; +import org.testng.annotations.Guice; +import org.testng.annotations.Test; + +import javax.inject.Inject; +import java.util.ArrayList; +import java.util.List; + +/** + * @author miller + */ +@Test(groups = "userAPI") +@Guice(modules = ApiTestModule.class) +public class WxMpUserBlacklistServiceImplTest { + @Inject + protected WxMpServiceImpl wxService; + + @Test + public void testGetBlacklist() throws Exception { + WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); + WxMpUserBlacklistGetResult wxMpUserBlacklistGetResult = this.wxService.getBlackListService().getBlacklist(configStorage.getOpenid()); + Assert.assertNotNull(wxMpUserBlacklistGetResult); + Assert.assertFalse(wxMpUserBlacklistGetResult.getCount() == -1); + Assert.assertFalse(wxMpUserBlacklistGetResult.getTotal() == -1); + Assert.assertFalse(wxMpUserBlacklistGetResult.getOpenidList().size() == -1); + System.out.println(wxMpUserBlacklistGetResult); + } + + @Test + public void testPushToBlacklist() throws Exception { + WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); + List openidList = new ArrayList<>(); + openidList.add(configStorage.getOpenid()); + this.wxService.getBlackListService().pushToBlacklist(openidList); + } + + @Test + public void testPullFromBlacklist() throws Exception { + WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); + List openidList = new ArrayList<>(); + openidList.add(configStorage.getOpenid()); + this.wxService.getBlackListService().pullFromBlacklist(openidList); + } + +} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java index 05ac40c9..4242df10 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java @@ -1,6 +1,11 @@ + package me.chanjar.weixin.mp.api.impl; +import java.util.ArrayList; +import java.util.List; + import org.testng.Assert; +import org.testng.annotations.BeforeTest; import org.testng.annotations.Guice; import org.testng.annotations.Test; @@ -8,6 +13,8 @@ import com.google.inject.Inject; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.ApiTestModule; +import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage; +import me.chanjar.weixin.mp.bean.WxMpUserQuery; import me.chanjar.weixin.mp.bean.result.WxMpUser; import me.chanjar.weixin.mp.bean.result.WxMpUserList; @@ -22,20 +29,46 @@ import me.chanjar.weixin.mp.bean.result.WxMpUserList; public class WxMpUserServiceImplTest { @Inject - protected WxMpServiceImpl wxService; + private WxMpServiceImpl wxService; + + private WxXmlMpInMemoryConfigStorage configProvider; + + @BeforeTest + public void setup() { + this.configProvider = (WxXmlMpInMemoryConfigStorage) this.wxService + .getWxMpConfigStorage(); + } public void testUserUpdateRemark() throws WxErrorException { - ApiTestModule.WxXmlMpInMemoryConfigStorage configProvider = (ApiTestModule.WxXmlMpInMemoryConfigStorage) wxService.getWxMpConfigStorage(); - this.wxService.getUserService().userUpdateRemark(configProvider.getOpenId(), "测试备注名"); + this.wxService.getUserService() + .userUpdateRemark(this.configProvider.getOpenid(), "测试备注名"); } public void testUserInfo() throws WxErrorException { - ApiTestModule.WxXmlMpInMemoryConfigStorage configProvider = (ApiTestModule.WxXmlMpInMemoryConfigStorage) wxService.getWxMpConfigStorage(); - WxMpUser user = this.wxService.getUserService().userInfo(configProvider.getOpenId(), null); + WxMpUser user = this.wxService.getUserService() + .userInfo(this.configProvider.getOpenid(), null); Assert.assertNotNull(user); System.out.println(user); } + public void testUserInfoList() throws WxErrorException { + List openids = new ArrayList<>(); + openids.add(this.configProvider.getOpenid()); + List userList = this.wxService.getUserService() + .userInfoList(openids); + Assert.assertEquals(userList.size(), 1); + System.out.println(userList); + } + + public void testUserInfoListByWxMpUserQuery() throws WxErrorException { + WxMpUserQuery query = new WxMpUserQuery(); + query.add(this.configProvider.getOpenid(), "zh_CN"); + List userList = this.wxService.getUserService() + .userInfoList(query); + Assert.assertEquals(userList.size(), 1); + System.out.println(userList); + } + public void testUserList() throws WxErrorException { WxMpUserList wxMpUserList = this.wxService.getUserService().userList(null); Assert.assertNotNull(wxMpUserList); @@ -45,15 +78,4 @@ public class WxMpUserServiceImplTest { System.out.println(wxMpUserList); } - public void testGroupQueryUserGroup() throws WxErrorException { - ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) wxService.getWxMpConfigStorage(); - long groupid = this.wxService.getGroupService().userGetGroup(configStorage.getOpenId()); - Assert.assertTrue(groupid != -1l); - } - - public void testGroupMoveUser() throws WxErrorException { - ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) wxService.getWxMpConfigStorage(); - this.wxService.getGroupService().userUpdateGroup(configStorage.getOpenId(), this.wxService.getGroupService().groupGet().get(3).getId()); - } - } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImplTest.java new file mode 100644 index 00000000..9fc579c9 --- /dev/null +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImplTest.java @@ -0,0 +1,82 @@ +package me.chanjar.weixin.mp.api.impl; + +import java.util.List; + +import org.testng.Assert; +import org.testng.annotations.Guice; +import org.testng.annotations.Test; + +import com.google.inject.Inject; + +import me.chanjar.weixin.mp.api.ApiTestModule; +import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage; +import me.chanjar.weixin.mp.bean.tag.WxTagListUser; +import me.chanjar.weixin.mp.bean.tag.WxUserTag; + +/** + * + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/9/2. + */ +@Test +@Guice(modules = ApiTestModule.class) +public class WxMpUserTagServiceImplTest { + @Inject + protected WxMpServiceImpl wxService; + + private Long tagId = 2L; + + @Test + public void testTagCreate() throws Exception { + String tagName = "测试标签" + System.currentTimeMillis(); + WxUserTag res = this.wxService.getUserTagService().tagCreate(tagName); + System.out.println(res); + this.tagId = res.getId(); + Assert.assertEquals(tagName, res.getName()); + } + + @Test + public void testTagGet() throws Exception { + List res = this.wxService.getUserTagService().tagGet(); + System.out.println(res); + Assert.assertNotNull(res); + } + + @Test(dependsOnMethods = { "testTagCreate" }) + public void testTagUpdate() throws Exception { + String tagName = "修改标签" + System.currentTimeMillis(); + Boolean res = this.wxService.getUserTagService().tagUpdate(this.tagId, tagName); + System.out.println(res); + Assert.assertTrue(res); + } + + @Test(dependsOnMethods = { "testTagCreate" }) + public void testTagDelete() throws Exception { + Boolean res = this.wxService.getUserTagService().tagDelete(this.tagId); + System.out.println(res); + Assert.assertTrue(res); + } + + @Test + public void testTagListUser() throws Exception { + WxTagListUser res = this.wxService.getUserTagService().tagListUser(this.tagId, null); + System.out.println(res); + Assert.assertNotNull(res); + } + + @Test + public void testBatchUntagging() throws Exception { + String[] openids = new String[]{((WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage()).getOpenid()}; + boolean res = this.wxService.getUserTagService().batchUntagging(this.tagId, openids); + System.out.println(res); + Assert.assertTrue(res); + } + + @Test + public void testUserTagList() throws Exception { + List res = this.wxService.getUserTagService().userTagList( + ((WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage()).getOpenid()); + System.out.println(res); + Assert.assertNotNull(res); + } +} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxMpXmlMessageTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxMpXmlMessageTest.java index 3885ec32..87d8428b 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxMpXmlMessageTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxMpXmlMessageTest.java @@ -54,8 +54,8 @@ public class WxMpXmlMessageTest { + "" + ""; WxMpXmlMessage wxMessage = WxMpXmlMessage.fromXml(xml); - Assert.assertEquals(wxMessage.getToUserName(), "toUser"); - Assert.assertEquals(wxMessage.getFromUserName(), "fromUser"); + Assert.assertEquals(wxMessage.getToUser(), "toUser"); + Assert.assertEquals(wxMessage.getFromUser(), "fromUser"); Assert.assertEquals(wxMessage.getCreateTime(), new Long(1348831860l)); Assert.assertEquals(wxMessage.getMsgType(), WxConsts.XML_MSG_TEXT); Assert.assertEquals(wxMessage.getContent(), "this is a test"); @@ -135,8 +135,8 @@ public class WxMpXmlMessageTest { + "" + ""; WxMpXmlMessage wxMessage = WxMpXmlMessage.fromXml(xml); - Assert.assertEquals(wxMessage.getToUserName(), "toUser"); - Assert.assertEquals(wxMessage.getFromUserName(), "fromUser"); + Assert.assertEquals(wxMessage.getToUser(), "toUser"); + Assert.assertEquals(wxMessage.getFromUser(), "fromUser"); Assert.assertEquals(wxMessage.getCreateTime(), new Long(1348831860l)); Assert.assertEquals(wxMessage.getMsgType(), WxConsts.XML_MSG_TEXT); Assert.assertEquals(wxMessage.getContent(), "this is a test"); diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java index f7913aef..5a5275d4 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java @@ -8,7 +8,7 @@ import org.junit.Test; import com.thoughtworks.xstream.XStream; import me.chanjar.weixin.common.util.xml.XStreamInitializer; -import me.chanjar.weixin.mp.bean.result.WxRedpackResult; +import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; public class WxRedpackResultTest { @@ -16,8 +16,8 @@ public class WxRedpackResultTest { @Before public void setup() { - xstream = XStreamInitializer.getInstance(); - xstream.processAnnotations(WxRedpackResult.class); + this.xstream = XStreamInitializer.getInstance(); + this.xstream.processAnnotations(WxRedpackResult.class); } @Test public void loadSuccessResult() { @@ -35,7 +35,7 @@ public class WxRedpackResultTest { "100000000020150520314766074200\n" + "20150520102602\n" + ""; - WxRedpackResult wxMpRedpackResult = (WxRedpackResult) xstream.fromXML(successSample); + WxRedpackResult wxMpRedpackResult = (WxRedpackResult) this.xstream.fromXML(successSample); assertEquals("SUCCESS", wxMpRedpackResult.getReturnCode()); assertEquals("SUCCESS", wxMpRedpackResult.getResultCode()); assertEquals("20150520102602", wxMpRedpackResult.getSendTime()); @@ -54,7 +54,7 @@ public class WxRedpackResultTest { "\n" + "1\n" + ""; - WxRedpackResult wxMpRedpackResult = (WxRedpackResult) xstream.fromXML(failureSample); + WxRedpackResult wxMpRedpackResult = (WxRedpackResult) this.xstream.fromXML(failureSample); assertEquals("FAIL", wxMpRedpackResult.getReturnCode()); assertEquals("FAIL", wxMpRedpackResult.getResultCode()); assertEquals("onqOjjmM1tad-3ROpncN-yUfa6uI", wxMpRedpackResult.getReOpenid()); diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java new file mode 100644 index 00000000..feb50c5a --- /dev/null +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java @@ -0,0 +1,33 @@ +package me.chanjar.weixin.mp.bean.pay; + +import java.lang.reflect.Field; +import java.util.Map.Entry; + +import org.joor.Reflect; +import org.testng.annotations.Test; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@Test +public class WxSendRedpackRequestTest { + + public void test() throws NoSuchFieldException, SecurityException { + + WxSendRedpackRequest request = new WxSendRedpackRequest(); + request.setMchBillno("123"); + request.setActName("ab"); + for (Entry entry : Reflect.on(request).fields().entrySet()) { + Reflect reflect = entry.getValue(); + if (reflect.get() == null) { + continue; + } + + Field field = WxSendRedpackRequest.class.getDeclaredField(entry.getKey()); + if (field.isAnnotationPresent(XStreamAlias.class)) { + System.err.println(reflect.get() + " = " + field.getAnnotation(XStreamAlias.class).value()); + } + } + + } + +} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoGuessNumberHandler.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoGuessNumberHandler.java index 345ec9f2..f35b3b87 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoGuessNumberHandler.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoGuessNumberHandler.java @@ -1,5 +1,9 @@ package me.chanjar.weixin.mp.demo; +import java.util.Map; +import java.util.Random; +import java.util.regex.Pattern; + import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.session.WxSession; import me.chanjar.weixin.common.session.WxSessionManager; @@ -10,10 +14,6 @@ import me.chanjar.weixin.mp.bean.WxMpCustomMessage; import me.chanjar.weixin.mp.bean.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage; -import java.util.Map; -import java.util.Random; -import java.util.regex.Pattern; - public class DemoGuessNumberHandler implements WxMpMessageHandler, WxMpMessageMatcher { private Random random = new Random(); @@ -30,7 +30,7 @@ public class DemoGuessNumberHandler implements WxMpMessageHandler, WxMpMessageMa } private boolean isUserAnswering(WxMpXmlMessage message) { - return pattern.matcher(message.getContent()).matches(); + return this.pattern.matcher(message.getContent()).matches(); } @Override @@ -50,31 +50,31 @@ public class DemoGuessNumberHandler implements WxMpMessageHandler, WxMpMessageMa } protected void letsGo(WxMpXmlMessage wxMessage, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException { - WxSession session = sessionManager.getSession(wxMessage.getFromUserName()); + WxSession session = sessionManager.getSession(wxMessage.getFromUser()); if (session.getAttribute("guessing") == null) { WxMpCustomMessage m = WxMpCustomMessage .TEXT() - .toUser(wxMessage.getFromUserName()) + .toUser(wxMessage.getFromUser()) .content("请猜一个100以内的数字") .build(); - wxMpService.customMessageSend(m); + wxMpService.getKefuService().customMessageSend(m); } else { WxMpCustomMessage m = WxMpCustomMessage .TEXT() - .toUser(wxMessage.getFromUserName()) + .toUser(wxMessage.getFromUser()) .content("放弃了吗?那请重新猜一个100以内的数字") .build(); - wxMpService.customMessageSend(m); + wxMpService.getKefuService().customMessageSend(m); } session.setAttribute("guessing", Boolean.TRUE); - session.setAttribute("number", random.nextInt(100)); + session.setAttribute("number", this.random.nextInt(100)); } protected void giveHint(WxMpXmlMessage wxMessage, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException { - WxSession session = sessionManager.getSession(wxMessage.getFromUserName()); + WxSession session = sessionManager.getSession(wxMessage.getFromUser()); if (session.getAttribute("guessing") == null) { return; @@ -89,26 +89,26 @@ public class DemoGuessNumberHandler implements WxMpMessageHandler, WxMpMessageMa if (guessNumber < answer) { WxMpCustomMessage m = WxMpCustomMessage .TEXT() - .toUser(wxMessage.getFromUserName()) + .toUser(wxMessage.getFromUser()) .content("小了") .build(); - wxMpService.customMessageSend(m); + wxMpService.getKefuService().customMessageSend(m); } else if (guessNumber > answer) { WxMpCustomMessage m = WxMpCustomMessage .TEXT() - .toUser(wxMessage.getFromUserName()) + .toUser(wxMessage.getFromUser()) .content("大了") .build(); - wxMpService.customMessageSend(m); + wxMpService.getKefuService().customMessageSend(m); } else { WxMpCustomMessage m = WxMpCustomMessage .TEXT() - .toUser(wxMessage.getFromUserName()) + .toUser(wxMessage.getFromUser()) .content("Bingo!") .build(); session.removeAttribute("guessing"); - wxMpService.customMessageSend(m); + wxMpService.getKefuService().customMessageSend(m); } } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoImageHandler.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoImageHandler.java index a22f28d7..cd733210 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoImageHandler.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoImageHandler.java @@ -24,8 +24,8 @@ public class DemoImageHandler implements WxMpMessageHandler { = WxMpXmlOutMessage .IMAGE() .mediaId(wxMediaUploadResult.getMediaId()) - .fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()) + .fromUser(wxMessage.getToUser()) + .toUser(wxMessage.getFromUser()) .build(); return m; } catch (WxErrorException e) { diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoOAuth2Handler.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoOAuth2Handler.java index de1c9546..5dc5437d 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoOAuth2Handler.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoOAuth2Handler.java @@ -21,7 +21,7 @@ public class DemoOAuth2Handler implements WxMpMessageHandler { wxMpService.getWxMpConfigStorage().getOauth2redirectUri(), WxConsts.OAUTH2_SCOPE_USER_INFO, null) + "\">测试oauth2"; return WxMpXmlOutMessage.TEXT().content(href) - .fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName()) + .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) .build(); } } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoTextHandler.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoTextHandler.java index 43f017be..9ee15a28 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoTextHandler.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoTextHandler.java @@ -17,8 +17,8 @@ public class DemoTextHandler implements WxMpMessageHandler { public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, WxMpService wxMpService, WxSessionManager sessionManager) { WxMpXmlOutTextMessage m - = WxMpXmlOutMessage.TEXT().content("测试加密消息").fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()).build(); + = WxMpXmlOutMessage.TEXT().content("测试加密消息").fromUser(wxMessage.getToUser()) + .toUser(wxMessage.getFromUser()).build(); return m; } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoInMemoryConfigStorage.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoInMemoryConfigStorage.java index becfbeb4..44b80647 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoInMemoryConfigStorage.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoInMemoryConfigStorage.java @@ -15,8 +15,8 @@ class WxMpDemoInMemoryConfigStorage extends WxMpInMemoryConfigStorage { @Override public String toString() { - return "SimpleWxConfigProvider [appId=" + appId + ", secret=" + secret + ", accessToken=" + accessToken - + ", expiresTime=" + expiresTime + ", token=" + token + ", aesKey=" + aesKey + "]"; + return "SimpleWxConfigProvider [appId=" + this.appId + ", secret=" + this.secret + ", accessToken=" + this.accessToken + + ", expiresTime=" + this.expiresTime + ", token=" + this.token + ", aesKey=" + this.aesKey + "]"; } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java index b89b2796..98b8d0cc 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java @@ -1,13 +1,18 @@ package me.chanjar.weixin.mp.demo; -import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.mp.api.*; -import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; +import java.io.IOException; +import java.io.InputStream; + import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; -import java.io.InputStream; +import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.mp.api.WxMpConfigStorage; +import me.chanjar.weixin.mp.api.WxMpMessageHandler; +import me.chanjar.weixin.mp.api.WxMpMessageRouter; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; public class WxMpDemoServer { @@ -23,10 +28,13 @@ public class WxMpDemoServer { ServletHandler servletHandler = new ServletHandler(); server.setHandler(servletHandler); - ServletHolder endpointServletHolder = new ServletHolder(new WxMpEndpointServlet(wxMpConfigStorage, wxMpService, wxMpMessageRouter)); + ServletHolder endpointServletHolder = new ServletHolder( + new WxMpEndpointServlet(wxMpConfigStorage, wxMpService, + wxMpMessageRouter)); servletHandler.addServletWithMapping(endpointServletHolder, "/*"); - ServletHolder oauthServletHolder = new ServletHolder(new WxMpOAuth2Servlet(wxMpService)); + ServletHolder oauthServletHolder = new ServletHolder( + new WxMpOAuth2Servlet(wxMpService)); servletHandler.addServletWithMapping(oauthServletHolder, "/oauth2/*"); server.start(); @@ -34,27 +42,30 @@ public class WxMpDemoServer { } private static void initWeixin() { - InputStream is1 = ClassLoader.getSystemResourceAsStream("test-config.xml"); - WxMpDemoInMemoryConfigStorage config = WxMpDemoInMemoryConfigStorage.fromXml(is1); - - wxMpConfigStorage = config; - wxMpService = new WxMpServiceImpl(); - wxMpService.setWxMpConfigStorage(config); - - WxMpMessageHandler logHandler = new DemoLogHandler(); - WxMpMessageHandler textHandler = new DemoTextHandler(); - WxMpMessageHandler imageHandler = new DemoImageHandler(); - WxMpMessageHandler oauth2handler = new DemoOAuth2Handler(); - DemoGuessNumberHandler guessNumberHandler = new DemoGuessNumberHandler(); - - wxMpMessageRouter = new WxMpMessageRouter(wxMpService); - wxMpMessageRouter - .rule().handler(logHandler).next() - .rule().msgType(WxConsts.XML_MSG_TEXT).matcher(guessNumberHandler).handler(guessNumberHandler).end() - .rule().async(false).content("哈哈").handler(textHandler).end() - .rule().async(false).content("图片").handler(imageHandler).end() - .rule().async(false).content("oauth").handler(oauth2handler).end() - ; + try (InputStream is1 = ClassLoader + .getSystemResourceAsStream("test-config.xml")) { + WxMpDemoInMemoryConfigStorage config = WxMpDemoInMemoryConfigStorage + .fromXml(is1); + + wxMpConfigStorage = config; + wxMpService = new WxMpServiceImpl(); + wxMpService.setWxMpConfigStorage(config); + + WxMpMessageHandler logHandler = new DemoLogHandler(); + WxMpMessageHandler textHandler = new DemoTextHandler(); + WxMpMessageHandler imageHandler = new DemoImageHandler(); + WxMpMessageHandler oauth2handler = new DemoOAuth2Handler(); + DemoGuessNumberHandler guessNumberHandler = new DemoGuessNumberHandler(); + wxMpMessageRouter = new WxMpMessageRouter(wxMpService); + wxMpMessageRouter.rule().handler(logHandler).next().rule() + .msgType(WxConsts.XML_MSG_TEXT).matcher(guessNumberHandler) + .handler(guessNumberHandler).end().rule().async(false).content("哈哈") + .handler(textHandler).end().rule().async(false).content("图片") + .handler(imageHandler).end().rule().async(false).content("oauth") + .handler(oauth2handler).end(); + } catch (IOException e) { + e.printStackTrace(); + } } } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpEndpointServlet.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpEndpointServlet.java index ae5fcba0..d052af6c 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpEndpointServlet.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpEndpointServlet.java @@ -42,7 +42,7 @@ public class WxMpEndpointServlet extends HttpServlet { String nonce = request.getParameter("nonce"); String timestamp = request.getParameter("timestamp"); - if (!wxMpService.checkSignature(timestamp, nonce, signature)) { + if (!this.wxMpService.checkSignature(timestamp, nonce, signature)) { // 消息签名不正确,说明不是公众平台发过来的消息 response.getWriter().println("非法请求"); return; @@ -62,7 +62,7 @@ public class WxMpEndpointServlet extends HttpServlet { if ("raw".equals(encryptType)) { // 明文传输的消息 WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream()); - WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage); + WxMpXmlOutMessage outMessage = this.wxMpMessageRouter.route(inMessage); if (outMessage != null) { response.getWriter().write(outMessage.toXml()); } @@ -72,9 +72,9 @@ public class WxMpEndpointServlet extends HttpServlet { if ("aes".equals(encryptType)) { // 是aes加密的消息 String msgSignature = request.getParameter("msg_signature"); - WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpConfigStorage, timestamp, nonce, msgSignature); - WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage); - response.getWriter().write(outMessage.toEncryptedXml(wxMpConfigStorage)); + WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), this.wxMpConfigStorage, timestamp, nonce, msgSignature); + WxMpXmlOutMessage outMessage = this.wxMpMessageRouter.route(inMessage); + response.getWriter().write(outMessage.toEncryptedXml(this.wxMpConfigStorage)); return; } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpOAuth2Servlet.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpOAuth2Servlet.java index b5a4f5f6..4008e1fb 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpOAuth2Servlet.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpOAuth2Servlet.java @@ -1,15 +1,16 @@ package me.chanjar.weixin.mp.demo; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; -import me.chanjar.weixin.mp.bean.result.WxMpUser; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; +import me.chanjar.weixin.mp.bean.result.WxMpUser; public class WxMpOAuth2Servlet extends HttpServlet { private static final long serialVersionUID = 1L; @@ -32,15 +33,15 @@ public class WxMpOAuth2Servlet extends HttpServlet { response.getWriter().println("

    code

    "); response.getWriter().println(code); - WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code); + WxMpOAuth2AccessToken wxMpOAuth2AccessToken = this.wxMpService.oauth2getAccessToken(code); response.getWriter().println("

    access token

    "); response.getWriter().println(wxMpOAuth2AccessToken.toString()); - WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null); + WxMpUser wxMpUser = this.wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null); response.getWriter().println("

    user info

    "); response.getWriter().println(wxMpUser.toString()); - wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken()); + wxMpOAuth2AccessToken = this.wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken()); response.getWriter().println("

    after refresh

    "); response.getWriter().println(wxMpOAuth2AccessToken.toString()); diff --git a/weixin-java-mp/src/test/resources/test-config.sample.xml b/weixin-java-mp/src/test/resources/test-config.sample.xml index 836b26c4..ad46a19e 100644 --- a/weixin-java-mp/src/test/resources/test-config.sample.xml +++ b/weixin-java-mp/src/test/resources/test-config.sample.xml @@ -5,7 +5,8 @@ 公众号EncodingAESKey 可以不填写 可以不填写 - 某个加你公众号的用户的openId + 某个加你公众号的用户的openId + 模版消息的模版ID 网页授权获取用户信息回调地址 网页应用授权登陆回调地址 完整客服账号,格式为:账号前缀@公众号微信号 diff --git a/weixin-java-mp/src/test/resources/testng.xml b/weixin-java-mp/src/test/resources/testng.xml index d821e398..6d5310ce 100644 --- a/weixin-java-mp/src/test/resources/testng.xml +++ b/weixin-java-mp/src/test/resources/testng.xml @@ -5,9 +5,6 @@ - - -