整理及重构

This commit is contained in:
Daniel Qian
2014-10-22 10:29:47 +08:00
parent 67795a092d
commit a8f5d07ff3
212 changed files with 1701 additions and 3459 deletions

View File

@@ -0,0 +1,30 @@
package me.chanjar.weixin.cp.api;
import me.chanjar.weixin.common.bean.WxAccessToken;
/**
* 微信客户端配置存储
* @author Daniel Qian
*
*/
public interface WxCpConfigStorage {
public void updateAccessToken(WxAccessToken accessToken);
public void updateAccessToken(String accessToken, int expiresIn);
public String getAccessToken();
public String getCorpId();
public String getCorpSecret();
public String getAgentId();
public String getToken();
public String getAesKey();
public int getExpiresIn();
}

View File

@@ -0,0 +1,81 @@
package me.chanjar.weixin.cp.api;
public class WxCpConsts {
///////////////////////
// 微信推送过来的消息的类型和发送给微信xml格式消息的消息类型
///////////////////////
public static final String XML_MSG_TEXT = "text";
public static final String XML_MSG_IMAGE = "image";
public static final String XML_MSG_VOICE = "voice";
public static final String XML_MSG_VIDEO = "video";
public static final String XML_MSG_NEWS = "news";
public static final String XML_MSG_LOCATION = "location";
public static final String XML_MSG_LINK = "link";
public static final String XML_MSG_EVENT = "event";
///////////////////////
// 消息的消息类型
///////////////////////
public static final String CUSTOM_MSG_TEXT = "text";
public static final String CUSTOM_MSG_IMAGE = "image";
public static final String CUSTOM_MSG_VOICE = "voice";
public static final String CUSTOM_MSG_VIDEO = "video";
public static final String CUSTOM_MSG_NEWS = "news";
public static final String CUSTOM_MSG_FILE = "file";
///////////////////////
// 微信端推送过来的事件类型
///////////////////////
public static final String EVT_SUBSCRIBE = "subscribe";
public static final String EVT_UNSUBSCRIBE = "unsubscribe";
public static final String EVT_SCAN = "SCAN";
public static final String EVT_LOCATION = "LOCATION";
public static final String EVT_CLICK = "CLICK";
public static final String EVT_VIEW = "VIEW";
public static final String EVT_MASS_SEND_JOB_FINISH = "MASSSENDJOBFINISH";
public static final String EVT_SCANCODE_PUSH = "scancode_push";
public static final String EVT_SCANCODE_WAITMSG = "scancode_waitmsg";
public static final String EVT_PIC_SYSPHOTO = "pic_sysphoto";
public static final String EVT_PIC_PHOTO_OR_ALBUM = "pic_photo_or_album";
public static final String EVT_PIC_WEIXIN = "pic_weixin";
public static final String EVT_LOCATION_SELECT = "location_select";
///////////////////////
// 上传多媒体文件的类型
///////////////////////
public static final String MEDIA_IMAGE = "image";
public static final String MEDIA_VOICE = "voice";
public static final String MEDIA_VIDEO = "video";
public static final String MEDIA_FILE = "file";
///////////////////////
// 文件类型
///////////////////////
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_MP4 = "mp4";
///////////////////////
// 自定义菜单的按钮类型
///////////////////////
/** 点击推事件 */
public static final String BUTTON_CLICK = "click";
/** 跳转URL */
public static final String BUTTON_VIEW = "view";
/** 扫码推事件 */
public static final String BUTTON_SCANCODE_PUSH = "scancode_push";
/** 扫码推事件且弹出“消息接收中”提示框 */
public static final String BUTTON_SCANCODE_WAITMSG = "scancode_waitmsg";
/** 弹出系统拍照发图 */
public static final String PIC_SYSPHOTO = "pic_sysphoto";
/** 弹出拍照或者相册发图 */
public static final String PIC_PHOTO_OR_ALBUM = "pic_photo_or_album";
/** 弹出微信相册发图器 */
public static final String PIC_WEIXIN = "pic_weixin";
/** 弹出地理位置选择器 */
public static final String LOCATION_SELECT = "location_select";
}

View File

