42 Commits

Author SHA1 Message Date
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
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
42418a2d0d upgrade to version 1.1.8 2015-07-17 15:30:20 +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
f30211ce98 upgrade version 1.1.8-SNAPSHOT 2015-07-10 14:03:37 +08:00
Daniel Qian
6239abcbcc update 2015-07-10 13:59:28 +08:00
Daniel Qian
1ade007250 upgrade to 1.1.7 2015-07-10 13:57:40 +08:00
Daniel Qian
ee2cf21efc fix: issue #163 2015-07-02 09:40:12 +08:00
Daniel Qian
d707140d06 upgrade to 1.1.7-SNAPSHOT 2015-06-26 16:40:07 +08:00
Daniel Qian
825393dd9a Merge branch 'develop' 2015-06-26 16:38:30 +08:00
Daniel Qian
0491e23456 upgrade to 1.1.6 2015-06-26 16:38:08 +08:00
Daniel Qian
4da9ea5dd5 Merge pull request #155 from huansinho/master
临时文件目录配置
2015-06-15 13:04:50 +08:00
huansinho
f107bd2f44 增加临时文件目录配置
在下载多媒体文件下载时可以指定临时文件目录。
2015-06-14 02:37:31 +08:00
huansinho
50949b1ff5 增加忽略eclipse本地配置文件目录 2015-06-14 01:16:20 +08:00
Daniel Qian
bb22974d65 Merge pull request #151 from darknesstm/develop
统一使用getHttpClient
2015-06-03 15:51:22 +08:00
darknesstm
622094bcdf 统一使用getHttpClient,使得可以复用httpClient 2015-06-03 15:39:06 +08:00
Daniel Qian
bd3fb69bef update to 1.1.6-SNAPSHOT 2015-05-27 09:18:06 +08:00
Daniel Qian
f0432e6930 Merge branch 'develop' 2015-05-27 09:16:23 +08:00
Daniel Qian
72db0a2a76 update to 1.1.5 2015-05-27 09:15:57 +08:00
Daniel Qian
f7b5b52808 fix: compile error 2015-05-14 08:51:50 +08:00
Daniel Qian
ab916ddd71 issue #138 tagAddUsers 接口少了一个参数 2015-05-13 19:47:50 +08:00
Daniel Qian
29cc3f6558 format 2015-04-30 15:39:35 +08:00
Daniel Qian
214b969f4d Merge pull request #135 from oohusl/develop
公众号支付 @oohusl
2015-04-30 15:32:13 +08:00
oohusl
5aba724633 公众号支付 2015-04-29 20:34:26 +08:00
Daniel Qian
b3110991a7 Merge pull request #131 from dxwts/develop
修改文件类型arm为amr
2015-04-24 16:40:38 +08:00
dxw
fcd3a9d76b 修改文件类型arm为amr 2015-04-24 16:38:51 +08:00
Daniel Qian
ffc0fc442d upgrade to 1.1.5-SNAPSHOT 2015-04-16 14:19:47 +08:00
Daniel Qian
6f3dfc7740 Merge branch 'develop' 2015-04-16 14:18:54 +08:00
Daniel Qian
e84ca8dab9 Merge branch 'develop' 2015-03-23 11:09:32 +08:00
Daniel Qian
eccbf08809 Merge branch 'develop'
Conflicts:
	README.md
2015-03-23 11:07:58 +08:00
Daniel Qian
b2179faf3e fix README 2015-02-26 15:10:33 +08:00
Daniel Qian
0cd6033205 Merge branch 'develop' 2015-02-25 15:33:17 +08:00
56 changed files with 2262 additions and 188 deletions

44
.gitignore vendored
View File

@@ -1,21 +1,23 @@
*.class
test-output
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
target
.project
.classpath
sw-pom.xml
*.iml
test-config.xml
*.class
test-output
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
target
.project
.classpath
.settings
sw-pom.xml
*.iml
test-config.xml
.idea

View File

@@ -17,7 +17,7 @@ weixin-java-tools
<dependency>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>1.1.4</version>
<version>1.2.0</version>
</dependency>
```
@@ -27,7 +27,7 @@ weixin-java-tools
<dependency>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-cp</artifactId>
<version>1.1.4</version>
<version>1.2.0</version>
</dependency>
```

