63 Commits

Author SHA1 Message Date
Daniel Qian
8485af028a upgrade to 1.3.0 2015-09-11 09:05:15 +08:00
Daniel Qian
cd3237d9cc Merge pull request #198 from ajffdnt/develop
增加企业号异步任务接口
2015-09-10 17:24:28 +08:00
Daniel Qian
8935048040 Merge pull request #202 from alanchenup/f-url
增加点击图文消息跳转链接
2015-09-04 13:10:47 +08:00
alanchen
a645a28267 增加点击图文消息跳转链接 2015-09-03 17:54:51 +08:00
Daniel Qian
5630b865c2 issue #200 2015-08-26 08:42:00 +08:00
Daniel Qian
e39c259aaa Merge pull request #194 from ukid/develop
[BUG FIX]类型转换错误
2015-08-19 21:54:04 +08:00
ukid
6ede883f71 format with spaces 2015-08-19 18:36:06 +08:00
caosk
afaa0a3bde 增加查看通讯录全量更新结果的接口 2015-08-15 20:05:32 +08:00
caosk
57acfd5330 增加企业用户和部门的全量同步接口 2015-08-14 18:45:13 +08:00
ukid
ff67476c28 1.修改方法getJSSDKCallbackData中的类型错误
2.修改支付签名字段名称,方便客户端直接调用支付
2015-08-14 10:24:23 +08:00
Daniel Qian
2f2543673f Merge pull request #193 from ajffdnt/develop
企业号用户增加enable属性,可以同步本地系统的用户有效性
2015-08-13 16:06:31 +08:00
caosk
cf8f279818 企业号用户增加enable属性,可以同步本地系统的用户有效性,微信异常消息加冒号,代码已验证 2015-08-13 16:00:05 +08:00
ajffdnt
c7054c1a30 Merge pull request #1 from chanjarster/develop
Develop
2015-08-13 14:09:59 +08:00
Daniel Qian
acedf39518 issue #172 upgrade httpclient to 4.5 2015-08-13 09:05:57 +08:00
Daniel Qian
d2765ccc5e Merge pull request #190 from ajffdnt/develop
修改企业号用户的性别问题
2015-08-11 12:54:31 +08:00
caosk
2a2b7ad0c3 Merge branch 'develop' of https://github.com/ajffdnt/weixin-java-tools.git into develop 2015-08-10 15:34:06 +08:00
Daniel Qian
c50c3a09c8 针对issue #189 的修改 2015-08-10 15:33:42 +08:00
Daniel Qian
4fd58a8f8e Merge pull request #186 from ssls/master
公众号支持消息转发到多客服
2015-08-04 16:41:11 +08:00
ssls
2942e1e85c 2015-08-04 16:33:39 +08:00
ssls
f252792e43 修改注释里的TEXT为TRANSFER_CUSTOMER_SERVICE 2015-08-04 16:17:07 +08:00
Daniel Qian
cf9ccbc54d fix: issue #128 2015-08-03 17:30:28 +08:00
ssls
ce109695e7 2015-08-03 17:09:44 +08:00
Daniel Qian
0acae5783a Merge pull request #184 from codepiano/develop
使用java1.7新语法,改进序列化代码
2015-07-30 08:57:20 +08:00
codepiano
4da11fcd74 使用java1.7新语法,改进序列化代码 2015-07-29 20:47:41 +08:00
Daniel Qian
a00d693c34 Merge pull request #183 from codepiano/develop
补充永久素材相关方法到接口中,优化接口参数
2015-07-28 08:50:29 +08:00
codepiano
49a4ab6a6e 补充永久素材相关方法到接口中,优化接口参数 2015-07-27 22:28:05 +08:00
Daniel Qian
08338b0835 Merge pull request #142 from ukid/develop
修改js分享所需参数,去掉jsapiTicket,增加appid
2015-07-27 13:30:44 +08:00
Daniel Qian
c6d0f18a4c upgrade to 1.2.1-SNAPSHOT 2015-07-27 13:17:21 +08:00
Daniel Qian
14c82c11ba Merge branch 'develop' 2015-07-27 13:12:49 +08:00
Daniel Qian
871a34677d upgrade to 1.2.0 2015-07-27 13:12:27 +08:00
Daniel Qian
2f642d0e99 Merge pull request #174 from codepiano/develop
实现永久素材相关接口 @codepiano
2015-07-27 09:24:09 +08:00
codepiano
d7d9734bf1 实现永久素材相关接口 2015-07-23 18:08:38 +08:00
Daniel Qian
24891af5be Merge pull request #176 from crab890715/develop
将微信自定义的事件修正为不区分大小写,
比如框架定义的事件常量为click,但微信传递过来的却是CLICK
2015-07-23 11:19:58 +08:00
liuwj
bc054d6259 将微信自带的一些常量修正为不区分大小写匹配
比如框架定义的事件常量为click,但微信传递过来的却是CLICK
2015-07-23 11:16:36 +08:00
liuwj
b9923b3ecf 将微信自带的一些常量修正为不区分大小写匹配
比如框架定义的事件常量为click,但微信传递过来的却是CLICK
2015-07-23 11:15:07 +08:00
Daniel Qian
a1b72bda8c Update README.md 2015-07-22 08:50:12 +08:00
ukid
f48a6f9c0e Merge commit '3853c7ee4050e67b9211c385147444100aa69ee5' into develop
* commit '3853c7ee4050e67b9211c385147444100aa69ee5':
  upgrade to 1.1.9-SNAPSHOT
  upgrade to version 1.1.8
  个人信息缺少remark和groupId
2015-07-21 17:10:23 +08:00
Daniel Qian
3853c7ee40 Merge pull request #170 from dwandw/develop
个人信息缺少remark和groupId
2015-07-20 08:57:55 +08:00
li.dai
d04d955cb6 Merge branch 'master' into develop 2015-07-18 10:31:27 +08:00
Daniel Qian
d162e31454 upgrade to 1.1.9-SNAPSHOT 2015-07-17 15:39:33 +08:00
Daniel Qian
74cbe68644 Merge branch 'develop'
Conflicts:
	README.md
2015-07-17 15:32:32 +08:00
Daniel Qian
42418a2d0d upgrade to version 1.1.8 2015-07-17 15:30:20 +08:00
ukid
7bb414fbe4 Merge commit '8d950286588c2784b75f88a72132ace4ef987c4d' into develop
* commit '8d950286588c2784b75f88a72132ace4ef987c4d':
  fix: IDEA 导入的时候总是会将编译level变成5.0的问题
  #165 #167
  #165 MediaDownloadRequestExecutor出错后就没有办法下载了
  upgrade version 1.1.8-SNAPSHOT
  update
  upgrade to 1.1.7
2015-07-14 18:02:39 +08:00
Daniel Qian
8d95028658 fix: IDEA 导入的时候总是会将编译level变成5.0的问题 2015-07-13 17:28:27 +08:00
Daniel Qian
d3d61d753e #165 #167 2015-07-13 17:25:46 +08:00
Daniel Qian
4bee1ba2eb #165 MediaDownloadRequestExecutor出错后就没有办法下载了 2015-07-13 12:32:00 +08:00
li.dai
d42e84be68 个人信息缺少remark和groupId 2015-07-11 14:01:57 +08:00
Daniel Qian
399017dce8 update 2015-07-10 14:04:11 +08:00
Daniel Qian
f30211ce98 upgrade version 1.1.8-SNAPSHOT 2015-07-10 14:03:37 +08:00
Daniel Qian
8032b30b9d Merge branch 'develop' 2015-07-10 13:59:45 +08:00
Daniel Qian
6239abcbcc update 2015-07-10 13:59:28 +08:00
Daniel Qian
6f60050aa2 Merge branch 'develop' 2015-07-10 13:58:12 +08:00
Daniel Qian
1ade007250 upgrade to 1.1.7 2015-07-10 13:57:40 +08:00
ukid
a312760d32 Merge commit 'ee2cf21efc8cf43fa2334a23e7437f1ccd646fbe' into develop
* commit 'ee2cf21efc8cf43fa2334a23e7437f1ccd646fbe':
  fix: issue #163
2015-07-09 11:12:49 +08:00
Daniel Qian
ee2cf21efc fix: issue #163 2015-07-02 09:40:12 +08:00
ukid
49990279b7 Merge commit 'd707140d066f6648e7a2872ca3c0c8f866d4fac6' into develop
* commit 'd707140d066f6648e7a2872ca3c0c8f866d4fac6':
  upgrade to 1.1.7-SNAPSHOT
  upgrade to 1.1.6
2015-07-01 16:48:25 +08:00
Daniel Qian
d707140d06 upgrade to 1.1.7-SNAPSHOT 2015-06-26 16:40:07 +08:00
ukid
55f1d964bb Merge commit '4da9ea5dd5210674ccc3d20d470d337857182474' into develop
* commit '4da9ea5dd5210674ccc3d20d470d337857182474':
  增加临时文件目录配置
  增加忽略eclipse本地配置文件目录
  fix README
2015-06-17 13:10:10 +08:00
ukid
60731d229c Merge commit 'bb22974d6553dc85202bee5b027ccddde3a2e7b2' into develop
* commit 'bb22974d6553dc85202bee5b027ccddde3a2e7b2':
  统一使用getHttpClient,使得可以复用httpClient
2015-06-10 14:22:11 +08:00
ukid
5bd2c489b7 Merge commit 'bd3fb69befd63826975b281bbe23d05622496219' into develop
* commit 'bd3fb69befd63826975b281bbe23d05622496219':
  update to 1.1.6-SNAPSHOT
  update to 1.1.5
2015-05-27 11:49:59 +08:00
ukid
8eb028ffb4 添加读取支付回调内容接口 2015-05-22 11:20:43 +08:00
ukid
b27798209b 增加公众号支付信息查询接口
修改部分注释
2015-05-22 10:50:25 +08:00
ukid
b205b7bff2 修改js分享所需参数,去掉jsapiTicket,增加appid 2015-05-21 13:21:00 +08:00
57 changed files with 2864 additions and 241 deletions

View File

@@ -17,7 +17,7 @@ weixin-java-tools
<dependency>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>1.1.6</version>
<version>1.3.0</version>
</dependency>
```
@@ -27,7 +27,7 @@ weixin-java-tools
<dependency>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-cp</artifactId>
<version>1.1.6</version>
<version>1.3.0</version>
</dependency>
```
@@ -50,3 +50,9 @@ weixin-java-tools
* [1.0.3升级指南](https://github.com/chanjarster/weixin-java-tools/wiki/1_0_3升级指南)
* [1.1.0升级指南](https://github.com/chanjarster/weixin-java-tools/wiki/1_1_0升级指南)
* [1.1.1升级指南](https://github.com/chanjarster/weixin-java-tools/wiki/1_1_1升级指南)
## 关于Pull Request
非常欢迎和感谢对本项目发起Pull Request的同学不过本项目基于[git flow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow)开发流程因此在发起Pull Request的时候请选择develop分支。
且本项目代码风格是用2个空格代表一个tab因此在发起PR时注意一下否则很容易发生在IDE格式化代码后与原代码产生大量diff这样我在阅读PR的时候就很困难。

14
pom.xml
View File

@@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-parent</artifactId>
<version>1.1.6</version>
<version>1.3.0</version>
<packaging>pom</packaging>
<name>WeiXin Java Tools - Parent</name>
<description>微信公众号、企业号上级POM</description>
@@ -41,7 +41,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<downloadJavadocs>true</downloadJavadocs>
<downloadSources>true</downloadSources>
<httpclient.version>4.3.5</httpclient.version>
<httpclient.version>4.5</httpclient.version>
<slf4j.version>1.7.10</slf4j.version>
<logback.version>1.1.2</logback.version>
</properties>
@@ -225,6 +225,16 @@
<goals>deploy</goals>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-parent</artifactId>
<version>1.1.6</version>
<version>1.3.0</version>
</parent>
<artifactId>weixin-java-common</artifactId>

View File

@@ -29,6 +29,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_TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service";
///////////////////////
// 群发消息的消息类型
@@ -137,4 +138,11 @@ public class WxConsts {
/** 弹出授权页面可通过openid拿到昵称、性别、所在地。并且即使在未关注的情况下只要用户授权也能获取其信息 */
public static final String OAUTH2_SCOPE_USER_INFO = "snsapi_userinfo";
///////////////////////
// 永久素材类型
///////////////////////
public static final String MATERIAL_NEWS = "news";
public static final String MATERIAL_VOICE = "voice";
public static final String MATERIAL_IMAGE = "image";
public static final String MATERIAL_VIDEO = "video";
}

View File

@@ -6,11 +6,10 @@ import java.io.Serializable;
* jspai signature
*/
public class WxJsapiSignature implements Serializable {
private String appid;
private String noncestr;
private String jsapiTicket;
private long timestamp;
private String url;
@@ -33,14 +32,6 @@ public class WxJsapiSignature implements Serializable {
this.noncestr = noncestr;
}
public String getJsapiTicket() {
return jsapiTicket;
}
public void setJsapiTicket(String jsapiTicket) {
this.jsapiTicket = jsapiTicket;
}
public long getTimestamp() {
return timestamp;
}
@@ -57,4 +48,12 @@ public class WxJsapiSignature implements Serializable {
this.url = url;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
}

View File

@@ -49,7 +49,7 @@ public class WxError implements Serializable {
@Override
public String toString() {
return "微信错误 errcode=" + errorCode + ", errmsg=" + errorMsg + "\njson:" + json;
return "微信错误: errcode=" + errorCode + ", errmsg=" + errorMsg + "\njson:" + json;
}
}

View File

@@ -53,26 +53,29 @@ public class MediaDownloadRequestExecutor implements RequestExecutor<File, Strin
httpGet.setConfig(config);
}
CloseableHttpResponse response = httpclient.execute(httpGet);
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
// 下载媒体文件出错
if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
throw new WxErrorException(WxError.fromJson(responseContent));
Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
// 下载媒体文件出错
if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
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;
}
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;
}
protected String getFileName(CloseableHttpResponse response) {

View File

@@ -39,13 +39,14 @@ public class MediaUploadRequestExecutor implements RequestExecutor<WxMediaUpload
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
}
CloseableHttpResponse response = httpclient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
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 WxMediaUploadResult.fromJson(responseContent);
}
return WxMediaUploadResult.fromJson(responseContent);
}
}