@@ -0,0 +1,98 @@
package me.chanjar.weixin.cp.api;
import me.chanjar.weixin.common.bean.WxAccessToken;
/**
* 基于内存的微信配置provider在实际生产环境中应该将这些配置持久化
* @author Daniel Qian
*
*/
public class WxCpInMemoryConfigStorage implements WxCpConfigStorage {
protected String corpId;
protected String corpSecret;
protected String token;
protected String accessToken;
protected String aesKey;
protected String agentId;
protected int expiresIn;
public void updateAccessToken(WxAccessToken accessToken) {
updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
}
public void updateAccessToken(String accessToken, int expiresIn) {
this.accessToken = accessToken;
this.expiresIn = expiresIn;
}
public String getAccessToken() {
return this.accessToken;
}
public String getCorpId() {
return this.corpId;
}
public String getCorpSecret() {
return this.corpSecret;
}
public String getToken() {
return this.token;
}
public int getExpiresIn() {
return this.expiresIn;
}
public void setCorpId(String corpId) {
this.corpId = corpId;
}
public void setCorpSecret(String corpSecret) {
this.corpSecret = corpSecret;
}
public void setToken(String token) {
this.token = token;
}
public String getAesKey() {
return aesKey;
}
public void setAesKey(String aesKey) {
this.aesKey = aesKey;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public String getAgentId() {
return agentId;
}
public void setAgentId(String agentId) {
this.agentId = agentId;
}
@Override
public String toString() {
return "WxInMemoryCpConfigStorage{" +
"appidOrCorpid='" + corpId + '\'' +
", corpSecret='" + corpSecret + '\'' +
", token='" + token + '\'' +
", accessToken='" + accessToken + '\'' +
", aesKey='" + aesKey + '\'' +
", agentId='" + agentId + '\'' +
", expiresIn=" + expiresIn +
'}';
}
}

View File

@@ -0,0 +1,23 @@
package me.chanjar.weixin.cp.api;
import java.util.Map;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
/**
* 处理微信推送消息的处理器接口
* @author Daniel Qian
*
*/
public interface WxCpMessageHandler {
/**
*
* @param wxMessage
* @param context 上下文如果handler或interceptor之间有信息要传递可以用这个
* @return xml格式的消息如果在异步规则里处理的话可以返回null
*/
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context);
}

View File

@@ -0,0 +1,22 @@
package me.chanjar.weixin.cp.api;
import java.util.Map;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
/**
* 微信消息拦截器,可以用来做验证
* @author Daniel Qian
*
*/
public interface WxCpMessageInterceptor {
/**
* 拦截微信消息
* @param wxMessage
* @param context 上下文如果handler或interceptor之间有信息要传递可以用这个
* @return true代表OKfalse代表不OK
*/
public boolean intercept(WxCpXmlMessage wxMessage, Map<String, Object> context);
}

View File