12
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.4</version>
<version>1.2.0</version>
<packaging>pom</packaging>
<name>WeiXin Java Tools - Parent</name>
<description>微信公众号、企业号上级POM</description>
@@ -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.4</version>
<version>1.2.0</version>
</parent>
<artifactId>weixin-java-common</artifactId>

View File

@@ -105,7 +105,7 @@ public class WxConsts {
///////////////////////
public static final String FILE_JPG = "jpeg";
public static final String FILE_MP3 = "mp3";
public static final String FILE_ARM = "arm";
public static final String FILE_AMR = "amr";
public static final String FILE_MP4 = "mp4";
@@ -137,4 +137,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

@@ -1,5 +1,7 @@
package me.chanjar.weixin.common.util.crypto;
import org.apache.commons.codec.digest.DigestUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
@@ -21,7 +23,7 @@ public class SHA1 {
for (String a : arr) {
sb.append(a);
}
return genStr(sb.toString());
return DigestUtils.sha1Hex(sb.toString());
}
/**
@@ -40,25 +42,6 @@ public class SHA1 {
sb.append('&');
}
}
return genStr(sb.toString());
return DigestUtils.sha1Hex(sb.toString());
}
public static String genStr(String str) throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.update(str.getBytes());
byte[] output = sha1.digest();
return bytesToHex(output);
}
protected static String bytesToHex(byte[] b) {
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
StringBuffer buf = new StringBuffer();
for (int j = 0; j < b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]);
}
return buf.toString();
}
}
}

View File

@@ -14,6 +14,7 @@
package me.chanjar.weixin.common.util.crypto;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
@@ -27,8 +28,7 @@ import javax.xml.parsers.ParserConfigurationException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;
import java.util.*;
public class WxCryptUtil {
@@ -224,6 +224,36 @@ public class WxCryptUtil {
}
/**
* 微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3)
* @param packageParams 原始参数
* @param signKey 加密Key(即 商户Key)
* @param charset 编码
* @return 签名字符串
*/
public static String createSign(Map<String, String> packageParams, String signKey) {
SortedMap<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.putAll(packageParams);
List<String> keys = new ArrayList<String>(packageParams.keySet());
Collections.sort(keys);
StringBuffer toSign = new StringBuffer();
for (String key : keys) {
String value = packageParams.get(key);
if (null != value && !"".equals(value) && !"sign".equals(key)
&& !"key".equals(key)) {
toSign.append(key + "=" + value + "&");
}
}
toSign.append("key=" + signKey);
System.out.println(toSign.toString());
String sign = DigestUtils.md5Hex(toSign.toString())
.toUpperCase();
return sign;
}
/**
* 将一个数字转换成生成4个字节的网络字节序bytes数组
*

View File

@@ -7,18 +7,25 @@ import java.io.InputStream;
public class FileUtils {
/**
* 创建临时文件
* @param inputStream
* @param name 文件名
* @param ext 扩展名
* @param tmpDirFile 临时文件夹目录
* @return
* @throws IOException
*/
public static File createTmpFile(InputStream inputStream, String name, String ext) throws IOException {
public static File createTmpFile(InputStream inputStream, String name, String ext, File tmpDirFile) throws IOException {
FileOutputStream fos = null;
try {
File tmpFile = File.createTempFile(name, '.' + ext);
File tmpFile;
if (tmpDirFile == null) {
tmpFile = File.createTempFile(name, '.' + ext);
} else {
tmpFile = File.createTempFile(name, '.' + ext, tmpDirFile);
}
tmpFile.deleteOnExit();
fos = new FileOutputStream(tmpFile);
int read = 0;
@@ -43,5 +50,17 @@ public class FileUtils {
}
}
}
/**
* 创建临时文件
* @param inputStream
* @param name 文件名
* @param ext 扩展名
* @return
* @throws IOException
*/
public static File createTmpFile(InputStream inputStream, String name, String ext) throws IOException {
return createTmpFile(inputStream, name, ext, null);
}
}

View File

@@ -25,6 +25,18 @@ import java.util.regex.Pattern;
*
*/
public class MediaDownloadRequestExecutor implements RequestExecutor<File, String> {
private File tmpDirFile;
public MediaDownloadRequestExecutor() {
super();
}
public MediaDownloadRequestExecutor(File tmpDirFile) {
super();
this.tmpDirFile = tmpDirFile;
}
@Override
public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, ClientProtocolException, IOException {
@@ -41,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]);
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.4</version>
<version>1.2.0</version>
</parent>
<artifactId>weixin-java-cp</artifactId>

View File

@@ -1,5 +1,7 @@
package me.chanjar.weixin.cp.api;
import java.io.File;
import me.chanjar.weixin.common.bean.WxAccessToken;
/**
@@ -58,5 +60,7 @@ public interface WxCpConfigStorage {
public String getHttp_proxy_username();
public String getHttp_proxy_password();
public File getTmpDirFile();
}

View File

@@ -1,5 +1,7 @@
package me.chanjar.weixin.cp.api;
import java.io.File;
import me.chanjar.weixin.common.bean.WxAccessToken;
/**
@@ -28,6 +30,8 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage {
protected volatile String jsapiTicket;
protected volatile long jsapiTicketExpiresTime;
protected volatile File tmpDirFile;
public String getAccessToken() {
return this.accessToken;
}
@@ -189,7 +193,16 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage {
", http_proxy_password='" + http_proxy_password + '\'' +
", jsapiTicket='" + jsapiTicket + '\'' +
", jsapiTicketExpiresTime='" + jsapiTicketExpiresTime + '\'' +
", tmpDirFile='" + tmpDirFile + '\'' +
'}';
}
public File getTmpDirFile() {
return tmpDirFile;
}
public void setTmpDirFile(File tmpDirFile) {
this.tmpDirFile = tmpDirFile;
}
}

View File

@@ -399,7 +399,7 @@ public interface WxCpService {
* @param tagId
* @param userIds
*/
void tagAddUsers(String tagId, List<String> userIds) throws WxErrorException;
void tagAddUsers(String tagId, List<String> userIds, List<String> partyIds) throws WxErrorException;
/**
* <pre>

View File

@@ -78,6 +78,11 @@ public class WxCpServiceImpl implements WxCpService {
protected WxSessionManager sessionManager = new StandardSessionManager();
/**
* 临时文件目录
*/
protected File tmpDirFile;
public boolean checkSignature(String msgSignature, String timestamp, String nonce, String data) {
try {
return SHA1.gen(wxCpConfigStorage.getToken(), timestamp, nonce, data).equals(msgSignature);
@@ -112,8 +117,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);
@@ -236,7 +243,8 @@ 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(), url, "media_id=" + media_id);
return execute(new MediaDownloadRequestExecutor(wxCpConfigStorage.getTmpDirFile()), url, "media_id=" + media_id);
}
@@ -271,7 +279,8 @@ public class WxCpServiceImpl implements WxCpService {
return WxCpGsonBuilder.INSTANCE.create()
.fromJson(
tmpJsonElement.getAsJsonObject().get("department"),
new TypeToken<List<WxCpDepart>>() { }.getType()
new TypeToken<List<WxCpDepart>>() {
}.getType()
);
}
@@ -389,7 +398,8 @@ public class WxCpServiceImpl implements WxCpService {
return WxCpGsonBuilder.INSTANCE.create()
.fromJson(
tmpJsonElement.getAsJsonObject().get("taglist"),
new TypeToken<List<WxCpTag>>() { }.getType()
new TypeToken<List<WxCpTag>>() {
}.getType()
);
}
@@ -406,15 +416,24 @@ public class WxCpServiceImpl implements WxCpService {
}
@Override
public void tagAddUsers(String tagId, List<String> userIds) throws WxErrorException {
public void tagAddUsers(String tagId, List<String> userIds, List<String> partyIds) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers";
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("tagid", tagId);
JsonArray jsonArray = new JsonArray();
for (String userId : userIds) {
jsonArray.add(new JsonPrimitive(userId));
if (userIds != null) {
JsonArray jsonArray = new JsonArray();
for (String userId : userIds) {
jsonArray.add(new JsonPrimitive(userId));
}
jsonObject.add("userlist", jsonArray);
}
if (partyIds != null) {
JsonArray jsonArray = new JsonArray();
for (String userId : partyIds) {
jsonArray.add(new JsonPrimitive(userId));
}
jsonObject.add("partylist", jsonArray);
}
jsonObject.add("userlist", jsonArray);
post(url, jsonObject.toString());
}
@@ -627,6 +646,14 @@ public class WxCpServiceImpl implements WxCpService {
public void setSessionManager(WxSessionManager sessionManager) {
this.sessionManager = sessionManager;
}
public File getTmpDirFile() {
return tmpDirFile;
}
public void setTmpDirFile(File tmpDirFile) {
this.tmpDirFile = tmpDirFile;
}
public static void main(String[] args) {
Float a = 3.1f;

View File

@@ -42,7 +42,7 @@ public class WxCpTagAPITest {
public void testTagAddUsers() throws Exception {
List<String> userIds = new ArrayList<String>();
userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage)configStorage).getUserId());
wxService.tagAddUsers(tagId, userIds);
wxService.tagAddUsers(tagId, userIds, null);
}
@Test(dependsOnMethods = "testTagAddUsers")

View File

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

View File

@@ -1,5 +1,7 @@
package me.chanjar.weixin.mp.api;
import java.io.File;
import me.chanjar.weixin.common.bean.WxAccessToken;
/**
@@ -50,6 +52,10 @@ public interface WxMpConfigStorage {
public String getSecret();
public String getPartnerId();
public String getPartnerKey();
public String getToken();
public String getAesKey();
@@ -64,7 +70,8 @@ public interface WxMpConfigStorage {
public String getHttp_proxy_username();
public String getHttp_proxy_password();
public File getTmpDirFile();
}

View File

@@ -1,5 +1,7 @@
package me.chanjar.weixin.mp.api;
import java.io.File;
import me.chanjar.weixin.common.bean.WxAccessToken;
/**
@@ -11,6 +13,8 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
protected volatile String appId;
protected volatile String secret;
protected volatile String partnerId;
protected volatile String partnerKey;
protected volatile String token;
protected volatile String accessToken;
protected volatile String aesKey;
@@ -26,6 +30,11 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
protected volatile String jsapiTicket;
protected volatile long jsapiTicketExpiresTime;
/**
* 临时文件目录
*/
protected volatile File tmpDirFile;
public String getAccessToken() {
return this.accessToken;
}
@@ -168,6 +177,8 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
"appId='" + appId + '\'' +
", secret='" + secret + '\'' +
", token='" + token + '\'' +
", partnerId='" + partnerId + '\'' +
", partnerKey='" + partnerKey + '\'' +
", accessToken='" + accessToken + '\'' +
", aesKey='" + aesKey + '\'' +
", expiresTime=" + expiresTime +
@@ -177,6 +188,35 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
", http_proxy_password='" + http_proxy_password + '\'' +
", jsapiTicket='" + jsapiTicket + '\'' +
", jsapiTicketExpiresTime='" + jsapiTicketExpiresTime + '\'' +
", tmpDirFile='" + tmpDirFile + '\'' +
'}';
}
@Override
public String getPartnerId() {
return partnerId;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
@Override
public String getPartnerKey() {
return partnerKey;
}
public void setPartnerKey(String partnerKey) {
this.partnerKey = partnerKey;
}
@Override
public File getTmpDirFile() {
return this.tmpDirFile;
}
public void setTmpDirFile(File tmpDirFile) {
this.tmpDirFile = tmpDirFile;
}
}

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

