46 Commits

Author SHA1 Message Date
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
669552e503 upgrade to 1.1.4 2015-04-16 14:15:43 +08:00
Daniel Qian
d29fdd1427 Merge pull request #122 from SimonDolph/develop
添加可自定义oauth2 redirectURI的方法
2015-04-10 12:57:12 +08:00
Daniel Qian
0fb143600b issue #123 WxCpServiceImpl#tagGet 返回数据中没有tagname 2015-04-07 11:39:23 +08:00
SimonDolph
37c8ebac2c 添加可自定义oauth2 redirectURI的方法 2015-04-01 17:14:37 +08:00
Daniel Qian
a5d05d3458 issue #113 企业号oauth2getUserInfo报errcode=40029, errmsg=invalid code 2015-03-24 16:49:48 +08:00
Daniel Qian
7efdd448d1 fix: issue #112 2015-03-23 16:25:45 +08:00
Daniel Qian
82016c02bf version prompt 2015-03-23 11:20:40 +08:00
Daniel Qian
dfd2ade23f prompt to stable version 2015-03-23 11:09:23 +08:00
Daniel Qian
0c66505e45 #111 修复从文件系统反序列化WxMenu时,在windows平台下会存在编码问题 2015-03-20 17:40:15 +08:00
Daniel Qian
8254caf9ed #111 2015-03-20 15:05:26 +08:00
Daniel Qian
b885d2a1a9 #111 的unit test code 2015-03-20 14:59:59 +08:00
Daniel Qian
913f49e470 删除没有用的测试用例 2015-03-20 14:24:50 +08:00
Daniel Qian
8a7192813d fix README 2015-02-26 15:12:03 +08:00
Daniel Qian
0ae7a75f56 issue #109 企业号几个方法添加agentId参数 2015-02-26 15:05:06 +08:00
Daniel Qian
b648c55444 upgrade to 1.1.3-SNAPSHOT 2015-02-25 15:36:19 +08:00
Daniel Qian
316e54baaa upgrade to 1.1.2 2015-02-25 15:32:33 +08:00
Daniel Qian
978c51b90d issue #100 用户分析数据接口 2015-02-25 15:17:52 +08:00
Daniel Qian
fb10acf6fd issue #101 获取微信服务器IP地址 2015-02-25 14:37:15 +08:00
Daniel Qian
fd24b53202 modify README 2015-02-12 09:42:52 +08:00
Daniel Qian
b8d011e73e issue #105 WxCpService.oauth2buildAuthorizationUrl方法设计错误 2015-02-11 17:56:48 +08:00
Daniel Qian
2a439a6690 issue #107 请给实体类加上Serializable 2015-02-10 14:11:23 +08:00
Daniel Qian
8e7fcc64b3 add travis status 2015-02-09 09:41:03 +08:00
Daniel Qian
dc9161844e add travis support 2015-02-09 09:35:35 +08:00
Daniel Qian
7e46113bbc add travis support 2015-02-09 09:30:44 +08:00
Daniel Qian
1e94c452ba issue #104 WxCpService.oauth2getUserInfo方法不会去刷新access token 2015-02-09 09:07:54 +08:00
Daniel Qian
d2eb529ab2 issue #99 Wx*MessageRouter.isDuplicateMessage方法逻辑错误 2015-02-04 17:12:02 +08:00
Daniel Qian
57e9beaae0 issue #91 添加企业号JS_API的支持 2015-02-04 17:09:15 +08:00
Daniel Qian
acb3e7e01b Merge branch 'master' into develop 2015-02-04 12:00:56 +08:00
Daniel Qian
0a7323940d Update README.md 2015-02-04 11:56:59 +08:00
Daniel Qian
1b503a7e44 Update README.md 2015-02-04 11:56:36 +08:00
Daniel Qian
95d8bd3c47 issue #99 Wx*MessageRouter.isDuplicateMessage方法逻辑错误 2015-02-04 11:49:01 +08:00
Daniel Qian
1e5e098775 issue #92 A bug in me.chanjar.weixin.mp.api.WxMpServiceImpl.java at line 449 2015-02-04 11:45:12 +08:00
Daniel Qian
3ae057af8f issue #95 获取关注者列表userList方法,当没有关注者时,报异常 2015-02-04 11:43:07 +08:00
Daniel Qian
4740f1f37b issue #91 2015-01-27 15:53:29 +08:00
Daniel Qian
5b49c63d14 issue #91 添加企业号JS_API的支持 2015-01-27 14:45:11 +08:00
Daniel Qian
6d383fa90e issue #90 WxMpUser添加sexId字段,和微信返回的性别字段保持一致 2015-01-27 13:34:14 +08:00
Daniel Qian
4dc297c5ed upgrade to 1.1.2-SNAPSHOT 2015-01-25 11:17:48 +08:00
70 changed files with 1217 additions and 157 deletions

1
.gitignore vendored
View File

@@ -19,3 +19,4 @@ target
sw-pom.xml
*.iml
test-config.xml
.idea

13
.travis.yml Normal file
View File

@@ -0,0 +1,13 @@
language: java
jdk:
- oraclejdk7
script: "mvn clean install -Dmaven.test.skip=true"
branches:
only:
- develop
notifications:
email:
- chanjarster@gmail.com

View File