@@ -0,0 +1,307 @@
package me.chanjar.weixin.cp.api;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
/**
* <pre>
* 微信消息路由器通过代码化的配置把来自微信的消息交给handler处理
*
* 说明:
* 1. 配置路由规则时要按照从细到粗的原则,否则可能消息可能会被提前处理
* 2. 默认情况下消息只会被处理一次,除非使用 {@link Rule#next()}
* 3. 规则的结束必须用{@link Rule#end()}或者{@link Rule#next()},否则不会生效
*
* 使用方法:
* WxCpMessageRouter router = new WxCpMessageRouter();
* router
* .rule()
* .msgType("MSG_TYPE").event("EVENT").eventKey("EVENT_KEY").content("CONTENT")
* .interceptor(interceptor, ...).handler(handler, ...)
* .end()
* .rule()
* // 另外一个匹配规则
* .end()
* ;
*
* // 将WxXmlMessage交给消息路由器
* router.route(message);
*
* </pre>
* @author Daniel Qian
*
*/
public class WxCpMessageRouter {
private final List<Rule> rules = new ArrayList<Rule>();
private final ExecutorService es = Executors.newCachedThreadPool();
/**
* 开始一个新的Route规则
* @return
*/
public Rule rule() {
return new Rule(this);
}
/**
* 处理微信消息
* @param wxMessage
*/
public WxCpXmlOutMessage route(final WxCpXmlMessage wxMessage) {
final List<Rule> matchRules = new ArrayList<Rule>();
// 收集匹配的规则
for (final Rule rule : rules) {
if (rule.test(wxMessage)) {
matchRules.add(rule);
}
}
if (matchRules.size() == 0) {
return null;
}
if (matchRules.get(0).async) {
// 只要第一个是异步的,那就异步执行
// 在另一个线程里执行
es.submit(new Runnable() {
public void run() {
for (final Rule rule : matchRules) {
rule.service(wxMessage);
if (!rule.reEnter) {
break;
}
}
}
});
return null;
}
WxCpXmlOutMessage res = null;
for (final Rule rule : matchRules) {
// 返回最后一个匹配规则的结果
res = rule.service(wxMessage);
if (!rule.reEnter) {
break;
}
}
return res;
}
public static class Rule {
private final WxCpMessageRouter routerBuilder;
private boolean async = true;
private String msgType;
private String event;
private String eventKey;
private String content;
private String rContent;
private boolean reEnter = false;
private Integer agentId;
private List<WxCpMessageHandler> handlers = new ArrayList<WxCpMessageHandler>();
private List<WxCpMessageInterceptor> interceptors = new ArrayList<WxCpMessageInterceptor>();
protected Rule(WxCpMessageRouter routerBuilder) {
this.routerBuilder = routerBuilder;
}
/**
* 设置是否异步执行默认是true
* @param async
* @return
*/
public Rule async(boolean async) {
this.async = async;
return this;
}
/**
* 如果agentId匹配
* @param agentId
* @return
*/
public Rule agentId(Integer agentId) {
this.agentId = agentId;
return this;
}
/**
* 如果msgType等于某值
* @param msgType
* @return
*/
public Rule msgType(String msgType) {
this.msgType = msgType;
return this;
}
/**
* 如果event等于某值
* @param event
* @return
*/
public Rule event(String event) {
this.event = event;
return this;
}
/**
* 如果eventKey等于某值
* @param eventKey
* @return
*/
public Rule eventKey(String eventKey) {
this.eventKey = eventKey;
return this;
}
/**
* 如果content等于某值
* @param content
* @return
*/
public Rule content(String content) {
this.content = content;
return this;
}
/**
* 如果content匹配该正则表达式
* @param regex
* @return
*/
public Rule rContent(String regex) {
this.rContent = regex;
return this;
}
/**
* 设置微信消息拦截器
* @param interceptor
* @return
*/
public Rule interceptor(WxCpMessageInterceptor interceptor) {
return interceptor(interceptor, (WxCpMessageInterceptor[]) null);
}
/**
* 设置微信消息拦截器
* @param interceptor
* @param otherInterceptors
* @return
*/
public Rule interceptor(WxCpMessageInterceptor interceptor, WxCpMessageInterceptor... otherInterceptors) {
this.interceptors.add(interceptor);
if (otherInterceptors != null && otherInterceptors.length > 0) {
for (WxCpMessageInterceptor i : otherInterceptors) {
this.interceptors.add(i);
}
}
return this;
}
/**
* 设置微信消息处理器
* @param handler
* @return
*/
public Rule handler(WxCpMessageHandler handler) {
return handler(handler, (WxCpMessageHandler[]) null);
}
/**
* 设置微信消息处理器
* @param handler
* @param otherHandlers
* @return
*/
public Rule handler(WxCpMessageHandler handler, WxCpMessageHandler... otherHandlers) {
this.handlers.add(handler);
if (otherHandlers != null && otherHandlers.length > 0) {
for (WxCpMessageHandler i : otherHandlers) {
this.handlers.add(i);
}
}
return this;
}
/**
* 规则结束,代表如果一个消息匹配该规则,那么它将不再会进入其他规则
* @return
*/
public WxCpMessageRouter end() {
this.routerBuilder.rules.add(this);
return this.routerBuilder;
}
/**
* 规则结束,但是消息还会进入其他规则
* @return
*/
public WxCpMessageRouter next() {
this.reEnter = true;
return end();
}
protected boolean test(WxCpXmlMessage wxMessage) {
return
(this.agentId == null || this.agentId.equals(wxMessage.getAgentId()))
&&
(this.msgType == null || this.msgType.equals(wxMessage.getMsgType()))
&&
(this.event == null || this.event.equals(wxMessage.getEvent()))
&&
(this.eventKey == null || this.eventKey.equals(wxMessage.getEventKey()))
&&
(this.content == null || this.content.equals(wxMessage.getContent() == null ? null : wxMessage.getContent().trim()))
&&
(this.rContent == null || Pattern.matches(this.rContent, wxMessage.getContent() == null ? "" : wxMessage.getContent().trim()))
;
}
/**
* 处理微信推送过来的消息
* @param wxMessage
* @return true 代表继续执行别的routerfalse 代表停止执行别的router
*/
protected WxCpXmlOutMessage service(WxCpXmlMessage wxMessage) {
Map<String, Object> context = new HashMap<String, Object>();
// 如果拦截器不通过
for (WxCpMessageInterceptor interceptor : this.interceptors) {
if (!interceptor.intercept(wxMessage, context)) {
return null;
}
}
// 交给handler处理
WxCpXmlOutMessage res = null;
for (WxCpMessageHandler handler : this.handlers) {
// 返回最后handler的结果
res = handler.handle(wxMessage, context);
}
return res;
}
}
}