@@ -11,9 +11,11 @@ import me.chanjar.weixin.mp.bean.result.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 微信API的Service
@@ -332,6 +334,18 @@ public interface WxMpService {
*/
public WxMpQrCodeTicket qrCodeCreateLastTicket(int scene_id) throws WxErrorException;
/**
* <pre>
* 换取永久字符串二维码ticket
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=生成带参数的二维码
* </pre>
*
* @param scene_str 参数。字符串类型长度现在为1到64
* @return
* @throws WxErrorException
*/
public WxMpQrCodeTicket qrCodeCreateLastTicket(String scene_str) throws WxErrorException;
/**
* <pre>
* 换取二维码图片文件jpg格式
@@ -528,4 +542,32 @@ public interface WxMpService {
*/
void setMaxRetryTimes(int maxRetryTimes);
/**
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=9_1)
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"
* @param openId 支付人openId
* @param outTradeNo 商户端对应订单号
* @param amt 金额(单位元)
* @param body 商品描述
* @param tradeType 交易类型 JSAPINATIVEAPPWAP
* @param ip 发起支付的客户端IP
* @param notifyUrl 通知地址
* @return
*/
WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String notifyUrl);
/**
* 该接口调用“统一下单”接口并拼装JSSDK发起支付请求需要的参数
* 详见http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E5.8F.91.E8.B5.B7.E4.B8.80.E4.B8.AA.E5.BE.AE.E4.BF.A1.E6.94.AF.E4.BB.98.E8.AF.B7.E6.B1.82
* @param openId 支付人openId
* @param outTradeNo 商户端对应订单号
* @param amt 金额(单位元)
* @param body 商品描述
* @param tradeType 交易类型 JSAPINATIVEAPPWAP
* @param ip 发起支付的客户端IP
* @param notifyUrl 通知地址
* @return
*/
Map<String, String> getJSSDKPayInfo(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String notifyUrl);
}

