big update:去除被动消息实体、commons包、dom4j包

This commit is contained in:
jinyu
2015-05-12 23:27:39 +08:00
parent 165f4b3bb8
commit 3d0c3e2c9c
84 changed files with 836 additions and 3287 deletions
+1 -6
View File
@@ -16,7 +16,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<finalName>weixin4j-mp-${project.version}</finalName>
<finalName>${project.name}-${project.version}</finalName>
</configuration>
</plugin>
</plugins>
@@ -42,11 +42,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
@@ -7,8 +7,6 @@ import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.Response;
@@ -19,6 +17,7 @@ import com.foxinmy.weixin4j.mp.payment.coupon.CouponDetail;
import com.foxinmy.weixin4j.mp.payment.coupon.CouponResult;
import com.foxinmy.weixin4j.mp.payment.coupon.CouponStock;
import com.foxinmy.weixin4j.util.RandomUtil;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* 代金券API
@@ -66,7 +65,7 @@ public class CouponApi extends MpApi {
// openid记录数(目前支持num=1
map.put("openid_count", "1");
// 操作员帐号, 默认为商户号 可在商户平台配置操作员对应的api权限
if (StringUtils.isBlank(opUserId)) {
if (StringUtil.isBlank(opUserId)) {
opUserId = weixinAccount.getMchId();
}
map.put("op_user_id", opUserId);
@@ -158,10 +157,10 @@ public class CouponApi extends MpApi {
map.put("appid", weixinAccount.getId());
map.put("mch_id", weixinAccount.getMchId());
map.put("nonce_str", RandomUtil.generateString(16));
if (StringUtils.isNotBlank(weixinAccount.getDeviceInfo())) {
if (StringUtil.isNotBlank(weixinAccount.getDeviceInfo())) {
map.put("device_info", weixinAccount.getDeviceInfo());
}
if (StringUtils.isNotBlank(weixinAccount.getSubMchId())) {
if (StringUtil.isNotBlank(weixinAccount.getSubMchId())) {
map.put("sub_mch_id", weixinAccount.getSubMchId());
}
return map;
@@ -6,7 +6,6 @@ import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.entity.mime.content.ByteArrayBody;
import com.alibaba.fastjson.JSON;
@@ -21,6 +20,7 @@ import com.foxinmy.weixin4j.mp.model.CustomRecord;
import com.foxinmy.weixin4j.mp.model.KfAccount;
import com.foxinmy.weixin4j.mp.model.KfSession;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.foxinmy.weixin4j.util.DigestUtil;
import com.foxinmy.weixin4j.util.IOUtil;
/**
@@ -136,7 +136,7 @@ public class CustomApi extends MpApi {
JSONObject obj = new JSONObject();
obj.put("kf_account", id);
obj.put("nickname", name);
obj.put("password", DigestUtils.md5Hex(pwd));
obj.put("password", DigestUtil.MD5(pwd));
String custom_add_uri = getRequestUri("custom_add_uri");
Token token = tokenHolder.getToken();
Response response = request.post(
@@ -167,7 +167,7 @@ public class CustomApi extends MpApi {
JSONObject obj = new JSONObject();
obj.put("kf_account", id);
obj.put("nickname", name);
obj.put("password", DigestUtils.md5Hex(pwd));
obj.put("password", DigestUtil.MD5(pwd));
String custom_update_uri = getRequestUri("custom_update_uri");
Token token = tokenHolder.getToken();
Response response = request.post(
@@ -3,8 +3,6 @@ package com.foxinmy.weixin4j.mp.api;
import java.io.File;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException;
@@ -17,6 +15,7 @@ import com.foxinmy.weixin4j.tuple.MpArticle;
import com.foxinmy.weixin4j.tuple.MpNews;
import com.foxinmy.weixin4j.tuple.Tuple;
import com.foxinmy.weixin4j.tuple.Video;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* 群发相关API
@@ -132,7 +131,7 @@ public class MassApi extends MpApi {
if (tuple instanceof MpNews) {
MpNews _news = (MpNews) tuple;
List<MpArticle> _articles = _news.getArticles();
if (StringUtils.isBlank(_news.getMediaId())
if (StringUtil.isBlank(_news.getMediaId())
&& (_articles == null || _articles.isEmpty())) {
throw new WeixinException(
"mass fail:mediaId or articles is required");
@@ -203,7 +202,7 @@ public class MassApi extends MpApi {
if (tuple instanceof MpNews) {
MpNews _news = (MpNews) tuple;
List<MpArticle> _articles = _news.getArticles();
if (StringUtils.isBlank(_news.getMediaId())
if (StringUtil.isBlank(_news.getMediaId())
&& (_articles == null || _articles.isEmpty())) {
throw new WeixinException(
"mass fail:mediaId or articles is required");
@@ -9,7 +9,6 @@ import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
@@ -32,6 +31,7 @@ import com.foxinmy.weixin4j.type.MediaType;
import com.foxinmy.weixin4j.util.ConfigUtil;
import com.foxinmy.weixin4j.util.FileUtil;
import com.foxinmy.weixin4j.util.IOUtil;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* 素材相关API
@@ -65,7 +65,7 @@ public class MediaApi extends MpApi {
public String uploadMedia(File file, boolean isMaterial)
throws WeixinException, IOException {
String mediaTypeKey = IOUtil.getExtension(file.getName());
if (StringUtils.isBlank(mediaTypeKey)) {
if (StringUtil.isBlank(mediaTypeKey)) {
mediaTypeKey = FileUtil.getFileType(file);
}
MediaType mediaType = MediaType.getMediaType(mediaTypeKey);
@@ -1,7 +1,5 @@
package com.foxinmy.weixin4j.mp.api;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.JsonResult;
@@ -10,6 +8,7 @@ import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.mp.message.NotifyMessage;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.foxinmy.weixin4j.tuple.NotifyTuple;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* 客服消息API
@@ -70,7 +69,7 @@ public class NotifyApi extends MpApi {
obj.put("touser", notify.getTouser());
obj.put("msgtype", msgtype);
obj.put(msgtype, tuple);
if (StringUtils.isNotBlank(kfAccount)) {
if (StringUtil.isNotBlank(kfAccount)) {
JSONObject kf = new JSONObject();
kf.put("kf_account", kfAccount);
obj.put("customservice", kf);
@@ -24,8 +24,6 @@ import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -52,7 +50,9 @@ import com.foxinmy.weixin4j.mp.util.ExcelUtil;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.foxinmy.weixin4j.util.ConfigUtil;
import com.foxinmy.weixin4j.util.DateUtil;
import com.foxinmy.weixin4j.util.DigestUtil;
import com.foxinmy.weixin4j.util.MapUtil;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* V2支付API
@@ -91,7 +91,7 @@ public class Pay2Api extends PayApi {
sb.append("&partner=").append(weixinAccount.getPartnerId());
String part = sb.toString();
sb.append("&key=").append(weixinAccount.getPartnerKey());
String sign = DigestUtils.md5Hex(sb.toString()).toUpperCase();
String sign = DigestUtil.MD5(sb.toString()).toUpperCase();
sb.delete(0, sb.length());
sb.append(part).append("&sign=").append(sign);
@@ -172,7 +172,7 @@ public class Pay2Api extends PayApi {
map.put("total_fee", DateUtil.formaFee2Fen(totalFee));
map.put("refund_fee", DateUtil.formaFee2Fen(refundFee));
map.put(idQuery.getType().getName(), idQuery.getId());
if (StringUtils.isBlank(opUserId)) {
if (StringUtil.isBlank(opUserId)) {
opUserId = weixinAccount.getPartnerId();
}
map.put("op_user_id", opUserId);
@@ -261,7 +261,7 @@ public class Pay2Api extends PayApi {
String outRefundNo, double totalFee, double refundFee,
String opUserId, String opUserPasswd) throws WeixinException {
Map<String, String> mopara = new HashMap<String, String>();
mopara.put("op_user_passwd", DigestUtils.md5Hex(opUserPasswd));
mopara.put("op_user_passwd", DigestUtil.MD5(opUserPasswd));
return refund(caFile, idQuery, outRefundNo, totalFee, refundFee,
opUserId, mopara);
}
@@ -301,11 +301,11 @@ public class Pay2Api extends PayApi {
String opUserId, String opUserPasswd, String recvUserId,
String reccvUserName, RefundType refundType) throws WeixinException {
Map<String, String> mopara = new HashMap<String, String>();
mopara.put("op_user_passwd", DigestUtils.md5Hex(opUserPasswd));
if (StringUtils.isNotBlank(recvUserId)) {
mopara.put("op_user_passwd", DigestUtil.MD5(opUserPasswd));
if (StringUtil.isNotBlank(recvUserId)) {
mopara.put("recv_user_id", recvUserId);
}
if (StringUtils.isNotBlank(reccvUserName)) {
if (StringUtil.isNotBlank(reccvUserName)) {
mopara.put("reccv_user_name", reccvUserName);
}
if (refundType != null) {
@@ -389,7 +389,7 @@ public class Pay2Api extends PayApi {
map.put("cft_signtype", "0");
map.put("mchtype", Integer.toString(billType.getVal()));
map.put("key", weixinAccount.getPartnerKey());
String sign = DigestUtils.md5Hex(MapUtil
String sign = DigestUtil.MD5(MapUtil
.toJoinString(map, false, false));
map.put("sign", sign.toLowerCase());
Response response = request.get(downloadbill_uri, map);
@@ -18,7 +18,6 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -45,6 +44,7 @@ import com.foxinmy.weixin4j.token.TokenHolder;
import com.foxinmy.weixin4j.util.ConfigUtil;
import com.foxinmy.weixin4j.util.DateUtil;
import com.foxinmy.weixin4j.util.RandomUtil;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* V3(商户平台版)支付API
@@ -134,7 +134,7 @@ public class Pay3Api extends PayApi {
map.put("out_refund_no", outRefundNo);
map.put("total_fee", DateUtil.formaFee2Fen(totalFee));
map.put("refund_fee", DateUtil.formaFee2Fen(refundFee));
if (StringUtils.isBlank(opUserId)) {
if (StringUtil.isBlank(opUserId)) {
opUserId = weixinAccount.getMchId();
}
map.put("op_user_id", opUserId);
@@ -459,7 +459,7 @@ public class Pay3Api extends PayApi {
map.put("appid", weixinAccount.getId());
map.put("mch_id", weixinAccount.getMchId());
map.put("nonce_str", RandomUtil.generateString(16));
if (StringUtils.isNotBlank(weixinAccount.getDeviceInfo())) {
if (StringUtil.isNotBlank(weixinAccount.getDeviceInfo())) {
map.put("device_info", weixinAccount.getDeviceInfo());
}
if (idQuery != null) {
@@ -1,40 +0,0 @@
package com.foxinmy.weixin4j.mp.event;
import com.foxinmy.weixin4j.message.event.EventMessage;
import com.foxinmy.weixin4j.mp.type.EventType;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* 客服关闭会话事件
*
* @className KfCloseEventMessage
* @author jy
* @date 2015年3月22日
* @since JDK 1.7
* @see <a
* href="http://mp.weixin.qq.com/wiki/2/6c20f3e323bdf5986cfcb33cbd3b829a.html#.E4.BC.9A.E8.AF.9D.E7.8A.B6.E6.80.81.E9.80.9A.E7.9F.A5.E4.BA.8B.E4.BB.B6">会话状态通知事件</a>
*/
public class KfCloseEventMessage extends EventMessage {
private static final long serialVersionUID = 3644449346935205541L;
public KfCloseEventMessage() {
super(EventType.kf_close_session.name());
}
/**
* 客服账号
*/
@XStreamAlias("KfAccount")
private String kfAccount;
public String getKfAccount() {
return kfAccount;
}
@Override
public String toString() {
return "KfCloseEventMessage [kfAccount=" + kfAccount + ", ="
+ super.toString() + "]";
}
}
@@ -1,40 +0,0 @@
package com.foxinmy.weixin4j.mp.event;
import com.foxinmy.weixin4j.message.event.EventMessage;
import com.foxinmy.weixin4j.mp.type.EventType;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* 客服接入会话事件
*
* @className KfCreateEventMessage
* @author jy
* @date 2015年3月22日
* @since JDK 1.7
* @see <a
* href="http://mp.weixin.qq.com/wiki/2/6c20f3e323bdf5986cfcb33cbd3b829a.html#.E4.BC.9A.E8.AF.9D.E7.8A.B6.E6.80.81.E9.80.9A.E7.9F.A5.E4.BA.8B.E4.BB.B6">会话状态通知事件</a>
*/
public class KfCreateEventMessage extends EventMessage {
private static final long serialVersionUID = -8968189700999202108L;
public KfCreateEventMessage() {
super(EventType.kf_create_session.name());
}
/**
* 客服账号
*/
@XStreamAlias("KfAccount")
private String kfAccount;
public String getKfAccount() {
return kfAccount;
}
@Override
public String toString() {
return "KfCreateEventMessage [kfAccount=" + kfAccount + ", ="
+ super.toString() + "]";
}
}
@@ -1,48 +0,0 @@
package com.foxinmy.weixin4j.mp.event;
import com.foxinmy.weixin4j.message.event.EventMessage;
import com.foxinmy.weixin4j.mp.type.EventType;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* 客服转接会话事件
*
* @className KfSwitchEventMessage
* @author jy
* @date 2015年3月22日
* @since JDK 1.7
* @see <a
* href="http://mp.weixin.qq.com/wiki/2/6c20f3e323bdf5986cfcb33cbd3b829a.html#.E4.BC.9A.E8.AF.9D.E7.8A.B6.E6.80.81.E9.80.9A.E7.9F.A5.E4.BA.8B.E4.BB.B6">会话状态通知事件</a>
*/
public class KfSwitchEventMessage extends EventMessage {
private static final long serialVersionUID = 4319501074109623413L;
public KfSwitchEventMessage() {
super(EventType.kf_switch_session.name());
}
/**
* 来自的客服账号
*/
@XStreamAlias("FromKfAccount")
private String fromKfAccount;
/**
* 转移给客服账号
*/
@XStreamAlias("ToKfAccount")
private String toKfAccount;
public String getFromKfAccount() {
return fromKfAccount;
}
public String getToKfAccount() {
return toKfAccount;
}
@Override
public String toString() {
return "KfSwitchEventMessage [fromKfAccount=" + fromKfAccount
+ ", toKfAccount=" + toKfAccount + "]";
}
}
@@ -1,129 +0,0 @@
package com.foxinmy.weixin4j.mp.event;
import java.util.HashMap;
import java.util.Map;
import com.foxinmy.weixin4j.message.event.EventMessage;
import com.foxinmy.weixin4j.mp.type.EventType;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
* 群发消息事件推送
*
* @className MassEventMessage
* @author jy
* @date 2014年4月27日
* @since JDK 1.7
* @see <a
* href="http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html#.E4.BA.8B.E4.BB.B6.E6.8E.A8.E9.80.81.E7.BE.A4.E5.8F.91.E7.BB.93.E6.9E.9C">群发回调</a>
*/
public class MassEventMessage extends EventMessage {
private static final long serialVersionUID = -1660543255873723895L;
public MassEventMessage() {
super(EventType.masssendjobfinish.name());
}
/**
* 群发后的状态信息 为“send success”或“send fail”或“err(num)
*/
@XStreamAlias("Status")
private String status;
/**
* group_id下粉丝数;或者openid_list中的粉丝数
*/
@XStreamAlias("TotalCount")
private int totalCount;
/**
* 过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数,原则上,FilterCount =
* SentCount + ErrorCount
*/
@XStreamAlias("FilterCount")
private int filterCount;
/**
* 发送成功的粉丝数
*/
@XStreamAlias("SentCount")
private int sentCount;
/**
* 发送失败的粉丝数
*/
@XStreamAlias("ErrorCount")
private int errorCount;
@XStreamOmitField
private final static Map<String, String> statusMap;
static {
statusMap = new HashMap<String, String>();
statusMap.put("sendsuccess", "发送成功");
statusMap.put("send_success", "发送成功");
statusMap.put("success", "发送成功");
statusMap.put("send success", "发送成功");
statusMap.put("sendfail", "发送失败");
statusMap.put("send_fail", "发送失败");
statusMap.put("fail", "发送失败");
statusMap.put("send fail", "发送失败");
statusMap.put("err(10001)", "涉嫌广告");
statusMap.put("err(20001)", "涉嫌政治");
statusMap.put("err(20004)", "涉嫌社会");
statusMap.put("err(20006)", "涉嫌违法犯罪");
statusMap.put("err(20008)", "涉嫌欺诈");
statusMap.put("err(20013)", "涉嫌版权");
statusMap.put("err(22000)", "涉嫌互推(互相宣传)");
statusMap.put("err(21000)", "涉嫌其他");
}
public String getStatus() {
return status;
}
/**
* 发送状态描述</br> err(10001,涉嫌广告) err(20001,涉嫌政治) err(20004,涉嫌社会)</br>
* err(20002,涉嫌色情) err(20006,涉嫌违法犯罪) err(20008,涉嫌欺诈)</br> err(20013,涉嫌版权)
* err(22000,涉嫌互推(互相宣传) err(21000,涉嫌其他)
*
* @param status
* @return 中文描述
*/
public String getStatusDesc() {
return statusMap.get(status.toLowerCase());
}
/**
* 发送状态描述</br> err(10001,涉嫌广告) err(20001,涉嫌政治) err(20004,涉嫌社会)</br>
* err(20002,涉嫌色情) err(20006,涉嫌违法犯罪) err(20008,涉嫌欺诈)</br> err(20013,涉嫌版权)
* err(22000,涉嫌互推(互相宣传) err(21000,涉嫌其他)
*
* @param status
* @return 中文描述
*/
public static String getStatusDesc(String status) {
return statusMap.get(status.toLowerCase());
}
public int getTotalCount() {
return totalCount;
}
public int getFilterCount() {
return filterCount;
}
public int getSentCount() {
return sentCount;
}
public int getErrorCount() {
return errorCount;
}
@Override
public String toString() {
return "MassEventMessage [status=" + getStatusDesc() + ", totalCount="
+ totalCount + ", filterCount=" + filterCount + ", sentCount="
+ sentCount + ", errorCount=" + errorCount + ", "
+ super.toString() + "]";
}
}
@@ -1,57 +0,0 @@
package com.foxinmy.weixin4j.mp.event;
import com.foxinmy.weixin4j.message.event.EventMessage;
import com.foxinmy.weixin4j.mp.type.EventType;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* 扫描二维码事件
*
* @className ScanEventMessage
* @author jy.hu
* @date 2014年4月6日
* @since JDK 1.7
* @see <a
* href="http://mp.weixin.qq.com/wiki/2/5baf56ce4947d35003b86a9805634b1e.html#.E6.89.AB.E6.8F.8F.E5.B8.A6.E5.8F.82.E6.95.B0.E4.BA.8C.E7.BB.B4.E7.A0.81.E4.BA.8B.E4.BB.B6">扫描二维码事件</a>
*/
public class ScanEventMessage extends EventMessage {
private static final long serialVersionUID = 8078674062833071562L;
public ScanEventMessage() {
super(EventType.scan.name());
}
public ScanEventMessage(String eventType) {
super(eventType);
}
/**
* 事件KEY值,是一个32位无符号整数,即创建二维码时的二维码scene_id
*/
@XStreamAlias("EventKey")
private String eventKey;
/**
* 二维码的ticket,可用来换取二维码图片
*/
@XStreamAlias("Ticket")
private String ticket;
public String getEventKey() {
return eventKey;
}
public String getTicket() {
return ticket;
}
public String getParameter() {
return eventKey.replace("qrscene_", "");
}
@Override
public String toString() {
return "ScanEventMessage [eventKey=" + eventKey + ", ticket=" + ticket
+ ", " + super.toString() + "]";
}
}
@@ -1,27 +0,0 @@
package com.foxinmy.weixin4j.mp.event;
import com.foxinmy.weixin4j.type.EventType;
/**
* 关注/取消关注事件</br> <font color="red">包括直接关注与扫描关注</font>
*
* @className ScribeEventMessage
* @author jy.hu
* @date 2014年4月6日
* @since JDK 1.7
* @see <a
* href="http://mp.weixin.qq.com/wiki/2/5baf56ce4947d35003b86a9805634b1e.html#.E5.85.B3.E6.B3.A8.2F.E5.8F.96.E6.B6.88.E5.85.B3.E6.B3.A8.E4.BA.8B.E4.BB.B6">订阅号、服务号的关注/取消关注事件</a>
*/
public class ScribeEventMessage extends ScanEventMessage {
private static final long serialVersionUID = -6846321620262204915L;
public ScribeEventMessage() {
super(EventType.subscribe.name());
}
@Override
public String toString() {
return "ScribeEventMessage [" + super.toString() + "]";
}
}
@@ -1,40 +0,0 @@
package com.foxinmy.weixin4j.mp.event;
import com.foxinmy.weixin4j.message.event.EventMessage;
import com.foxinmy.weixin4j.mp.type.EventType;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* 模板消息事件推送(公众平台)
*
* @className TemplatesendjobfinishMessage
* @author jy
* @date 2014年9月19日
* @since JDK 1.7
* @see <a
* href="http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html#.E4.BA.8B.E4.BB.B6.E6.8E.A8.E9.80.81">模板消息事件推送</a>
*/
public class TemplatesendjobfinishMessage extends EventMessage {
private static final long serialVersionUID = -2903359365988594012L;
public TemplatesendjobfinishMessage() {
super(EventType.templatesendjobfinish.name());
}
/**
* 推送状态 如failed: system failed
*/
@XStreamAlias("Status")
private String status;
public String getStatus() {
return status;
}
@Override
public String toString() {
return "TemplatesendjobfinishMessage [status=" + status + ", "
+ super.toString() + "]";
}
}
@@ -3,12 +3,11 @@ package com.foxinmy.weixin4j.mp.model;
import java.io.Serializable;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.model.Gender;
import com.foxinmy.weixin4j.mp.type.FaceSize;
import com.foxinmy.weixin4j.mp.type.Lang;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* 用户对象
@@ -135,7 +134,7 @@ public class User implements Serializable {
}
public String getHeadimgurl(FaceSize size) {
if (StringUtils.isNotBlank(headimgurl)) {
if (StringUtil.isNotBlank(headimgurl)) {
StringBuilder sb = new StringBuilder(headimgurl);
return sb.replace(0, (headimgurl.length() - 1), size.getInt() + "")
.toString();
@@ -1,8 +1,7 @@
package com.foxinmy.weixin4j.mp.model;
import org.apache.commons.lang3.StringUtils;
import com.foxinmy.weixin4j.model.WeixinAccount;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* 微信公众平台信息
@@ -101,7 +100,7 @@ public class WeixinMpAccount extends WeixinAccount {
public int getVersion() {
if (version == 0) {
return StringUtils.isNotBlank(mchId) ? 3 : 2;
return StringUtil.isNotBlank(mchId) ? 3 : 2;
}
return version;
}
@@ -3,9 +3,6 @@ package com.foxinmy.weixin4j.mp.payment;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.PayException;
@@ -24,8 +21,10 @@ import com.foxinmy.weixin4j.mp.type.SignType;
import com.foxinmy.weixin4j.mp.type.TradeType;
import com.foxinmy.weixin4j.util.ConfigUtil;
import com.foxinmy.weixin4j.util.DateUtil;
import com.foxinmy.weixin4j.util.DigestUtil;
import com.foxinmy.weixin4j.util.MapUtil;
import com.foxinmy.weixin4j.util.RandomUtil;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.xml.XmlStream;
/**
@@ -73,7 +72,7 @@ public class PayUtil {
*/
public static String createPayJsRequestJsonV2(PayPackageV2 payPackage,
WeixinMpAccount weixinAccount) {
if (StringUtils.isBlank(payPackage.getPartner())) {
if (StringUtil.isBlank(payPackage.getPartner())) {
payPackage.setPartner(weixinAccount.getPartnerId());
}
JsPayRequestV2 jsPayRequest = new JsPayRequestV2(weixinAccount,
@@ -115,8 +114,7 @@ public class PayUtil {
* @return
*/
public static String paysignSha(Object obj) {
return DigestUtils
.sha1Hex(MapUtil.toJoinString(obj, false, true, null));
return DigestUtil.SHA1(MapUtil.toJoinString(obj, false, true, null));
}
/**
@@ -132,8 +130,7 @@ public class PayUtil {
public static String paysignSha(Object obj, String paySignKey) {
Map<String, String> extra = new HashMap<String, String>();
extra.put("appKey", paySignKey);
return DigestUtils.sha1Hex(MapUtil
.toJoinString(obj, false, true, extra));
return DigestUtil.SHA1(MapUtil.toJoinString(obj, false, true, extra));
}
/**
@@ -154,7 +151,7 @@ public class PayUtil {
// stringSignTemp 进行 md5 运算
// 再将得到的 字符串所有字符转换为大写 ,得到 sign 值 signValue。
sb.append("&key=").append(paySignKey);
return DigestUtils.md5Hex(sb.toString()).toUpperCase();
return DigestUtil.SHA1(sb.toString()).toUpperCase();
}
/**
@@ -224,7 +221,7 @@ public class PayUtil {
*/
public static PrePay createPrePay(PayPackageV3 payPackage, String paySignKey)
throws PayException {
if (StringUtils.isBlank(payPackage.getSign())) {
if (StringUtil.isBlank(payPackage.getSign())) {
payPackage.setSign(paysignMd5(payPackage, paySignKey));
}
String payJsRequestXml = XmlStream.to(payPackage).replaceAll("__", "_");
@@ -2,14 +2,13 @@ package com.foxinmy.weixin4j.mp.payment.coupon;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.mp.payment.v3.ApiResult;
import com.foxinmy.weixin4j.mp.type.CouponStatus;
import com.foxinmy.weixin4j.mp.type.CouponStockType;
import com.foxinmy.weixin4j.mp.type.CouponType;
import com.foxinmy.weixin4j.util.DateUtil;
import com.foxinmy.weixin4j.util.StringUtil;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
@@ -315,7 +314,7 @@ public class CouponDetail extends ApiResult {
@JSONField(deserialize = false, serialize = false)
public Date getFormatUseTime() {
return StringUtils.isNotBlank(useTime) ? DateUtil
return StringUtil.isNotBlank(useTime) ? DateUtil
.parse2yyyyMMddHHmmss(useTime) : null;
}
@@ -2,10 +2,9 @@ package com.foxinmy.weixin4j.mp.payment.v2;
import java.io.Serializable;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.mp.type.SignType;
import com.foxinmy.weixin4j.util.StringUtil;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
@@ -68,7 +67,7 @@ public class ApiResult implements Serializable {
}
public String getRetMsg() {
return StringUtils.isNotBlank(retMsg) ? retMsg : null;
return StringUtil.isNotBlank(retMsg) ? retMsg : null;
}
public void setRetMsg(String retMsg) {
@@ -2,11 +2,10 @@ package com.foxinmy.weixin4j.mp.payment.v2;
import java.beans.Transient;
import org.apache.commons.codec.digest.DigestUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.mp.model.WeixinMpAccount;
import com.foxinmy.weixin4j.mp.payment.PayRequest;
import com.foxinmy.weixin4j.util.DigestUtil;
import com.foxinmy.weixin4j.util.MapUtil;
/**
@@ -48,7 +47,7 @@ public class JsPayRequestV2 extends PayRequest {
// 再将得到的 字符串所有字符转换为大写 ,得到 sign 值 signValue。
sb.append("&key=").append(partnerKey);
// c---> & d---->
String sign = DigestUtils.md5Hex(sb.toString()).toUpperCase();
String sign = DigestUtil.MD5(sb.toString()).toUpperCase();
sb.delete(0, sb.length());
// c.对传入参数中所有键值对的 value 进行 urlencode 转码后重新拼接成字符串 string2
sb.append(MapUtil.toJoinString(payPackage, true, false, null))
@@ -1,10 +1,9 @@
package com.foxinmy.weixin4j.mp.payment.v2;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.mp.type.RefundChannel;
import com.foxinmy.weixin4j.mp.type.RefundStatus;
import com.foxinmy.weixin4j.util.StringUtil;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
@@ -123,11 +122,11 @@ public class RefundDetail extends ApiResult {
}
public String getRecvUserId() {
return StringUtils.isNotBlank(recvUserId) ? recvUserId : null;
return StringUtil.isNotBlank(recvUserId) ? recvUserId : null;
}
public String getReccvUserName() {
return StringUtils.isNotBlank(reccvUserName) ? reccvUserName : null;
return StringUtil.isNotBlank(reccvUserName) ? reccvUserName : null;
}
@Override
@@ -2,9 +2,8 @@ package com.foxinmy.weixin4j.mp.payment.v2;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.util.StringUtil;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
@@ -52,7 +51,7 @@ public class RefundRecord extends ApiResult {
}
public String getOutTradeNo() {
return StringUtils.isNotBlank(outTradeNo) ? outTradeNo : null;
return StringUtil.isNotBlank(outTradeNo) ? outTradeNo : null;
}
public int getCount() {
@@ -1,9 +1,8 @@
package com.foxinmy.weixin4j.mp.payment.v3;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.http.XmlResult;
import com.foxinmy.weixin4j.util.StringUtil;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
@@ -83,7 +82,7 @@ public class ApiResult extends XmlResult {
}
public String getSubMchId() {
return StringUtils.isNotBlank(subMchId) ? subMchId : null;
return StringUtil.isNotBlank(subMchId) ? subMchId : null;
}
public void setSubMchId(String subMchId) {
@@ -2,13 +2,12 @@ package com.foxinmy.weixin4j.mp.payment.v3;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.mp.payment.coupon.CouponInfo;
import com.foxinmy.weixin4j.mp.type.CurrencyType;
import com.foxinmy.weixin4j.mp.type.RefundChannel;
import com.foxinmy.weixin4j.mp.type.RefundStatus;
import com.foxinmy.weixin4j.util.StringUtil;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
@@ -140,7 +139,7 @@ public class RefundDetail extends ApiResult {
@JSONField(deserialize = false, serialize = false)
public RefundChannel getFormatRefundChannel() {
if (StringUtils.isNotBlank(refundChannel)) {
if (StringUtil.isNotBlank(refundChannel)) {
return RefundChannel.valueOf(refundChannel.toUpperCase());
}
return null;
@@ -170,7 +169,7 @@ public class RefundDetail extends ApiResult {
@JSONField(deserialize = false, serialize = false)
public RefundStatus getFormatRefundStatus() {
if (StringUtils.isNotBlank(refundStatus)) {
if (StringUtil.isNotBlank(refundStatus)) {
return RefundStatus.valueOf(refundStatus);
}
return null;
@@ -1,3 +0,0 @@
模拟微信公众平台登陆
(模拟登录|启用开发者模式|修改服务器配置|修改回调地址|启用服务器配置....more)
@@ -1,666 +0,0 @@
package com.foxinmy.weixin4j.mp.spider;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.util.IOUtil;
import com.foxinmy.weixin4j.util.RandomUtil;
/**
* 模拟微信公众平台登陆
*
* <p>
* (模拟登录|启用开发者模式|修改服务器配置|修改回调地址|启用服务器配置....more)
* </p>
*
* @className WeixinExecutor
* @author jy
* @date 2014年8月15日
* @since JDK 1.7
* @see
*/
public class WeixinExecutor {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final static Map<String, String> accountMap = new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
put("名称", "name");
put("头像", "avatar");
put("登录邮箱", "loginEmail");
put("原始ID", "originalId");
put("微信号", "weixinNo");
put("类型", "accountType");
put("认证情况", "weixinVerify");
put("主体信息", "bodyInfo");
put("介绍", "introduce");
put("所在地址", "address");
put("二维码", "qrcodeUrl");
}
};
private AbstractHttpClient client;
private HttpHost host;
private JSONObject weixin;
// 服务器响应地址
private String pushurl;
// oauth授权回调地址
private String backurl;
// 服务器校验token
private String token;
// 公众号用户名
private String uname;
// 公众号密码
private String pwd;
// 登录时验证码(如果有)
private String imgcode;
// 当要求输入验证码时,cookie需带上
private String sig;
public WeixinExecutor(String backurl, String pushurl, String token,
String uname, String pwd, String imgcode, String sig) {
this.backurl = backurl;
this.pushurl = pushurl;
this.token = token;
this.uname = uname;
this.pwd = pwd;
this.imgcode = StringUtils.isBlank(imgcode) ? "" : imgcode;
this.sig = sig;
weixin = new JSONObject();
weixin.put("host", "mp.weixin.qq.com");
weixin.put("base", "https://mp.weixin.qq.com");
weixin.put("auth", "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN");
weixin.put(
"call",
"https://mp.weixin.qq.com/advanced/callbackprofile?t=ajax-response&token=%s&lang=zh_CN");
weixin.put("start",
"https://mp.weixin.qq.com/misc/skeyform?form=advancedswitchform");
weixin.put("back",
"https://mp.weixin.qq.com/merchant/myservice?action=set_oauth_domain&f=json");
weixin.put("verifycode",
"https://mp.weixin.qq.com/cgi-bin/verifycode?username=" + uname
+ "&r=%s");
weixin.put("bedeveloper",
"https://mp.weixin.qq.com/advanced/advanced?action=agreement");
List<BasicHeader> headers = new ArrayList<BasicHeader>();
headers.add(new BasicHeader("Origin", weixin.getString("base")));
headers.add(new BasicHeader("Connection", "keep-alive"));
headers.add(new BasicHeader(
"User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"));
client = new DefaultHttpClient();
client.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setBooleanParameter(
"http.protocol.single-cookie-header", true);
client.getParams().setParameter(ClientPNames.DEFAULT_HEADERS, headers);
host = new HttpHost(weixin.getString("host"), -1, "https");
}
public JSONObject process() {
// 1.登陆微信公众号
step1_login();
int code = weixin.getIntValue("code");
if (code == 0) {
// 2.收集相关信息
step2_collect();
code = weixin.getIntValue("code");
// 3.填写服务器配置
// 3-1.未初始化账号
// 3-2.已配置账号
if (code == 0) {
step3_setting();
}
code = weixin.getIntValue("code");
// 4.修改网页授权地址
if (code == 0) {
step4_back();
}
// 5.创建底部菜单 (调用封装好的API)
// 5-1.订阅号
// 5-2.服务号
// 6.完成
}
return weixin;
}
/**
* step1:登录操作
*/
private void step1_login() {
HttpPost method = new HttpPost(weixin.getString("auth"));
try {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", uname));
parameters.add(new BasicNameValuePair("pwd", DigestUtils.md5Hex(pwd
.getBytes(Consts.UTF_8))));
parameters.add(new BasicNameValuePair("f", "json"));
parameters.add(new BasicNameValuePair("imgcode", imgcode));
if (!StringUtils.isBlank(imgcode)) {
method.addHeader("Cookie", "sig=" + sig);
}
method.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
method.addHeader("Referer", weixin.getString("base"));
HttpResponse response = client.execute(host, method);
HttpEntity entity = response.getEntity();
Document root = Jsoup.parse(entity.getContent(),
Consts.UTF_8.name(), weixin.getString("base"));
StatusLine line = response.getStatusLine();
logger.info("step1_login--->status={},body=\n{}", line,
root.toString());
if (line.getStatusCode() == HttpStatus.SC_OK) {
JSONObject body = JSON.parseObject(root.body().text());
String msg = "";
int code = 0;
switch (body.getIntValue("ret")
+ body.getJSONObject("base_resp").getIntValue("ret")) {
case -1:
msg = "系统错误,请稍候再试。";
code = -1;
break;
case -2:
msg = "帐号或密码错误。";
code = 100;
break;
case -23:
msg = "您输入的帐号或者密码不正确,请重新输入。";
code = 101;
break;
case -21:
msg = "不存在该帐户。";
code = 102;
break;
case -7:
msg = "您目前处于访问受限状态。";
code = 103;
break;
case -8:
msg = "请输入图中的验证码";
code = 104;
break;
case -27:
msg = "您输入的验证码不正确,请重新输入";
code = 105;
break;
case -26:
msg = "该公众会议号已经过期,无法再登录使用。";
code = 106;
break;
case 0:
msg = "成功登录,正在跳转...";
break;
case -25:
msg = "海外帐号请在公众平台海外版登录,<a href=\"http://admin.wechat.com/\">点击登录</a>";
code = 107;
break;
default:
msg = "未知错误";
code = 108;
break;
}
if (code == 0) {
weixin.put(
"urlToken",
getQueryMap(body.getString("redirect_url")).get(
"token"));
weixin.put("indexUrl", String.format("%s%s",
weixin.getString("base"),
body.getString("redirect_url")));
weixin.put("step", "1");
} else {
if (code == 104 || code == 105) {
// 下载验证码
HttpGet get = new HttpGet(String.format(
weixin.getString("verifycode"),
System.currentTimeMillis()));
get.setHeaders(method.getAllHeaders());
response = client.execute(host, get);
StringBuffer base64 = new StringBuffer();
base64.append("data:")
.append(response.getFirstHeader("Content-Type")
.getValue()).append(";base64,");
base64.append(new String(
Base64.encodeBase64(IOUtil.toByteArray(response
.getEntity().getContent())),
Consts.UTF_8));
weixin.put("verifydata", base64.toString());
List<Cookie> cookieList = client.getCookieStore()
.getCookies();
for (Cookie cookie : cookieList) {
if (cookie.getName().equals("sig")) {
weixin.put("sig", cookie.getValue());
break;
}
}
}
weixin.put("code", code);
weixin.put("msg", msg);
}
} else {
weixin.put("code", "-3");
weixin.put("msg", "网络异常,请稍后重试!");
}
} catch (Exception e) {
weixin.put("code", "-2");
weixin.put("msg", "服务器繁忙,请稍后重试!");
weixin.put("exception", e.getMessage());
logger.error("step1_login catch error", e);
} finally {
if (weixin.getIntValue("code") != 0) {
client.getConnectionManager().shutdown();
}
}
}
/**
* step2:收集信息
*/
private void step2_collect() {
String url = weixin.getString("indexUrl");
HttpGet method = new HttpGet(url);
try {
method.addHeader("Referer", weixin.getString("base"));
HttpResponse response = client.execute(host, method);
HttpEntity entity = response.getEntity();
Document root = Jsoup.parse(entity.getContent(),
Consts.UTF_8.name(), weixin.getString("base"));
StatusLine line = response.getStatusLine();
logger.info("step2_setting--->status={},body=\n{}", line,
root.toString());
if (line.getStatusCode() == HttpStatus.SC_OK) {
Element ele = root.getElementById("menuBar")
.getElementsByTag("dl").last();
url = ele.getElementsByTag("a").last().absUrl("href");
weixin.put("developerUrl", url);
method.addHeader("Referer", url);
url = ele.previousElementSibling().getElementsByTag("a")
.first().absUrl("href");
weixin.put("settingUrl", url);
method.setURI(URI.create(url));
response = client.execute(host, method);
entity = response.getEntity();
root = Jsoup.parse(entity.getContent(), Consts.UTF_8.name(),
weixin.getString("base"));
line = response.getStatusLine();
weixin.put("step", "2-1");
// 公众号配置页面
if (line.getStatusCode() == HttpStatus.SC_OK) {
Elements eles = root.getElementById("settingArea")
.getElementsByTag("li");
String key, value;
for (Element element : eles) {
key = element.getElementsByTag("h4").first().text();
ele = element.getElementsByClass("meta_content")
.first();
if (ele.children().isEmpty()) {
value = ele.text();
} else {
if (ele.child(0).tagName().equalsIgnoreCase("a")) {
value = ele.child(0).absUrl("href");
} else if (ele.child(0).tagName()
.equalsIgnoreCase("img")) {
value = ele.child(0).absUrl("src");
} else {
value = ele.text();
}
}
weixin.put(accountMap.get(key), value);
}
weixin.put("isVerify", weixin.getString("weixinVerify")
.contains("微信认证"));
weixin.put("isService", weixin.getString("accountType")
.contains("服务号"));
weixin.put("isSubscribe", weixin.getString("accountType")
.contains("订阅号"));
value = weixin.getString("qrcodeUrl");
method.setURI(URI.create(value));
response = client.execute(host, method);
weixin.put("qrcodeData", IOUtil.toByteArray(response
.getEntity().getContent()));
weixin.put("step", "2-2");
// 开发者页面
method.addHeader("Referer", url);
method.setURI(URI.create(weixin.getString("developerUrl")));
response = client.execute(host, method);
entity = response.getEntity();
root = Jsoup.parse(entity.getContent(),
Consts.UTF_8.name(), weixin.getString("base"));
line = response.getStatusLine();
if (line.getStatusCode() == HttpStatus.SC_OK) {
// 还没有成为开发者 2014.10-06 jy.hu
// 触发成为开发者动作
ele = root.getElementById("js_toBeDeveloper");
if (ele != null && ele.hasText()) {
HttpPost post = new HttpPost(URI.create(weixin
.getString("bedeveloper")));
post.addHeader("Referer", url);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("token",
weixin.getString("urlToken")));
parameters.add(new BasicNameValuePair("f", "json"));
parameters.add(new BasicNameValuePair("ajax", "1"));
parameters.add(new BasicNameValuePair("lang",
"zh_CN"));
parameters.add(new BasicNameValuePair("random",
System.currentTimeMillis() + ""));
post.setEntity(new UrlEncodedFormEntity(parameters,
Consts.UTF_8));
response = client.execute(host, post);
entity = response.getEntity();
root = Jsoup.parse(entity.getContent(),
Consts.UTF_8.name(),
weixin.getString("base"));
line = response.getStatusLine();
logger.info(
"step2_bedeveloper--->status={},body=\n{}",
line, root.toString());
if (line.getStatusCode() == HttpStatus.SC_OK) {
JSONObject body = JSON.parseObject(root.body()
.text());
if (body.getIntValue("ret") == 0) {
method.addHeader("Referer", url);
method.setURI(URI.create(weixin
.getString("developerUrl")));
response = client.execute(host, method);
entity = response.getEntity();
root = Jsoup.parse(entity.getContent(),
Consts.UTF_8.name(),
weixin.getString("base"));
} else {
weixin.put("code", "-100");
weixin.put("msg", "成为开发者失败!");
return;
}
}
}
// 初始化状态
// 配置未启用状态
// 配置已启用状态
eles = root.getElementsByClass("developer_info_opr");
if (eles != null && eles.hasText()) {
weixin.put("developerModifyUrl", eles.first()
.children().first().absUrl("href"));
weixin.put("status",
eles.text().contains("启用") ? "READY"
: "RUNNING");
} else {
weixin.put("status", "INIT");
}
// appid&appsecret
if (weixin.getBooleanValue("isService")
|| (weixin.getBooleanValue("isSubscribe") && weixin
.getBooleanValue("isVerify"))) {
eles = root
.getElementsByClass("developer_info_item")
.first().children().last()
.getElementsByClass("frm_controls");
weixin.put("appId", eles.first().text());
weixin.put("appSecret",
eles.last().text().replace("重置", "").trim());
}
weixin.put("step", "2-3");
}
} else {
weixin.put("code", "-3");
weixin.put("msg", "网络异常,请稍后重试!");
}
} else {
weixin.put("code", "-3");
weixin.put("msg", "网络异常,请稍后重试!");
}
} catch (Exception e) {
weixin.put("code", "-2");
weixin.put("msg", "服务器繁忙,请稍后重试!");
weixin.put("exception", e.getMessage());
logger.error("step2_collect catch error", e);
} finally {
if (weixin.getIntValue("code") != 0) {
client.getConnectionManager().shutdown();
}
}
}
/**
* step3:填写配置
*/
private void step3_setting() {
HttpPost method = new HttpPost(String.format(weixin.getString("call"),
weixin.getString("urlToken")));
try {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("url", pushurl));
parameters.add(new BasicNameValuePair("callback_token", token));
// EncodingAESKey | 消息加解密方式(明文0,兼容1,安全2)
parameters.add(new BasicNameValuePair("encoding_aeskey", RandomUtil
.generateString(43)));
parameters
.add(new BasicNameValuePair("callback_encrypt_mode", "0"));
parameters.add(new BasicNameValuePair("operation_seq", RandomUtil
.generateStringByNumberChar(9)));
method.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
method.addHeader("Referer", weixin.getString("developerModifyUrl"));
HttpResponse response = client.execute(host, method);
HttpEntity entity = response.getEntity();
Document root = Jsoup.parse(entity.getContent(),
Consts.UTF_8.name(), weixin.getString("base"));
StatusLine line = response.getStatusLine();
logger.info("step3_setting--->status={},body=\n{}", line,
root.toString());
if (line.getStatusCode() == HttpStatus.SC_OK) {
JSONObject body = JSON.parseObject(root.body().text());
String msg = "";
int code = 0;
switch (body.getIntValue("ret")
+ body.getJSONObject("base_resp").getIntValue("ret")) {
case -201:
msg = "无效的URL";
code = 200;
break;
case -202:
msg = "无效的Token";
code = 201;
break;
case -203:
msg = "操作频率太快,请休息一下。";
code = 202;
break;
case -204:
msg = "请先在设置页面完善当前帐号信息";
code = 203;
break;
case -205:
msg = "该URL可能存在安全风险,请检查";
code = 207;
break;
case -301:
msg = "请求URL超时";
code = 204;
break;
case -302:
msg = "服务器没有正确响应Token验证,请稍后重试";
code = 205;
break;
case -104:
msg = "参数错误,请重新填写。";
code = 206;
break;
case 0:
msg = "配置成功..";
break;
default:
msg = "未知错误";
code = 108;
break;
}
if (code == 0) {
// 触发启用按钮
if (!weixin.getString("status").equals("RUNNING")) {
parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("token", weixin
.getString("urlToken")));
parameters.add(new BasicNameValuePair("f", "json"));
parameters.add(new BasicNameValuePair("ajax", "1"));
parameters.add(new BasicNameValuePair("flag", "1"));
parameters.add(new BasicNameValuePair("type", "2"));
parameters.add(new BasicNameValuePair("lang", "zh_CN"));
parameters.add(new BasicNameValuePair("random", System
.currentTimeMillis() + ""));
method.setEntity(new UrlEncodedFormEntity(parameters,
Consts.UTF_8));
method.setURI(URI.create(weixin.getString("start")));
response = client.execute(host, method);
entity = response.getEntity();
root = Jsoup.parse(entity.getContent(),
Consts.UTF_8.name(), weixin.getString("base"));
line = response.getStatusLine();
logger.info("step3_setting--->status={},body=\n{}",
line, root.toString());
if (line.getStatusCode() == HttpStatus.SC_OK) {
body = JSON.parseObject(root.body().text());
if (body.getIntValue("ret")
+ body.getJSONObject("base_resp")
.getIntValue("ret") != 0) {
weixin.put("code", 300);
weixin.put("msg", "启用开发者模式失败,请稍后再试!");
}
}
}
weixin.put("step", "3");
} else {
weixin.put("code", code);
weixin.put("msg", msg);
}
} else {
weixin.put("code", "-3");
weixin.put("msg", "网络异常,请稍后重试!");
}
} catch (Exception e) {
weixin.put("code", "-2");
weixin.put("msg", "服务器繁忙,请稍后重试!");
weixin.put("exception", e.getMessage());
logger.error("step3_setting catch error", e);
} finally {
if (weixin.getIntValue("code") != 0) {
client.getConnectionManager().shutdown();
}
}
}
/**
* step4:修改回调
*/
private void step4_back() {
try {
if (weixin.getBooleanValue("isVerify")) {
HttpPost method = new HttpPost(weixin.getString("back"));
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("domain", backurl));
parameters.add(new BasicNameValuePair("token", weixin
.getString("urlToken")));
parameters.add(new BasicNameValuePair("f", "json"));
parameters.add(new BasicNameValuePair("ajax", "1"));
parameters.add(new BasicNameValuePair("flag", "1"));
parameters.add(new BasicNameValuePair("lang", "zh_CN"));
parameters.add(new BasicNameValuePair("random", System
.currentTimeMillis() + ""));
method.setEntity(new UrlEncodedFormEntity(parameters,
Consts.UTF_8));
method.addHeader("Referer", weixin.getString("developerUrl"));
HttpResponse response = client.execute(host, method);
HttpEntity entity = response.getEntity();
Document root = Jsoup.parse(entity.getContent(),
Consts.UTF_8.name(), weixin.getString("base"));
StatusLine line = response.getStatusLine();
logger.info("step4_back--->status={},body=\n{}", line,
root.toString());
if (line.getStatusCode() == HttpStatus.SC_OK) {
JSONObject body = JSON.parseObject(root.body().text());
if (body.getIntValue("ret")
+ body.getJSONObject("base_resp")
.getIntValue("ret") != 0) {
weixin.put("code", "400");
weixin.put("msg", "修改授权回调地址失败!");
}
weixin.put("step", "4");
}
} else {
logger.info("公众号尚未认证,放弃本次修改授权回调地址操作。{}", weixin);
}
} catch (Exception e) {
weixin.put("code", "-2");
weixin.put("msg", "服务器繁忙,请稍后重试!");
weixin.put("exception", e.getMessage());
logger.error("step4_back catch error", e);
} finally {
client.getConnectionManager().shutdown();
}
}
private Map<String, String> getQueryMap(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
}
@@ -1,55 +0,0 @@
package com.foxinmy.weixin4j.mp.type;
/**
* 公众号事件类型
*
* @className EventType
* @author jy
* @date 2014年9月30日
* @since JDK 1.7
* @see
*/
public enum EventType {
/**
* 二维码扫描事件
*
* @see com.foxinmy.weixin4j.mp.event.ScanEventMessage
*/
scan,
/**
* 群发消息事件
*
* @see com.foxinmy.weixin4j.mp.event.MassEventMessage
*/
masssendjobfinish,
/**
* 模板消息事件
*
* @see com.foxinmy.weixin4j.mp.event.TemplatesendjobfinishMessage
*/
templatesendjobfinish,
/**
* 客服接入会话事件
*
* @see com.foxinmy.weixin4j.mp.event.KfCreateEventMessage
*/
kf_create_session,
/**
* 客服关闭会话事件
*
* @see com.foxinmy.weixin4j.mp.event.KfCloseEventMessage
*/
kf_close_session,
/**
* 客服转接会话事件
*
* @see com.foxinmy.weixin4j.mp.event.KfSwitchEventMessage
*/
kf_switch_session,
/**
* 异步任务完成事件
*
* @see com.foxinmy.weixin4j.mp.event.BatchjobresultMessage
*/
batch_job_result;
}
@@ -11,7 +11,6 @@ import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
@@ -32,6 +31,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* excel工具类
@@ -55,7 +55,7 @@ public class ExcelUtil {
*/
public static String[][] read(File file) throws Exception {
String fileExt = getExtension(file.getName());
if (StringUtils.isNotBlank(fileExt)) {
if (StringUtil.isNotBlank(fileExt)) {
if (fileExt.toLowerCase().equals("xls")) {// 2003
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(file));
@@ -75,7 +75,7 @@ public class ExcelUtil {
public static String[][] read4Special(File file, String fileName,
int columnSize) throws Exception {
String fileExt = getExtension(fileName);
if (StringUtils.isNotBlank(fileExt)) {
if (StringUtil.isNotBlank(fileExt)) {
if (fileExt.toLowerCase().equals("xls")) {// 2003
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(file));
@@ -0,0 +1,323 @@
package com.foxinmy.weixin4j.mp.util;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.PayException;
import com.foxinmy.weixin4j.http.XmlResult;
import com.foxinmy.weixin4j.model.Consts;
import com.foxinmy.weixin4j.mp.model.WeixinMpAccount;
import com.foxinmy.weixin4j.mp.payment.JsPayNotify;
import com.foxinmy.weixin4j.mp.payment.PayPackage;
import com.foxinmy.weixin4j.mp.payment.PayUtil;
import com.foxinmy.weixin4j.mp.payment.conver.CouponConverter;
import com.foxinmy.weixin4j.mp.payment.v2.NativePayNotifyV2;
import com.foxinmy.weixin4j.mp.payment.v2.NativePayResponseV2;
import com.foxinmy.weixin4j.mp.payment.v2.PayFeedback;
import com.foxinmy.weixin4j.mp.payment.v2.PayPackageV2;
import com.foxinmy.weixin4j.mp.payment.v2.PayWarn;
import com.foxinmy.weixin4j.mp.payment.v3.NativePayNotifyV3;
import com.foxinmy.weixin4j.mp.payment.v3.NativePayResponseV3;
import com.foxinmy.weixin4j.mp.payment.v3.PayPackageV3;
import com.foxinmy.weixin4j.mp.type.TradeType;
import com.foxinmy.weixin4j.util.ConfigUtil;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.xml.XmlStream;
/**
* 支付示例
*
* @className PayDemo
* @author jy
* @date 2014年10月28日
* @since JDK 1.7
* @see
*/
public final class PayDemo {
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* JSAPI支付
*
* @return
*/
public JSONObject jsPay() {
JSONObject obj = new JSONObject();
WeixinMpAccount weixinAccount = JSON.parseObject(
ConfigUtil.getValue("account"), WeixinMpAccount.class);
// V3 支付
PayPackage payPackage = new PayPackageV3(weixinAccount, "用户openid",
"商品描述", "系统内部订单号", 1d, "IP地址", TradeType.JSAPI);
// V2 支付
payPackage = new PayPackageV2("商品描述", weixinAccount.getPartnerId(),
"系统内部订单号", 1d, "回调地址", "IP地址");
payPackage.setAttach("ID");
String jspay = null;
try {
jspay = PayUtil.createPayJsRequestJson(payPackage, weixinAccount);
} catch (PayException e) {
log.error("create jspay error,{}", weixinAccount, e);
}
if (StringUtil.isBlank(jspay)) {
obj.put("code", "-2");
obj.put("msg", "创建支付链接失败!");
return obj;
}
obj.put("code", "0");
obj.put("jspay", jspay);
/*
* 编辑收货地址 SnsToken token = (SnsToken) getSession("AccessToken");
* obj.put("editaddress", PayUtil.createAddressRequestJson(
* wx.getAppId(), getFullLoction(), token.getAccess_token()));
*/
log.info("js pay....{}", obj);
return obj;
}
/**
* JSAPI(V2)支付成功(前端)时的回调通知<br>
* &ltxml&gt</br> &ltOpenId&gt&lt![CDATA[111222]]&gt&lt/OpenId&gt</br>
* &ltAppId&gt&lt![CDATA[wwwwb4f85f3a797777]]&gt&lt/AppId&gt</br>
* &ltIsSubscribe&gt1&lt/IsSubscribe&gt</br>
* &ltTimeStamp&gt1369743511&lt/TimeStamp&gt</br>
* &ltNonceStr&gt&lt![CDATA[jALldRTHAFd5Tgs5]]&gt&lt/NonceStr&gt</br>
* &ltAppSignature>&lt![CDATA[bafe07f060f22dcda0bfdb4b5ff756f973aecffa]]&gt
* &lt/AppSignature&gt</br>
* &ltSignMethod>&lt![CDATA[sha1]]&gt&lt/SignMethod&gt</br> &lt/xml&gt</br>
* 参与签名的字段为: appid、appkey、timestamp、noncestr、openid、issubscribe
*
* @param 订单信息
* @param inputStream
* 用户信息
*
* @see com.foxinmy.weixin4j.mp.payment.JsPayNotify
* @return success或其他
*/
public String jsNotifyV2(InputStream inputStream) {
Map<String, String> objMap = new HashMap<String, String>();
/*
* 收集url中携带的参数 /pay/notify/back?attach=8&bank_billno=201410293351060&
* bank_type=2032&discount=0&fee_type=1&input_charset=UTF-8&
* notify_id=9fKbVf_qg6y-
* wSjtSMV0PLXeEn2oGfTM1s9dWSvR2B9U6iFQRTzmjrMWKUxvh9mpBLvnh8aqFbC_OFk1pTvFnFUO00Lln4fh
* & out_trade_no=D14102900031&partner=1221928801&product_fee=1&
* sign=B9D6E772C271C9B86B8436FC9F5DFC1A&
* sign_type=MD5&time_end=20141029183707&
* total_fee=1&trade_mode=1&trade_state=0&
* transaction_id=1221928801201410296039230054&transport_fee=0
*/
log.info("jspay_notify_orderinfo,{}", objMap);
JsPayNotify payNotify = XmlStream.get(inputStream, JsPayNotify.class);
log.info("jspay_notify_userinfo,{}", payNotify);
WeixinMpAccount weixinAccount = JSON.parseObject(
ConfigUtil.getValue("account"), WeixinMpAccount.class);
// 验证财付通签名
String sign = objMap.get("sign");
objMap.remove("sign");
String _sign = PayUtil
.paysignMd5(objMap, weixinAccount.getPartnerKey());
log.info("财付通签名----->sign={},vaild_sign={}", sign, _sign);
if (!sign.equals(_sign)) {
return "fail";
}
objMap.clear();
// 验证微信签名
sign = payNotify.getPaySign();
payNotify.setPaySign(null);
payNotify.setSignType(null);
String vaild_sign = PayUtil.paysignSha(payNotify,
weixinAccount.getPaySignKey());
log.info("微信签名----->sign={},vaild_sign={}", sign, vaild_sign);
if (!sign.equals(vaild_sign)) {
return "fail";
}
// 处理业务逻辑
return "success";
}
/**
* JSAPI(V3)支付成功(前端)时的回调通知
*
*
* @param inputStream
* 订单回调
* @return &ltxml&gt<br>
* &ltreturn_code&gtSUCCESS/FAIL&lt/return_code&gt<br>
* &ltreturn_msg&gt如非空,为错误 原因签名失败参数格式校验错误&lt/return_msg&gt<br>
* &lt/xml&gt
* @throws DocumentException
* @see <a
* href="http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7">支付结果通知</a>
*/
public String jsNotifyV3(InputStream inputStream) {
String orderXml = "从inputStream中读取订单信息";
com.foxinmy.weixin4j.mp.payment.v3.Order order = CouponConverter
.fromXML(orderXml,
com.foxinmy.weixin4j.mp.payment.v3.Order.class);
log.info("jsapi_notify_order_info:", order);
String sign = order.getSign();
order.setSign(null);
WeixinMpAccount weixinAccount = JSON.parseObject(
ConfigUtil.getValue("account"), WeixinMpAccount.class);
String valid_sign = PayUtil.paysignMd5(order,
weixinAccount.getPaySignKey());
// 如果订单中存在代金券的情况并不适用
log.info("微信签名----->sign={},vaild_sign={}", sign, valid_sign);
if (!sign.equals(valid_sign)) {
return XmlStream.to(new XmlResult(Consts.FAIL, "签名错误"));
}
// 处理业务逻辑
return XmlStream.to(new XmlResult(Consts.SUCCESS, ""));
}
/**
* V2.x版本Native支付时POST数据<br>
* &ltxml&gt</br> &ltOpenId&gt&lt![CDATA[111222]]&gt&lt/OpenId&gt</br>
* &ltAppId&gt&lt![CDATA[wwwwb4f85f3a797777]]&gt&lt/AppId&gt</br>
* &ltIsSubscribe&gt1&lt/IsSubscribe&gt</br>
* &ltProductId&gt[CDATA[000000]]&lt/ProductId&gt</br>
* &ltTimeStamp&gt1369743511&lt/TimeStamp&gt</br>
* &ltNonceStr&gt&lt![CDATA[jALldRTHAFd5Tgs5]]&gt&lt/NonceStr&gt</br>
* &ltAppSignature>&lt![CDATA[bafe07f060f22dcda0bfdb4b5ff756f973aecffa]]&gt
* &lt/AppSignature&gt</br>
* &ltSignMethod>&lt![CDATA[sha1]]&gt&lt/SignMethod&gt</br> &lt/xml&gt</br>
* 参与签名的字段为: appid、appkey、timestamp、noncestr、openid、issubscribe、productId
*
* @param inputStream
*
* @return 必须返回一个带有Package信息的xml字符串
*/
public String nativeNotifyV2(InputStream inputStream) {
// V2.x版本
NativePayNotifyV2 payNotify = XmlStream.get(inputStream,
NativePayNotifyV2.class);
log.info("native_pay_notify,{}", payNotify);
WeixinMpAccount weixinAccount = JSON.parseObject(
ConfigUtil.getValue("account"), WeixinMpAccount.class);
String sign = payNotify.getPaySign();
payNotify.setPaySign(null);
payNotify.setSignType(null);
// 验证微信签名
String vaild_sign = PayUtil.paysignSha(payNotify,
weixinAccount.getPaySignKey());
log.info("微信签名----->sign={},vaild_sign={}", sign, vaild_sign);
if (!sign.equals(vaild_sign)) {
return "fail";
}
// 构造订单信息
PayPackageV2 payPackage = new PayPackageV2("商品描述",
weixinAccount.getPartnerId(), "系统内部订单号", 1d, "回调地址", "IP地址");
NativePayResponseV2 payResponse = new NativePayResponseV2(
weixinAccount, payPackage);
return XmlStream.to(payResponse);
}
/**
* V3.x版本native回调<br>
* &ltxml&gt</br> &ltopenid&gt&lt![CDATA[111222]]&gt&lt/openid&gt</br>
* &ltappid&gt&lt![CDATA[wwwwb4f85f3a797777]]&gt&lt/appid&gt</br>
* &ltmch_id&gt&lt![CDATA[1100022]]&gt&lt/mch_id&gt</br>
* &ltis_subscribe&gt1&lt/is_subscribe&gt</br>
* &ltproduct_id&gt[CDATA[000000]]&lt/product_id&gt</br>
* &ltnonce_str&gt&lt![CDATA[jALldRTHAFd5Tgs5]]&gt&lt/nonce_str&gt</br>
* &ltsign>&lt![CDATA[bafe07f060f22dcda0bfdb4b5ff756f973aecffa]]&gt
* &lt/sign&gt</br> &lt/xml&gt</br>
*
* @return
* @throws PayException
*/
public String nativeNotifyV3(InputStream inputStream) throws PayException {
NativePayNotifyV3 payNotify = XmlStream.get(inputStream,
NativePayNotifyV3.class);
String sign = payNotify.getSign();
payNotify.setSign(null);
WeixinMpAccount weixinAccount = JSON.parseObject(
ConfigUtil.getValue("account"), WeixinMpAccount.class);
String valid_sign = PayUtil.paysignMd5(payNotify,
weixinAccount.getPaySignKey());
log.info("微信签名----->sign={},vaild_sign={}", sign, valid_sign);
// 生成Package
PayPackageV3 payPackage = new PayPackageV3(weixinAccount, "用户openid",
"商品描述", "系统内部订单号", 1d, "IP地址", TradeType.NATIVE);
payPackage.setProductId(payNotify.getProductId());
if (!sign.equals(valid_sign)) {
// 校验失败
NativePayResponseV3 payReponse = new NativePayResponseV3("签名失败",
null);
payReponse.setSign(PayUtil.paysignMd5(payReponse,
weixinAccount.getPaySignKey()));
return XmlStream.to(payReponse);
}
// 成功返回
NativePayResponseV3 payReponse = new NativePayResponseV3(payPackage,
weixinAccount.getPaySignKey());
payReponse.setSign(PayUtil.paysignMd5(payReponse,
weixinAccount.getPaySignKey()));
return XmlStream.to(payReponse);
}
/**
* 告警通知 需要成功返回 success </br> &ltxml&gt</br>
* &ltAppId&gt&lt![CDATA[wxf8b4f85f3a794e77]]&gt&lt/AppId&gt</br>
* &ltErrorType&gt1001&lt/ErrorType&gt</br>
* &ltDescription&gt&lt![CDATA[错误描述]]>&lt/Description&gt</br>
* &ltAlarmContent&gt&lt![CDATA[错误详情]]>&lt/AlarmContent&gt</br>
* &ltTimeStamp&gt1393860740&lt/TimeStamp&gt</br>
* &ltAppSignature&gt&lt![CDATA[签名方式跟JsPayRequest中的paySign一样]]&gt&lt/
* AppSignature&gt</br>
* &ltSignMethod&gt&lt![CDATA[sha1]]&gt&lt/SignMethod&gt</br>
* &lt/xml&gt</br>
* 参与签名字段:alarmcontent、appid、appkey、description、errortype、timestamp
*
* @param inputStream
* xml数据
* @see com.foxinmy.weixin4j.mp.payment.v2.PayWarn
* @return
*/
public String warning(InputStream inputStream) {
PayWarn payWarn = XmlStream.get(inputStream, PayWarn.class);
log.info("pay_warning,{}", payWarn);
WeixinMpAccount weixinAccount = JSON.parseObject(
ConfigUtil.getValue("account"), WeixinMpAccount.class);
String sign = payWarn.getPaySign();
payWarn.setPaySign(null);
payWarn.setSignType(null);
// 验证微信签名
String vaild_sign = PayUtil.paysignSha(payWarn,
weixinAccount.getPaySignKey());
log.info("微信签名----->sign={},vaild_sign={}", sign, vaild_sign);
return "success";
}
/**
* 用户维权
*
* @param inputStream
* @see com.foxinmy.weixin4j.mp.payment.v2.PayFeedback
* @return
*/
public String feedback(InputStream inputStream) {
PayFeedback feedback = XmlStream.get(inputStream, PayFeedback.class);
log.info("pay_feedback_info:{}", feedback);
WeixinMpAccount weixinAccount = JSON.parseObject(
ConfigUtil.getValue("account"), WeixinMpAccount.class);
// 验证微信签名
Map<String, String> obj = new HashMap<String, String>();
obj.put("openid", feedback.getOpenId());
obj.put("appid", feedback.getAppId());
obj.put("timestamp", feedback.getTimeStamp());
obj.put("appkey", weixinAccount.getPaySignKey());
String sign = PayUtil.paysignSha(obj);
log.info("微信签名----->sign={},vaild_sign={}", sign, feedback.getPaySign());
return "success";
}
}
@@ -1,4 +1,4 @@
package com.foxinmy.weixin4j.mp.test.msg;
package com.foxinmy.weixin4j.mp.test;
import java.io.File;
import java.io.IOException;
@@ -16,7 +16,6 @@ import com.foxinmy.weixin4j.mp.api.CustomApi;
import com.foxinmy.weixin4j.mp.model.CustomRecord;
import com.foxinmy.weixin4j.mp.model.KfAccount;
import com.foxinmy.weixin4j.mp.model.KfSession;
import com.foxinmy.weixin4j.mp.test.TokenTest;
/**
* 客服消息测试
@@ -1,4 +1,4 @@
package com.foxinmy.weixin4j.mp.test.msg;
package com.foxinmy.weixin4j.mp.test;
import java.io.File;
import java.io.IOException;
@@ -13,8 +13,6 @@ import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.JsonResult;
import com.foxinmy.weixin4j.mp.api.MassApi;
import com.foxinmy.weixin4j.mp.api.MediaApi;
import com.foxinmy.weixin4j.mp.event.MassEventMessage;
import com.foxinmy.weixin4j.mp.test.TokenTest;
import com.foxinmy.weixin4j.tuple.Image;
import com.foxinmy.weixin4j.tuple.MpArticle;
import com.foxinmy.weixin4j.tuple.Text;
@@ -30,7 +28,7 @@ import com.foxinmy.weixin4j.type.MediaType;
* @since JDK 1.7
* @see
*/
public class MassMsgTest extends TokenTest {
public class MassTest extends TokenTest {
private MassApi massApi;
private MediaApi mediaApi;
@@ -107,7 +105,6 @@ public class MassMsgTest extends TokenTest {
public void getMassNews() throws WeixinException {
String status = massApi.getMassNews("82358");
System.out.println(status);
System.out.println(MassEventMessage.getStatusDesc(status));
Assert.assertNotNull(status);
}
}
@@ -1,4 +1,4 @@
package com.foxinmy.weixin4j.mp.test.msg;
package com.foxinmy.weixin4j.mp.test;
import java.io.File;
import java.io.IOException;
@@ -12,7 +12,6 @@ import com.foxinmy.weixin4j.http.JsonResult;
import com.foxinmy.weixin4j.mp.api.MediaApi;
import com.foxinmy.weixin4j.mp.api.NotifyApi;
import com.foxinmy.weixin4j.mp.message.NotifyMessage;
import com.foxinmy.weixin4j.mp.test.TokenTest;
import com.foxinmy.weixin4j.tuple.Image;
import com.foxinmy.weixin4j.tuple.Music;
import com.foxinmy.weixin4j.tuple.News;
@@ -30,7 +29,7 @@ import com.foxinmy.weixin4j.type.MediaType;
* @since JDK 1.7
* @see
*/
public class NotifyMsgTest extends TokenTest {
public class NotifyTest extends TokenTest {
private NotifyApi notifyApi;
private MediaApi mediaApi;
@@ -1,4 +1,4 @@
package com.foxinmy.weixin4j.mp.test.msg;
package com.foxinmy.weixin4j.mp.test;
import org.junit.Assert;
import org.junit.Before;
@@ -8,10 +8,9 @@ import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.JsonResult;
import com.foxinmy.weixin4j.mp.api.TmplApi;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.foxinmy.weixin4j.mp.test.TokenTest;
import com.foxinmy.weixin4j.mp.type.IndustryType;
public class TemplateMsgTest extends TokenTest {
public class TemplateTest extends TokenTest {
private TmplApi tmplApi;
@Before
@@ -1,11 +1,5 @@
package com.foxinmy.weixin4j.mp.test;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -36,19 +30,4 @@ public class TokenTest {
public void test() throws WeixinException {
Assert.assertNotNull(tokenHolder.getToken());
}
public static void main(String[] args) throws Exception {
String wikiUrl = "http://qydev.weixin.qq.com/wiki/index.php?title=%E5%85%A8%E5%B1%80%E8%BF%94%E5%9B%9E%E7%A0%81%E8%AF%B4%E6%98%8E";
// wikiUrl =
// "http://mp.weixin.qq.com/wiki/17/fa4e1434e57290788bde25603fa2fcbd.html";
Document doc = Jsoup.parse(new URL(wikiUrl), 5000);
Elements errors = doc.getElementsByTag("tr");
String node = "<error><code>%s</code><text>%s</text></error>";
StringBuilder xml = new StringBuilder();
for (Element error : errors) {
xml.append(String.format(node, error.child(0).text(), error
.child(1).text()));
}
System.err.println(xml);
}
}
@@ -1,64 +0,0 @@
package com.foxinmy.weixin4j.mp.test.msg;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException;
public class AesMsgTest extends MessagePush {
StringBuilder xmlSb = new StringBuilder();
@Test
public void testValidate() throws WeixinException, IOException {
String para = "?signature=0d2366aedb4f3531cfa4297c1e4ea7eece2311d9&echostr=2143641595566077626&timestamp=1415951914&nonce=165976363";
xmlSb.delete(0, xmlSb.length());
String response = get(para);
Assert.assertEquals("2143641595566077626", response);
}
@Test
public void testType1() throws WeixinException, IOException {
String para = "?signature=6dd806a20a314723e78bc58742a1b98a7adfd151&timestamp=1415979366&nonce=1865915590";
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[gh_248c6f91d64f]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[oyFLst1bqtuTcxK-ojF8hOGtLQao]]></FromUserName>");
xmlSb.append("<CreateTime>1415979365</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[CLICK]]></Event>");
xmlSb.append("<EventKey><![CDATA[CHECKIN]]></EventKey>");
xmlSb.append("</xml>");
String response = push(para, xmlSb.toString());
Assert.assertNotNull(response);
}
@Test
public void testType2() throws WeixinException, IOException {
String para = "?signature=ad05f836772d1cbba1ff2edb7be4b9c9fb3a43d5&timestamp=1415980001&nonce=1803216865&encrypt_type=raw&msg_signature=c0d38e9ca00548f7142627ec2908a4fe8481025e";
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[gh_248c6f91d64f]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[oyFLst1bqtuTcxK-ojF8hOGtLQao]]></FromUserName>");
xmlSb.append("<CreateTime>1415980001</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[CLICK]]></Event>");
xmlSb.append("<EventKey><![CDATA[CHECKIN]]></EventKey>");
xmlSb.append("</xml>");
String response = push(para, xmlSb.toString());
Assert.assertNotNull(response);
}
@Test
public void testType3() throws WeixinException, IOException {
String para = "?signature=ad05f836772d1cbba1ff2edb7be4b9c9fb3a43d5&timestamp=1415980001&nonce=1803216865&encrypt_type=aes&msg_signature=c0d38e9ca00548f7142627ec2908a4fe8481025e";
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[gh_248c6f91d64f]]></ToUserName>");
xmlSb.append("<Encrypt><![CDATA[R6VQIWDR14XgSRLm25zc7V/WJYqK15gsUiMh0u/5GTMZME6jGtHkyfVN079ZPL065b+ZDq3TnoFKKtjtZlzcodY6Fm8+EujvtbTdVMMFSwdo8AwqVViAn09+DDfqPaNvbHUSiYsL3qlxArs1MH6APRUHFo7MU/piY1x2stJc8+kv28xtF+K8Aou0RuPO7PeQ18Zu/GkLnYNiI1E7UG31UYfOgVKcRjeE0PXa18iF5LBS8G/ce/l+/pH/DJWUBw5uXaqSOlo21tctlgLXu3bYUUkIu8tT49QwhHvRZILtO9icoyCNuTA7iTcHIdlAe1bD1S0ncmopIQCGmoU2/AXC2CCi6trONf3EPNKKKfDeQYHadnVZOg6kTX2cnYmHZLviYeLzjCKFSqSNkimoSKQ/Dcutpsq1D82NCwiExUZW4oo=]]></Encrypt>");
xmlSb.append("</xml>");
String response = push(para, xmlSb.toString());
Assert.assertNotNull(response);
}
}
@@ -1,179 +0,0 @@
package com.foxinmy.weixin4j.mp.test.msg;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException;
/**
* 接收事件消息格式测试
*
* @author jy.hu
* @date 2014年3月24日
* @since JDK 1.7
*/
public class EventMsgTest extends MessagePush {
private StringBuilder xmlSb = new StringBuilder();
/***************** event message *********************/
@Test
public void scribe() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[subscribe]]></Event>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void scan() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[SCAN]]></Event>");
xmlSb.append("<EventKey><![CDATA[SCENE_VALUE]]></EventKey>");
xmlSb.append("<Ticket><![CDATA[TICKET]]></Ticket>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void scan_scribe() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml><ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[subscribe]]></Event>");
xmlSb.append("<EventKey><![CDATA[qrscene_123123]]></EventKey>");
xmlSb.append("<Ticket><![CDATA[TICKET]]></Ticket>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void location() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[fromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[LOCATION]]></Event>");
xmlSb.append("<Latitude>23.137466</Latitude>");
xmlSb.append("<Longitude>113.352425</Longitude>");
xmlSb.append("<Precision>119.385040</Precision>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void menu_click() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[CLICK]]></Event>");
xmlSb.append("<EventKey><![CDATA[EVENTKEY]]></EventKey>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void menu_link() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[VIEW]]></Event>");
xmlSb.append("<EventKey><![CDATA[www.qq.com]]></EventKey>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void menu_scan() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[scancode_waitmsg]]></Event>");
xmlSb.append("<EventKey><![CDATA[www.qq.com]]></EventKey>");
xmlSb.append("<ScanCodeInfo><ScanType><![CDATA[qrcode]]></ScanType>");
xmlSb.append("<ScanResult><![CDATA[1]]></ScanResult>");
xmlSb.append("</ScanCodeInfo>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void menu_photo() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[pic_weixin]]></Event>");
xmlSb.append("<EventKey><![CDATA[www.qq.com]]></EventKey>");
xmlSb.append("<SendPicsInfo><Count>1</Count>");
xmlSb.append("<PicList><item><PicMd5Sum><![CDATA[1b5f7c23b5bf75682a53e7b6d163e185]]></PicMd5Sum>");
xmlSb.append("</item></PicList></SendPicsInfo>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void menu_location() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[event]]></MsgType>");
xmlSb.append("<Event><![CDATA[location_select]]></Event>");
xmlSb.append("<EventKey><![CDATA[www.qq.com]]></EventKey>");
xmlSb.append("<SendLocationInfo><Location_X><![CDATA[23]]></Location_X>");
xmlSb.append("<Location_Y><![CDATA[113]]></Location_Y>");
xmlSb.append("<Scale><![CDATA[15]]></Scale>");
xmlSb.append("<Label><![CDATA[ 广州市海珠区客村艺苑路 106号]]></Label>");
xmlSb.append("<Poiname><![CDATA[]]></Poiname></SendLocationInfo>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
}
@@ -1,144 +0,0 @@
package com.foxinmy.weixin4j.mp.test.msg;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException;
/**
* 接受一般消息格式测试
*
* @author jy.hu
* @date 2014年3月24日
* @since JDK 1.7
*/
public class InMsgTest extends MessagePush {
private StringBuilder xmlSb = new StringBuilder();
/***************** common message *********************/
@Test
public void text() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[fromUser]]></FromUserName>");
xmlSb.append("<CreateTime>1348831860</CreateTime>");
xmlSb.append("<MsgType><![CDATA[text]]></MsgType>");
xmlSb.append("<Content><![CDATA[this is a test]]></Content>");
xmlSb.append("<MsgId>1234567890123456</MsgId>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void image() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[image]]></MsgType>");
xmlSb.append("<PicUrl><![CDATA[this is a url]]></PicUrl>");
xmlSb.append("<MediaId><![CDATA[media_id]]></MediaId>");
xmlSb.append("<MsgId>1234567890123456</MsgId>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void voice() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[voice]]></MsgType>");
xmlSb.append("<MediaId><![CDATA[media_id]]></MediaId>");
xmlSb.append("<Format><![CDATA[Format]]></Format>");
xmlSb.append("<MsgId>1234567890123456</MsgId>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void re_voice() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[voice]]></MsgType>");
xmlSb.append("<MediaId><![CDATA[media_id]]></MediaId>");
xmlSb.append("<Format><![CDATA[Format]]></Format>");
xmlSb.append("<Recognition><![CDATA[腾讯微信团队]]></Recognition>");
xmlSb.append("<MsgId>1234567890123456</MsgId>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void video() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[video]]></MsgType>");
xmlSb.append("<MediaId><![CDATA[media_id]]></MediaId>");
xmlSb.append("<ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId>");
xmlSb.append("<MsgId>1234567890123456</MsgId>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void location() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[location]]></MsgType>");
xmlSb.append("<Location_X>23.134521</Location_X>");
xmlSb.append("<Location_Y>113.358803</Location_Y>");
xmlSb.append("<Scale>20</Scale>");
xmlSb.append("<Label><![CDATA[位置信息]]></Label>");
xmlSb.append("<MsgId>1234567890123456</MsgId>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
@Test
public void link() throws WeixinException, IOException {
xmlSb.delete(0, xmlSb.length());
xmlSb.append("<xml>");
xmlSb.append("<ToUserName><![CDATA[toUser]]></ToUserName>");
xmlSb.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
xmlSb.append("<CreateTime>123456789</CreateTime>");
xmlSb.append("<MsgType><![CDATA[link]]></MsgType>");
xmlSb.append("<Title><![CDATA[公众平台官网链接]]></Title>");
xmlSb.append("<Description><![CDATA[公众平台官网链接]]></Description>");
xmlSb.append("<Url><![CDATA[url]]></Url>");
xmlSb.append("<MsgId>1234567890123456</MsgId>");
xmlSb.append("</xml>");
String response = push(xmlSb.toString());
Assert.assertNotNull(response);
System.out.println(response);
}
}
@@ -1,68 +0,0 @@
package com.foxinmy.weixin4j.mp.test.msg;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
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.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.foxinmy.weixin4j.exception.WeixinException;
public class MessagePush {
private final String server = "http://localhost:8080";
private final HttpClient httpClient;
private final HttpPost httpPost;
private final HttpGet httpGet;
public MessagePush() {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost();
httpPost.setURI(URI.create(server));
httpGet = new HttpGet();
httpGet.setURI(URI.create(server));
}
public String get(String para) throws WeixinException, IOException {
httpGet.setURI(URI.create(server + para));
HttpResponse httpResponse = httpClient.execute(httpGet);
return entity(httpResponse);
}
public String push(String xml) throws WeixinException, IOException {
return push("", xml);
}
public String push(String para, String xml) throws WeixinException,
IOException {
httpPost.setURI(URI.create(server + para));
httpPost.setEntity(new StringEntity(xml, StandardCharsets.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
return entity(httpResponse);
}
private String entity(HttpResponse httpResponse) throws WeixinException,
IOException {
StatusLine statusLine = httpResponse.getStatusLine();
int status = statusLine.getStatusCode();
if (status != HttpStatus.SC_OK) {
throw new WeixinException(Integer.toString(status), "request fail");
}
if (status == HttpStatus.SC_MOVED_PERMANENTLY
|| status == HttpStatus.SC_MOVED_TEMPORARILY) {
throw new WeixinException(Integer.toString(status), "uri moved");
}
return EntityUtils.toString(httpResponse.getEntity(),
StandardCharsets.UTF_8);
}
}