View File

@@ -0,0 +1,290 @@
package me.chanjar.weixin.cp.api;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.cp.bean.*;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.common.exception.WxErrorException;
/**
* 微信API的Service
*/
public interface WxCpService {
/**
* <pre>
* 验证推送过来的消息的正确性
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=验证消息真实性
* </pre>
*
* @param msgSignature
* @param timestamp
* @param nonce
* @param data 微信传输过来的数据有可能是echoStr有可能是xml消息
* @return
*/
public boolean checkSignature(String msgSignature, String timestamp, String nonce, String data);
/**
* <pre>
* 用在二次验证的时候
* 企业在员工验证成功后,调用本方法告诉企业号平台该员工关注成功。
* </pre>
*
* @param userId
*/
public void userAuthenticated(String userId) throws WxErrorException;
/**
* <pre>
* 获取access_token本方法线程安全
* 且在多线程同时刷新时只刷新一次避免超出2000次/日的调用次数上限
* 另本service的所有方法都会在access_token过期是调用此方法
* 程序员在非必要情况下尽量不要主动调用此方法
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=获取access_token
* </pre>
*
* @throws me.chanjar.weixin.common.exception.WxErrorException
*/
public void accessTokenRefresh() throws WxErrorException;
/**
* <pre>
* 上传多媒体文件
* 上传的多媒体文件有格式和大小限制,如下:
* 图片image: 1M支持JPG格式
* 语音voice2M播放长度不超过60s支持AMR\MP3格式
* 视频video10MB支持MP4格式
* 缩略图thumb64KB支持JPG格式
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=上传下载多媒体文件
* </pre>
*
* @param mediaType 媒体类型, 请看{@link WxCpConsts}
* @param fileType 文件类型,请看{@link WxCpConsts}
* @param inputStream 输入流
* @throws WxErrorException
*/
public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream)
throws WxErrorException, IOException;
/**
* @param mediaType
* @param file
* @throws WxErrorException
* @see #mediaUpload(String, String, InputStream)
*/
public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException;
/**
* <pre>
* 下载多媒体文件
* 根据微信文档视频文件下载不了会返回null
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=上传下载多媒体文件
* </pre>
*
* @return 保存到本地的临时文件
* @throws WxErrorException
* @params media_id
*/
public File mediaDownload(String media_id) throws WxErrorException;
/**
* <pre>
* 发送消息
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=发送消息
* </pre>
*
* @param message
* @throws WxErrorException
*/
public void messageSend(WxCpMessage message) throws WxErrorException;
/**
* <pre>
* 自定义菜单创建接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单创建接口
* </pre>
*
* @param menu
* @throws WxErrorException
*/
public void menuCreate(WxMenu menu) throws WxErrorException;
/**
* <pre>
* 自定义菜单删除接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单删除接口
* </pre>
*
* @throws WxErrorException
*/
public void menuDelete() throws WxErrorException;
/**
* <pre>
* 自定义菜单查询接口
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=自定义菜单查询接口
* </pre>
*
* @return
* @throws WxErrorException
*/
public WxMenu menuGet() throws WxErrorException;
/**
* <pre>
* 部门管理接口 - 创建部门
* 最多支持创建500个部门
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=部门管理接口
* </pre>
*
* @param depart 部门
* @return 部门id
* @throws WxErrorException
*/
public Integer departCreate(WxCpDepart depart) throws WxErrorException;
/**
* <pre>
* 部门管理接口 - 查询所有部门
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=部门管理接口
* </pre>
*
* @return
* @throws WxErrorException
*/
public List<WxCpDepart> departGet() throws WxErrorException;
/**
* <pre>
* 部门管理接口 - 修改部门名
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=部门管理接口
* 如果id为0(未部门),1(黑名单),2(星标组)或者不存在的id微信会返回系统繁忙的错误
* </pre>
*
* @param group 要更新的groupgroup的id,name必须设置
* @throws WxErrorException
*/
public void departUpdate(WxCpDepart group) throws WxErrorException;
/**
* <pre>
* 部门管理接口 - 删除部门
* </pre>
*
* @param departId
* @throws WxErrorException
*/
public void departDelete(Integer departId) throws WxErrorException;
/**
* http://qydev.weixin.qq.com/wiki/index.php?title=管理成员#.E8.8E.B7.E5.8F.96.E9.83.A8.E9.97.A8.E6.88.90.E5.91.98
*
* @param departId 必填。部门id
* @param fetchChild 非必填。1/0是否递归获取子部门下面的成员
* @param status 非必填。0获取全部员工1获取已关注成员列表2获取禁用成员列表4获取未关注成员列表。status可叠加
* @return
* @throws WxErrorException
*/
public List<WxCpUser> departGetUsers(Integer departId, Boolean fetchChild, Integer status) throws WxErrorException;
/**
* 新建用户
*
* @param user
* @throws WxErrorException
*/
public void userCreate(WxCpUser user) throws WxErrorException;
/**
* 更新用户
*
* @param user
* @throws WxErrorException
*/
public void userUpdate(WxCpUser user) throws WxErrorException;
/**
* 删除用户
*
* @param userid
* @throws WxErrorException
*/
public void userDelete(String userid) throws WxErrorException;
/**
* 获取用户
*
* @param userid
* @return
* @throws WxErrorException
*/
public WxCpUser userGet(String userid) throws WxErrorException;
/**
* 创建标签
*
* @param tagName
* @return
*/
public String tagCreate(String tagName) throws WxErrorException;
/**
* 更新标签
*
* @param tagId
* @param tagName
*/
public void tagUpdate(String tagId, String tagName) throws WxErrorException;
/**
* 删除标签
*
* @param tagId
*/
public void tagDelete(String tagId) throws WxErrorException;
/**
* 获得标签列表
*
* @return
*/
public List<WxCpTag> tagGet() throws WxErrorException;
/**
* 获取标签成员
*
* @param tagId
* @return
*/
public List<WxCpUser> tagGetUsers(String tagId) throws WxErrorException;
/**
* 增加标签成员
*
* @param tagId
* @param userIds
*/
public void tagAddUsers(String tagId, List<String> userIds) throws WxErrorException;
/**
* 移除标签成员
*
* @param tagId
* @param userIds
*/
public void tagRemoveUsers(String tagId, List<String> userIds) throws WxErrorException;
/**
* 注入 {@link WxCpConfigStorage} 的实现
*
* @param wxConfigProvider
*/
public void setWxCpConfigStorage(WxCpConfigStorage wxConfigProvider);
}