View File

@@ -33,13 +33,14 @@ public class SimpleGetRequestExecutor implements RequestExecutor<String, String>
httpGet.setConfig(config);
}
CloseableHttpResponse response = httpclient.execute(httpGet);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return responseContent;
}
return responseContent;
}
}

View File

@@ -40,13 +40,14 @@ public class SimplePostRequestExecutor implements RequestExecutor<String, String
httpPost.setEntity(entity);
}
CloseableHttpResponse response = httpclient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
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 responseContent;
}
return responseContent;
}
}

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-parent</artifactId>
<version>1.1.6</version>
<version>1.3.0</version>
</parent>
<artifactId>weixin-java-cp</artifactId>

View File

@@ -408,7 +408,7 @@ public interface WxCpService {
* </pre>
* @param redirectUri
* @param state
* @return code
* @return url
*/
String oauth2buildAuthorizationUrl(String redirectUri, String state);
@@ -556,4 +556,26 @@ public interface WxCpService {
* @param sessionManager
*/
void setSessionManager(WxSessionManager sessionManager);
/**
* 上传部门列表覆盖企业号上的部门信息
* @param mediaId
* @throws WxErrorException
*/
String replaceParty(String mediaId) throws WxErrorException;
/**
* 上传用户列表覆盖企业号上的用户信息
* @param mediaId
* @throws WxErrorException
*/
String replaceUser(String mediaId) throws WxErrorException;
/**
* 获取异步任务结果
* @param joinId
* @return
* @throws WxErrorException
*/
String getTaskResult(String joinId) throws WxErrorException;
}

View File

@@ -1,13 +1,14 @@
package me.chanjar.weixin.cp.api;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.sun.media.sound.SoftTuning;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxMenu;
@@ -21,13 +22,19 @@ 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.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.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -43,14 +50,13 @@ import org.apache.http.impl.client.HttpClients;
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.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
public class WxCpServiceImpl implements WxCpService {
@@ -117,8 +123,10 @@ public class WxCpServiceImpl implements WxCpService {
httpGet.setConfig(config);
}
CloseableHttpClient httpclient = getHttpclient();
CloseableHttpResponse response = httpclient.execute(httpGet);
String resultContent = new BasicResponseHandler().handleResponse(response);
String resultContent = null;
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
resultContent = new BasicResponseHandler().handleResponse(response);
}
WxError error = WxError.fromJson(resultContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
@@ -241,7 +249,6 @@ public class WxCpServiceImpl implements WxCpService {
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);
}
@@ -549,6 +556,9 @@ public class WxCpServiceImpl implements WxCpService {
}
protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException {
if (uri.indexOf("access_token=") != -1) {
throw new IllegalArgumentException("uri参数中不允许有access_token: " + uri);
}
String accessToken = getAccessToken(false);
String uriWithAccessToken = uri;
@@ -645,6 +655,28 @@ public class WxCpServiceImpl implements WxCpService {
this.sessionManager = sessionManager;
}
@Override
public String replaceParty(String mediaId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/replaceparty";
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("media_id", mediaId);
return post(url, jsonObject.toString());
}
@Override
public String replaceUser(String mediaId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/replaceuser";
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("media_id", mediaId);
return post(url, jsonObject.toString());
}
@Override
public String getTaskResult(String joinId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/getresult?jobid="+joinId;
return get(url, null);
}
public File getTmpDirFile() {
return tmpDirFile;
}

View File

@@ -24,6 +24,7 @@ public class WxCpUser implements Serializable {
private String weiXinId;
private String avatar;
private Integer status;
private Integer enable;
private final List<Attr> extAttrs = new ArrayList<Attr>();
public String getUserId() {
@@ -114,6 +115,14 @@ public class WxCpUser implements Serializable {
this.status = status;
}
public Integer getEnable() {
return enable;
}
public void setEnable(Integer enable) {
this.enable = enable;
}
public void addExtAttr(String name, String value) {
this.extAttrs.add(new Attr(name, value));
}

View File

@@ -38,14 +38,7 @@ public class WxCpUserGsonAdapter implements JsonDeserializer<WxCpUser>, JsonSeri
user.setPosition(GsonHelper.getString(o, "position"));
user.setMobile(GsonHelper.getString(o, "mobile"));
Integer gender = GsonHelper.getInteger(o, "gender");
if (new Integer(1).equals(gender)) {
user.setGender("");
} else if (new Integer(2).equals(gender)) {
user.setGender("");
} else {
user.setGender("未知");
}
user.setGender(GsonHelper.getString(o, "gender"));
user.setTel(GsonHelper.getString(o, "tel"));
user.setEmail(GsonHelper.getString(o, "email"));
user.setWeiXinId(GsonHelper.getString(o, "weixinid"));
@@ -88,7 +81,7 @@ public class WxCpUserGsonAdapter implements JsonDeserializer<WxCpUser>, JsonSeri
o.addProperty("mobile", user.getMobile());
}
if (user.getGender() != null) {
o.addProperty("gender", user.getGender().equals("") ? 0 : 1);
o.addProperty("gender", user.getGender());
}
if (user.getTel() != null) {
o.addProperty("tel", user.getTel());
@@ -105,6 +98,9 @@ public class WxCpUserGsonAdapter implements JsonDeserializer<WxCpUser>, JsonSeri
if (user.getStatus() != null) {
o.addProperty("status", user.getStatus());
}
if (user.getEnable() != null) {
o.addProperty("enable", user.getEnable());
}
if (user.getExtAttrs().size() > 0) {
JsonArray attrsJsonArray = new JsonArray();
for (WxCpUser.Attr attr : user.getExtAttrs()) {

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-parent</artifactId>
<version>1.1.6</version>
<version>1.3.0</version>
</parent>
<artifactId>weixin-java-mp</artifactId>
<name>WeiXin Java Tools - MP</name>

View File

@@ -192,26 +192,31 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
'}';
}
@Override
public String getPartnerId() {
return partnerId;
}
@Override
public String getPartnerId() {
return partnerId;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
@Override
public String getPartnerKey() {
return partnerKey;
}
@Override
public String getPartnerKey() {
return partnerKey;
}
public void setPartnerKey(String partnerKey) {
this.partnerKey = partnerKey;
}
public void setPartnerKey(String partnerKey) {
this.partnerKey = partnerKey;
}
@Override
public File getTmpDirFile() {
return this.tmpDirFile;
}
public void setTmpDirFile(File tmpDirFile) {
this.tmpDirFile = tmpDirFile;
}
@Override
public File getTmpDirFile() {
return this.getTmpDirFile();
}
}

View File

@@ -204,15 +204,21 @@ public class WxMpMessageRouterRule {
return end();
}
/**
* 将微信自定义的事件修正为不区分大小写,
* 比如框架定义的事件常量为click但微信传递过来的却是CLICK
* @param wxMessage
* @return
*/
protected boolean test(WxMpXmlMessage wxMessage) {
return
(this.fromUser == null || this.fromUser.equals(wxMessage.getFromUserName()))
&&
(this.msgType == null || this.msgType.equals(wxMessage.getMsgType()))
(this.msgType == null || this.msgType.toLowerCase().equals((wxMessage.getMsgType()==null?null:wxMessage.getMsgType().toLowerCase())))
&&
(this.event == null || this.event.equals(wxMessage.getEvent()))
(this.event == null || this.event.toLowerCase().equals((wxMessage.getEvent()==null?null:wxMessage.getEvent().toLowerCase())))
&&
(this.eventKey == null || this.eventKey.equals(wxMessage.getEventKey()))
(this.eventKey == null || this.eventKey.toLowerCase().equals((wxMessage.getEventKey()==null?null:wxMessage.getEventKey().toLowerCase())))
&&
(this.content == null || this.content
.equals(wxMessage.getContent() == null ? null : wxMessage.getContent().trim()))

View File

@@ -47,9 +47,9 @@ public interface WxMpService {
* <pre>
* 获取access_token本方法线程安全
* 且在多线程同时刷新时只刷新一次避免超出2000次/日的调用次数上限
*
*
* 另本service的所有方法都会在access_token过期是调用此方法
*
*
* 程序员在非必要情况下尽量不要主动调用此方法
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=获取access_token
@@ -111,6 +111,135 @@ public interface WxMpService {
*/
public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream) throws WxErrorException, IOException;
/**
* <pre>
* 上传非图文永久素材
*
* 上传的多媒体文件有格式和大小限制,如下:
* 图片image: 图片大小不超过2M支持bmp/png/jpeg/jpg/gif格式
* 语音voice语音大小不超过5M长度不超过60秒支持mp3/wma/wav/amr格式
* 视频video在上传视频素材时需要POST另一个表单id为description包含素材的描述信息内容格式为JSON
* 缩略图thumb文档未说明
*
* 详情请见: http://mp.weixin.qq.com/wiki/14/7e6c03263063f4813141c3e17dd4350a.html
* </pre>
* @param mediaType 媒体类型, 请看{@link me.chanjar.weixin.common.api.WxConsts}
* @param material 上传的素材, 请看{@link me.chanjar.weixin.mp.bean.WxMpMaterial}
* @return
* @throws WxErrorException
*/
public WxMpMaterialUploadResult materialFileUpload(String mediaType, WxMpMaterial material) throws WxErrorException;
/**
* <pre>
* 上传永久图文素材
*
* 详情请见: http://mp.weixin.qq.com/wiki/14/7e6c03263063f4813141c3e17dd4350a.html
* </pre>
* @param news 上传的图文消息, 请看{@link me.chanjar.weixin.mp.bean.WxMpMaterialNews}
* @return
* @throws WxErrorException
*/
public WxMpMaterialUploadResult materialNewsUpload(WxMpMaterialNews news) throws WxErrorException;
/**
* <pre>
* 下载声音或者图片永久素材
*
* 详情请见: http://mp.weixin.qq.com/wiki/4/b3546879f07623cb30df9ca0e420a5d0.html
* </pre>
* @param media_id 永久素材的id
* @return
* @throws WxErrorException
*/
public InputStream materialImageOrVoiceDownload(String media_id) throws WxErrorException;
/**
* <pre>
* 获取视频永久素材的信息和下载地址
*
* 详情请见: http://mp.weixin.qq.com/wiki/4/b3546879f07623cb30df9ca0e420a5d0.html
* </pre>
* @param media_id 永久素材的id
* @return
* @throws WxErrorException
*/
public WxMpMaterialVideoInfoResult materialVideoInfo(String media_id) throws WxErrorException;
/**
* <pre>
* 获取图文永久素材的信息
*
* 详情请见: http://mp.weixin.qq.com/wiki/4/b3546879f07623cb30df9ca0e420a5d0.html
* </pre>
* @param media_id 永久素材的id
* @return
* @throws WxErrorException
*/
public WxMpMaterialNews materialNewsInfo(String media_id) throws WxErrorException;
/**
* <pre>
* 更新图文永久素材
*
* 详情请见: http://mp.weixin.qq.com/wiki/4/19a59cba020d506e767360ca1be29450.html
* </pre>
* @param wxMpMaterialArticleUpdate 用来更新图文素材的bean, 请看{@link me.chanjar.weixin.mp.bean.WxMpMaterialArticleUpdate}
* @return
* @throws WxErrorException
*/
public boolean materialNewsUpdate(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate) throws WxErrorException;
/**
* <pre>
* 删除永久素材
*
* 详情请见: http://mp.weixin.qq.com/wiki/5/e66f61c303db51a6c0f90f46b15af5f5.html
* </pre>
* @param media_id 永久素材的id
* @return
* @throws WxErrorException
*/
public boolean materialDelete(String media_id) throws WxErrorException;
/**
* <pre>
* 获取各类素材总数
*
* 详情请见: http://mp.weixin.qq.com/wiki/16/8cc64f8c189674b421bee3ed403993b8.html
* </pre>
* @return
* @throws WxErrorException
*/
public WxMpMaterialCountResult materialCount() throws WxErrorException;
/**
* <pre>
* 分页获取图文素材列表
*
* 详情请见: http://mp.weixin.qq.com/wiki/12/2108cd7aafff7f388f41f37efa710204.html
* </pre>
* @param offset 从全部素材的该偏移位置开始返回0表示从第一个素材 返回
* @param count 返回素材的数量取值在1到20之间
* @return
* @throws WxErrorException
*/
public WxMpMaterialNewsBatchGetResult materialNewsBatchGet(int offset, int count) throws WxErrorException;
/**
* <pre>
* 分页获取其他媒体素材列表
*
* 详情请见: http://mp.weixin.qq.com/wiki/12/2108cd7aafff7f388f41f37efa710204.html
* </pre>
* @param type 媒体类型, 请看{@link me.chanjar.weixin.common.api.WxConsts}
* @param offset 从全部素材的该偏移位置开始返回0表示从第一个素材 返回
* @param count 返回素材的数量取值在1到20之间
* @return
* @throws WxErrorException
*/
public WxMpMaterialFileBatchGetResult materialFileBatchGet(String type, int offset, int count) throws WxErrorException;
/**
* @see #mediaUpload(String, String, InputStream)
* @param mediaType
@@ -118,7 +247,7 @@ public interface WxMpService {
* @throws WxErrorException
*/
public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException;
/**
* <pre>
* 下载多媒体文件
@@ -130,7 +259,7 @@ public interface WxMpService {
* @throws WxErrorException
*/
public File mediaDownload(String media_id) throws WxErrorException;
/**
* <pre>
* 发送客服消息
@@ -140,11 +269,11 @@ public interface WxMpService {
* @throws WxErrorException
*/
public void customMessageSend(WxMpCustomMessage message) throws WxErrorException;
/**
* <pre>
* 上传群发用的图文消息,上传后才能群发图文消息
*
* 上传群发用的图文消息,上传后才能群发图文消息
*
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=高级群发接口
* </pre>
* @param news
@@ -153,7 +282,7 @@ public interface WxMpService {
* @see #massOpenIdsMessageSend(me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage)
*/
public WxMpMassUploadResult massNewsUpload(WxMpMassNews news) throws WxErrorException;
/**
* <pre>
* 上传群发用的视频,上传后才能群发视频消息
@@ -175,10 +304,10 @@ public interface WxMpService {
* </pre>
* @param message
* @throws WxErrorException
* @return
* @return
*/
public WxMpMassSendResult massGroupMessageSend(WxMpMassGroupMessage message) throws WxErrorException;
/**
* <pre>
* 按openId列表群发消息
@@ -201,7 +330,7 @@ public interface WxMpService {
* @throws WxErrorException
*/
public void menuCreate(WxMenu menu) throws WxErrorException;
/**
* <pre>
* 自定义菜单删除接口
@@ -210,7 +339,7 @@ public interface WxMpService {
* @throws WxErrorException
*/
public void menuDelete() throws WxErrorException;
/**
* <pre>
* 自定义菜单查询接口
@@ -227,11 +356,11 @@ public interface WxMpService {
* 最多支持创建500个分组
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
* </pre>
* @param name 分组名字30个字符以内
* @param name 分组名字30个字符以内
* @throws WxErrorException
*/
public WxMpGroup groupCreate(String name) throws WxErrorException;
/**
* <pre>
* 分组管理接口 - 查询所有分组
@@ -241,34 +370,34 @@ public interface WxMpService {
* @throws WxErrorException
*/
public List<WxMpGroup> groupGet() throws WxErrorException;
/**
* <pre>
* 分组管理接口 - 查询用户所在分组
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
* </pre>
* @param openid 微信用户的openid
* @param openid 微信用户的openid
* @throws WxErrorException
*/
public long userGetGroup(String openid) throws WxErrorException;
/**
* <pre>
* 分组管理接口 - 修改分组名
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
*
*
* 如果id为0(未分组),1(黑名单),2(星标组)或者不存在的id微信会返回系统繁忙的错误
* </pre>
* @param group 要更新的groupgroup的id,name必须设置
* @param group 要更新的groupgroup的id,name必须设置
* @throws WxErrorException
*/
public void groupUpdate(WxMpGroup group) throws WxErrorException;
/**
* <pre>
* 分组管理接口 - 移动用户分组
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=分组管理接口
*
*
* 如果to_groupid为0(未分组),1(黑名单),2(星标组)或者不存在的id微信会返回系统繁忙的错误
* </pre>
* @param openid 用户openid
@@ -294,7 +423,7 @@ public interface WxMpService {
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=获取用户基本信息
* </pre>
* @param openid 用户openid
* @param lang 语言zh_CN 简体(默认)zh_TW 繁体en 英语
* @param lang 语言zh_CN 简体(默认)zh_TW 繁体en 英语
* @return
* @throws WxErrorException
*/
@@ -397,7 +526,7 @@ public interface WxMpService {
* </pre>
* @param scope
* @param state
* @return code
* @return url
*/
public String oauth2buildAuthorizationUrl(String scope, String state);
@@ -410,7 +539,7 @@ public interface WxMpService {
* 用户授权完成后的重定向链接无需urlencode, 方法内会进行encode
* @param scope
* @param state
* @return code
* @return url
*/
public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state);
/**
@@ -543,7 +672,7 @@ public interface WxMpService {
void setMaxRetryTimes(int maxRetryTimes);
/**
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=9_1)
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"
* @param openId 支付人openId
* @param outTradeNo 商户端对应订单号
@@ -570,4 +699,19 @@ public interface WxMpService {
*/
Map<String, String> getJSSDKPayInfo(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_2
* @param transactionId
* @param outTradeNo
*/
WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo);
/**
* 读取支付结果通知
* 详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
* @param xmlData
* @return
*/
WxMpPayCallback getJSSDKCallbackData(String xmlData);
}

View File

@@ -1,16 +1,24 @@
package me.chanjar.weixin.mp.api;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.thoughtworks.xstream.XStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
@@ -21,14 +29,53 @@ import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.common.util.crypto.WxCryptUtil;
import me.chanjar.weixin.common.util.fs.FileUtils;
import me.chanjar.weixin.common.util.http.*;
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.http.Utf8ResponseHandler;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.mp.bean.*;
import me.chanjar.weixin.mp.bean.result.*;
import me.chanjar.weixin.mp.bean.WxMpCustomMessage;
import me.chanjar.weixin.mp.bean.WxMpGroup;
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.WxMpMassVideo;
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.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.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.WxMpPayCallback;
import me.chanjar.weixin.mp.bean.result.WxMpPayResult;
import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult;
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.WxMpUserCumulate;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import me.chanjar.weixin.mp.bean.result.WxMpUserSummary;
import me.chanjar.weixin.mp.util.http.MaterialDeleteRequestExecutor;
import me.chanjar.weixin.mp.util.http.MaterialNewsInfoRequestExecutor;
import me.chanjar.weixin.mp.util.http.MaterialUploadRequestExecutor;
import me.chanjar.weixin.mp.util.http.MaterialVideoInfoRequestExecutor;
import me.chanjar.weixin.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor;
import me.chanjar.weixin.mp.util.http.QrCodeRequestExecutor;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
@@ -47,13 +94,13 @@ import org.apache.http.impl.client.HttpClients;
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.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.thoughtworks.xstream.XStream;
public class WxMpServiceImpl implements WxMpService {
@@ -102,8 +149,7 @@ public class WxMpServiceImpl implements WxMpService {
if (wxMpConfigStorage.isAccessTokenExpired()) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
+ "&appid=" + wxMpConfigStorage.getAppId()
+ "&secret=" + wxMpConfigStorage.getSecret()
;
+ "&secret=" + wxMpConfigStorage.getSecret();
try {
HttpGet httpGet = new HttpGet(url);
if (httpProxy != null) {
@@ -165,6 +211,7 @@ public class WxMpServiceImpl implements WxMpService {
"url=" + url
);
WxJsapiSignature jsapiSignature = new WxJsapiSignature();
jsapiSignature.setAppid(wxMpConfigStorage.getAppId());
jsapiSignature.setTimestamp(timestamp);
jsapiSignature.setNoncestr(noncestr);
jsapiSignature.setUrl(url);
@@ -179,12 +226,12 @@ public class WxMpServiceImpl implements WxMpService {
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send";
execute(new SimplePostRequestExecutor(), url, message.toJson());
}
public void menuCreate(WxMenu menu) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/menu/create";
execute(new SimplePostRequestExecutor(), url, menu.toJson());
}
public void menuDelete() throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/menu/delete";
execute(new SimpleGetRequestExecutor(), url, null);
@@ -205,31 +252,117 @@ public class WxMpServiceImpl implements WxMpService {
}
public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream) throws WxErrorException, IOException {
return mediaUpload(mediaType,FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType));
return mediaUpload(mediaType, FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType));
}
public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException {
String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType;
return execute(new MediaUploadRequestExecutor(), url, file);
}
public File mediaDownload(String media_id) throws WxErrorException {
String url = "http://file.api.weixin.qq.com/cgi-bin/media/get";
return execute(new MediaDownloadRequestExecutor(wxMpConfigStorage.getTmpDirFile()), url, "media_id=" + media_id);
}
public WxMpMaterialUploadResult materialFileUpload(String mediaType, WxMpMaterial material) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?type=" + mediaType;
return execute(new MaterialUploadRequestExecutor(), url, material);
}
public WxMpMaterialUploadResult materialNewsUpload(WxMpMaterialNews news) throws WxErrorException {
if (news == null || news.isEmpty()) {
throw new IllegalArgumentException("news is empty!");
}
String url = "https://api.weixin.qq.com/cgi-bin/material/add_news";
String responseContent = post(url, news.toJson());
return WxMpMaterialUploadResult.fromJson(responseContent);
}
public InputStream materialImageOrVoiceDownload(String media_id) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/get_material";
return execute(new MaterialVoiceAndImageDownloadRequestExecutor(wxMpConfigStorage.getTmpDirFile()), url, media_id);
}
public WxMpMaterialVideoInfoResult materialVideoInfo(String media_id) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/get_material";
return execute(new MaterialVideoInfoRequestExecutor(), url, media_id);
}
public WxMpMaterialNews materialNewsInfo(String media_id) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/get_material";
return execute(new MaterialNewsInfoRequestExecutor(), url, media_id);
}
public boolean materialNewsUpdate(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/update_news";
String responseText = post(url, wxMpMaterialArticleUpdate.toJson());
WxError wxError = WxError.fromJson(responseText);
if (wxError.getErrorCode() == 0) {
return true;
} else {
throw new WxErrorException(wxError);
}
}
public boolean materialDelete(String media_id) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/del_material";
return execute(new MaterialDeleteRequestExecutor(), url, media_id);
}
public WxMpMaterialCountResult materialCount() throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount";
String responseText = get(url, null);
WxError wxError = WxError.fromJson(responseText);
if (wxError.getErrorCode() == 0) {
return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialCountResult.class);
} else {
throw new WxErrorException(wxError);
}
}
public WxMpMaterialNewsBatchGetResult materialNewsBatchGet(int offset, int count) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material";
Map<String, Object> params = new HashMap<>();
params.put("type", WxConsts.MATERIAL_NEWS);
params.put("offset", offset);
params.put("count", count);
String responseText = post(url, WxGsonBuilder.create().toJson(params));
WxError wxError = WxError.fromJson(responseText);
if (wxError.getErrorCode() == 0) {
return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialNewsBatchGetResult.class);
} else {
throw new WxErrorException(wxError);
}
}
public WxMpMaterialFileBatchGetResult materialFileBatchGet(String type, int offset, int count) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material";
Map<String, Object> params = new HashMap<>();
params.put("type", type);
params.put("offset", offset);
params.put("count", count);
String responseText = post(url, WxGsonBuilder.create().toJson(params));
WxError wxError = WxError.fromJson(responseText);
if (wxError.getErrorCode() == 0) {
return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialFileBatchGetResult.class);
} else {
throw new WxErrorException(wxError);
}
}
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());
return WxMpMassUploadResult.fromJson(responseContent);
}
public WxMpMassUploadResult massVideoUpload(WxMpMassVideo video) throws WxErrorException {
String url = "http://file.api.weixin.qq.com/cgi-bin/media/uploadvideo";
String responseContent = execute(new SimplePostRequestExecutor(), url, video.toJson());
return WxMpMassUploadResult.fromJson(responseContent);
}
public WxMpMassSendResult massGroupMessageSend(WxMpMassGroupMessage message) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall";
String responseContent = execute(new SimplePostRequestExecutor(), url, message.toJson());
@@ -241,17 +374,17 @@ public class WxMpServiceImpl implements WxMpService {
String responseContent = execute(new SimplePostRequestExecutor(), url, message.toJson());
return WxMpMassSendResult.fromJson(responseContent);
}
public WxMpGroup groupCreate(String name) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/groups/create";
JsonObject json = new JsonObject();
JsonObject groupJson = new JsonObject();
json.add("group", groupJson);
groupJson.addProperty("name", name);
String responseContent = execute(
new SimplePostRequestExecutor(),
url,
new SimplePostRequestExecutor(),
url,
json.toString());
return WxMpGroup.fromJson(responseContent);
}
@@ -264,9 +397,11 @@ public class WxMpServiceImpl implements WxMpService {
* 查询时返回的是 { groups : [ { id : ..., name : ..., count : ... }, ... ] }
*/
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("groups"), new TypeToken<List<WxMpGroup>>(){}.getType());
return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("groups"),
new TypeToken<List<WxMpGroup>>() {
}.getType());
}
public long userGetGroup(String openid) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/groups/getid";
JsonObject o = new JsonObject();
@@ -275,12 +410,12 @@ public class WxMpServiceImpl implements WxMpService {
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return GsonHelper.getAsLong(tmpJsonElement.getAsJsonObject().get("groupid"));
}
public void groupUpdate(WxMpGroup group) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/groups/update";
execute(new SimplePostRequestExecutor(), url, group.toJson());
}
public void userUpdateGroup(String openid, long to_groupid) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/groups/members/update";
JsonObject json = new JsonObject();
@@ -288,7 +423,7 @@ public class WxMpServiceImpl implements WxMpService {
json.addProperty("to_groupid", to_groupid);
execute(new SimplePostRequestExecutor(), url, json.toString());
}
public void userUpdateRemark(String openid, String remark) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark";
JsonObject json = new JsonObject();
@@ -296,25 +431,25 @@ public class WxMpServiceImpl implements WxMpService {
json.addProperty("remark", remark);
execute(new SimplePostRequestExecutor(), url, json.toString());
}
public WxMpUser userInfo(String openid, String lang) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/user/info";
lang = lang == null ? "zh_CN" : lang;
String responseContent = execute(new SimpleGetRequestExecutor(), url, "openid=" + openid + "&lang=" + lang);
return WxMpUser.fromJson(responseContent);
}
public WxMpUserList userList(String next_openid) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/user/get";
String responseContent = execute(new SimpleGetRequestExecutor(), url, next_openid == null ? null : "next_openid=" + next_openid);
return WxMpUserList.fromJson(responseContent);
}
public WxMpQrCodeTicket qrCodeCreateTmpTicket(int scene_id, Integer expire_seconds) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create";
JsonObject json = new JsonObject();
json.addProperty("action_name", "QR_SCENE");
if(expire_seconds != null) {
if (expire_seconds != null) {
json.addProperty("expire_seconds", expire_seconds);
}
JsonObject actionInfo = new JsonObject();
@@ -325,7 +460,7 @@ public class WxMpServiceImpl implements WxMpService {
String responseContent = execute(new SimplePostRequestExecutor(), url, json.toString());
return WxMpQrCodeTicket.fromJson(responseContent);
}
public WxMpQrCodeTicket qrCodeCreateLastTicket(int scene_id) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create";
JsonObject json = new JsonObject();
@@ -351,12 +486,12 @@ public class WxMpServiceImpl implements WxMpService {
String responseContent = execute(new SimplePostRequestExecutor(), url, json.toString());
return WxMpQrCodeTicket.fromJson(responseContent);
}
public File qrCodePicture(WxMpQrCodeTicket ticket) throws WxErrorException {
String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode";
return execute(new QrCodeRequestExecutor(), url, ticket);
}
public String shortUrl(String long_url) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/shorturl";
JsonObject o = new JsonObject();
@@ -387,7 +522,7 @@ public class WxMpServiceImpl implements WxMpService {
@Override
public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state) {
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" ;
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
url += "appid=" + wxMpConfigStorage.getAppId();
url += "&redirect_uri=" + URIUtil.encodeURIComponent(redirectURI);
url += "&response_type=code";
@@ -402,7 +537,7 @@ public class WxMpServiceImpl implements WxMpService {
@Override
public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
url += "appid=" + wxMpConfigStorage.getAppId();
url += "appid=" + wxMpConfigStorage.getAppId();
url += "&secret=" + wxMpConfigStorage.getSecret();
url += "&code=" + code;
url += "&grant_type=authorization_code";
@@ -499,7 +634,8 @@ public class WxMpServiceImpl implements WxMpService {
param.addProperty("end_date", SIMPLE_DATE_FORMAT.format(endDate));
String responseContent = post(url, param.toString());
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), new TypeToken<List<WxMpUserSummary>>(){}.getType());
return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), new TypeToken<List<WxMpUserSummary>>() {
}.getType());
}
@Override
@@ -510,7 +646,9 @@ public class WxMpServiceImpl implements WxMpService {
param.addProperty("end_date", SIMPLE_DATE_FORMAT.format(endDate));
String responseContent = post(url, param.toString());
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), new TypeToken<List<WxMpUserCumulate>>(){}.getType());
return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"),
new TypeToken<List<WxMpUserCumulate>>() {
}.getType());
}
public String get(String url, String queryParam) throws WxErrorException {
@@ -523,6 +661,7 @@ public class WxMpServiceImpl implements WxMpService {
/**
* 向微信端发送请求在这里执行的策略是当发生access_token过期时才去刷新然后重新执行请求而不是全局定时请求
*
* @param executor
* @param uri
* @param data
@@ -551,17 +690,20 @@ public class WxMpServiceImpl implements WxMpService {
throw e;
}
}
} while(++retryTimes < maxRetryTimes);
} while (++retryTimes < maxRetryTimes);
throw new RuntimeException("微信服务端异常,超出重试次数");
}
protected <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException {
if (uri.indexOf("access_token=") != -1) {
throw new IllegalArgumentException("uri参数中不允许有access_token: " + uri);
}
String accessToken = getAccessToken(false);
String uriWithAccessToken = uri;
uriWithAccessToken += uri.indexOf('?') == -1 ? "?access_token=" + accessToken : "&access_token=" + accessToken;
try {
return executor.execute(getHttpclient(), httpProxy, uriWithAccessToken, data);
} catch (WxErrorException e) {
@@ -599,9 +741,9 @@ public class WxMpServiceImpl implements WxMpService {
String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username();
String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password();
if(StringUtils.isNotBlank(http_proxy_host)) {
if (StringUtils.isNotBlank(http_proxy_host)) {
// 使用代理服务器
if(StringUtils.isNotBlank(http_proxy_username)) {
if (StringUtils.isNotBlank(http_proxy_username)) {
// 需要用户认证的代理服务器
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
@@ -643,7 +785,7 @@ public class WxMpServiceImpl implements WxMpService {
packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo);
packageParams.put("total_fee", (int)(amt*100) + "");
packageParams.put("total_fee", (int) (amt * 100) + "");
packageParams.put("spbill_create_ip", ip);
packageParams.put("notify_url", callbackUrl);
packageParams.put("trade_type", tradeType);
@@ -651,18 +793,18 @@ public class WxMpServiceImpl implements WxMpService {
String sign = WxCryptUtil.createSign(packageParams, wxMpConfigStorage.getPartnerKey());
String xml = "<xml>" +
"<appid>" + wxMpConfigStorage.getAppId() + "</appid>" +
"<mch_id>" + wxMpConfigStorage.getPartnerId() + "</mch_id>" +
"<nonce_str>" + nonce_str + "</nonce_str>" +
"<sign>" + sign + "</sign>" +
"<body><![CDATA[" + body + "]]></body>" +
"<out_trade_no>" + outTradeNo + "</out_trade_no>" +
"<total_fee>" + packageParams.get("total_fee") + "</total_fee>" +
"<spbill_create_ip>" + ip + "</spbill_create_ip>" +
"<notify_url>" + callbackUrl + "</notify_url>" +
"<trade_type>" + tradeType + "</trade_type>" +
"<openid>" + openId + "</openid>" +
"</xml>";
"<appid>" + wxMpConfigStorage.getAppId() + "</appid>" +
"<mch_id>" + wxMpConfigStorage.getPartnerId() + "</mch_id>" +
"<nonce_str>" + nonce_str + "</nonce_str>" +
"<sign>" + sign + "</sign>" +
"<body><![CDATA[" + body + "]]></body>" +
"<out_trade_no>" + outTradeNo + "</out_trade_no>" +
"<total_fee>" + packageParams.get("total_fee") + "</total_fee>" +
"<spbill_create_ip>" + ip + "</spbill_create_ip>" +
"<notify_url>" + callbackUrl + "</notify_url>" +
"<trade_type>" + tradeType + "</trade_type>" +
"<openid>" + openId + "</openid>" +
"</xml>";
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder");
if (httpProxy != null) {
@@ -690,7 +832,7 @@ public class WxMpServiceImpl implements WxMpService {
WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(openId, outTradeNo, amt, body, tradeType, ip, callbackUrl);
String prepayId = wxMpPrepayIdResult.getPrepay_id();
if (prepayId == null || prepayId.equals("")) {
throw new RuntimeException("get prepayid error");
throw new RuntimeException("get prepayid error");
}
Map<String, String> payInfo = new HashMap<String, String>();
@@ -702,7 +844,64 @@ public class WxMpServiceImpl implements WxMpService {
payInfo.put("signType", "MD5");
String finalSign = WxCryptUtil.createSign(payInfo, wxMpConfigStorage.getPartnerKey());
payInfo.put("sign", finalSign);
payInfo.put("paySign", finalSign);
return payInfo;
}
@Override
public WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) {
String nonce_str = System.currentTimeMillis() + "";
SortedMap<String, String> packageParams = new TreeMap<String, String>();
packageParams.put("appid", wxMpConfigStorage.getAppId());
packageParams.put("mch_id", wxMpConfigStorage.getPartnerId());
packageParams.put("transaction_id", transactionId);
packageParams.put("out_trade_no", outTradeNo);
packageParams.put("nonce_str", nonce_str);
String sign = WxCryptUtil.createSign(packageParams, wxMpConfigStorage.getPartnerKey());
String xml = "<xml>" +
"<appid>" + wxMpConfigStorage.getAppId() + "</appid>" +
"<mch_id>" + wxMpConfigStorage.getPartnerId() + "</mch_id>" +
"<transaction_id>" + transactionId + "</transaction_id>" +
"<out_trade_no>" + outTradeNo + "</out_trade_no>" +
"<nonce_str>" + nonce_str + "</nonce_str>" +
"<sign>" + sign + "</sign>" +
"</xml>";
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery");
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(config);
}
StringEntity entity = new StringEntity(xml, Consts.UTF_8);
httpPost.setEntity(entity);
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", WxMpPayResult.class);
WxMpPayResult wxMpPayResult = (WxMpPayResult) xstream.fromXML(responseContent);
return wxMpPayResult;
} catch (IOException e) {
e.printStackTrace();
}
return new WxMpPayResult();
}
@Override
public WxMpPayCallback getJSSDKCallbackData(String xmlData) {
try {
XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", WxMpPayCallback.class);
WxMpPayCallback wxMpCallback = (WxMpPayCallback) xstream.fromXML(xmlData);
return wxMpCallback;
} catch (Exception e){
e.printStackTrace();
}
return new WxMpPayCallback();
}
}

View File

@@ -8,25 +8,29 @@ import java.util.List;
/**
* 群发时用到的图文消息素材
* @author chanjarster
*
* @author chanjarster
*/
public class WxMpMassNews implements Serializable {
private List<WxMpMassNewsArticle> articles = new ArrayList<WxMpMassNewsArticle>();
public List<WxMpMassNewsArticle> getArticles() {
return articles;
}
public void addArticle(WxMpMassNewsArticle article) {
this.articles.add(article);
}
public String toJson() {
return WxMpGsonBuilder.INSTANCE.create().toJson(this);
}
public boolean isEmpty() {
return articles == null || articles.isEmpty();
}
/**
* <pre>
* 群发图文消息article
@@ -38,8 +42,8 @@ public class WxMpMassNews implements Serializable {
* 6. digest 图文消息的描述
* 7, showCoverPic 是否显示封面true为显示false为不显示
* </pre>
* @author chanjarster
*
* @author chanjarster
*/
public static class WxMpMassNewsArticle {
/**
@@ -70,49 +74,73 @@ public class WxMpMassNews implements Serializable {
* 是否显示封面true为显示false为不显示
*/
private boolean showCoverPic;
public String getThumbMediaId() {
return thumbMediaId;
}
public void setThumbMediaId(String thumbMediaId) {
this.thumbMediaId = thumbMediaId;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContentSourceUrl() {
return contentSourceUrl;
}
public void setContentSourceUrl(String contentSourceUrl) {
this.contentSourceUrl = contentSourceUrl;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDigest() {
return digest;
}
public void setDigest(String digest) {
this.digest = digest;
}
public boolean isShowCoverPic() {
return showCoverPic;
}
public void setShowCoverPic(boolean showCoverPic) {
this.showCoverPic = showCoverPic;
}
@Override
public String toString() {
return "WxMpMassNewsArticle [" + "thumbMediaId=" + thumbMediaId + ", author=" + author + ", title=" + title +
", contentSourceUrl=" + contentSourceUrl + ", content=" + content + ", digest=" + digest +
", showCoverPic=" + showCoverPic + "]";
}
}
@Override
public String toString() {
return "WxMpMassNews [" + "articles=" + articles + "]";
}
}

View File

@@ -0,0 +1,67 @@
package me.chanjar.weixin.mp.bean;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class WxMpMaterial {
private String name;
private File file;
private String videoTitle;
private String videoIntroduction;
public WxMpMaterial() {
}
public WxMpMaterial(String name, File file, String videoTitle, String videoIntroduction) {
this.name = name;
this.file = file;
this.videoTitle = videoTitle;
this.videoIntroduction = videoIntroduction;
}
public Map<String, String> getForm() {
Map<String, String> form = new HashMap<String, String>();
form.put("title", videoTitle);
form.put("introduction", videoIntroduction);
return form;
}
public String getVideoTitle() {
return videoTitle;
}
public void setVideoTitle(String videoTitle) {
this.videoTitle = videoTitle;
}
public String getVideoIntroduction() {
return videoIntroduction;
}
public void setVideoIntroduction(String videoIntroduction) {
this.videoIntroduction = videoIntroduction;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
@Override
public String toString() {
return "WxMpMaterial [" + "name=" + name + ", file=" + file + ", videoTitle=" + videoTitle + ", videoIntroduction=" + videoIntroduction + "]";
}
}

View File

@@ -0,0 +1,45 @@
package me.chanjar.weixin.mp.bean;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
public class WxMpMaterialArticleUpdate implements Serializable {
private String mediaId;
private int index;
private WxMpMaterialNews.WxMpMaterialNewsArticle articles;
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public WxMpMaterialNews.WxMpMaterialNewsArticle getArticles() {
return articles;
}
public void setArticles(WxMpMaterialNews.WxMpMaterialNewsArticle articles) {
this.articles = articles;
}
public String toJson() {
return WxMpGsonBuilder.create().toJson(this);
}
@Override
public String toString() {
return "WxMpMaterialArticleUpdate [" + "mediaId=" + mediaId + ", index=" + index + ", articles=" + articles + "]";
}
}

View File

@@ -0,0 +1,156 @@
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 WxMpMaterialNews implements Serializable {
private List<WxMpMaterialNewsArticle> articles = new ArrayList<WxMpMaterialNewsArticle>();
public List<WxMpMaterialNewsArticle> getArticles() {
return articles;
}
public void addArticle(WxMpMaterialNewsArticle article) {
this.articles.add(article);
}
public String toJson() {
return WxMpGsonBuilder.INSTANCE.create().toJson(this);
}
public boolean isEmpty() {
return articles == null || articles.isEmpty();
}
/**
* <pre>
* 群发图文消息article
* 1. thumbMediaId (必填) 图文消息缩略图的media_id可以在基础支持-上传多媒体文件接口中获得
* 2. author 图文消息的作者
* 3. title (必填) 图文消息的标题
* 4. contentSourceUrl 在图文消息页面点击“阅读原文”后的页面链接
* 5. content (必填) 图文消息页面的内容支持HTML标签
* 6. digest 图文消息的描述
* 7. showCoverPic 是否显示封面true为显示false为不显示
* 8. url 点击图文消息跳转链接
* </pre>
*
* @author chanjarster
*/
public static class WxMpMaterialNewsArticle {
/**
* (必填) 图文消息缩略图的media_id可以在基础支持-上传多媒体文件接口中获得
*/
private String thumbMediaId;
/**
* 图文消息的作者
*/
private String author;
/**
* (必填) 图文消息的标题
*/
private String title;
/**
* 在图文消息页面点击“阅读原文”后的页面链接
*/
private String contentSourceUrl;
/**
* (必填) 图文消息页面的内容支持HTML标签
*/
private String content;
/**
* 图文消息的描述
*/
private String digest;
/**
* 是否显示封面true为显示false为不显示
*/
private boolean showCoverPic;
/**
* 点击图文消息跳转链接
* @return
*/
private String url;
public String getThumbMediaId() {
return thumbMediaId;
}
public void setThumbMediaId(String thumbMediaId) {
this.thumbMediaId = thumbMediaId;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContentSourceUrl() {
return contentSourceUrl;
}
public void setContentSourceUrl(String contentSourceUrl) {
this.contentSourceUrl = contentSourceUrl;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDigest() {
return digest;
}
public void setDigest(String digest) {
this.digest = digest;
}
public boolean isShowCoverPic() {
return showCoverPic;
}
public void setShowCoverPic(boolean showCoverPic) {
this.showCoverPic = showCoverPic;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "WxMpMassNewsArticle [" + "thumbMediaId=" + thumbMediaId + ", author=" + author + ", title=" + title +
", contentSourceUrl=" + contentSourceUrl + ", content=" + content + ", digest=" + digest +
", showCoverPic=" + showCoverPic +", url=" + url + "]";
}
}
@Override
public String toString() {
return "WxMpMaterialNews [" + "articles=" + articles + "]";
}
}

View File

@@ -121,4 +121,12 @@ public abstract class WxMpXmlOutMessage implements Serializable {
public static NewsBuilder NEWS() {
return new NewsBuilder();
}
/**
* 获得客服消息builder
*
* @return
*/
public static TransferCustomerServiceBuilder TRANSFER_CUSTOMER_SERVICE() {
return new TransferCustomerServiceBuilder();
}
}

View File

@@ -0,0 +1,41 @@
package me.chanjar.weixin.mp.bean;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;
import me.chanjar.weixin.common.util.xml.XStreamMediaIdConverter;
@XStreamAlias("xml")
public class WxMpXmlOutTransferCustomerServiceMessage extends WxMpXmlOutMessage {
@XStreamAlias("TransInfo")
protected final TransInfo transInfo = new TransInfo();
public WxMpXmlOutTransferCustomerServiceMessage() {
this.msgType = WxConsts.CUSTOM_MSG_TRANSFER_CUSTOMER_SERVICE;
}
public String getKfAccount() {
return transInfo.getKfAccount();
}
public void setKfAccount(String kfAccount) {
transInfo.setKfAccount(kfAccount);
}
@XStreamAlias("TransInfo")
public static class TransInfo {
@XStreamAlias("KfAccount")
@XStreamConverter(value=XStreamCDataConverter.class)
private String kfAccount;
public String getKfAccount() {
return kfAccount;
}
public void setKfAccount(String kfAccount) {
this.kfAccount = kfAccount;
}
}
}

View File

@@ -0,0 +1,28 @@
package me.chanjar.weixin.mp.bean.outxmlbuilder;
import me.chanjar.weixin.mp.bean.WxMpXmlOutTransferCustomerServiceMessage;
/**
* 客服消息builder
* <pre>
* 用法: WxMpCustomMessage m = WxMpCustomMessage.TRANSFER_CUSTOMER_SERVICE().content(...).toUser(...).build();
* </pre>
*
* @author chanjarster
*/
public final class TransferCustomerServiceBuilder extends BaseBuilder<TransferCustomerServiceBuilder, WxMpXmlOutTransferCustomerServiceMessage> {
private String kfAccount;
public TransferCustomerServiceBuilder kfAccount(String kfAccount) {
this.kfAccount = kfAccount;
return this;
}
public WxMpXmlOutTransferCustomerServiceMessage build() {
WxMpXmlOutTransferCustomerServiceMessage m = new WxMpXmlOutTransferCustomerServiceMessage();
setCommon(m);
m.setKfAccount(kfAccount);
return m;
}
}

View File

@@ -0,0 +1,50 @@
package me.chanjar.weixin.mp.bean.result;
import java.io.Serializable;
public class WxMpMaterialCountResult implements Serializable {
private int voiceCount;
private int videoCount;
private int imageCount;
private int newsCount;
public int getVoiceCount() {
return voiceCount;
}
public void setVoiceCount(int voiceCount) {
this.voiceCount = voiceCount;
}
public int getVideoCount() {
return videoCount;
}
public void setVideoCount(int videoCount) {
this.videoCount = videoCount;
}
public int getImageCount() {
return imageCount;
}
public void setImageCount(int imageCount) {
this.imageCount = imageCount;
}
public int getNewsCount() {
return newsCount;
}
public void setNewsCount(int newsCount) {
this.newsCount = newsCount;
}
@Override
public String toString() {
return "WxMpMaterialCountResult [" + "voiceCount=" + voiceCount + ", videoCount=" + videoCount
+ ", imageCount=" + imageCount + ", newsCount=" + newsCount + "]";
}
}

View File

@@ -0,0 +1,85 @@
package me.chanjar.weixin.mp.bean.result;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class WxMpMaterialFileBatchGetResult implements Serializable {
private int totalCount;
private int itemCount;
private List<WxMaterialFileBatchGetNewsItem> items;
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getItemCount() {
return itemCount;
}
public void setItemCount(int itemCount) {
this.itemCount = itemCount;
}
public List<WxMaterialFileBatchGetNewsItem> getItems() {
return items;
}
public void setItems(List<WxMaterialFileBatchGetNewsItem> items) {
this.items = items;
}
@Override
public String toString() {
return "WxMpMaterialFileBatchGetResult [" + "totalCount=" + totalCount + ", itemCount=" + itemCount + ", items=" + items + "]";
}
public static class WxMaterialFileBatchGetNewsItem {
private String mediaId;
private Date updateTime;
private String name;
private String url;
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "WxMaterialFileBatchGetNewsItem [" + "mediaId=" + mediaId + ", updateTime=" + updateTime + ", name=" + name + ", url=" + url + "]";
}
}
}

View File

@@ -0,0 +1,78 @@
package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.bean.WxMpMaterialNews;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class WxMpMaterialNewsBatchGetResult implements Serializable {
private int totalCount;
private int itemCount;
private List<WxMaterialNewsBatchGetNewsItem> items;
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getItemCount() {
return itemCount;
}
public void setItemCount(int itemCount) {
this.itemCount = itemCount;
}
public List<WxMaterialNewsBatchGetNewsItem> getItems() {
return items;
}
public void setItems(List<WxMaterialNewsBatchGetNewsItem> items) {
this.items = items;
}
@Override
public String toString() {
return "WxMpMaterialNewsBatchGetResult [" + "totalCount=" + totalCount + ", itemCount=" + itemCount + ", items=" + items + "]";
}
public static class WxMaterialNewsBatchGetNewsItem {
private String mediaId;
private Date updateTime;
private WxMpMaterialNews content;
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public WxMpMaterialNews getContent() {
return content;
}
public void setContent(WxMpMaterialNews content) {
this.content = content;
}
@Override
public String toString() {
return "WxMaterialNewsBatchGetNewsItem [" + "mediaId=" + mediaId + ", updateTime=" + updateTime + ", content=" + content + "]";
}
}
}

View File

@@ -0,0 +1,38 @@
package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
public class WxMpMaterialUploadResult implements Serializable {
private String mediaId;
private String url;
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public static WxMpMaterialUploadResult fromJson(String json) {
return WxMpGsonBuilder.create().fromJson(json, WxMpMaterialUploadResult.class);
}
@Override
public String toString() {
return "WxMpMaterialUploadResult [media_id=" + mediaId + ", url=" + url + "]";
}
}

View File

@@ -0,0 +1,46 @@
package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
public class WxMpMaterialVideoInfoResult implements Serializable {
private String title;
private String description;
private String downUrl;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDownUrl() {
return downUrl;
}
public void setDownUrl(String downUrl) {
this.downUrl = downUrl;
}
public static WxMpMaterialVideoInfoResult fromJson(String json) {
return WxMpGsonBuilder.create().fromJson(json, WxMpMaterialVideoInfoResult.class);
}
@Override
public String toString() {
return "WxMpMaterialVideoInfoResult [title=" + title + ", description=" + description + ", downUrl=" + downUrl + "]";
}
}

View File

@@ -0,0 +1,279 @@
package me.chanjar.weixin.mp.bean.result;
import java.io.Serializable;
/**
* pre> 订单支付状态回调
*
* 支付结果通知(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7)
*
* /pre>
*
* @author ukid
*/
public class WxMpPayCallback implements Serializable {
private String return_code;
private String return_msg;
private String appid;
private String mch_id;
private String device_info;
private String nonce_str;
private String sign;
private String result_code;
private String err_code;
private String err_code_des;
private String openid;
private String is_subscribe;
private String trade_type;
private String bank_type;
private String total_fee;
private String fee_type;
private String cash_fee;
private String cash_fee_type;
private String coupon_fee;
private String coupon_count;
private String coupon_batch_id_$n;
private String coupon_id_$n;
private String coupon_fee_$n;
private String transaction_id;
private String out_trade_no;
private String attach;
private String time_end;
public String getReturn_code() {
return return_code;
}
public String getReturn_msg() {
return return_msg;
}
public String getAppid() {
return appid;
}
public String getMch_id() {
return mch_id;
}
public String getDevice_info() {
return device_info;
}
public String getNonce_str() {
return nonce_str;
}
public String getSign() {
return sign;
}
public String getResult_code() {
return result_code;
}
public String getErr_code() {
return err_code;
}
public String getErr_code_des() {
return err_code_des;
}
public String getOpenid() {
return openid;
}
public String getIs_subscribe() {
return is_subscribe;
}
public String getTrade_type() {
return trade_type;
}
public String getBank_type() {
return bank_type;
}
public String getTotal_fee() {
return total_fee;
}
public String getFee_type() {
return fee_type;
}
public String getCash_fee() {
return cash_fee;
}
public String getCash_fee_type() {
return cash_fee_type;
}
public String getCoupon_fee() {
return coupon_fee;
}
public String getCoupon_count() {
return coupon_count;
}
public String getCoupon_batch_id_$n() {
return coupon_batch_id_$n;
}
public String getCoupon_id_$n() {
return coupon_id_$n;
}
public String getCoupon_fee_$n() {
return coupon_fee_$n;
}
public String getTransaction_id() {
return transaction_id;
}
public String getOut_trade_no() {
return out_trade_no;
}
public String getAttach() {
return attach;
}
public String getTime_end() {
return time_end;
}
public void setReturn_code(String return_code) {
this.return_code = return_code;
}
public void setReturn_msg(String return_msg) {
this.return_msg = return_msg;
}
public void setAppid(String appid) {
this.appid = appid;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public void setDevice_info(String device_info) {
this.device_info = device_info;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public void setSign(String sign) {
this.sign = sign;
}
public void setResult_code(String result_code) {
this.result_code = result_code;
}
public void setErr_code(String err_code) {
this.err_code = err_code;
}
public void setErr_code_des(String err_code_des) {
this.err_code_des = err_code_des;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public void setIs_subscribe(String is_subscribe) {
this.is_subscribe = is_subscribe;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
public void setBank_type(String bank_type) {
this.bank_type = bank_type;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public void setFee_type(String fee_type) {
this.fee_type = fee_type;
}
public void setCash_fee(String cash_fee) {
this.cash_fee = cash_fee;
}
public void setCash_fee_type(String cash_fee_type) {
this.cash_fee_type = cash_fee_type;
}
public void setCoupon_fee(String coupon_fee) {
this.coupon_fee = coupon_fee;
}
public void setCoupon_count(String coupon_count) {
this.coupon_count = coupon_count;
}
public void setCoupon_batch_id_$n(String coupon_batch_id_$n) {
this.coupon_batch_id_$n = coupon_batch_id_$n;
}
public void setCoupon_id_$n(String coupon_id_$n) {
this.coupon_id_$n = coupon_id_$n;
}
public void setCoupon_fee_$n(String coupon_fee_$n) {
this.coupon_fee_$n = coupon_fee_$n;
}
public void setTransaction_id(String transaction_id) {
this.transaction_id = transaction_id;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public void setAttach(String attach) {
this.attach = attach;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
@Override
public String toString() {
return "WxMpPayCallback [return_code=" + return_code + ", return_msg="
+ return_msg + ", appid=" + appid + ", mch_id=" + mch_id
+ ", device_info=" + device_info + ", nonce_str=" + nonce_str
+ ", sign=" + sign + ", result_code=" + result_code
+ ", err_code=" + err_code + ", err_code_des=" + err_code_des
+ ", openid=" + openid + ", is_subscribe=" + is_subscribe
+ ", trade_type=" + trade_type + ", bank_type=" + bank_type
+ ", total_fee=" + total_fee + ", fee_type=" + fee_type
+ ", cash_fee=" + cash_fee + ", cash_fee_type=" + cash_fee_type
+ ", coupon_fee=" + coupon_fee + ", coupon_count="
+ coupon_count + ", coupon_batch_id_$n=" + coupon_batch_id_$n
+ ", coupon_id_$n=" + coupon_id_$n + ", coupon_fee_$n="
+ coupon_fee_$n + ", transaction_id=" + transaction_id
+ ", out_trade_no=" + out_trade_no + ", attach=" + attach
+ ", time_end=" + time_end + "]";
}
}

View File

@@ -0,0 +1,215 @@
package me.chanjar.weixin.mp.bean.result;
import java.io.Serializable;
/**
* <pre>
* 查询订单支付状态返回的结果
*
* 查询订单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2)
*
* </pre>
*
* @author ukid
*/
public class WxMpPayResult implements Serializable {
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 err_code;
private String err_code_des;
private String trade_state;
private String device_info;
private String openid;
private String is_subscribe;
private String trade_type;
private String bank_type;
private String total_fee;
private String coupon_fee;
private String fee_type;
private String transaction_id;
private String out_trade_no;
private String attach;
private String time_end;
public String getReturn_code() {
return return_code;
}
public String getReturn_msg() {
return return_msg;
}
public String getAppid() {
return appid;
}
public String getMch_id() {
return mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public String getSign() {
return sign;
}
public String getResult_code() {
return result_code;
}
public String getErr_code() {
return err_code;
}
public String getErr_code_des() {
return err_code_des;
}
public String getTrade_state() {
return trade_state;
}
public String getDevice_info() {
return device_info;
}
public String getOpenid() {
return openid;
}
public String getIs_subscribe() {
return is_subscribe;
}
public String getTrade_type() {
return trade_type;
}
public String getBank_type() {
return bank_type;
}
public String getTotal_fee() {
return total_fee;
}
public String getCoupon_fee() {
return coupon_fee;
}
public String getFee_type() {
return fee_type;
}
public String getTransaction_id() {
return transaction_id;
}
public String getOut_trade_no() {
return out_trade_no;
}
public String getAttach() {
return attach;
}
public String getTime_end() {
return time_end;
}
public void setReturn_code(String return_code) {
this.return_code = return_code;
}
public void setReturn_msg(String return_msg) {
this.return_msg = return_msg;
}
public void setAppid(String appid) {
this.appid = appid;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public void setSign(String sign) {
this.sign = sign;
}
public void setResult_code(String result_code) {
this.result_code = result_code;
}
public void setErr_code(String err_code) {
this.err_code = err_code;
}
public void setErr_code_des(String err_code_des) {
this.err_code_des = err_code_des;
}
public void setTrade_state(String trade_state) {
this.trade_state = trade_state;
}
public void setDevice_info(String device_info) {
this.device_info = device_info;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public void setIs_subscribe(String is_subscribe) {
this.is_subscribe = is_subscribe;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
public void setBank_type(String bank_type) {
this.bank_type = bank_type;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public void setCoupon_fee(String coupon_fee) {
this.coupon_fee = coupon_fee;
}
public void setFee_type(String fee_type) {
this.fee_type = fee_type;
}
public void setTransaction_id(String transaction_id) {
this.transaction_id = transaction_id;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public void setAttach(String attach) {
this.attach = attach;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
}

View File

@@ -4,10 +4,9 @@ import java.io.Serializable;
/**
* <pre>
* 群发消息一发送就返回的结果
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
*
* 真正的群发消息是否发送成功要看
* http://mp.weixin.qq.com/wiki/index.php?title=高级群发接口#.E4.BA.8B.E4.BB.B6.E6.8E.A8.E9.80.81.E7.BE.A4.E5.8F.91.E7.BB.93.E6.9E.9C
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
*
* </pre>
*

View File

@@ -23,6 +23,8 @@ public class WxMpUser implements Serializable {
protected Long subscribeTime;
protected String unionId;
protected Integer sexId;
protected String remark;
protected Integer groupId;
public Boolean getSubscribe() {
return subscribe;
@@ -103,6 +105,19 @@ public class WxMpUser implements Serializable {
this.sexId = sexId;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public static WxMpUser fromJson(String json) {
return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUser.class);
}
@@ -121,6 +136,8 @@ public class WxMpUser implements Serializable {
", headImgUrl='" + headImgUrl + '\'' +
", subscribeTime=" + subscribeTime +
", unionId='" + unionId + '\'' +
", remark='" + remark + '\'' +
", groupId='" + groupId + '\'' +
'}';
}
}

View File

@@ -0,0 +1,47 @@
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.RequestExecutor;
import me.chanjar.weixin.common.util.http.Utf8ResponseHandler;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
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.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MaterialDeleteRequestExecutor implements RequestExecutor<Boolean, String> {
public MaterialDeleteRequestExecutor() {
super();
}
public Boolean execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(config);
}
Map<String, String> params = new HashMap<>();
params.put("media_id", materialId);
httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params)));
CloseableHttpResponse response = httpclient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
} else {
return true;
}
}
}

View File

@@ -0,0 +1,48 @@
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.RequestExecutor;
import me.chanjar.weixin.common.util.http.Utf8ResponseHandler;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.mp.bean.WxMpMaterialNews;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
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.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MaterialNewsInfoRequestExecutor implements RequestExecutor<WxMpMaterialNews, String> {
public MaterialNewsInfoRequestExecutor() {
super();
}
public WxMpMaterialNews execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(config);
}
Map<String, String> params = new HashMap<>();
params.put("media_id", materialId);
httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params)));
CloseableHttpResponse response = httpclient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
} else {
return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class);
}
}
}

View File

@@ -0,0 +1,58 @@
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.RequestExecutor;
import me.chanjar.weixin.common.util.http.Utf8ResponseHandler;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.mp.bean.WxMpMaterial;
import me.chanjar.weixin.mp.bean.result.WxMpMaterialUploadResult;
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.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.*;
import java.util.Map;
public class MaterialUploadRequestExecutor implements RequestExecutor<WxMpMaterialUploadResult, WxMpMaterial> {
public WxMpMaterialUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, WxMpMaterial material) throws WxErrorException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(uri);
if (httpProxy != null) {
RequestConfig response = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(response);
}
if (material != null) {
File file = material.getFile();
if (file == null || !file.exists()) {
throw new FileNotFoundException();
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addPart("media", new InputStreamBody(bufferedInputStream, material.getName()));
Map<String, String> form = material.getForm();
if (material.getForm() != null) {
multipartEntityBuilder.addTextBody("description", WxGsonBuilder.create().toJson(form));
}
httpPost.setEntity(multipartEntityBuilder.build());
httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
}
CloseableHttpResponse response = httpclient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
} else {
return WxMpMaterialUploadResult.fromJson(responseContent);
}
}
}

View File

@@ -0,0 +1,47 @@
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.RequestExecutor;
import me.chanjar.weixin.common.util.http.Utf8ResponseHandler;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.mp.bean.result.WxMpMaterialVideoInfoResult;
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.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MaterialVideoInfoRequestExecutor implements RequestExecutor<WxMpMaterialVideoInfoResult, String> {
public MaterialVideoInfoRequestExecutor() {
super();
}
public WxMpMaterialVideoInfoResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(config);
}
Map<String, String> params = new HashMap<>();
params.put("media_id", materialId);
httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params)));
CloseableHttpResponse response = httpclient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
} else {
return WxMpMaterialVideoInfoResult.fromJson(responseContent);
}
}
}

View File

@@ -0,0 +1,65 @@
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 org.apache.commons.io.IOUtils;
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.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;
public class MaterialVoiceAndImageDownloadRequestExecutor implements RequestExecutor<InputStream, String> {
private File tmpDirFile;
public MaterialVoiceAndImageDownloadRequestExecutor() {
super();
}
public MaterialVoiceAndImageDownloadRequestExecutor(File tmpDirFile) {
super();
this.tmpDirFile = tmpDirFile;
}
public InputStream execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(config);
}
Map<String, String> params = new HashMap<>();
params.put("media_id", materialId);
httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params)));
CloseableHttpResponse response = httpclient.execute(httpPost);
// 下载媒体文件出错
InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
byte[] responseContent = IOUtils.toByteArray(inputStream);
String responseContentString = new String(responseContent, "UTF-8");
if (responseContentString.length() < 100) {
try {
WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class);
if (wxError.getErrorCode() != 0) {
throw new WxErrorException(wxError);
}
} catch (com.google.gson.JsonSyntaxException ex) {
return new ByteArrayInputStream(responseContent);
}
}
return new ByteArrayInputStream(responseContent);
}
}

View File

@@ -47,20 +47,21 @@ public class QrCodeRequestExecutor implements RequestExecutor<File, WxMpQrCodeTi
httpGet.setConfig(config);
}
CloseableHttpResponse response = httpclient.execute(httpGet);
Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
// 出错
if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
throw new WxErrorException(WxError.fromJson(responseContent));
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
// 出错
if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
throw new WxErrorException(WxError.fromJson(responseContent));
}
}
InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
File localFile = FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
return localFile;
}
InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
File localFile = FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
return localFile;
}
}

View File

@@ -8,7 +8,7 @@ import me.chanjar.weixin.mp.bean.result.*;
public class WxMpGsonBuilder {
public static final GsonBuilder INSTANCE = new GsonBuilder();
static {
INSTANCE.disableHtmlEscaping();
INSTANCE.registerTypeAdapter(WxMpCustomMessage.class, new WxMpCustomMessageGsonAdapter());
@@ -27,10 +27,21 @@ public class WxMpGsonBuilder {
INSTANCE.registerTypeAdapter(WxMpOAuth2AccessToken.class, new WxMpOAuth2AccessTokenAdapter());
INSTANCE.registerTypeAdapter(WxMpUserSummary.class, new WxMpUserSummaryGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpUserCumulate.class, new WxMpUserCumulateGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialUploadResult.class, new WxMpMaterialUploadResultAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialVideoInfoResult.class, new WxMpMaterialVideoInfoResultAdapter());
INSTANCE.registerTypeAdapter(WxMpMassNews.WxMpMassNewsArticle.class, new WxMpMassNewsArticleGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialArticleUpdate.class, new WxMpMaterialArticleUpdateGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialCountResult.class, new WxMpMaterialCountResultAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialNews.class, new WxMpMaterialNewsGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialNews.WxMpMaterialNewsArticle.class, new WxMpMaterialNewsArticleGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialNewsBatchGetResult.class, new WxMpMaterialNewsBatchGetGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem.class, new WxMpMaterialNewsBatchGetGsonItemAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialFileBatchGetResult.class, new WxMpMaterialFileBatchGetGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem.class, new WxMpMaterialFileBatchGetGsonItemAdapter());
}
public static Gson create() {
return INSTANCE.create();
}
}

View File

@@ -0,0 +1,72 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
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.WxMpMassNews;
import java.lang.reflect.Type;
public class WxMpMassNewsArticleGsonAdapter implements JsonSerializer<WxMpMassNews.WxMpMassNewsArticle>, JsonDeserializer<WxMpMassNews.WxMpMassNewsArticle> {
public JsonElement serialize(WxMpMassNews.WxMpMassNewsArticle article, Type typeOfSrc, JsonSerializationContext context) {
JsonObject articleJson = new JsonObject();
articleJson.addProperty("thumb_media_id", article.getThumbMediaId());
articleJson.addProperty("title", article.getTitle());
articleJson.addProperty("content", article.getContent());
if (null != article.getAuthor()) {
articleJson.addProperty("author", article.getAuthor());
}
if (null != article.getContentSourceUrl()) {
articleJson.addProperty("content_source_url", article.getContentSourceUrl());
}
if (null != article.getDigest()) {
articleJson.addProperty("digest", article.getDigest());
}
articleJson.addProperty("show_cover_pic", article.isShowCoverPic() ? "1" : "0");
return articleJson;
}
public WxMpMassNews.WxMpMassNewsArticle deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject articleInfo = jsonElement.getAsJsonObject();
WxMpMassNews.WxMpMassNewsArticle article = new WxMpMassNews.WxMpMassNewsArticle();
JsonElement title = articleInfo.get("title");
if (title != null && !title.isJsonNull()) {
article.setTitle(GsonHelper.getAsString(title));
}
JsonElement content = articleInfo.get("content");
if (content != null && !content.isJsonNull()) {
article.setContent(GsonHelper.getAsString(content));
}
JsonElement contentSourceUrl = articleInfo.get("content_source_url");
if (contentSourceUrl != null && !contentSourceUrl.isJsonNull()) {
article.setContentSourceUrl(GsonHelper.getAsString(contentSourceUrl));
}
JsonElement author = articleInfo.get("author");
if (author != null && !author.isJsonNull()) {
article.setAuthor(GsonHelper.getAsString(author));
}
JsonElement digest = articleInfo.get("digest");
if (digest != null && !digest.isJsonNull()) {
article.setDigest(GsonHelper.getAsString(digest));
}
JsonElement thumbMediaId = articleInfo.get("thumb_media_id");
if (thumbMediaId != null && !thumbMediaId.isJsonNull()) {
article.setThumbMediaId(GsonHelper.getAsString(thumbMediaId));
}
JsonElement showCoverPic = articleInfo.get("show_cover_pic");
if (showCoverPic != null && !showCoverPic.isJsonNull()) {
article.setShowCoverPic(GsonHelper.getAsBoolean(showCoverPic));
}
return article;
}
}

View File

@@ -13,33 +13,32 @@ import me.chanjar.weixin.mp.bean.WxMpMassNews;
import java.lang.reflect.Type;
public class WxMpMassNewsGsonAdapter implements JsonSerializer<WxMpMassNews> {
public class WxMpMassNewsGsonAdapter implements JsonSerializer<WxMpMassNews>, JsonDeserializer<WxMpMassNews> {
public JsonElement serialize(WxMpMassNews message, Type typeOfSrc, JsonSerializationContext context) {
JsonObject newsJson = new JsonObject();
JsonArray articleJsonArray = new JsonArray();
for (WxMpMassNews.WxMpMassNewsArticle article : message.getArticles()) {
JsonObject articleJson = new JsonObject();
articleJson.addProperty("thumb_media_id", article.getThumbMediaId());
articleJson.addProperty("title", article.getTitle());
articleJson.addProperty("content", article.getContent());
if (null != article.getAuthor()) {
articleJson.addProperty("author", article.getAuthor());
}
if (null != article.getContentSourceUrl()) {
articleJson.addProperty("content_source_url", article.getContentSourceUrl());
}
if (null != article.getDigest()) {
articleJson.addProperty("digest", article.getDigest());
}
articleJson.addProperty("show_cover_pic", article.isShowCoverPic() ? "1" : "0");
JsonObject articleJson = WxMpGsonBuilder.create().toJsonTree(article, WxMpMassNews.WxMpMassNewsArticle.class).getAsJsonObject();
articleJsonArray.add(articleJson);
}
newsJson.add("articles", articleJsonArray);
return newsJson;
}
public WxMpMassNews deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
WxMpMassNews wxMpMassNews = new WxMpMassNews();
JsonObject json = jsonElement.getAsJsonObject();
if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) {
JsonArray articles = json.getAsJsonArray("articles");
for (JsonElement article1 : articles) {
JsonObject articleInfo = article1.getAsJsonObject();
WxMpMassNews.WxMpMassNewsArticle article = WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMassNews.WxMpMassNewsArticle.class);
wxMpMassNews.addArticle(article);
}
}
return wxMpMassNews;
}
}

View File

@@ -0,0 +1,30 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
package me.chanjar.weixin.mp.util.json;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import me.chanjar.weixin.mp.bean.WxMpMaterialArticleUpdate;
import me.chanjar.weixin.mp.bean.WxMpMaterialNews;
import java.lang.reflect.Type;
public class WxMpMaterialArticleUpdateGsonAdapter implements JsonSerializer<WxMpMaterialArticleUpdate> {
public JsonElement serialize(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate, Type typeOfSrc, JsonSerializationContext context) {
JsonObject articleUpdateJson = new JsonObject();
articleUpdateJson.addProperty("media_id", wxMpMaterialArticleUpdate.getMediaId());
articleUpdateJson.addProperty("index", wxMpMaterialArticleUpdate.getIndex());
articleUpdateJson.add("articles", WxMpGsonBuilder.create().toJsonTree(wxMpMaterialArticleUpdate.getArticles(), WxMpMaterialNews.WxMpMaterialNewsArticle.class));
return articleUpdateJson;
}
}

View File

@@ -0,0 +1,41 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
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.result.WxMpMaterialCountResult;
import java.lang.reflect.Type;
/**
* @author codepiano
*/
public class WxMpMaterialCountResultAdapter implements JsonDeserializer<WxMpMaterialCountResult> {
public WxMpMaterialCountResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
WxMpMaterialCountResult countResult = new WxMpMaterialCountResult();
JsonObject materialCountResultJsonObject = json.getAsJsonObject();
if (materialCountResultJsonObject.get("voice_count") != null && !materialCountResultJsonObject.get("voice_count").isJsonNull()) {
countResult.setVoiceCount(GsonHelper.getAsInteger(materialCountResultJsonObject.get("voice_count")));
}
if (materialCountResultJsonObject.get("video_count") != null && !materialCountResultJsonObject.get("video_count").isJsonNull()) {
countResult.setVideoCount(GsonHelper.getAsInteger(materialCountResultJsonObject.get("video_count")));
}
if (materialCountResultJsonObject.get("image_count") != null && !materialCountResultJsonObject.get("image_count").isJsonNull()) {
countResult.setImageCount(GsonHelper.getAsInteger(materialCountResultJsonObject.get("image_count")));
}
if (materialCountResultJsonObject.get("news_count") != null && !materialCountResultJsonObject.get("news_count").isJsonNull()) {
countResult.setNewsCount(GsonHelper.getAsInteger(materialCountResultJsonObject.get("news_count")));
}
return countResult;
}
}

View File

@@ -0,0 +1,41 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
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.result.WxMpMaterialFileBatchGetResult;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class WxMpMaterialFileBatchGetGsonAdapter implements JsonDeserializer<WxMpMaterialFileBatchGetResult> {
public WxMpMaterialFileBatchGetResult deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
WxMpMaterialFileBatchGetResult wxMpMaterialFileBatchGetResult = new WxMpMaterialFileBatchGetResult();
JsonObject json = jsonElement.getAsJsonObject();
if (json.get("total_count") != null && !json.get("total_count").isJsonNull()) {
wxMpMaterialFileBatchGetResult.setTotalCount(GsonHelper.getAsInteger(json.get("total_count")));
}
if (json.get("item_count") != null && !json.get("item_count").isJsonNull()) {
wxMpMaterialFileBatchGetResult.setItemCount(GsonHelper.getAsInteger(json.get("item_count")));
}
if (json.get("item") != null && !json.get("item").isJsonNull()) {
JsonArray item = json.getAsJsonArray("item");
List<WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem> items = new ArrayList<>();
for (JsonElement anItem : item) {
JsonObject articleInfo = anItem.getAsJsonObject();
items.add(WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem.class));
}
wxMpMaterialFileBatchGetResult.setItems(items);
}
return wxMpMaterialFileBatchGetResult;
}
}

View File

@@ -0,0 +1,37 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
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.result.WxMpMaterialFileBatchGetResult;
import java.lang.reflect.Type;
import java.util.Date;
public class WxMpMaterialFileBatchGetGsonItemAdapter implements JsonDeserializer<WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem> {
public WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem wxMaterialFileBatchGetNewsItem = new WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem();
JsonObject json = jsonElement.getAsJsonObject();
if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) {
wxMaterialFileBatchGetNewsItem.setMediaId(GsonHelper.getAsString(json.get("media_id")));
}
if (json.get("update_time") != null && !json.get("update_time").isJsonNull()) {
wxMaterialFileBatchGetNewsItem.setUpdateTime(new Date(1000 * GsonHelper.getAsLong(json.get("update_time"))));
}
if (json.get("name") != null && !json.get("name").isJsonNull()) {
wxMaterialFileBatchGetNewsItem.setName(GsonHelper.getAsString(json.get("name")));
}
if (json.get("url") != null && !json.get("url").isJsonNull()) {
wxMaterialFileBatchGetNewsItem.setUrl(GsonHelper.getAsString(json.get("url")));
}
return wxMaterialFileBatchGetNewsItem;
}
}

View File

@@ -0,0 +1,79 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
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.WxMpMaterialNews;
import java.lang.reflect.Type;
public class WxMpMaterialNewsArticleGsonAdapter implements JsonSerializer<WxMpMaterialNews.WxMpMaterialNewsArticle>, JsonDeserializer<WxMpMaterialNews.WxMpMaterialNewsArticle> {
public JsonElement serialize(WxMpMaterialNews.WxMpMaterialNewsArticle article, Type typeOfSrc, JsonSerializationContext context) {
JsonObject articleJson = new JsonObject();
articleJson.addProperty("thumb_media_id", article.getThumbMediaId());
articleJson.addProperty("title", article.getTitle());
articleJson.addProperty("content", article.getContent());
if (null != article.getAuthor()) {
articleJson.addProperty("author", article.getAuthor());
}
if (null != article.getContentSourceUrl()) {
articleJson.addProperty("content_source_url", article.getContentSourceUrl());
}
if (null != article.getDigest()) {
articleJson.addProperty("digest", article.getDigest());
}
articleJson.addProperty("show_cover_pic", article.isShowCoverPic() ? "1" : "0");
if (null != article.getUrl()) {
articleJson.addProperty("url", article.getUrl());
}
return articleJson;
}
public WxMpMaterialNews.WxMpMaterialNewsArticle deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject articleInfo = jsonElement.getAsJsonObject();
WxMpMaterialNews.WxMpMaterialNewsArticle article = new WxMpMaterialNews.WxMpMaterialNewsArticle();
JsonElement title = articleInfo.get("title");
if (title != null && !title.isJsonNull()) {
article.setTitle(GsonHelper.getAsString(title));
}
JsonElement content = articleInfo.get("content");
if (content != null && !content.isJsonNull()) {
article.setContent(GsonHelper.getAsString(content));
}
JsonElement contentSourceUrl = articleInfo.get("content_source_url");
if (contentSourceUrl != null && !contentSourceUrl.isJsonNull()) {
article.setContentSourceUrl(GsonHelper.getAsString(contentSourceUrl));
}
JsonElement author = articleInfo.get("author");
if (author != null && !author.isJsonNull()) {
article.setAuthor(GsonHelper.getAsString(author));
}
JsonElement digest = articleInfo.get("digest");
if (digest != null && !digest.isJsonNull()) {
article.setDigest(GsonHelper.getAsString(digest));
}
JsonElement thumbMediaId = articleInfo.get("thumb_media_id");
if (thumbMediaId != null && !thumbMediaId.isJsonNull()) {
article.setThumbMediaId(GsonHelper.getAsString(thumbMediaId));
}
JsonElement showCoverPic = articleInfo.get("show_cover_pic");
if (showCoverPic != null && !showCoverPic.isJsonNull()) {
article.setShowCoverPic(GsonHelper.getAsBoolean(showCoverPic));
}
JsonElement url = articleInfo.get("url");
if (url != null && !url.isJsonNull()) {
article.setUrl(GsonHelper.getAsString(url));
}
return article;
}
}

View File

@@ -0,0 +1,41 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
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.result.WxMpMaterialNewsBatchGetResult;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class WxMpMaterialNewsBatchGetGsonAdapter implements JsonDeserializer<WxMpMaterialNewsBatchGetResult> {
public WxMpMaterialNewsBatchGetResult deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = new WxMpMaterialNewsBatchGetResult();
JsonObject json = jsonElement.getAsJsonObject();
if (json.get("total_count") != null && !json.get("total_count").isJsonNull()) {
wxMpMaterialNewsBatchGetResult.setTotalCount(GsonHelper.getAsInteger(json.get("total_count")));
}
if (json.get("item_count") != null && !json.get("item_count").isJsonNull()) {
wxMpMaterialNewsBatchGetResult.setItemCount(GsonHelper.getAsInteger(json.get("item_count")));
}
if (json.get("item") != null && !json.get("item").isJsonNull()) {
JsonArray item = json.getAsJsonArray("item");
List<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem> items = new ArrayList<>();
for (JsonElement anItem : item) {
JsonObject articleInfo = anItem.getAsJsonObject();
items.add(WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem.class));
}
wxMpMaterialNewsBatchGetResult.setItems(items);
}
return wxMpMaterialNewsBatchGetResult;
}
}

View File

@@ -0,0 +1,36 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
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.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.result.WxMpMaterialNewsBatchGetResult;
import java.lang.reflect.Type;
import java.util.Date;
public class WxMpMaterialNewsBatchGetGsonItemAdapter implements JsonDeserializer<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem> {
public WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem wxMaterialNewsBatchGetNewsItem = new WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem();
JsonObject json = jsonElement.getAsJsonObject();
if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) {
wxMaterialNewsBatchGetNewsItem.setMediaId(GsonHelper.getAsString(json.get("media_id")));
}
if (json.get("update_time") != null && !json.get("update_time").isJsonNull()) {
wxMaterialNewsBatchGetNewsItem.setUpdateTime(new Date(1000 * GsonHelper.getAsLong(json.get("update_time"))));
}
if (json.get("content") != null && !json.get("content").isJsonNull()) {
JsonObject newsItem = json.getAsJsonObject("content");
wxMaterialNewsBatchGetNewsItem.setContent(WxMpGsonBuilder.create().fromJson(newsItem, WxMpMaterialNews.class));
}
return wxMaterialNewsBatchGetNewsItem;
}
}

View File

@@ -0,0 +1,44 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
package me.chanjar.weixin.mp.util.json;
import com.google.gson.*;
import me.chanjar.weixin.mp.bean.WxMpMaterialNews;
import java.lang.reflect.Type;
public class WxMpMaterialNewsGsonAdapter implements JsonSerializer<WxMpMaterialNews>, JsonDeserializer<WxMpMaterialNews> {
public JsonElement serialize(WxMpMaterialNews wxMpMaterialNews, Type typeOfSrc, JsonSerializationContext context) {
JsonObject newsJson = new JsonObject();
JsonArray articleJsonArray = new JsonArray();
for (WxMpMaterialNews.WxMpMaterialNewsArticle article : wxMpMaterialNews.getArticles()) {
JsonObject articleJson = WxMpGsonBuilder.create().toJsonTree(article, WxMpMaterialNews.WxMpMaterialNewsArticle.class).getAsJsonObject();
articleJsonArray.add(articleJson);
}
newsJson.add("articles", articleJsonArray);
return newsJson;
}
public WxMpMaterialNews deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
WxMpMaterialNews wxMpMaterialNews = new WxMpMaterialNews();
JsonObject json = jsonElement.getAsJsonObject();
if (json.get("news_item") != null && !json.get("news_item").isJsonNull()) {
JsonArray articles = json.getAsJsonArray("news_item");
for (JsonElement article1 : articles) {
JsonObject articleInfo = article1.getAsJsonObject();
WxMpMaterialNews.WxMpMaterialNewsArticle article = WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMaterialNews.WxMpMaterialNewsArticle.class);
wxMpMaterialNews.addArticle(article);
}
}
return wxMpMaterialNews;
}
}

View File

@@ -0,0 +1,35 @@
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
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.result.WxMpMaterialUploadResult;
import java.lang.reflect.Type;
/**
* @author codepiano
*/
public class WxMpMaterialUploadResultAdapter implements JsonDeserializer<WxMpMaterialUploadResult> {
public WxMpMaterialUploadResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
WxMpMaterialUploadResult uploadResult = new WxMpMaterialUploadResult();
JsonObject uploadResultJsonObject = json.getAsJsonObject();
if (uploadResultJsonObject.get("url") != null && !uploadResultJsonObject.get("url").isJsonNull()) {
uploadResult.setUrl(GsonHelper.getAsString(uploadResultJsonObject.get("url")));
}
if (uploadResultJsonObject.get("media_id") != null && !uploadResultJsonObject.get("media_id").isJsonNull()) {
uploadResult.setMediaId(GsonHelper.getAsString(uploadResultJsonObject.get("media_id")));
}
return uploadResult;
}
}

View File

@@ -0,0 +1,30 @@
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.result.WxMpMaterialVideoInfoResult;
import java.lang.reflect.Type;
/**
* @author codepiano
*/
public class WxMpMaterialVideoInfoResultAdapter implements JsonDeserializer<WxMpMaterialVideoInfoResult> {
public WxMpMaterialVideoInfoResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
WxMpMaterialVideoInfoResult uploadResult = new WxMpMaterialVideoInfoResult();
JsonObject uploadResultJsonObject = json.getAsJsonObject();
if (uploadResultJsonObject.get("title") != null && !uploadResultJsonObject.get("title").isJsonNull()) {
uploadResult.setTitle(GsonHelper.getAsString(uploadResultJsonObject.get("title")));
}
if (uploadResultJsonObject.get("description") != null && !uploadResultJsonObject.get("description").isJsonNull()) {
uploadResult.setDescription(GsonHelper.getAsString(uploadResultJsonObject.get("description")));
}
if (uploadResultJsonObject.get("down_url") != null && !uploadResultJsonObject.get("down_url").isJsonNull()) {
uploadResult.setDownUrl(GsonHelper.getAsString(uploadResultJsonObject.get("down_url")));
}
return uploadResult;
}
}

View File

@@ -30,6 +30,8 @@ public class WxMpUserGsonAdapter implements JsonDeserializer<WxMpUser> {
wxMpUser.setSubscribeTime(GsonHelper.getLong(o, "subscribe_time"));
wxMpUser.setUnionId(GsonHelper.getString(o, "unionid"));
Integer sexId = GsonHelper.getInteger(o, "sex");
wxMpUser.setRemark(GsonHelper.getString(o, "remark"));
wxMpUser.setGroupId(GsonHelper.getInteger(o, "groupid"));
wxMpUser.setSexId(sexId);
if(new Integer(1).equals(sexId)) {
wxMpUser.setSex("");

View File

@@ -0,0 +1,237 @@
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.common.util.fs.FileUtils;
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.*;
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 java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* 测试多媒体文件上传下载
*
* @author codepiano
*/
@Test(groups = "materialAPI")
@Guice(modules = ApiTestModule.class)
public class WxMpMaterialAPITest {
@Inject
protected WxMpServiceImpl wxService;
private Map<String, Map<String, Object>> media_ids = new LinkedHashMap<>();
// 缩略图的id测试上传图文使用
private String thumbMediaId = "";
// 单图文消息media_id
private String singleNewsMediaId = "";
// 多图文消息media_id
private String multiNewsMediaId = "";
// 先查询保存测试开始前永久素材数据
private WxMpMaterialCountResult wxMaterialCountResultBeforeTest;
@Test(dataProvider = "uploadMaterial")
public void testUploadMaterial(String mediaType, String fileType, String fileName) throws WxErrorException, IOException {
if (wxMaterialCountResultBeforeTest == null) {
wxMaterialCountResultBeforeTest = wxService.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 = wxService.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();
}
Map<String, Object> 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);
}
@Test(dependsOnMethods = {"testUploadMaterial"})
public void testAddNews() throws WxErrorException {
// 单图文消息
WxMpMaterialNews wxMpMaterialNewsSingle = new WxMpMaterialNews();
WxMpMaterialNews.WxMpMaterialNewsArticle mpMaterialNewsArticleSingle = new WxMpMaterialNews.WxMpMaterialNewsArticle();
mpMaterialNewsArticleSingle.setAuthor("author");
mpMaterialNewsArticleSingle.setThumbMediaId(thumbMediaId);
mpMaterialNewsArticleSingle.setTitle("single title");
mpMaterialNewsArticleSingle.setContent("single content");
mpMaterialNewsArticleSingle.setContentSourceUrl("content url");
mpMaterialNewsArticleSingle.setShowCoverPic(true);
mpMaterialNewsArticleSingle.setDigest("single news");
wxMpMaterialNewsSingle.addArticle(mpMaterialNewsArticleSingle);
// 多图文消息
WxMpMaterialNews wxMpMaterialNewsMultiple = new WxMpMaterialNews();
WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticleMutiple1 = new WxMpMaterialNews.WxMpMaterialNewsArticle();
wxMpMaterialNewsArticleMutiple1.setAuthor("author1");
wxMpMaterialNewsArticleMutiple1.setThumbMediaId(thumbMediaId);
wxMpMaterialNewsArticleMutiple1.setTitle("multi title1");
wxMpMaterialNewsArticleMutiple1.setContent("content 1");
wxMpMaterialNewsArticleMutiple1.setContentSourceUrl("content url");
wxMpMaterialNewsArticleMutiple1.setShowCoverPic(true);
wxMpMaterialNewsArticleMutiple1.setDigest("");
WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticleMultiple2 = new WxMpMaterialNews.WxMpMaterialNewsArticle();
wxMpMaterialNewsArticleMultiple2.setAuthor("author2");
wxMpMaterialNewsArticleMultiple2.setThumbMediaId(thumbMediaId);
wxMpMaterialNewsArticleMultiple2.setTitle("multi title2");
wxMpMaterialNewsArticleMultiple2.setContent("content 2");
wxMpMaterialNewsArticleMultiple2.setContentSourceUrl("content url");
wxMpMaterialNewsArticleMultiple2.setShowCoverPic(true);
wxMpMaterialNewsArticleMultiple2.setDigest("");
wxMpMaterialNewsMultiple.addArticle(wxMpMaterialNewsArticleMutiple1);
wxMpMaterialNewsMultiple.addArticle(wxMpMaterialNewsArticleMultiple2);
WxMpMaterialUploadResult resSingle = wxService.materialNewsUpload(wxMpMaterialNewsSingle);
singleNewsMediaId = resSingle.getMediaId();
WxMpMaterialUploadResult resMulti = wxService.materialNewsUpload(wxMpMaterialNewsMultiple);
multiNewsMediaId = resMulti.getMediaId();
}
@Test(dependsOnMethods = {"testAddNews"})
public void testMaterialCount() throws WxErrorException {
WxMpMaterialCountResult wxMaterialCountResult = wxService.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());
}
@DataProvider
public Object[][] uploadMaterial() {
return new Object[][]{
new Object[]{WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, "mm.jpeg"},
new Object[]{WxConsts.MEDIA_VOICE, WxConsts.FILE_MP3, "mm.mp3"},
new Object[]{WxConsts.MEDIA_VIDEO, WxConsts.FILE_MP4, "mm.mp4"},
new Object[]{WxConsts.MEDIA_THUMB, WxConsts.FILE_JPG, "mm.jpeg"}
};
}
@Test(dependsOnMethods = {"testMaterialCount"}, dataProvider = "downloadMaterial")
public void testDownloadMaterial(String media_id) throws WxErrorException, IOException {
Map<String, Object> materialInfo = media_ids.get(media_id);
Assert.assertNotNull(materialInfo);
String filename = materialInfo.get("filename").toString();
if (filename.endsWith(".mp3") || filename.endsWith(".jpeg")) {
InputStream inputStream = wxService.materialImageOrVoiceDownload(media_id);
Assert.assertNotNull(inputStream);
IOUtils.closeQuietly(inputStream);
}
if (filename.endsWith("mp4")) {
WxMpMaterialVideoInfoResult wxMaterialVideoInfoResult = wxService.materialVideoInfo(media_id);
Assert.assertNotNull(wxMaterialVideoInfoResult);
Assert.assertNotNull(wxMaterialVideoInfoResult.getDownUrl());
}
}
@Test(dependsOnMethods = {"testAddNews"})
public void testGetNewsInfo() throws WxErrorException {
WxMpMaterialNews wxMpMaterialNewsSingle = wxService.materialNewsInfo(singleNewsMediaId);
WxMpMaterialNews wxMpMaterialNewsMultiple = wxService.materialNewsInfo(multiNewsMediaId);
Assert.assertNotNull(wxMpMaterialNewsSingle);
Assert.assertNotNull(wxMpMaterialNewsMultiple);
}
@Test(dependsOnMethods = {"testGetNewsInfo"})
public void testUpdateNewsInfo() throws WxErrorException {
WxMpMaterialNews wxMpMaterialNewsSingle = wxService.materialNewsInfo(singleNewsMediaId);
Assert.assertNotNull(wxMpMaterialNewsSingle);
WxMpMaterialArticleUpdate wxMpMaterialArticleUpdateSingle = new WxMpMaterialArticleUpdate();
WxMpMaterialNews.WxMpMaterialNewsArticle articleSingle = wxMpMaterialNewsSingle.getArticles().get(0);
articleSingle.setContent("content single update");
wxMpMaterialArticleUpdateSingle.setMediaId(singleNewsMediaId);
wxMpMaterialArticleUpdateSingle.setArticles(articleSingle);
wxMpMaterialArticleUpdateSingle.setIndex(0);
boolean resultSingle = wxService.materialNewsUpdate(wxMpMaterialArticleUpdateSingle);
Assert.assertTrue(resultSingle);
wxMpMaterialNewsSingle = wxService.materialNewsInfo(singleNewsMediaId);
Assert.assertNotNull(wxMpMaterialNewsSingle);
Assert.assertEquals("content single update", wxMpMaterialNewsSingle.getArticles().get(0).getContent());
WxMpMaterialNews wxMpMaterialNewsMultiple = wxService.materialNewsInfo(multiNewsMediaId);
Assert.assertNotNull(wxMpMaterialNewsMultiple);
WxMpMaterialArticleUpdate wxMpMaterialArticleUpdateMulti = new WxMpMaterialArticleUpdate();
WxMpMaterialNews.WxMpMaterialNewsArticle articleMulti = wxMpMaterialNewsMultiple.getArticles().get(1);
articleMulti.setContent("content 2 update");
wxMpMaterialArticleUpdateMulti.setMediaId(multiNewsMediaId);
wxMpMaterialArticleUpdateMulti.setArticles(articleMulti);
wxMpMaterialArticleUpdateMulti.setIndex(1);
boolean resultMulti = wxService.materialNewsUpdate(wxMpMaterialArticleUpdateMulti);
Assert.assertTrue(resultMulti);
wxMpMaterialNewsMultiple = wxService.materialNewsInfo(multiNewsMediaId);
Assert.assertNotNull(wxMpMaterialNewsMultiple);
Assert.assertEquals("content 2 update", wxMpMaterialNewsMultiple.getArticles().get(1).getContent());
}
@Test(dependsOnMethods = {"testUpdateNewsInfo"})
public void testMaterialNewsList() throws WxErrorException {
WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = wxService.materialNewsBatchGet(0, 20);
return;
}
@Test(dependsOnMethods = {"testMaterialNewsList"})
public void testMaterialFileList() throws WxErrorException {
WxMpMaterialFileBatchGetResult wxMpMaterialVoiceBatchGetResult = wxService.materialFileBatchGet(WxConsts.MATERIAL_VOICE, 0, 20);
WxMpMaterialFileBatchGetResult wxMpMaterialVideoBatchGetResult = wxService.materialFileBatchGet(WxConsts.MATERIAL_VIDEO, 0, 20);
WxMpMaterialFileBatchGetResult wxMpMaterialImageBatchGetResult = wxService.materialFileBatchGet(WxConsts.MATERIAL_IMAGE, 0, 20);
return;
}
@Test(dependsOnMethods = {"testMaterialFileList"}, dataProvider = "allTestMaterial")
public void testDeleteMaterial(String mediaId) throws WxErrorException {
boolean result = wxService.materialDelete(mediaId);
Assert.assertTrue(result);
}
@DataProvider
public Object[][] downloadMaterial() {
Object[][] params = new Object[this.media_ids.size()][];
int index = 0;
for (String mediaId : this.media_ids.keySet()) {
params[index] = new Object[]{mediaId};
index++;
}
return params;
}
@DataProvider
public Iterator<Object[]> allTestMaterial() {
List<Object[]> params = new ArrayList<>();
for (String mediaId : this.media_ids.keySet()) {
params.add(new Object[]{mediaId});
}
params.add(new Object[]{this.singleNewsMediaId});
params.add(new Object[]{this.multiNewsMediaId});
return params.iterator();
}
}