@@ -1,4 +1,8 @@
weixin-java-tools
[![Build Status](https://travis-ci.org/chanjarster/weixin-java-tools.svg?branch=develop)](https://travis-ci.org/chanjarster/weixin-java-tools)
![Maven Central](https://img.shields.io/maven-central/v/me.chanjar/weixin-java-parent.svg)
===========
微信公众号、企业号Java SDK。
@@ -13,7 +17,7 @@ weixin-java-tools
<dependency>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>1.1.1</version>
<version>1.1.5</version>
</dependency>
```
@@ -23,7 +27,7 @@ weixin-java-tools
<dependency>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-cp</artifactId>
<version>1.1.1</version>
<version>1.1.5</version>
</dependency>
```
@@ -39,4 +43,10 @@ weixin-java-tools
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>
</repositories>
```
```
## 升级指南
* [1.0.3升级指南](https://github.com/chanjarster/weixin-java-tools/wiki/1_0_3升级指南)
* [1.1.0升级指南](https://github.com/chanjarster/weixin-java-tools/wiki/1_1_0升级指南)
* [1.1.1升级指南](https://github.com/chanjarster/weixin-java-tools/wiki/1_1_1升级指南)

View File

@@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-parent</artifactId>
<version>1.1.1</version>
<version>1.1.5</version>
<packaging>pom</packaging>
<name>WeiXin Java Tools - Parent</name>
<description>微信公众号、企业号上级POM</description>

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>me.chanjar</groupId>
<artifactId>weixin-java-parent</artifactId>
<version>1.1.1</version>
<version>1.1.5</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";

View File

@@ -1,4 +1,4 @@
package me.chanjar.weixin.common.util;
package me.chanjar.weixin.common.api;
import me.chanjar.weixin.common.exception.WxErrorException;

View File

@@ -1,4 +1,4 @@
package me.chanjar.weixin.common.util;
package me.chanjar.weixin.common.api;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

View File

@@ -2,7 +2,9 @@ package me.chanjar.weixin.common.bean;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
public class WxAccessToken {
import java.io.Serializable;
public class WxAccessToken implements Serializable {
private String accessToken;

View File

@@ -1,9 +1,11 @@
package me.chanjar.weixin.mp.bean.result;
package me.chanjar.weixin.common.bean;
import java.io.Serializable;
/**
* jspai signature
*/
public class WxMpJsapiSignature {
public class WxJsapiSignature implements Serializable {
private String noncestr;

View File

@@ -2,17 +2,20 @@ package me.chanjar.weixin.common.bean;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import org.apache.commons.codec.Charsets;
/**
* 企业号菜单
* @author Daniel Qian
*
*/
public class WxMenu {
public class WxMenu implements Serializable {
private List<WxMenuButton> buttons = new ArrayList<WxMenuButton>();
@@ -27,15 +30,34 @@ public class WxMenu {
public String toJson() {
return WxGsonBuilder.create().toJson(this);
}
/**
* 要用 http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html 格式来反序列化
* 相比 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html 的格式外层多套了一个menu
* @param json
* @return
*/
public static WxMenu fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxMenu.class);
}
/**
* 要用 http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html 格式来反序列化
* 相比 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html 的格式外层多套了一个menu
* @param is
* @return
*/
public static WxMenu fromJson(InputStream is) {
return WxGsonBuilder.create().fromJson(new InputStreamReader(is), WxMenu.class);
return WxGsonBuilder.create().fromJson(new InputStreamReader(is, Charsets.UTF_8), WxMenu.class);
}
@Override
public String toString() {
return "WxMenu{" +
"buttons=" + buttons +
'}';
}
public static class WxMenuButton {
private String type;
@@ -84,7 +106,17 @@ public class WxMenu {
public void setSubButtons(List<WxMenuButton> subButtons) {
this.subButtons = subButtons;
}
@Override
public String toString() {
return "WxMenuButton{" +
"type='" + type + '\'' +
", name='" + name + '\'' +
", key='" + key + '\'' +
", url='" + url + '\'' +
", subButtons=" + subButtons +
'}';
}
}
}

View File

@@ -2,13 +2,15 @@ package me.chanjar.weixin.common.bean.result;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
/**
* 微信错误码说明
* http://mp.weixin.qq.com/wiki/index.php?title=全局返回码说明
* @author Daniel Qian
*
*/
public class WxError {
public class WxError implements Serializable {
private int errorCode;

View File

@@ -2,7 +2,9 @@ package me.chanjar.weixin.common.bean.result;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
public class WxMediaUploadResult {
import java.io.Serializable;
public class WxMediaUploadResult implements Serializable {
private String type;
private String mediaId;

View File

@@ -1,5 +1,6 @@
package me.chanjar.weixin.common.util;
import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@@ -0,0 +1,17 @@
package me.chanjar.weixin.common.util;
public class RandomUtils {
private static final String RANDOM_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final java.util.Random RANDOM = new java.util.Random();
public static String getRandomStr() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 16; i++) {
sb.append(RANDOM_STR.charAt(RANDOM.nextInt(RANDOM_STR.length())));
}
return sb.toString();
}
}

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

@@ -1,5 +1,6 @@
package me.chanjar.weixin.common.util;
import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker;
import org.testng.Assert;
import org.testng.annotations.Test;

View File

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

View File

@@ -22,6 +22,20 @@ public interface WxCpConfigStorage {
public void updateAccessToken(String accessToken, int expiresIn);
public String getJsapiTicket();
public boolean isJsapiTicketExpired();
/**
* 强制将jsapi ticket过期掉
*/
public void expireJsapiTicket();
/**
* 应该是线程安全的
* @param jsapiTicket
*/
public void updateJsapiTicket(String jsapiTicket, int expiresInSeconds);
public String getCorpId();

View File

@@ -25,6 +25,9 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage {
protected volatile String http_proxy_username;
protected volatile String http_proxy_password;
protected volatile String jsapiTicket;
protected volatile long jsapiTicketExpiresTime;
public String getAccessToken() {
return this.accessToken;
}
@@ -46,6 +49,37 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage {
this.expiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000l;
}
@Override
public String getJsapiTicket() {
return jsapiTicket;
}
public void setJsapiTicket(String jsapiTicket) {
this.jsapiTicket = jsapiTicket;
}
public long getJsapiTicketExpiresTime() {
return jsapiTicketExpiresTime;
}
public void setJsapiTicketExpiresTime(long jsapiTicketExpiresTime) {
this.jsapiTicketExpiresTime = jsapiTicketExpiresTime;
}
public boolean isJsapiTicketExpired() {
return System.currentTimeMillis() > this.jsapiTicketExpiresTime;
}
public synchronized void updateJsapiTicket(String jsapiTicket, int expiresInSeconds) {
this.jsapiTicket = jsapiTicket;
// 预留200秒的时间
this.jsapiTicketExpiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000l;
}
public void expireJsapiTicket() {
this.jsapiTicketExpiresTime = 0;
}
public String getCorpId() {
return this.corpId;
}
@@ -153,6 +187,8 @@ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage {
", http_proxy_port=" + http_proxy_port +
", http_proxy_username='" + http_proxy_username + '\'' +
", http_proxy_password='" + http_proxy_password + '\'' +
", jsapiTicket='" + jsapiTicket + '\'' +
", jsapiTicketExpiresTime='" + jsapiTicketExpiresTime + '\'' +
'}';
}

View File

@@ -5,9 +5,9 @@ import me.chanjar.weixin.common.session.InternalSessionManager;
import me.chanjar.weixin.common.session.StandardSessionManager;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.LogExceptionHandler;
import me.chanjar.weixin.common.util.WxErrorExceptionHandler;
import me.chanjar.weixin.common.util.WxMessageDuplicateChecker;
import me.chanjar.weixin.common.util.WxMessageInMemoryDuplicateChecker;
import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.common.api.WxMessageDuplicateChecker;
import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import org.slf4j.Logger;
@@ -87,8 +87,8 @@ public class WxCpMessageRouter {
/**
* <pre>
* 设置自定义的 {@link me.chanjar.weixin.common.util.WxMessageDuplicateChecker}
* 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.util.WxMessageInMemoryDuplicateChecker}
* 设置自定义的 {@link me.chanjar.weixin.common.api.WxMessageDuplicateChecker}
* 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker}
* </pre>
* @param messageDuplicateChecker
*/
@@ -109,7 +109,7 @@ public class WxCpMessageRouter {
/**
* <pre>
* 设置自定义的{@link me.chanjar.weixin.common.util.WxErrorExceptionHandler}
* 设置自定义的{@link me.chanjar.weixin.common.api.WxErrorExceptionHandler}
* 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.util.LogExceptionHandler}
* </pre>
* @param exceptionHandler
@@ -204,7 +204,8 @@ public class WxCpMessageRouter {
messageId = String.valueOf(wxMessage.getCreateTime())
+ "-" +String.valueOf(wxMessage.getAgentId() == null ? "" : wxMessage.getAgentId())
+ "-" + wxMessage.getFromUserName()
+ "-" + String.valueOf(wxMessage.getEventKey() == null ? "" : wxMessage.getEvent());
+ "-" + String.valueOf(wxMessage.getEventKey() == null ? "" : wxMessage.getEventKey())
+ "-" + String.valueOf(wxMessage.getEvent() == null ? "" : wxMessage.getEvent())
;
} else {
messageId = String.valueOf(wxMessage.getMsgId());

View File

@@ -2,7 +2,7 @@ package me.chanjar.weixin.cp.api;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.WxErrorExceptionHandler;
import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;

View File

@@ -1,5 +1,6 @@
package me.chanjar.weixin.cp.api;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
@@ -67,6 +68,38 @@ public interface WxCpService {
*/
String getAccessToken(boolean forceRefresh) throws WxErrorException;
/**
* 获得jsapi_ticket,不强制刷新jsapi_ticket
* @see #getJsapiTicket(boolean)
* @return
* @throws WxErrorException
*/
public String getJsapiTicket() throws WxErrorException;
/**
* <pre>
* 获得jsapi_ticket
* 获得时会检查jsapiToken是否过期如果过期了那么就刷新一下否则就什么都不干
*
* 详情请见http://qydev.weixin.qq.com/wiki/index.php?title=微信JS接口#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95
* </pre>
* @param forceRefresh 强制刷新
* @return
* @throws WxErrorException
*/
public String getJsapiTicket(boolean forceRefresh) throws WxErrorException;
/**
* <pre>
* 创建调用jsapi时所需要的签名
*
* 详情请见http://qydev.weixin.qq.com/wiki/index.php?title=微信JS接口#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95
* </pre>
* @param url url
* @return
*/
public WxJsapiSignature createJsapiSignature(String url) throws WxErrorException;
/**
* <pre>
* 上传多媒体文件
@@ -122,34 +155,87 @@ public interface WxCpService {
* <pre>
* 自定义菜单创建接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单创建接口
*
* 注意: 这个方法使用WxCpConfigStorage里的agentId
* </pre>
* @see #menuCreate(String, me.chanjar.weixin.common.bean.WxMenu)
*
* @param menu
* @throws WxErrorException
*/
void menuCreate(WxMenu menu) throws WxErrorException;
/**
* <pre>
* 自定义菜单创建接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单创建接口
*
* 注意: 这个方法不使用WxCpConfigStorage里的agentId需要开发人员自己给出
* </pre>
* @see #menuCreate(me.chanjar.weixin.common.bean.WxMenu)
*
* @param agentId 企业号应用的id
* @param menu
* @throws WxErrorException
*/
void menuCreate(String agentId, WxMenu menu) throws WxErrorException;
/**
* <pre>
* 自定义菜单删除接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单删除接口
*
* 注意: 这个方法使用WxCpConfigStorage里的agentId
* </pre>
* @see #menuDelete(String)
*
* @throws WxErrorException
*/
void menuDelete() throws WxErrorException;
/**
* <pre>
* 自定义菜单删除接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单删除接口
*
* 注意: 这个方法不使用WxCpConfigStorage里的agentId需要开发人员自己给出
* </pre>
* @see #menuDelete()
*
* @param agentId 企业号应用的id
* @throws WxErrorException
*/
void menuDelete(String agentId) throws WxErrorException;
/**
* <pre>
* 自定义菜单查询接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单查询接口
*
* 注意: 这个方法使用WxCpConfigStorage里的agentId
* </pre>
* @see #menuGet(String)
*
* @return
* @throws WxErrorException
*/
WxMenu menuGet() throws WxErrorException;
/**
* <pre>
* 自定义菜单查询接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单查询接口
*
* 注意: 这个方法不使用WxCpConfigStorage里的agentId需要开发人员自己给出
* </pre>
* @see #menuGet()
*
* @param agentId 企业号应用的id
* @return
* @throws WxErrorException
*/
WxMenu menuGet(String agentId) throws WxErrorException;
/**
* <pre>
* 部门管理接口 - 创建部门
@@ -313,29 +399,51 @@ 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>
* 构造oauth2授权的url连接
* 详情请见: http://qydev.weixin.qq.com/wiki/index.php?title=企业获取code
* </pre>
* @param redirectUri
* @param state
* @return code
*/
String oauth2buildAuthorizationUrl(String state);
String oauth2buildAuthorizationUrl(String redirectUri, String state);
/**
* <pre>
* 用oauth2获取用户信息
* http://qydev.weixin.qq.com/wiki/index.php?title=根据code获取成员信息
* 因为企业号oauth2.0必须在应用设置里设置通过ICP备案的可信域名所以无法测试因此这个方法很可能是坏的。
*
* 注意: 这个方法使用WxCpConfigStorage里的agentId
* </pre>
* @see #oauth2getUserInfo(String, String)
*
* @param code
* @return [userid, deviceid]
*/
String[] oauth2getUserInfo(String code) throws WxErrorException;
/**
* <pre>
* 用oauth2获取用户信息
* http://qydev.weixin.qq.com/wiki/index.php?title=根据code获取成员信息
* 因为企业号oauth2.0必须在应用设置里设置通过ICP备案的可信域名所以无法测试因此这个方法很可能是坏的。
*
* 注意: 这个方法不使用WxCpConfigStorage里的agentId需要开发人员自己给出
* </pre>
* @see #oauth2getUserInfo(String)
*
* @param agentId 企业号应用的id
* @param code
* @return [userid, deviceid]
*/
String[] oauth2getUserInfo(String agentId, String code) throws WxErrorException;
/**
* 移除标签成员
*

View File

@@ -7,7 +7,9 @@ import com.google.gson.JsonPrimitive;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.sun.media.sound.SoftTuning;
import me.chanjar.weixin.common.bean.WxAccessToken;
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;
@@ -15,6 +17,7 @@ import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.StandardSessionManager;
import me.chanjar.weixin.common.session.WxSession;
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.fs.FileUtils;
@@ -44,6 +47,8 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
@@ -54,7 +59,12 @@ public class WxCpServiceImpl implements WxCpService {
/**
* 全局的是否正在刷新access token的锁
*/
protected static final Object GLOBAL_ACCESS_TOKEN_REFRESH_LOCK = new Object();
protected final Object globalAccessTokenRefreshLock = new Object();
/**
* 全局的是否正在刷新jsapi_ticket的锁
*/
protected final Object globalJsapiTicketRefreshLock = new Object();
protected WxCpConfigStorage wxCpConfigStorage;
@@ -90,7 +100,7 @@ public class WxCpServiceImpl implements WxCpService {
wxCpConfigStorage.expireAccessToken();
}
if (wxCpConfigStorage.isAccessTokenExpired()) {
synchronized (GLOBAL_ACCESS_TOKEN_REFRESH_LOCK) {
synchronized (globalAccessTokenRefreshLock) {
if (wxCpConfigStorage.isAccessTokenExpired()) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?"
+ "&corpid=" + wxCpConfigStorage.getCorpId()
@@ -121,23 +131,87 @@ public class WxCpServiceImpl implements WxCpService {
return wxCpConfigStorage.getAccessToken();
}
public String getJsapiTicket() throws WxErrorException {
return getJsapiTicket(false);
}
public String getJsapiTicket(boolean forceRefresh) throws WxErrorException {
if (forceRefresh) {
wxCpConfigStorage.expireJsapiTicket();
}
if (wxCpConfigStorage.isJsapiTicketExpired()) {
synchronized (globalJsapiTicketRefreshLock) {
if (wxCpConfigStorage.isJsapiTicketExpired()) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket";
String responseContent = execute(new SimpleGetRequestExecutor(), url, null);
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject();
String jsapiTicket = tmpJsonObject.get("ticket").getAsString();
int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt();
wxCpConfigStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds);
}
}
}
return wxCpConfigStorage.getJsapiTicket();
}
public WxJsapiSignature createJsapiSignature(String url) throws WxErrorException {
long timestamp = System.currentTimeMillis() / 1000;
String noncestr = RandomUtils.getRandomStr();
String jsapiTicket = getJsapiTicket(false);
try {
String signature = SHA1.genWithAmple(
"jsapi_ticket=" + jsapiTicket,
"noncestr=" + noncestr,
"timestamp=" + timestamp,
"url=" + url
);
WxJsapiSignature jsapiSignature = new WxJsapiSignature();
jsapiSignature.setTimestamp(timestamp);
jsapiSignature.setNoncestr(noncestr);
jsapiSignature.setUrl(url);
jsapiSignature.setSignature(signature);
return jsapiSignature;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public void messageSend(WxCpMessage message) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send";
post(url, message.toJson());
}
@Override
public void menuCreate(WxMenu menu) throws WxErrorException {
menuCreate(wxCpConfigStorage.getAgentId(), menu);
}
@Override
public void menuCreate(String agentId, WxMenu menu) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?agentid=" + wxCpConfigStorage.getAgentId();
post(url, menu.toJson());
}
@Override
public void menuDelete() throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/delete?agentid=" + wxCpConfigStorage.getAgentId();
menuDelete(wxCpConfigStorage.getAgentId());
}
@Override
public void menuDelete(String agentId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/delete?agentid=" + agentId;
get(url, null);
}
@Override
public WxMenu menuGet() throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/get?agentid=" + wxCpConfigStorage.getAgentId();
return menuGet(wxCpConfigStorage.getAgentId());
}
@Override
public WxMenu menuGet(String agentId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/get?agentid=" + agentId;
try {
String resultContent = get(url, null);
return WxMenu.fromJson(resultContent);
@@ -197,7 +271,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()
);
}
@@ -315,7 +390,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()
);
}
@@ -332,15 +408,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());
}
@@ -358,10 +443,10 @@ public class WxCpServiceImpl implements WxCpService {
}
@Override
public String oauth2buildAuthorizationUrl(String state) {
public String oauth2buildAuthorizationUrl(String redirectUri, String state) {
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" ;
url += "appid=" + wxCpConfigStorage.getCorpId();
url += "&redirect_uri=" + URIUtil.encodeURIComponent(wxCpConfigStorage.getOauth2redirectUri());
url += "&redirect_uri=" + URIUtil.encodeURIComponent(redirectUri);
url += "&response_type=code";
url += "&scope=snsapi_base";
if (state != null) {
@@ -373,22 +458,18 @@ public class WxCpServiceImpl implements WxCpService {
@Override
public String[] oauth2getUserInfo(String code) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?";
url += "access_token=" + wxCpConfigStorage.getAccessToken();
url += "&code=" + code;
url += "&agendid=" + wxCpConfigStorage.getAgentId();
return oauth2getUserInfo(wxCpConfigStorage.getAgentId(), code);
}
try {
RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
String responseText = executor.execute(getHttpclient(), httpProxy, url, null);
JsonElement je = Streams.parse(new JsonReader(new StringReader(responseText)));
JsonObject jo = je.getAsJsonObject();
return new String[] {GsonHelper.getString(jo, "UserId"), GsonHelper.getString(jo, "DeviceId")};
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
@Override
public String[] oauth2getUserInfo(String agentId, String code) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?"
+ "code=" + code
+ "&agendid=" + agentId;
String responseText = get(url, null);
JsonElement je = Streams.parse(new JsonReader(new StringReader(responseText)));
JsonObject jo = je.getAsJsonObject();
return new String[] {GsonHelper.getString(jo, "UserId"), GsonHelper.getString(jo, "DeviceId")};
}
@Override
@@ -477,7 +558,7 @@ public class WxCpServiceImpl implements WxCpService {
* 42001 access_token超时
*/
if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001) {
// 强制设置wxMpConfigStorage它的access token过期了这样在下一次请求里就会刷新access token
// 强制设置wxCpConfigStorage它的access token过期了这样在下一次请求里就会刷新access token
wxCpConfigStorage.expireAccessToken();
return execute(executor, uri, data);
}
@@ -558,4 +639,12 @@ public class WxCpServiceImpl implements WxCpService {
this.sessionManager = sessionManager;
}
public static void main(String[] args) {
Float a = 3.1f;
System.out.println(3.1d);
System.out.println(new BigDecimal(3.1d));
System.out.println(new BigDecimal(a));
System.out.println(a.toString());
System.out.println(a.doubleValue());
}
}

View File

@@ -2,12 +2,14 @@ package me.chanjar.weixin.cp.bean;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import java.io.Serializable;
/**
* 微信部门
*
* @author Daniel Qian
*/
public class WxCpDepart {
public class WxCpDepart implements Serializable {
private Integer id;
private String name;

View File

@@ -3,6 +3,7 @@ package me.chanjar.weixin.cp.bean;
import me.chanjar.weixin.cp.bean.messagebuilder.*;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@@ -11,7 +12,7 @@ import java.util.List;
* @author Daniel Qian
*
*/
public class WxCpMessage {
public class WxCpMessage implements Serializable {
private String toUser;
private String toParty;

View File

@@ -2,10 +2,12 @@ package me.chanjar.weixin.cp.bean;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import java.io.Serializable;
/**
* Created by Daniel Qian
*/
public class WxCpTag {
public class WxCpTag implements Serializable {
private String id;

View File

@@ -2,6 +2,7 @@ package me.chanjar.weixin.cp.bean;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@@ -10,7 +11,7 @@ import java.util.List;
*
* @author Daniel Qian
*/
public class WxCpUser {
public class WxCpUser implements Serializable {
private String userId;
private String name;

View File

@@ -10,6 +10,7 @@ import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@@ -25,7 +26,7 @@ import java.util.List;
* @author Daniel Qian
*/
@XStreamAlias("xml")
public class WxCpXmlMessage {
public class WxCpXmlMessage implements Serializable {
///////////////////////
// 以下都是微信推送过来的消息的xml的element所对应的属性

View File

@@ -34,7 +34,7 @@ public class WxCpMessageGsonAdapter implements JsonSerializer<WxCpMessage> {
messageJson.addProperty("toparty", message.getToParty());
}
if (StringUtils.isNotBlank(message.getToTag())) {
messageJson.addProperty("totag", message.getToUser());
messageJson.addProperty("totag", message.getToTag());
}
if (WxConsts.CUSTOM_MSG_TEXT.equals(message.getMsgType())) {
JsonObject text = new JsonObject();

View File

@@ -19,17 +19,17 @@ import java.lang.reflect.Type;
*/
public class WxCpTagGsonAdapter implements JsonSerializer<WxCpTag>, JsonDeserializer<WxCpTag> {
public JsonElement serialize(WxCpTag group, Type typeOfSrc, JsonSerializationContext context) {
public JsonElement serialize(WxCpTag tag, Type typeOfSrc, JsonSerializationContext context) {
JsonObject o = new JsonObject();
o.addProperty("tagid", group.getId());
o.addProperty("tagname", group.getName());
o.addProperty("tagid", tag.getId());
o.addProperty("tagname", tag.getName());
return o;
}
public WxCpTag deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
return new WxCpTag(GsonHelper.getString(jsonObject, "tagid"), GsonHelper.getString(jsonObject, "name"));
return new WxCpTag(GsonHelper.getString(jsonObject, "tagid"), GsonHelper.getString(jsonObject, "tagname"));
}
}

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

@@ -62,7 +62,7 @@ public class WxCpDemoServer {
@Override
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
WxCpService wxCpService, WxSessionManager sessionManager) {
String href = "<a href=\"" + wxCpService.oauth2buildAuthorizationUrl(null)
String href = "<a href=\"" + wxCpService.oauth2buildAuthorizationUrl(wxCpConfigStorage.getOauth2redirectUri(), null)
+ "\">测试oauth2</a>";
return WxCpXmlOutMessage
.TEXT()

View File

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

View File

@@ -50,6 +50,10 @@ public interface WxMpConfigStorage {
public String getSecret();
public String getPartnerId();
public String getPartnerKey();
public String getToken();
public String getAesKey();

View File

@@ -11,6 +11,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;
@@ -51,6 +53,18 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
return jsapiTicket;
}
public void setJsapiTicket(String jsapiTicket) {
this.jsapiTicket = jsapiTicket;
}
public long getJsapiTicketExpiresTime() {
return jsapiTicketExpiresTime;
}
public void setJsapiTicketExpiresTime(long jsapiTicketExpiresTime) {
this.jsapiTicketExpiresTime = jsapiTicketExpiresTime;
}
public boolean isJsapiTicketExpired() {
return System.currentTimeMillis() > this.jsapiTicketExpiresTime;
}
@@ -156,6 +170,8 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
"appId='" + appId + '\'' +
", secret='" + secret + '\'' +
", token='" + token + '\'' +
", partnerId='" + partnerId + '\'' +
", partnerKey='" + partnerKey + '\'' +
", accessToken='" + accessToken + '\'' +
", aesKey='" + aesKey + '\'' +
", expiresTime=" + expiresTime +
@@ -168,4 +184,21 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
'}';
}
@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;
}
}

View File

@@ -5,9 +5,9 @@ import me.chanjar.weixin.common.session.InternalSessionManager;
import me.chanjar.weixin.common.session.StandardSessionManager;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.LogExceptionHandler;
import me.chanjar.weixin.common.util.WxErrorExceptionHandler;
import me.chanjar.weixin.common.util.WxMessageDuplicateChecker;
import me.chanjar.weixin.common.util.WxMessageInMemoryDuplicateChecker;
import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.common.api.WxMessageDuplicateChecker;
import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import org.slf4j.Logger;
@@ -87,8 +87,8 @@ public class WxMpMessageRouter {
/**
* <pre>
* 设置自定义的 {@link me.chanjar.weixin.common.util.WxMessageDuplicateChecker}
* 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.util.WxMessageInMemoryDuplicateChecker}
* 设置自定义的 {@link me.chanjar.weixin.common.api.WxMessageDuplicateChecker}
* 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker}
* </pre>
* @param messageDuplicateChecker
*/
@@ -109,7 +109,7 @@ public class WxMpMessageRouter {
/**
* <pre>
* 设置自定义的{@link me.chanjar.weixin.common.util.WxErrorExceptionHandler}
* 设置自定义的{@link me.chanjar.weixin.common.api.WxErrorExceptionHandler}
* 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.util.LogExceptionHandler}
* </pre>
* @param exceptionHandler
@@ -203,7 +203,8 @@ public class WxMpMessageRouter {
if (wxMessage.getMsgId() == null) {
messageId = String.valueOf(wxMessage.getCreateTime())
+ "-" + wxMessage.getFromUserName()
+ "-" + String.valueOf(wxMessage.getEventKey() == null ? "" : wxMessage.getEvent());
+ "-" + String.valueOf(wxMessage.getEventKey() == null ? "" : wxMessage.getEventKey())
+ "-" + String.valueOf(wxMessage.getEvent() == null ? "" : wxMessage.getEvent())
;
} else {
messageId = String.valueOf(wxMessage.getMsgId());

View File

@@ -2,7 +2,7 @@ package me.chanjar.weixin.mp.api;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.WxErrorExceptionHandler;
import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;

View File

@@ -1,10 +1,9 @@
package me.chanjar.weixin.mp.api;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSession;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.mp.bean.*;
import me.chanjar.weixin.mp.bean.result.*;
@@ -12,13 +11,18 @@ 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
*/
public interface WxMpService {
public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
/**
* <pre>
* 验证推送过来的消息的正确性
@@ -86,7 +90,7 @@ public interface WxMpService {
* @param url url
* @return
*/
public WxMpJsapiSignature createJsapiSignature(String url) throws WxErrorException;
public WxJsapiSignature createJsapiSignature(String url) throws WxErrorException;
/**
* <pre>
@@ -330,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格式
@@ -385,6 +401,18 @@ public interface WxMpService {
*/
public String oauth2buildAuthorizationUrl(String scope, String state);
/**
* <pre>
* 构造oauth2授权的url连接
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=网页授权获取用户基本信息
* </pre>
* @param redirectURI
* 用户授权完成后的重定向链接无需urlencode, 方法内会进行encode
* @param scope
* @param state
* @return code
*/
public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state);
/**
* <pre>
* 用code换取oauth2的access token
@@ -422,6 +450,40 @@ public interface WxMpService {
*/
public boolean oauth2validateAccessToken(WxMpOAuth2AccessToken oAuth2AccessToken);
/**
* <pre>
* 获取微信服务器IP地址
* http://mp.weixin.qq.com/wiki/0/2ad4b6bfd29f30f71d39616c2a0fcedc.html
* </pre>
* @return
* @throws WxErrorException
*/
String[] getCallbackIP() throws WxErrorException;
/**
* <pre>
* 获取用户增减数据
* http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html
* </pre>
* @param beginDate 最大时间跨度7天
* @param endDate endDate不能早于begingDate
* @return
* @throws WxErrorException
*/
List<WxMpUserSummary> getUserSummary(Date beginDate, Date endDate) throws WxErrorException;
/**
* <pre>
* 获取累计用户数据
* http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html
* </pre>
* @param beginDate 最大时间跨度7天
* @param endDate endDate不能早于begingDate
* @return
* @throws WxErrorException
*/
List<WxMpUserCumulate> getUserCumulate(Date beginDate, Date endDate) throws WxErrorException;
/**
* 当本Service没有实现某个API的时候可以用这个针对所有微信API中的GET请求
* @param url
@@ -480,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,26 +1,33 @@
package me.chanjar.weixin.mp.api;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.thoughtworks.xstream.XStream;
import 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.result.WxError;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.StandardSessionManager;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.RandomUtils;
import me.chanjar.weixin.common.util.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.json.WxMpGsonBuilder;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -29,6 +36,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;
@@ -40,17 +49,12 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.*;
public class WxMpServiceImpl implements WxMpService {
protected final String RANDOM_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
protected final Random RANDOM = new Random();
protected final Logger log = LoggerFactory.getLogger(WxMpServiceImpl.class);
/**
@@ -148,9 +152,9 @@ public class WxMpServiceImpl implements WxMpService {
return wxMpConfigStorage.getJsapiTicket();
}
public WxMpJsapiSignature createJsapiSignature(String url) throws WxErrorException {
public WxJsapiSignature createJsapiSignature(String url) throws WxErrorException {
long timestamp = System.currentTimeMillis() / 1000;
String noncestr = getRandomStr();
String noncestr = RandomUtils.getRandomStr();
String jsapiTicket = getJsapiTicket(false);
try {
String signature = SHA1.genWithAmple(
@@ -159,7 +163,7 @@ public class WxMpServiceImpl implements WxMpService {
"timestamp=" + timestamp,
"url=" + url
);
WxMpJsapiSignature jsapiSignature = new WxMpJsapiSignature();
WxJsapiSignature jsapiSignature = new WxJsapiSignature();
jsapiSignature.setTimestamp(timestamp);
jsapiSignature.setNoncestr(noncestr);
jsapiSignature.setUrl(url);
@@ -170,14 +174,6 @@ public class WxMpServiceImpl implements WxMpService {
}
}
protected String getRandomStr() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 16; i++) {
sb.append(RANDOM_STR.charAt(RANDOM.nextInt(RANDOM_STR.length())));
}
return sb.toString();
}
public void customMessageSend(WxMpCustomMessage message) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send";
execute(new SimplePostRequestExecutor(), url, message.toJson());
@@ -341,6 +337,19 @@ 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";
@@ -372,9 +381,14 @@ public class WxMpServiceImpl implements WxMpService {
@Override
public String oauth2buildAuthorizationUrl(String scope, String state) {
return this.oauth2buildAuthorizationUrl(wxMpConfigStorage.getOauth2redirectUri(), scope, state);
}
@Override
public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state) {
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" ;
url += "appid=" + wxMpConfigStorage.getAppId();
url += "&redirect_uri=" + URIUtil.encodeURIComponent(wxMpConfigStorage.getOauth2redirectUri());
url += "&redirect_uri=" + URIUtil.encodeURIComponent(redirectURI);
url += "&response_type=code";
url += "&scope=" + scope;
if (state != null) {
@@ -446,7 +460,7 @@ public class WxMpServiceImpl implements WxMpService {
@Override
public boolean oauth2validateAccessToken(WxMpOAuth2AccessToken oAuth2AccessToken) {
String url = "https://api.weixin.qq.com/sns/auth?";
url += "access_token=" + oAuth2AccessToken;
url += "access_token=" + oAuth2AccessToken.getAccessToken();
url += "&openid=" + oAuth2AccessToken.getOpenId();
try {
@@ -462,6 +476,42 @@ public class WxMpServiceImpl implements WxMpService {
return true;
}
@Override
public String[] getCallbackIP() throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip";
String responseContent = get(url, null);
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
JsonArray ipList = tmpJsonElement.getAsJsonObject().get("ip_list").getAsJsonArray();
String[] ipArray = new String[ipList.size()];
for (int i = 0; i < ipList.size(); i++) {
ipArray[i] = ipList.get(i).getAsString();
}
return ipArray;
}
@Override
public List<WxMpUserSummary> getUserSummary(Date beginDate, Date endDate) throws WxErrorException {
String url = "https://api.weixin.qq.com/datacube/getusersummary";
JsonObject param = new JsonObject();
param.addProperty("begin_date", SIMPLE_DATE_FORMAT.format(beginDate));
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());
}
@Override
public List<WxMpUserCumulate> getUserCumulate(Date beginDate, Date endDate) throws WxErrorException {
String url = "https://api.weixin.qq.com/datacube/getusercumulate";
JsonObject param = new JsonObject();
param.addProperty("begin_date", SIMPLE_DATE_FORMAT.format(beginDate));
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());
}
public String get(String url, String queryParam) throws WxErrorException {
return execute(new SimpleGetRequestExecutor(), url, queryParam);
}
@@ -581,4 +631,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 = httpClient.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

@@ -3,6 +3,7 @@ package me.chanjar.weixin.mp.bean;
import me.chanjar.weixin.mp.bean.custombuilder.*;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@@ -11,7 +12,7 @@ import java.util.List;
* @author chanjarster
*
*/
public class WxMpCustomMessage {
public class WxMpCustomMessage implements Serializable {
private String toUser;
private String msgType;

View File

@@ -2,12 +2,14 @@ package me.chanjar.weixin.mp.bean;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* 微信用户分组
* @author chanjarster
*
*/
public class WxMpGroup {
public class WxMpGroup implements Serializable {
private long id = -1;
private String name;

View File

@@ -2,12 +2,14 @@ package me.chanjar.weixin.mp.bean;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* 分组群发的消息
*
* @author chanjarster
*/
public class WxMpMassGroupMessage {
public class WxMpMassGroupMessage implements Serializable {
private Long groupId;
private String msgtype;

View File

@@ -2,6 +2,7 @@ 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;
@@ -10,7 +11,7 @@ import java.util.List;
* @author chanjarster
*
*/
public class WxMpMassNews {
public class WxMpMassNews implements Serializable {
private List<WxMpMassNewsArticle> articles = new ArrayList<WxMpMassNewsArticle>();

View File

@@ -2,6 +2,7 @@ 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;
@@ -10,7 +11,7 @@ import java.util.List;
*
* @author chanjarster
*/
public class WxMpMassOpenIdsMessage {
public class WxMpMassOpenIdsMessage implements Serializable {
private List<String> toUsers = new ArrayList<String>();
private String msgType;

View File

@@ -2,12 +2,14 @@ package me.chanjar.weixin.mp.bean;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* 群发时用到的视频素材
*
* @author chanjarster
*/
public class WxMpMassVideo {
public class WxMpMassVideo implements Serializable {
private String mediaId;
private String title;

View File

@@ -2,6 +2,8 @@ package me.chanjar.weixin.mp.bean;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* 语义理解查询用对象
*
@@ -9,7 +11,7 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
*
* @author Daniel Qian
*/
public class WxMpSemanticQuery {
public class WxMpSemanticQuery implements Serializable {
private String query;
private String category;

View File

@@ -1,9 +1,11 @@
package me.chanjar.weixin.mp.bean;
import java.io.Serializable;
/**
* @author Daniel Qian
*/
public class WxMpTemplateData {
public class WxMpTemplateData implements Serializable {
private String name;
private String value;

View File

@@ -2,10 +2,11 @@ package me.chanjar.weixin.mp.bean;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class WxMpTemplateMessage {
public class WxMpTemplateMessage implements Serializable {
private String toUser;
private String templateId;

View File

@@ -10,6 +10,7 @@ import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@@ -25,7 +26,7 @@ import java.util.List;
* @author chanjarster
*/
@XStreamAlias("xml")
public class WxMpXmlMessage {
public class WxMpXmlMessage implements Serializable {
///////////////////////
// 以下都是微信推送过来的消息的xml的element所对应的属性

View File

@@ -8,8 +8,10 @@ import me.chanjar.weixin.mp.bean.outxmlbuilder.*;
import me.chanjar.weixin.mp.util.crypto.WxMpCryptUtil;
import me.chanjar.weixin.mp.util.xml.XStreamTransformer;
import java.io.Serializable;
@XStreamAlias("xml")
public abstract class WxMpXmlOutMessage {
public abstract class WxMpXmlOutMessage implements Serializable {
@XStreamAlias("ToUserName")
@XStreamConverter(value=XStreamCDataConverter.class)

View File

@@ -2,6 +2,8 @@ package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* <pre>
* 群发消息一发送就返回的结果
@@ -13,7 +15,7 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
* @author chanjarster
*
*/
public class WxMpMassSendResult {
public class WxMpMassSendResult implements Serializable {
private String errorCode;
private String errorMsg;

View File

@@ -2,6 +2,8 @@ package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* <pre>
* 上传群发用的素材的结果
@@ -10,7 +12,7 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
* @author chanjarster
*
*/
public class WxMpMassUploadResult {
public class WxMpMassUploadResult implements Serializable {
private String type;
private String mediaId;

View File

@@ -2,7 +2,9 @@ package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
public class WxMpOAuth2AccessToken {
import java.io.Serializable;
public class WxMpOAuth2AccessToken implements Serializable {
private String accessToken;

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

@@ -2,12 +2,14 @@ package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* 换取二维码的Ticket
*
* @author chanjarster
*/
public class WxMpQrCodeTicket {
public class WxMpQrCodeTicket implements Serializable {
protected String ticket;
protected int expire_seconds = -1;

View File

@@ -2,6 +2,8 @@ package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* 语义理解查询结果对象
*
@@ -9,7 +11,7 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
*
* @author Daniel Qian
*/
public class WxMpSemanticQueryResult {
public class WxMpSemanticQueryResult implements Serializable {
private String query;
private String type;

View File

@@ -2,12 +2,14 @@ package me.chanjar.weixin.mp.bean.result;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import java.io.Serializable;
/**
* 微信用户信息
* @author chanjarster
*
*/
public class WxMpUser {
public class WxMpUser implements Serializable {
protected Boolean subscribe;
protected String openId;
@@ -20,7 +22,11 @@ public class WxMpUser {
protected String headImgUrl;
protected Long subscribeTime;
protected String unionId;
protected Integer sexId;
public Boolean getSubscribe() {
return subscribe;
}
public Boolean isSubscribe() {
return subscribe;
}
@@ -87,7 +93,16 @@ public class WxMpUser {
public void setUnionId(String unionId) {
this.unionId = unionId;
}
public Integer getSexId() {
return sexId;
}
public void setSexId(Integer sexId) {
this.sexId = sexId;
}
public static WxMpUser fromJson(String json) {
return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUser.class);
}

View File

@@ -0,0 +1,41 @@
package me.chanjar.weixin.mp.bean.result;
import java.io.Serializable;
import java.util.Date;
/**
* <pre>
* 累计用户数据接口的返回JSON数据包
* http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html
* </pre>
*/
public class WxMpUserCumulate implements Serializable {
private Date refDate;
private Integer cumulateUser;
public Date getRefDate() {
return refDate;
}
public void setRefDate(Date refDate) {
this.refDate = refDate;
}
public Integer getCumulateUser() {
return cumulateUser;
}
public void setCumulateUser(Integer cumulateUser) {
this.cumulateUser = cumulateUser;
}
@Override
public String toString() {
return "WxMpUserCumulate{" +
"refDate=" + refDate +
", cumulateUser=" + cumulateUser +
'}';
}
}

View File

@@ -0,0 +1,63 @@
package me.chanjar.weixin.mp.bean.result;
import java.io.Serializable;
import java.util.Date;
/**
* <pre>
* 用户增减数据接口的返回JSON数据包
* http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html
* </pre>
*/
public class WxMpUserSummary implements Serializable {
private Date refDate;
private Integer userSource;
private Integer newUser;
private Integer cancelUser;
public Date getRefDate() {
return refDate;
}
public void setRefDate(Date refDate) {
this.refDate = refDate;
}
public Integer getUserSource() {
return userSource;
}
public void setUserSource(Integer userSource) {
this.userSource = userSource;
}
public Integer getNewUser() {
return newUser;
}
public void setNewUser(Integer newUser) {
this.newUser = newUser;
}
public Integer getCancelUser() {
return cancelUser;
}
public void setCancelUser(Integer cancelUser) {
this.cancelUser = cancelUser;
}
@Override
public String toString() {
return "WxMpUserSummary{" +
"refDate=" + refDate +
", userSource=" + userSource +
", newUser=" + newUser +
", cancelUser=" + cancelUser +
'}';
}
}

View File

@@ -16,7 +16,7 @@ public class WxMpGsonBuilder {
INSTANCE.registerTypeAdapter(WxMpMassGroupMessage.class, new WxMpMassGroupMessageGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMassOpenIdsMessage.class, new WxMpMassOpenIdsMessageGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpGroup.class, new WxMpGroupGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpUser.class, new WxUserGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpUser.class, new WxMpUserGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpUserList.class, new WxUserListGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpMassVideo.class, new WxMpMassVideoAdapter());
INSTANCE.registerTypeAdapter(WxMpMassSendResult.class, new WxMpMassSendResultAdapter());
@@ -25,6 +25,8 @@ public class WxMpGsonBuilder {
INSTANCE.registerTypeAdapter(WxMpTemplateMessage.class, new WxMpTemplateMessageGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpSemanticQueryResult.class, new WxMpSemanticQueryResultAdapter());
INSTANCE.registerTypeAdapter(WxMpOAuth2AccessToken.class, new WxMpOAuth2AccessTokenAdapter());
INSTANCE.registerTypeAdapter(WxMpUserSummary.class, new WxMpUserSummaryGsonAdapter());
INSTANCE.registerTypeAdapter(WxMpUserCumulate.class, new WxMpUserCumulateGsonAdapter());
}
public static Gson create() {

View File

@@ -0,0 +1,47 @@
/*
* 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.WxMpMassUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpUserCumulate;
import me.chanjar.weixin.mp.bean.result.WxMpUserSummary;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
*
* @author Daniel Qian
*
*/
public class WxMpUserCumulateGsonAdapter implements JsonDeserializer<WxMpUserCumulate> {
private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
public WxMpUserCumulate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
WxMpUserCumulate cumulate = new WxMpUserCumulate();
JsonObject summaryJsonObject = json.getAsJsonObject();
try {
String refDate = GsonHelper.getString(summaryJsonObject, "ref_date");
if (refDate != null) {
cumulate.setRefDate(SIMPLE_DATE_FORMAT.parse(refDate));
}
cumulate.setCumulateUser(GsonHelper.getInteger(summaryJsonObject, "cumulate_user"));
} catch (ParseException e) {
throw new JsonParseException(e);
}
return cumulate;
}
}

View File

@@ -14,7 +14,7 @@ import me.chanjar.weixin.mp.bean.result.WxMpUser;
import java.lang.reflect.Type;
public class WxUserGsonAdapter implements JsonDeserializer<WxMpUser> {
public class WxMpUserGsonAdapter implements JsonDeserializer<WxMpUser> {
public WxMpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject o = json.getAsJsonObject();
@@ -29,10 +29,11 @@ public class WxUserGsonAdapter implements JsonDeserializer<WxMpUser> {
wxMpUser.setProvince(GsonHelper.getString(o, "province"));
wxMpUser.setSubscribeTime(GsonHelper.getLong(o, "subscribe_time"));
wxMpUser.setUnionId(GsonHelper.getString(o, "unionid"));
Integer sex = GsonHelper.getInteger(o, "sex");
if(new Integer(1).equals(sex)) {
Integer sexId = GsonHelper.getInteger(o, "sex");
wxMpUser.setSexId(sexId);
if(new Integer(1).equals(sexId)) {
wxMpUser.setSex("");
} else if (new Integer(2).equals(sex)) {
} else if (new Integer(2).equals(sexId)) {
wxMpUser.setSex("");
} else {
wxMpUser.setSex("未知");

View File

@@ -0,0 +1,47 @@
/*
* 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.WxMpMassUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpUserSummary;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
* @author Daniel Qian
*/
public class WxMpUserSummaryGsonAdapter implements JsonDeserializer<WxMpUserSummary> {
private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
public WxMpUserSummary deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
WxMpUserSummary summary = new WxMpUserSummary();
JsonObject summaryJsonObject = json.getAsJsonObject();
try {
String refDate = GsonHelper.getString(summaryJsonObject, "ref_date");
if (refDate != null) {
summary.setRefDate(SIMPLE_DATE_FORMAT.parse(refDate));
}
summary.setUserSource(GsonHelper.getInteger(summaryJsonObject, "user_source"));
summary.setNewUser(GsonHelper.getInteger(summaryJsonObject, "new_user"));
summary.setCancelUser(GsonHelper.getInteger(summaryJsonObject, "cancel_user"));
} catch (ParseException e) {
throw new JsonParseException(e);
}
return summary;
}
}

View File

@@ -22,9 +22,11 @@ public class WxUserListGsonAdapter implements JsonDeserializer<WxMpUserList> {
wxMpUserList.setTotal(GsonHelper.getInteger(o, "total"));
wxMpUserList.setCount(GsonHelper.getInteger(o, "count"));
wxMpUserList.setNextOpenId(GsonHelper.getString(o, "next_openid"));
JsonArray data = o.get("data").getAsJsonObject().get("openid").getAsJsonArray();
for (int i = 0; i < data.size(); i++) {
wxMpUserList.getOpenIds().add(GsonHelper.getAsString(data.get(i)));
if (!o.get("data").isJsonNull() && !o.get("data").getAsJsonObject().get("openid").isJsonNull()) {
JsonArray data = o.get("data").getAsJsonObject().get("openid").getAsJsonArray();
for (int i = 0; i < data.size(); i++) {
wxMpUserList.getOpenIds().add(GsonHelper.getAsString(data.get(i)));
}
}
return wxMpUserList;
}

View File

@@ -24,9 +24,54 @@ public class WxMpMenuAPITest {
@Test(dataProvider = "menu")
public void testCreateMenu(WxMenu wxMenu) throws WxErrorException {
System.out.println(wxMenu.toJson());
wxService.menuCreate(wxMenu);
}
@Test
public void testCreateMenu2() throws WxErrorException {
String a = "{\n"
+ " \"menu\": {\n"
+ " \"button\": [\n"
+ " {\n"
+ " \"type\": \"click\",\n"
+ " \"name\": \"今日歌曲\",\n"
+ " \"key\": \"V1001_TODAY_MUSIC\"\n"
+ " },\n"
+ " {\n"
+ " \"type\": \"click\",\n"
+ " \"name\": \"歌手简介\",\n"
+ " \"key\": \"V1001_TODAY_SINGER\"\n"
+ " },\n"
+ " {\n"
+ " \"name\": \"菜单\",\n"
+ " \"sub_button\": [\n"
+ " {\n"
+ " \"type\": \"view\",\n"
+ " \"name\": \"搜索\",\n"
+ " \"url\": \"http://www.soso.com/\"\n"
+ " },\n"
+ " {\n"
+ " \"type\": \"view\",\n"
+ " \"name\": \"视频\",\n"
+ " \"url\": \"http://v.qq.com/\"\n"
+ " },\n"
+ " {\n"
+ " \"type\": \"click\",\n"
+ " \"name\": \"赞一下我们\",\n"
+ " \"key\": \"V1001_GOOD\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ "}";
WxMenu menu = WxMenu.fromJson(a);
System.out.println(menu.toJson());
wxService.menuCreate(menu);
}
@Test(dependsOnMethods = { "testCreateMenu"})
public void testGetMenu() throws WxErrorException {
Assert.assertNotNull(wxService.menuGet());

View File

@@ -0,0 +1,69 @@
package me.chanjar.weixin.mp.api;
import com.google.inject.Inject;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSession;
import me.chanjar.weixin.mp.bean.WxMpMassGroupMessage;
import me.chanjar.weixin.mp.bean.WxMpMassNews;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.WxMpMassVideo;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;
import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpUserCumulate;
import me.chanjar.weixin.mp.bean.result.WxMpUserSummary;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
*
* @author chanjarster
*
*/
@Test(groups = "miscAPI", dependsOnGroups = { "baseAPI"})
@Guice(modules = ApiTestModule.class)
public class WxMpMiscAPITest {
@Inject
protected WxMpServiceImpl wxService;
@Test
public void testGetCallbackIP() throws WxErrorException {
String[] ipArray = wxService.getCallbackIP();
System.out.println(Arrays.toString(ipArray));
Assert.assertNotNull(ipArray);
Assert.assertNotEquals(ipArray.length, 0);
}
@Test
public void testGetUserSummary() throws WxErrorException, ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = simpleDateFormat.parse("2015-01-01");
Date endDate = simpleDateFormat.parse("2015-01-02");
List<WxMpUserSummary> summaries = wxService.getUserSummary(beginDate, endDate);
System.out.println(summaries);
Assert.assertNotNull(summaries);
}
@Test
public void testGetUserCumulate() throws WxErrorException, ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = simpleDateFormat.parse("2015-01-01");
Date endDate = simpleDateFormat.parse("2015-01-02");
List<WxMpUserCumulate> cumulates = wxService.getUserCumulate(beginDate, endDate);
System.out.println(cumulates);
Assert.assertNotNull(cumulates);
}
}

View File

@@ -15,6 +15,7 @@
<class name="me.chanjar.weixin.mp.api.WxMpShortUrlAPITest" />
<class name="me.chanjar.weixin.mp.api.WxMpMessageRouterTest" />
<class name="me.chanjar.weixin.mp.api.WxMpJsAPITest" />
<class name="me.chanjar.weixin.mp.api.WxMpMiscAPITest" />
</classes>
</test>