View File

@@ -0,0 +1,378 @@
package me.chanjar.weixin.cp.api;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.cp.bean.*;
import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.fs.FileUtils;
import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor;
import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor;
import com.google.gson.JsonElement;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
public class WxCpServiceImpl implements WxCpService {
/**
* 全局的是否正在刷新Access Token的flag
* true: 正在刷新
* false: 没有刷新
*/
protected static final AtomicBoolean GLOBAL_ACCESS_TOKEN_REFRESH_FLAG = new AtomicBoolean(false);
protected static final CloseableHttpClient httpclient = HttpClients.createDefault();
protected WxCpConfigStorage wxCpConfigStorage;
protected final ThreadLocal<Integer> retryTimes = new ThreadLocal<Integer>();
public boolean checkSignature(String msgSignature, String timestamp, String nonce, String data) {
try {
return SHA1.gen(wxCpConfigStorage.getToken(), timestamp, nonce, data).equals(msgSignature);
} catch (Exception e) {
return false;
}
}
public void userAuthenticated(String userId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?userid=" + userId;
execute(new SimpleGetRequestExecutor(), url, null);
}
public void accessTokenRefresh() throws WxErrorException {
if (!GLOBAL_ACCESS_TOKEN_REFRESH_FLAG.getAndSet(true)) {
try {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?"
+ "&corpid=" + wxCpConfigStorage.getCorpId()
+ "&corpsecret=" + wxCpConfigStorage.getCorpSecret();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpGet);
String resultContent = new BasicResponseHandler().handleResponse(response);
WxError error = WxError.fromJson(resultContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
wxCpConfigStorage.updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
} finally {
GLOBAL_ACCESS_TOKEN_REFRESH_FLAG.set(false);
}
} else {
// 每隔100ms检查一下是否刷新完毕了
while (GLOBAL_ACCESS_TOKEN_REFRESH_FLAG.get()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
// 刷新完毕了,就没他什么事儿了
}
}
public void messageSend(WxCpMessage message) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send";
execute(new SimplePostRequestExecutor(), url, message.toJson());
}
public void menuCreate(WxMenu menu) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?agentid=" + wxCpConfigStorage.getAgentId();
execute(new SimplePostRequestExecutor(), url, menu.toJson());
}
public void menuDelete() throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/delete?agentid=" + wxCpConfigStorage.getAgentId();
execute(new SimpleGetRequestExecutor(), url, null);
}
public WxMenu menuGet() throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/menu/get?agentid=" + wxCpConfigStorage.getAgentId();
try {
String resultContent = execute(new SimpleGetRequestExecutor(), url, null);
return WxMenu.fromJson(resultContent);
} catch (WxErrorException e) {
// 46003 不存在的菜单数据
if (e.getError().getErrorCode() == 46003) {
return null;
}
throw e;
}
}
public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream)
throws WxErrorException, IOException {
return mediaUpload(mediaType, FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType));
}
public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType;
return execute(new MediaUploadRequestExecutor(), url, file);
}
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);
}
public Integer departCreate(WxCpDepart depart) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create";
String responseContent = execute(
new SimplePostRequestExecutor(),
url,
depart.toJson());
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return GsonHelper.getAsInteger(tmpJsonElement.getAsJsonObject().get("id"));
}
public void departUpdate(WxCpDepart group) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/department/update";
execute(new SimplePostRequestExecutor(), url, group.toJson());
}
public void departDelete(Integer departId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?id=" + departId;
execute(new SimpleGetRequestExecutor(), url, null);
}
public List<WxCpDepart> departGet() throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list";
String responseContent = execute(new SimpleGetRequestExecutor(), url, null);
/*
* 操蛋的微信API创建时返回的是 { group : { id : ..., name : ...} }
* 查询时返回的是 { groups : [ { id : ..., name : ..., count : ... }, ... ] }
*/
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return WxCpGsonBuilder.INSTANCE.create()
.fromJson(
tmpJsonElement.getAsJsonObject().get("department"),
new TypeToken<List<WxCpDepart>>() { }.getType()
);
}
@Override
public void userCreate(WxCpUser user) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/create";
execute(new SimplePostRequestExecutor(), url, user.toJson());
}
@Override
public void userUpdate(WxCpUser user) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/update";
execute(new SimplePostRequestExecutor(), url, user.toJson());
}
@Override
public void userDelete(String userid) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?userid=" + userid;
execute(new SimpleGetRequestExecutor(), url, null);
}
@Override
public WxCpUser userGet(String userid) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?userid=" + userid;
String responseContent = execute(new SimpleGetRequestExecutor(), url, null);
return WxCpUser.fromJson(responseContent);
}
@Override
public List<WxCpUser> departGetUsers(Integer departId, Boolean fetchChild, Integer status) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?department_id=" + departId;
String params = "";
if (fetchChild != null) {
params += "&fetch_child=" + (fetchChild ? "1" : "0");
}
if (status != null) {
params += "&status=" + status;
} else {
params += "&status=0";
}
String responseContent = execute(new SimpleGetRequestExecutor(), url, params);
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return WxCpGsonBuilder.INSTANCE.create()
.fromJson(
tmpJsonElement.getAsJsonObject().get("userlist"),
new TypeToken<List<WxCpUser>>() { }.getType()
);
}
@Override
public String tagCreate(String tagName) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/create";
JsonObject o = new JsonObject();
o.addProperty("tagname", tagName);
String responseContent = execute(new SimplePostRequestExecutor(), url, o.toString());
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return tmpJsonElement.getAsJsonObject().get("tagid").getAsString();
}
@Override
public void tagUpdate(String tagId, String tagName) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/update";
JsonObject o = new JsonObject();
o.addProperty("tagid", tagId);
o.addProperty("tagname", tagName);
execute(new SimplePostRequestExecutor(), url, o.toString());
}
@Override
public void tagDelete(String tagId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/delete?tagid=" + tagId;
execute(new SimpleGetRequestExecutor(), url, null);
}
@Override
public List<WxCpTag> tagGet() throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list";
String responseContent = execute(new SimpleGetRequestExecutor(), url, null);
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return WxCpGsonBuilder.INSTANCE.create()
.fromJson(
tmpJsonElement.getAsJsonObject().get("taglist"),
new TypeToken<List<WxCpTag>>() { }.getType()
);
}
@Override
public List<WxCpUser> tagGetUsers(String tagId) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/get?tagid=" + tagId;
String responseContent = execute(new SimpleGetRequestExecutor(), url, null);
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return WxCpGsonBuilder.INSTANCE.create()
.fromJson(
tmpJsonElement.getAsJsonObject().get("userlist"),
new TypeToken<List<WxCpUser>>() { }.getType()
);
}
@Override
public void tagAddUsers(String tagId, List<String> userIds) 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));
}
jsonObject.add("userlist", jsonArray);
execute(new SimplePostRequestExecutor(), url, jsonObject.toString());
}
@Override
public void tagRemoveUsers(String tagId, List<String> userIds) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/deltagusers";
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("tagid", tagId);
JsonArray jsonArray = new JsonArray();
for (String userId : userIds) {
jsonArray.add(new JsonPrimitive(userId));
}
jsonObject.add("userlist", jsonArray);
execute(new SimplePostRequestExecutor(), url, jsonObject.toString());
}
/**
* 向微信端发送请求在这里执行的策略是当发生access_token过期时才去刷新然后重新执行请求而不是全局定时请求
*
* @param executor
* @param uri
* @param data
* @return
* @throws WxErrorException
*/
public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException {
if (StringUtils.isBlank(wxCpConfigStorage.getAccessToken())) {
accessTokenRefresh();
}
String accessToken = wxCpConfigStorage.getAccessToken();
String uriWithAccessToken = uri;
uriWithAccessToken += uri.indexOf('?') == -1 ? "?access_token=" + accessToken : "&access_token=" + accessToken;
try {
return executor.execute(uriWithAccessToken, data);
} catch (WxErrorException e) {
WxError error = e.getError();
/*
* 发生以下情况时尝试刷新access_token
* 40001 获取access_token时AppSecret错误或者access_token无效
* 42001 access_token超时
*/
if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001) {
accessTokenRefresh();
return execute(executor, uri, data);
}
/**
* -1 系统繁忙, 1000ms后重试
*/
if (error.getErrorCode() == -1) {
if (retryTimes.get() == null) {
retryTimes.set(0);
}
if (retryTimes.get() > 4) {
retryTimes.set(0);
throw new RuntimeException("微信服务端异常,超出重试次数");
}
int sleepMillis = 1000 * (1 << retryTimes.get());
try {
System.out.println("微信系统繁忙," + sleepMillis + "ms后重试");
Thread.sleep(sleepMillis);
retryTimes.set(retryTimes.get() + 1);
return execute(executor, uri, data);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
}
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return null;
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void setWxCpConfigStorage(WxCpConfigStorage wxConfigProvider) {
this.wxCpConfigStorage = wxConfigProvider;
}
}