View File

@@ -1,14 +1,16 @@
package me.chanjar.weixin.mp.api;
import com.google.gson.Gson;
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 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;
@@ -17,13 +19,16 @@ import me.chanjar.weixin.common.session.WxSessionManager;
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.crypto.WxCryptUtil;
import me.chanjar.weixin.common.util.fs.FileUtils;
import me.chanjar.weixin.common.util.http.*;
import me.chanjar.weixin.common.util.json.GsonHelper;
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.util.http.QrCodeRequestExecutor;
import me.chanjar.weixin.mp.util.http.*;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -32,6 +37,8 @@ import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
@@ -44,9 +51,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.*;
public class WxMpServiceImpl implements WxMpService {
@@ -95,16 +100,14 @@ 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) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpGet.setConfig(config);
}
CloseableHttpClient httpclient = getHttpclient();
CloseableHttpResponse response = httpclient.execute(httpGet);
CloseableHttpResponse response = getHttpclient().execute(httpGet);
String resultContent = new BasicResponseHandler().handleResponse(response);
WxError error = WxError.fromJson(resultContent);
if (error.getErrorCode() != 0) {
@@ -173,12 +176,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);
@@ -199,17 +202,103 @@ 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(), url, "media_id=" + media_id);
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(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<String, Object>();
params.put("type", type);
params.put("offset", offset);
params.put("count", count);
String responseText = post(url, new Gson().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<String, Object>();
params.put("type", type);
params.put("offset", offset);
params.put("count", count);
String responseText = post(url, new Gson().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 {
@@ -217,13 +306,13 @@ public class WxMpServiceImpl implements WxMpService {
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());
@@ -235,17 +324,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);
}
@@ -258,9 +347,10 @@ 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();
@@ -269,12 +359,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();
@@ -282,7 +372,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();
@@ -290,25 +380,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();
@@ -319,7 +409,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();
@@ -332,12 +422,25 @@ public class WxMpServiceImpl implements WxMpService {
String responseContent = execute(new SimplePostRequestExecutor(), url, json.toString());
return WxMpQrCodeTicket.fromJson(responseContent);
}
public WxMpQrCodeTicket qrCodeCreateLastTicket(String scene_str) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create";
JsonObject json = new JsonObject();
json.addProperty("action_name", "QR_LIMIT_STR_SCENE");
JsonObject actionInfo = new JsonObject();
JsonObject scene = new JsonObject();
scene.addProperty("scene_str", scene_str);
actionInfo.add("scene", scene);
json.add("action_info", actionInfo);
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();
@@ -368,7 +471,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";
@@ -383,7 +486,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";
@@ -480,7 +583,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
@@ -491,7 +595,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<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 {
@@ -504,6 +609,7 @@ public class WxMpServiceImpl implements WxMpService {
/**
* 向微信端发送请求在这里执行的策略是当发生access_token过期时才去刷新然后重新执行请求而不是全局定时请求
*
* @param executor
* @param uri
* @param data
@@ -532,17 +638,17 @@ 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 {
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) {
@@ -580,9 +686,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(
@@ -613,4 +719,77 @@ public class WxMpServiceImpl implements WxMpService {
this.maxRetryTimes = maxRetryTimes;
}
@Override
public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String callbackUrl) {
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("nonce_str", nonce_str);
packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo);
packageParams.put("total_fee", (int) (amt * 100) + "");
packageParams.put("spbill_create_ip", ip);
packageParams.put("notify_url", callbackUrl);
packageParams.put("trade_type", tradeType);
packageParams.put("openid", openId);
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>";
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder");
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 = getHttpclient().execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", WxMpPrepayIdResult.class);
WxMpPrepayIdResult wxMpPrepayIdResult = (WxMpPrepayIdResult) xstream.fromXML(responseContent);
return wxMpPrepayIdResult;
} catch (IOException e) {
e.printStackTrace();
}
return new WxMpPrepayIdResult();
}
@Override
public Map<String, String> getJSSDKPayInfo(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String callbackUrl) {
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");
}
Map<String, String> payInfo = new HashMap<String, String>();
payInfo.put("appId", wxMpConfigStorage.getAppId());
// 支付签名时间戳注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
payInfo.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
payInfo.put("nonceStr", System.currentTimeMillis() + "");
payInfo.put("package", "prepay_id=" + prepayId);
payInfo.put("signType", "MD5");
String finalSign = WxCryptUtil.createSign(payInfo, wxMpConfigStorage.getPartnerKey());
payInfo.put("sign", finalSign);
return payInfo;
}
}

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,141 @@
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为不显示
* </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;
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 "WxMpMaterialNews [" + "articles=" + articles + "]";
}
}

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,98 @@
package me.chanjar.weixin.mp.bean.result;
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
*
* </pre>
*
* @author chanjarster
*/
public class WxMpPrepayIdResult 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 prepay_id;
private String trade_type;
public String getReturn_code() {
return return_code;
}
public void setReturn_code(String return_code) {
this.return_code = return_code;
}
public String getReturn_msg() {
return return_msg;
}
public void setReturn_msg(String return_msg) {
this.return_msg = return_msg;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getResult_code() {
return result_code;
}
public void setResult_code(String result_code) {
this.result_code = result_code;
}
public String getPrepay_id() {
return prepay_id;
}
public void setPrepay_id(String prepay_id) {
this.prepay_id = prepay_id;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
}

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 com.google.gson.Gson;
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 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<String, String>();
params.put("media_id", materialId);
httpPost.setEntity(new StringEntity(new Gson().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 com.google.gson.Gson;
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.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<String, String>();
params.put("media_id", materialId);
httpPost.setEntity(new StringEntity(new Gson().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 com.google.gson.Gson;
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.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", new Gson().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 com.google.gson.Gson;
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.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<String, String>();
params.put("media_id", materialId);
httpPost.setEntity(new StringEntity(new Gson().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 com.google.gson.Gson;
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 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<String, String>();
params.put("media_id", materialId);
httpPost.setEntity(new StringEntity(new Gson().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 = new Gson().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<WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem>();
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,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.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");
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));
}
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<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem>();
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<String, Map<String, Object>>();
// 缩略图的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<String, Object>();
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(WxConsts.MATERIAL_NEWS, 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 (Iterator<String> iterator = this.media_ids.keySet().iterator(); iterator.hasNext(); ) {
params[index] = new Object[]{iterator.next()};
index++;
}
return params;
}
@DataProvider
public Iterator<Object[]> allTestMaterial() {
List<Object[]> params = new ArrayList<Object[]>();
for (Iterator<String> iterator = this.media_ids.keySet().iterator(); iterator.hasNext(); ) {
params.add(new Object[]{iterator.next()});
}
params.add(new Object[]{this.singleNewsMediaId});
params.add(new Object[]{this.multiNewsMediaId});
return params.iterator();
}
}