From fe2a6a65e3956e0dfbe4186fe642c34b7234160d Mon Sep 17 00:00:00 2001 From: YuJian Date: Fri, 23 Sep 2016 15:55:32 +0800 Subject: [PATCH 01/21] =?UTF-8?q?=E5=88=A0=E5=8E=BB@return=EF=BC=8C?= =?UTF-8?q?=E4=B8=8E=E5=B7=B2=E6=9C=89=E4=BB=A3=E7=A0=81=E9=A3=8E=E6=A0=BC?= =?UTF-8?q?=E4=BF=9D=E6=8C=81=E4=B8=80=E8=87=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java | 1 - 1 file changed, 1 deletion(-) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java index f1ed0fa7..0b126ab5 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java @@ -195,7 +195,6 @@ public class WxMpCustomMessage implements Serializable { /** * 获得卡券消息builder - * @return */ public static WxCardBuilder WXCARD() { return new WxCardBuilder(); From 3ba6dbb19a5f7f3c81e8d963e4793e1d5994f3aa Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sat, 24 Sep 2016 22:01:45 +0800 Subject: [PATCH 02/21] =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E5=AF=B9=E8=B1=A1=E5=8C=85=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../me/chanjar/weixin/mp/api/WxMpPayService.java | 14 +++++++++----- .../weixin/mp/api/impl/WxMpPayServiceImpl.java | 4 ++++ .../mp/bean/{result => pay}/WxMpPayCallback.java | 2 +- .../bean/{result => pay}/WxMpPayRefundResult.java | 2 +- .../mp/bean/{result => pay}/WxMpPayResult.java | 2 +- .../mp/bean/{result => pay}/WxRedpackResult.java | 2 +- .../weixin/mp/bean/WxRedpackResultTest.java | 2 +- 7 files changed, 18 insertions(+), 10 deletions(-) rename weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/{result => pay}/WxMpPayCallback.java (99%) rename weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/{result => pay}/WxMpPayRefundResult.java (99%) rename weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/{result => pay}/WxMpPayResult.java (99%) rename weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/{result => pay}/WxRedpackResult.java (98%) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java index 0db67cb7..2e748d24 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java @@ -1,10 +1,14 @@ package me.chanjar.weixin.mp.api; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.bean.result.*; - import java.util.Map; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback; +import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; +import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; +import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; +import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult; + /** * 微信支付相关接口 * Created by Binary Wang on 2016/7/28. @@ -116,7 +120,7 @@ public interface WxMpPayService { /** * 发送微信红包给个人用户 - *

+ *

    * 需要传入的必填参数如下:
    * mch_billno//商户订单号
    * send_name//商户名称
@@ -128,8 +132,8 @@ public interface WxMpPayService {
    * act_name//活动名称
    * remark //备注
    * 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5
-   * 

* 使用现金红包功能需要在xml配置文件中额外设置: + *

* 微信商户平台ID * 商户平台设置的API密钥 * diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index ce7f9517..9ff3c4ab 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -7,6 +7,10 @@ import me.chanjar.weixin.common.util.crypto.WxCryptUtil; import me.chanjar.weixin.common.util.http.Utf8ResponseHandler; import me.chanjar.weixin.common.util.xml.XStreamInitializer; import me.chanjar.weixin.mp.api.WxMpPayService; +import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback; +import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; +import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; +import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; import me.chanjar.weixin.mp.bean.result.*; import org.apache.http.Consts; import org.apache.http.HttpHost; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayCallback.java similarity index 99% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayCallback.java index 6e96f5e2..e32e721e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayCallback.java @@ -1,4 +1,4 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayRefundResult.java similarity index 99% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayRefundResult.java index 4d51e8f4..3f917fe0 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayRefundResult.java @@ -1,4 +1,4 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayResult.java similarity index 99% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayResult.java index 98bba87f..2978ba17 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayResult.java @@ -1,4 +1,4 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java similarity index 98% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java index be328668..1792be08 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java @@ -1,4 +1,4 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java index 77e7c172..5a5275d4 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java @@ -8,7 +8,7 @@ import org.junit.Test; import com.thoughtworks.xstream.XStream; import me.chanjar.weixin.common.util.xml.XStreamInitializer; -import me.chanjar.weixin.mp.bean.result.WxRedpackResult; +import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; public class WxRedpackResultTest { From 58d10b7deb5ee1156fb57c2da5c1930d762df081 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sat, 24 Sep 2016 22:38:30 +0800 Subject: [PATCH 03/21] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86javad?= =?UTF-8?q?oc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/me/chanjar/weixin/mp/api/WxMpPayService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java index 2e748d24..4de8332b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java @@ -119,7 +119,7 @@ public interface WxMpPayService { boolean checkJSSDKCallbackDataSignature(Map kvm, String signature); /** - * 发送微信红包给个人用户 + * 发送普通微信红包给个人用户 *
    * 需要传入的必填参数如下:
    * mch_billno//商户订单号
@@ -131,7 +131,7 @@ public interface WxMpPayService {
    * client_ip//服务器Ip地址
    * act_name//活动名称
    * remark //备注
-   * 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5
+   * 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
    * 使用现金红包功能需要在xml配置文件中额外设置:
    * 
* 微信商户平台ID From 748a81b577ff582e2c71a37f271b074b168e1bae Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sat, 24 Sep 2016 22:38:45 +0800 Subject: [PATCH 04/21] =?UTF-8?q?=E4=BF=AE=E6=94=B9toString=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../weixin/mp/bean/pay/WxRedpackResult.java | 21 ++++--------------- 1 file changed, 4 insertions(+), 17 deletions(-) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java index 1792be08..fa9ce561 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java @@ -2,6 +2,9 @@ package me.chanjar.weixin.mp.bean.pay; import java.io.Serializable; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + import com.thoughtworks.xstream.annotations.XStreamAlias; /** @@ -13,9 +16,6 @@ import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("xml") public class WxRedpackResult implements Serializable { - /** - * - */ private static final long serialVersionUID = -4837415036337132073L; @XStreamAlias("return_code") @@ -100,19 +100,6 @@ public class WxRedpackResult implements Serializable { @Override public String toString() { - return "WxRedpackResult{" + - "returnCode=" + this.returnCode + - ", returnMsg=" + this.returnMsg + - ", sign=" + this.sign + - ", errCode=" + this.errCode + - ", errCodeDes=" + this.errCodeDes + - ", mchBillno=" + this.mchBillno + - ", mchId=" + this.mchId + - ", wxappid=" + this.wxappid + - ", reOpenid=" + this.reOpenid + - ", totalAmount=" + this.totalAmount + - ", sendTime=" + this.sendTime + - ", sendListid=" + this.sendListid + - '}'; + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } } From d3edb449807e6284f7e8a94dc6f10e68304d96bb Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sat, 24 Sep 2016 22:39:30 +0800 Subject: [PATCH 05/21] =?UTF-8?q?=E5=88=9D=E6=AD=A5=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=E5=A5=BD=E5=8F=91=E9=80=81=E7=BA=A2=E5=8C=85=E7=9A=84=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=AF=B9=E8=B1=A1=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mp/bean/pay/WxSendRedpackRequest.java | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java new file mode 100644 index 00000000..95ee2bad --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java @@ -0,0 +1,159 @@ +package me.chanjar.weixin.mp.bean.pay; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +/** + * 发送红包请求参数对象 + * Created by Binary Wang on 2016/9/24. + * @author binarywang (https://github.com/binarywang) + */ +@XStreamAlias("xml") +public class WxSendRedpackRequest { + /** + * mch_billno + * 商户订单号(每个订单号必须唯一) 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。 接口根据商户订单号支持重入,如出现超时可再调用。 + */ + @XStreamAlias("mch_billno") + private String mchBillno; + + /** + * send_name + * 商户名称 + * 红包发送者名称 + */ + @XStreamAlias("send_name") + private String sendName; + + /** + * re_openid + * 接受红包的用户 用户在wxappid下的openid + */ + @XStreamAlias("re_openid") + private String reOpenid; + + /** + * total_amount + * 红包总额 + */ + @XStreamAlias("total_amount") + private Integer totalAmount; + + /** + * total_num + * 红包发放总人数 + */ + @XStreamAlias("total_num") + private Integer totalNum; + + /** + * amt_type + * 红包金额设置方式 + * ALL_RAND—全部随机,商户指定总金额和红包发放总人数,由微信支付随机计算出各红包金额 + * 裂变红包必填 + */ + @XStreamAlias("amt_type") + private String amtType; + + /** + * wishing + * 红包祝福语 + */ + @XStreamAlias("wishing") + private String wishing; + + /** + * client_ip + * 服务器Ip地址 + * 调用接口的机器Ip地址 + */ + @XStreamAlias("client_ip") + private String clientIp; + + /** + * act_name + * 活动名称 + */ + @XStreamAlias("act_name") + private String actName; + + /** + * remark + * 备注 + */ + @XStreamAlias("remark") + private String remark; + + /** + * wxappid + * 微信分配的公众账号ID(企业号corpid即为此appId)。接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的) + */ + @XStreamAlias("wxappid") + private String wxAppid; + + /** + * mch_id + * 微信支付分配的商户号 + */ + @XStreamAlias("mch_id") + private String mchId; + + /** + * nonce_str + * 随机字符串,不长于32位 + */ + @XStreamAlias("nonce_str") + private String nonceStr; + + /** + * sign + * 详见签名生成算法 + */ + @XStreamAlias("sign") + private String sign; + + /** + *
+   * scene_id
+   * 场景id
+   * PRODUCT_1:商品促销
+   * PRODUCT_2:抽奖
+   * PRODUCT_3:虚拟物品兑奖 
+   * PRODUCT_4:企业内部福利
+   * PRODUCT_5:渠道分润
+   * PRODUCT_6:保险回馈
+   * PRODUCT_7:彩票派奖
+   * PRODUCT_8:税务刮奖
+   * 非必填字段
+   * 
+ */ + @XStreamAlias("scene_id") + private String sceneId; + + /** + *
+   * risk_info
+   * 活动信息
+   * posttime:用户操作的时间戳
+   * mobile:业务系统账号的手机号,国家代码-手机号。不需要+号
+   * deviceid :mac 地址或者设备唯一标识 
+   * clientversion :用户操作的客户端版本
+   * 把值为非空的信息用key=value进行拼接,再进行urlencode
+   * urlencode(posttime=xx&mobile=xx&deviceid=xx)
+   *  非必填字段
+   * 
+ */ + @XStreamAlias("risk_info") + private String riskInfo; + + /** + *
+   * consume_mch_id
+   * 资金授权商户号
+   * 资金授权商户号
+   * 服务商替特约商户发放时使用  
+   * 非必填字段
+   * 
+ */ + @XStreamAlias("consume_mch_id") + private String consumeMchId; +} From 06c73ca6abdd0e06c8b4f9b2c3f8debd01b540bc Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sat, 24 Sep 2016 23:45:32 +0800 Subject: [PATCH 06/21] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=91=E9=80=81?= =?UTF-8?q?=E7=BA=A2=E5=8C=85=E7=9A=84=E9=87=8D=E8=BD=BD=E6=96=B9=E6=B3=95?= =?UTF-8?q?=EF=BC=8C=E5=87=86=E5=A4=87=E6=9B=BF=E4=BB=A3=E7=8E=B0=E6=9C=89?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/util/crypto/WxCryptUtil.java | 3 +- weixin-java-mp/pom.xml | 9 +- .../chanjar/weixin/mp/api/WxMpPayService.java | 13 ++ .../mp/api/impl/WxMpPayServiceImpl.java | 98 ++++++++++--- .../mp/bean/pay/WxSendRedpackRequest.java | 137 ++++++++++++++++++ 5 files changed, 234 insertions(+), 26 deletions(-) diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java index eb5df7af..19424e0b 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java @@ -85,8 +85,7 @@ public class WxCryptUtil { * @param signKey 加密Key(即 商户Key) * @return 签名字符串 */ - public static String createSign(Map packageParams, - String signKey) { + public static String createSignForPay(Map packageParams, String signKey) { SortedMap sortedMap = new TreeMap<>(); sortedMap.putAll(packageParams); diff --git a/weixin-java-mp/pom.xml b/weixin-java-mp/pom.xml index 0cfb1048..0e534d0b 100644 --- a/weixin-java-mp/pom.xml +++ b/weixin-java-mp/pom.xml @@ -1,7 +1,7 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 com.github.binarywang @@ -54,6 +54,11 @@ 2.9.4 test + + org.jooq + joor + 0.9.6 + diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java index 4de8332b..663444a7 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java @@ -7,6 +7,7 @@ import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback; import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; +import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult; /** @@ -138,5 +139,17 @@ public interface WxMpPayService { * 商户平台设置的API密钥 * */ + @Deprecated WxRedpackResult sendRedpack(Map parameters) throws WxErrorException; + + /** + * 发送微信红包给个人用户 + *
 
+   * 文档详见:
+   * 发送普通红包 https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
+   * 发送裂变红包 https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5&index=4
+   * 
+ */ + WxRedpackResult sendRedpack(WxSendRedpackRequest request) throws WxErrorException; + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index 9ff3c4ab..13ab0781 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -1,6 +1,28 @@ package me.chanjar.weixin.mp.api.impl; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.http.Consts; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.joor.Reflect; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.helpers.MessageFormatter; + +import com.beust.jcommander.internal.Maps; import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.annotations.XStreamAlias; + import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.crypto.WxCryptUtil; @@ -11,22 +33,8 @@ import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback; import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; -import me.chanjar.weixin.mp.bean.result.*; -import org.apache.http.Consts; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.helpers.MessageFormatter; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; +import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; +import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult; /** * Created by Binary Wang on 2016/7/28. @@ -77,7 +85,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { packageParams.put("nonce_str", System.currentTimeMillis() + ""); checkParameters(packageParams); - String sign = WxCryptUtil.createSign(packageParams, + String sign = WxCryptUtil.createSignForPay(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); @@ -211,7 +219,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { payInfo.put("codeUrl", wxMpPrepayIdResult.getCode_url()); } - String finalSign = WxCryptUtil.createSign(payInfo, + String finalSign = WxCryptUtil.createSignForPay(payInfo, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); payInfo.put("paySign", finalSign); return payInfo; @@ -238,7 +246,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { } packageParams.put("nonce_str", nonce_str); - packageParams.put("sign", WxCryptUtil.createSign(packageParams, + packageParams.put("sign", WxCryptUtil.createSignForPay(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); StringBuilder request = new StringBuilder(""); @@ -295,7 +303,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { refundParams.put("nonce_str", System.currentTimeMillis() + ""); refundParams.put("op_user_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - String sign = WxCryptUtil.createSign(refundParams, + String sign = WxCryptUtil.createSignForPay(refundParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); refundParams.put("sign", sign); @@ -354,11 +362,12 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public boolean checkJSSDKCallbackDataSignature(Map kvm, String signature) { - return signature.equals(WxCryptUtil.createSign(kvm, + return signature.equals(WxCryptUtil.createSignForPay(kvm, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); } @Override + @Deprecated public WxRedpackResult sendRedpack(Map parameters) throws WxErrorException { SortedMap packageParams = new TreeMap<>(parameters); @@ -368,7 +377,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("nonce_str", System.currentTimeMillis() + ""); - String sign = WxCryptUtil.createSign(packageParams, + String sign = WxCryptUtil.createSignForPay(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); @@ -409,4 +418,49 @@ public class WxMpPayServiceImpl implements WxMpPayService { } } + @Override + public WxRedpackResult sendRedpack(WxSendRedpackRequest request) throws WxErrorException { + XStream xstream = XStreamInitializer.getInstance(); + xstream.processAnnotations(WxRedpackResult.class); + + request.setWxAppid(this.wxMpService.getWxMpConfigStorage().getAppId()); + request.setMchId(this.wxMpService.getWxMpConfigStorage().getPartnerId()); + request.setNonceStr(System.currentTimeMillis() + ""); + + String sign = WxCryptUtil.createSignForPay(xmlBean2Map(request), + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + request.setSign(sign); + + String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; + if (request.getAmtType() != null) { + //裂变红包 + url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack"; + } + + String responseContent = this.wxMpService.post(url, xstream.toXML(request)); + return (WxRedpackResult) xstream.fromXML(responseContent); + } + + private Map xmlBean2Map(Object bean) { + Map result = Maps.newHashMap(); + for (Entry entry : Reflect.on(bean).fields().entrySet()) { + Reflect reflect = entry.getValue(); + if (reflect.get() == null) { + continue; + } + + try { + Field field = WxSendRedpackRequest.class.getDeclaredField(entry.getKey()); + if (field.isAnnotationPresent(XStreamAlias.class)) { + result.put(reflect.get().toString(), field.getAnnotation(XStreamAlias.class).value()); + } + } catch (NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } + + } + + return result; + } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java index 95ee2bad..ccf84ae9 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java @@ -156,4 +156,141 @@ public class WxSendRedpackRequest { */ @XStreamAlias("consume_mch_id") private String consumeMchId; + + public String getMchBillno() { + return mchBillno; + } + + public void setMchBillno(String mchBillno) { + this.mchBillno = mchBillno; + } + + public String getSendName() { + return sendName; + } + + public void setSendName(String sendName) { + this.sendName = sendName; + } + + public String getReOpenid() { + return reOpenid; + } + + public void setReOpenid(String reOpenid) { + this.reOpenid = reOpenid; + } + + public Integer getTotalAmount() { + return totalAmount; + } + + public void setTotalAmount(Integer totalAmount) { + this.totalAmount = totalAmount; + } + + public Integer getTotalNum() { + return totalNum; + } + + public void setTotalNum(Integer totalNum) { + this.totalNum = totalNum; + } + + public String getAmtType() { + return amtType; + } + + public void setAmtType(String amtType) { + this.amtType = amtType; + } + + public String getWishing() { + return wishing; + } + + public void setWishing(String wishing) { + this.wishing = wishing; + } + + public String getClientIp() { + return clientIp; + } + + public void setClientIp(String clientIp) { + this.clientIp = clientIp; + } + + public String getActName() { + return actName; + } + + public void setActName(String actName) { + this.actName = actName; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public String getWxAppid() { + return wxAppid; + } + + public void setWxAppid(String wxAppid) { + this.wxAppid = wxAppid; + } + + public String getMchId() { + return mchId; + } + + public void setMchId(String mchId) { + this.mchId = mchId; + } + + public String getNonceStr() { + return nonceStr; + } + + public void setNonceStr(String nonceStr) { + this.nonceStr = nonceStr; + } + + public String getSign() { + return sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getSceneId() { + return sceneId; + } + + public void setSceneId(String sceneId) { + this.sceneId = sceneId; + } + + public String getRiskInfo() { + return riskInfo; + } + + public void setRiskInfo(String riskInfo) { + this.riskInfo = riskInfo; + } + + public String getConsumeMchId() { + return consumeMchId; + } + + public void setConsumeMchId(String consumeMchId) { + this.consumeMchId = consumeMchId; + } + } From 7f830e2755b6a5bab348907b2510a1f87773122c Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sat, 24 Sep 2016 23:47:50 +0800 Subject: [PATCH 07/21] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=BC=BA=E5=B0=91?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java | 1 + 1 file changed, 1 insertion(+) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index 13ab0781..f331a143 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -421,6 +421,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public WxRedpackResult sendRedpack(WxSendRedpackRequest request) throws WxErrorException { XStream xstream = XStreamInitializer.getInstance(); + xstream.processAnnotations(WxSendRedpackRequest.class); xstream.processAnnotations(WxRedpackResult.class); request.setWxAppid(this.wxMpService.getWxMpConfigStorage().getAppId()); From b13d3c9e6d4be16727214b35b3c746d60519884d Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sun, 25 Sep 2016 00:28:58 +0800 Subject: [PATCH 08/21] =?UTF-8?q?=E4=B8=BA=E6=96=B0=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E7=9A=84=E5=8F=91=E9=80=81=E7=BA=A2=E5=8C=85=E7=9A=84=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=96=B9=E6=B3=95=E6=B7=BB=E5=8A=A0=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=EF=BC=8C=E4=BB=85=E6=B5=8B=E8=AF=95=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=A0=BC=E5=BC=8F=EF=BC=8C=E6=9C=AA=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E5=AE=9E=E9=99=85=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/util/crypto/WxCryptUtil.java | 33 --------------- .../util/http/SimplePostRequestExecutor.java | 12 ++++-- .../common/util/xml/XStreamInitializer.java | 9 ++++- .../mp/api/impl/WxMpPayServiceImpl.java | 40 ++++++++++++++----- .../mp/api/impl/WxMpPayServiceImplTest.java | 23 ++++++++++- .../mp/bean/pay/WxSendRedpackRequestTest.java | 33 +++++++++++++++ 6 files changed, 102 insertions(+), 48 deletions(-) create mode 100644 weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java index 19424e0b..fead486e 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java @@ -19,14 +19,8 @@ package me.chanjar.weixin.common.util.crypto; import java.io.StringReader; import java.nio.charset.Charset; -import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; import java.util.Random; -import java.util.SortedMap; -import java.util.TreeMap; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; @@ -36,7 +30,6 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.digest.DigestUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; @@ -79,32 +72,6 @@ public class WxCryptUtil { this.aesKey = Base64.decodeBase64(encodingAesKey + "="); } - /** - * 微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3) - * @param packageParams 原始参数 - * @param signKey 加密Key(即 商户Key) - * @return 签名字符串 - */ - public static String createSignForPay(Map packageParams, String signKey) { - SortedMap sortedMap = new TreeMap<>(); - sortedMap.putAll(packageParams); - - List keys = new ArrayList<>(packageParams.keySet()); - Collections.sort(keys); - - StringBuffer toSign = new StringBuffer(); - for (String key : keys) { - String value = packageParams.get(key); - if (null != value && !"".equals(value) && !"sign".equals(key) - && !"key".equals(key)) { - toSign.append(key + "=" + value + "&"); - } - } - toSign.append("key=" + signKey); - String sign = DigestUtils.md5Hex(toSign.toString()).toUpperCase(); - return sign; - } - static String extractEncryptPart(String xml) { try { DocumentBuilder db = builderLocal.get(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java index ad67bd51..3a137849 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.common.util.http; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; +import java.io.IOException; + import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -10,7 +10,8 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; -import java.io.IOException; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; /** * 简单的POST请求执行器,请求的参数是String, 返回的结果也是String @@ -34,6 +35,11 @@ public class SimplePostRequestExecutor implements RequestExecutor")) { + //xml格式输出直接返回 + return responseContent; + } + WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java index d885327a..ba49528a 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java @@ -1,5 +1,7 @@ package me.chanjar.weixin.common.util.xml; +import java.io.Writer; + import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; @@ -8,8 +10,6 @@ import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.security.NullPermission; import com.thoughtworks.xstream.security.PrimitiveTypePermission; -import java.io.Writer; - public class XStreamInitializer { public static XStream getInstance() { @@ -34,6 +34,11 @@ public class XStreamInitializer { } } + + @Override + public String encodeNode(String name) { + return name;//防止将_转换成__ + } }; } }); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index f331a143..979f4a23 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -8,6 +8,7 @@ import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; +import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -25,7 +26,6 @@ import com.thoughtworks.xstream.annotations.XStreamAlias; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.crypto.WxCryptUtil; import me.chanjar.weixin.common.util.http.Utf8ResponseHandler; import me.chanjar.weixin.common.util.xml.XStreamInitializer; import me.chanjar.weixin.mp.api.WxMpPayService; @@ -85,7 +85,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { packageParams.put("nonce_str", System.currentTimeMillis() + ""); checkParameters(packageParams); - String sign = WxCryptUtil.createSignForPay(packageParams, + String sign = this.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); @@ -219,7 +219,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { payInfo.put("codeUrl", wxMpPrepayIdResult.getCode_url()); } - String finalSign = WxCryptUtil.createSignForPay(payInfo, + String finalSign = this.createSign(payInfo, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); payInfo.put("paySign", finalSign); return payInfo; @@ -246,7 +246,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { } packageParams.put("nonce_str", nonce_str); - packageParams.put("sign", WxCryptUtil.createSignForPay(packageParams, + packageParams.put("sign", this.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); StringBuilder request = new StringBuilder(""); @@ -303,7 +303,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { refundParams.put("nonce_str", System.currentTimeMillis() + ""); refundParams.put("op_user_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - String sign = WxCryptUtil.createSignForPay(refundParams, + String sign = this.createSign(refundParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); refundParams.put("sign", sign); @@ -362,7 +362,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public boolean checkJSSDKCallbackDataSignature(Map kvm, String signature) { - return signature.equals(WxCryptUtil.createSignForPay(kvm, + return signature.equals(this.createSign(kvm, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); } @@ -377,7 +377,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("nonce_str", System.currentTimeMillis() + ""); - String sign = WxCryptUtil.createSignForPay(packageParams, + String sign = this.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); @@ -428,7 +428,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { request.setMchId(this.wxMpService.getWxMpConfigStorage().getPartnerId()); request.setNonceStr(System.currentTimeMillis() + ""); - String sign = WxCryptUtil.createSignForPay(xmlBean2Map(request), + String sign = this.createSign(xmlBean2Map(request), this.wxMpService.getWxMpConfigStorage().getPartnerKey()); request.setSign(sign); @@ -453,7 +453,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { try { Field field = WxSendRedpackRequest.class.getDeclaredField(entry.getKey()); if (field.isAnnotationPresent(XStreamAlias.class)) { - result.put(reflect.get().toString(), field.getAnnotation(XStreamAlias.class).value()); + result.put(field.getAnnotation(XStreamAlias.class).value(), reflect.get().toString()); } } catch (NoSuchFieldException | SecurityException e) { e.printStackTrace(); @@ -464,4 +464,26 @@ public class WxMpPayServiceImpl implements WxMpPayService { return result; } + /** + * 微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3) + * @param packageParams 原始参数 + * @param signKey 加密Key(即 商户Key) + * @return 签名字符串 + */ + private String createSign(Map packageParams, String signKey) { + SortedMap sortedMap = new TreeMap<>(packageParams); + + StringBuffer toSign = new StringBuffer(); + for (String key : sortedMap.keySet()) { + String value = packageParams.get(key); + if (null != value && !"".equals(value) && !"sign".equals(key) && !"key".equals(key)) { + toSign.append(key + "=" + value + "&"); + } + } + + toSign.append("key=" + signKey); + + return DigestUtils.md5Hex(toSign.toString()).toUpperCase(); + } + } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java index 79a5a631..b17d1206 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java @@ -1,12 +1,26 @@ package me.chanjar.weixin.mp.api.impl; +import org.testng.annotations.Guice; import org.testng.annotations.Test; +import com.google.inject.Inject; + +import me.chanjar.weixin.mp.api.ApiTestModule; +import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; +import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; + /** + * 测试支付相关接口 * Created by Binary Wang on 2016/7/28. * @author binarywang (https://github.com/binarywang) */ +@Test +@Guice(modules = ApiTestModule.class) public class WxMpPayServiceImplTest { + + @Inject + protected WxMpServiceImpl wxService; + @Test public void testGetPrepayId() throws Exception { @@ -54,7 +68,14 @@ public class WxMpPayServiceImplTest { @Test public void testSendRedpack() throws Exception { - + WxSendRedpackRequest request = new WxSendRedpackRequest(); + request.setActName("abc"); + request.setClientIp("aaa"); + request.setMchBillno("aaaa"); + request + .setReOpenid(((ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage()).getOpenid()); + WxRedpackResult redpackResult = this.wxService.getPayService().sendRedpack(request); + System.err.println(redpackResult); } } \ No newline at end of file diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java new file mode 100644 index 00000000..feb50c5a --- /dev/null +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java @@ -0,0 +1,33 @@ +package me.chanjar.weixin.mp.bean.pay; + +import java.lang.reflect.Field; +import java.util.Map.Entry; + +import org.joor.Reflect; +import org.testng.annotations.Test; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@Test +public class WxSendRedpackRequestTest { + + public void test() throws NoSuchFieldException, SecurityException { + + WxSendRedpackRequest request = new WxSendRedpackRequest(); + request.setMchBillno("123"); + request.setActName("ab"); + for (Entry entry : Reflect.on(request).fields().entrySet()) { + Reflect reflect = entry.getValue(); + if (reflect.get() == null) { + continue; + } + + Field field = WxSendRedpackRequest.class.getDeclaredField(entry.getKey()); + if (field.isAnnotationPresent(XStreamAlias.class)) { + System.err.println(reflect.get() + " = " + field.getAnnotation(XStreamAlias.class).value()); + } + } + + } + +} From e70c5394658d53995cff4a3a27c21cd424684aa9 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sun, 25 Sep 2016 00:35:19 +0800 Subject: [PATCH 09/21] =?UTF-8?q?=E5=AF=B9=E7=9B=B8=E5=BA=94=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E8=BF=9B=E8=A1=8C=E5=88=A4=E6=96=AD=EF=BC=8C=E5=8F=8A?= =?UTF-8?q?=E6=97=B6=E6=8A=9B=E5=87=BA=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index 979f4a23..09c7f261 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -439,7 +439,13 @@ public class WxMpPayServiceImpl implements WxMpPayService { } String responseContent = this.wxMpService.post(url, xstream.toXML(request)); - return (WxRedpackResult) xstream.fromXML(responseContent); + WxRedpackResult redpackResult = (WxRedpackResult) xstream.fromXML(responseContent); + if("FAIL".equals(redpackResult.getResultCode())){ + throw new WxErrorException( + WxError.newBuilder().setErrorMsg(redpackResult.getErrCode() + ":" + redpackResult.getErrCodeDes()).build()); + } + + return redpackResult; } private Map xmlBean2Map(Object bean) { @@ -465,7 +471,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { } /** - * 微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3) + * 微信公众号支付签名算法(详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3) * @param packageParams 原始参数 * @param signKey 加密Key(即 商户Key) * @return 签名字符串 From 64ec8a39720e0ce9aae15e11cfdd66904fa53142 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sun, 25 Sep 2016 00:56:14 +0800 Subject: [PATCH 10/21] =?UTF-8?q?=E4=B8=BA=E7=85=A7=E9=A1=BEtravis-ci?= =?UTF-8?q?=EF=BC=8C=E6=9A=82=E6=97=B6=E5=B1=8F=E8=94=BDaliyun=E7=9A=84rep?= =?UTF-8?q?o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index cb727c46..0bb9677c 100644 --- a/build.gradle +++ b/build.gradle @@ -12,9 +12,9 @@ subprojects { repositories { - mavenLocal() + //mavenLocal() - maven { url "http://maven.aliyun.com/nexus/content/groups/public" } + //maven { url "http://maven.aliyun.com/nexus/content/groups/public" } } From 29c6d14e05ed898bbf5c2b75309ef865df4b5cd5 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sun, 25 Sep 2016 00:57:54 +0800 Subject: [PATCH 11/21] =?UTF-8?q?=E4=B8=BA=E7=85=A7=E9=A1=BEtravis-ci?= =?UTF-8?q?=EF=BC=8C=E6=9A=82=E6=97=B6=E5=B1=8F=E8=94=BDaliyun=E7=9A=84rep?= =?UTF-8?q?o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 0bb9677c..a4fc7018 100644 --- a/build.gradle +++ b/build.gradle @@ -11,11 +11,11 @@ subprojects { targetCompatibility = 1.7 - repositories { + //repositories { //mavenLocal() //maven { url "http://maven.aliyun.com/nexus/content/groups/public" } - } + //} dependencies { From 19cfded2fb3a2fa205e0063edb0706d7d1c5b7c4 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sun, 25 Sep 2016 01:00:54 +0800 Subject: [PATCH 12/21] fix gradle repositories --- build.gradle | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index a4fc7018..cf7cc8f3 100644 --- a/build.gradle +++ b/build.gradle @@ -11,11 +11,11 @@ subprojects { targetCompatibility = 1.7 - //repositories { - //mavenLocal() - + repositories { + mavenLocal() + maven { url "http://central.maven.org/maven2" } //maven { url "http://maven.aliyun.com/nexus/content/groups/public" } - //} + } dependencies { From b12e52e1c05c1a233f928a3335f736415d71b8f8 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sun, 25 Sep 2016 01:12:01 +0800 Subject: [PATCH 13/21] add guava lib --- pom.xml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pom.xml b/pom.xml index 7ca43e66..a4670e35 100644 --- a/pom.xml +++ b/pom.xml @@ -51,6 +51,7 @@ 3.6.7 2.9.0 2.7 + 19.0 3.4 2.5 1.10 @@ -111,6 +112,10 @@ ${jedis.version} provided + + com.google.guava + guava + @@ -151,6 +156,11 @@ ${jetty.version} test + + com.google.guava + guava + ${guava.version} + From ea6a9b5de3887e80a4efe2463a0f865dc5a9e755 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sun, 25 Sep 2016 01:12:17 +0800 Subject: [PATCH 14/21] fix package for Maps --- .../java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index 09c7f261..bea7d448 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -20,7 +20,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.MessageFormatter; -import com.beust.jcommander.internal.Maps; +import com.google.common.collect.Maps; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; From 15e27003ea6289fd3b22fd4ea688c26f69fdc88a Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Sun, 25 Sep 2016 01:17:44 +0800 Subject: [PATCH 15/21] fix gradle and refactor pom --- build.gradle | 2 ++ pom.xml | 10 ++++++++++ weixin-java-mp/pom.xml | 5 ----- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index cf7cc8f3..ba705da9 100644 --- a/build.gradle +++ b/build.gradle @@ -24,6 +24,8 @@ subprojects { compile group: 'org.apache.httpcomponents', name: 'httpmime', version:'4.5' compile group: 'org.jodd', name: 'jodd-http', version:'3.6.7' compile group: 'com.google.code.gson', name: 'gson', version:'2.7' + compile group: 'com.google.guava', name: 'guava', version:'19.0' + compile group: 'org.jooq', name: 'joor', version:'0.9.6' compile group: 'commons-codec', name: 'commons-codec', version:'1.10' compile group: 'commons-io', name: 'commons-io', version:'2.5' compile group: 'org.apache.commons', name: 'commons-lang3', version:'3.4' diff --git a/pom.xml b/pom.xml index a4670e35..d79f2f72 100644 --- a/pom.xml +++ b/pom.xml @@ -52,6 +52,7 @@ 2.9.0 2.7 19.0 + 0.9.6 3.4 2.5 1.10 @@ -116,6 +117,10 @@ com.google.guava guava + + org.jooq + joor + @@ -161,6 +166,11 @@ guava ${guava.version} + + org.jooq + joor + ${joor.version} + diff --git a/weixin-java-mp/pom.xml b/weixin-java-mp/pom.xml index 0e534d0b..33a4f5ab 100644 --- a/weixin-java-mp/pom.xml +++ b/weixin-java-mp/pom.xml @@ -54,11 +54,6 @@ 2.9.4 test - - org.jooq - joor - 0.9.6 - From 6a19062e36a8fbf63397df6d5b2ff1690ad21d7f Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Mon, 26 Sep 2016 00:12:37 +0800 Subject: [PATCH 16/21] =?UTF-8?q?=E5=87=86=E5=A4=87=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E4=B8=8B=E5=8D=95=E6=8E=A5=E5=8F=A3=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chanjar/weixin/mp/api/WxMpPayService.java | 23 +- .../mp/api/impl/WxMpPayServiceImpl.java | 3 + .../mp/bean/pay/WxUnifiedOrderRequest.java | 197 ++++++++++++++++++ 3 files changed, 217 insertions(+), 6 deletions(-) create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java index 663444a7..06cdde7d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java @@ -8,6 +8,7 @@ import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest; import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult; /** @@ -17,7 +18,6 @@ import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult; */ public interface WxMpPayService { - /** * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1) * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识" @@ -39,12 +39,22 @@ public interface WxMpPayService { * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识" * * @param parameters All required/optional parameters for weixin payment + * @deprecated use me.chanjar.weixin.mp.api.WxMpPayService.unifiedOrder(WxUnifiedOrderRequest) instead */ + @Deprecated WxMpPrepayIdResult getPrepayId(Map parameters); + /** + * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1) + * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识" + * 接口地址:https://api.mch.weixin.qq.com/pay/unifiedorder + * + */ + WxMpPrepayIdResult unifiedOrder(WxUnifiedOrderRequest request); + /** * 该接口调用“统一下单”接口,并拼装发起支付请求需要的参数 - * 详见http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E5.8F.91.E8.B5.B7.E4.B8.80.E4.B8.AA.E5.BE.AE.E4.BF.A1.E6.94.AF.E4.BB.98.E8.AF.B7.E6.B1.82 + * 详见http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN * * @param parameters the required or optional parameters */ @@ -52,7 +62,7 @@ public interface WxMpPayService { /** * 该接口调用“统一下单”接口,并拼装NATIVE发起支付请求需要的参数 - * 详见http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E5.8F.91.E8.B5.B7.E4.B8.80.E4.B8.AA.E5.BE.AE.E4.BF.A1.E6.94.AF.E4.BB.98.E8.AF.B7.E6.B1.82 + * 详见http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN * tradeType 交易类型 NATIVE (其他交易类型JSAPI,APP,WAP) * * @param productId 商户商品ID @@ -61,14 +71,14 @@ public interface WxMpPayService { * @param body 商品描述 * @param ip 发起支付的客户端IP * @param notifyUrl 通知地址 - * @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPayInfo(Map) instead + * @deprecated Use me.chanjar.weixin.mp.api.WxMpPayService.getPayInfo(Map) instead */ @Deprecated Map getNativePayInfo(String productId, String outTradeNo, double amt, String body, String ip, String notifyUrl) throws WxErrorException; /** * 该接口调用“统一下单”接口,并拼装JSAPI发起支付请求需要的参数 - * 详见http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E5.8F.91.E8.B5.B7.E4.B8.80.E4.B8.AA.E5.BE.AE.E4.BF.A1.E6.94.AF.E4.BB.98.E8.AF.B7.E6.B1.82 + * 详见http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN * tradeType 交易类型 JSAPI(其他交易类型NATIVE,APP,WAP) * * @param openId 支付人openId @@ -77,7 +87,7 @@ public interface WxMpPayService { * @param body 商品描述 * @param ip 发起支付的客户端IP * @param notifyUrl 通知地址 - * @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPayInfo(Map) instead + * @deprecated Use me.chanjar.weixin.mp.api.WxMpPayService.getPayInfo(Map) instead */ @Deprecated Map getJsapiPayInfo(String openId, String outTradeNo, double amt, String body, String ip, String notifyUrl) throws WxErrorException; @@ -137,6 +147,7 @@ public interface WxMpPayService { * * 微信商户平台ID * 商户平台设置的API密钥 + * @deprecated use me.chanjar.weixin.mp.api.WxMpPayService.sendRedpack(WxSendRedpackRequest) instead * */ @Deprecated diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index bea7d448..29d37238 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -56,6 +56,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { } @Override + @Deprecated public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String callbackUrl) { @@ -144,6 +145,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { } @Override + @Deprecated public Map getJsapiPayInfo(String openId, String outTradeNo, double amt, String body, String ip, String callbackUrl) throws WxErrorException { @@ -164,6 +166,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { } @Override + @Deprecated public Map getNativePayInfo(String productId, String outTradeNo, double amt, String body, String ip, String callbackUrl) throws WxErrorException { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java new file mode 100644 index 00000000..f1c77ff5 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java @@ -0,0 +1,197 @@ +package me.chanjar.weixin.mp.bean.pay; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +/** + * 统一下单请求参数对象 + * Created by Binary Wang on 2016/9/25. + * @author binarywang (https://github.com/binarywang) + */ +@XStreamAlias("xml") +public class WxUnifiedOrderRequest { + /** + *
+   * 公众账号ID 
+   * appid 
+   * 是 
+   * String(32)  
+   * wxd678efh567hg6787  
+   * 微信分配的公众账号ID(企业号corpid即为此appId)
+   * 
+ */ + /** + *
+   * 商户号
+   * mch_id  
+   * 是 
+   * String(32)  
+   * 1230000109  
+   * 微信支付分配的商户号
+   * 
+ */ + /** + *
  
+   * 设备号 
+   * device_info 
+   * 否 
+   * String(32)  
+   * 013467007045764 
+   * 终端设备号(门店号或收银设备ID),注意:PC网页或公众号内支付请传"WEB"
+   * 
+ */ + /** + *
  
+   * 随机字符串 
+   * nonce_str 
+   * 是 
+   * String(32)  
+   * 5K8264ILTKCH16CQ2502SI8ZNMTM67VS  
+   * 随机字符串,不长于32位。推荐随机数生成算法
+   * 
+ */ + /** + *
  
+   * 签名  
+   * sign  
+   * 是
+   *  String(32)  
+   *  C380BEC2BFD727A4B6845133519F3AD6  
+   *  签名,详见签名生成算法
+   * 
+ */ + /** + *
  
+   * 商品描述  
+   * body  
+   * 是
+   * String(128) 
+   * 腾讯充值中心-QQ会员充值
+   * 商品简单描述,该字段须严格按照规范传递,具体请见参数规定
+   * 
+ */ + /** + *
  
+   * 商品详情  
+   * detail  
+   * 否
+   * String(6000) 
+   *  {  "goods_detail":[
+      {
+      "goods_id":"iphone6s_16G",
+      "wxpay_goods_id":"1001",
+      "goods_name":"iPhone6s 16G",
+      "goods_num":1,
+      "price":528800,
+      "goods_category":"123456",
+      "body":"苹果手机"
+      },
+      {
+      "goods_id":"iphone6s_32G",
+      "wxpay_goods_id":"1002",
+      "goods_name":"iPhone6s 32G",
+      "quantity":1,
+      "price":608800,
+      "goods_category":"123789",
+      "body":"苹果手机"
+      }
+      ]
+      } 
+              商品详细列表,使用Json格式,传输签名前请务必使用CDATA标签将JSON文本串保护起来。
+        goods_detail []:
+        └ goods_id String 必填 32 商品的编号
+        └ wxpay_goods_id String 可选 32 微信支付定义的统一商品编号
+        └ goods_name String 必填 256 商品名称
+        └ goods_num Int 必填 商品数量
+        └ price Int 必填 商品单价,单位为分
+        └ goods_category String 可选 32 商品类目ID
+        └ body String 可选 1000 商品描述信息
+   * 
+ */ + /** + *
  
+   * 附加数据  
+   * attach  
+   * 否 
+   * String(127) 
+   * 深圳分店 
+   *  附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
+   * 
+ */ + /** + *
  
+   * 商户订单号
+   * out_trade_no   
+   * 是 
+   * String(32)  
+   * 20150806125346  
+   * 商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
+   * 
+ */ + /** + *
  
+   * 货币类型  
+   * fee_type  
+   * 否 
+   * String(16)  
+   * CNY 
+   * 符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
+   * 
+ */ + /** + *
  
+   * 总金额 
+   * total_fee 
+   * 是 
+   * Int 
+   * 888 
+   * 订单总金额,单位为分,详见支付金额
+   * 
+ */ + /** + *
  
+   * 终端IP  
+   * spbill_create_ip 
+   * 是 
+   * String(16)  
+   * 123.12.12.123 
+   * APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
+   * 
+ */ + /** + *
  交易起始时间  time_start  否 String(14)  20091225091010  订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
+   * 
+ */ + /** + *
  交易结束时间  time_expire 否 String(14)  20091227091010 
+   * 
+ */ + /** + *
  订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则
+   *   注意:最短失效时间间隔必须大于5分钟
+   * 
+ */ + /** + *
  商品标记  goods_tag 否 String(32)  WXG 商品标记,代金券或立减优惠功能的参数,说明详见代金券或立减优惠
+   * 
+ */ + /** + *
  通知地址  notify_url  是 String(256) http://www.weixin.qq.com/wxpay/pay.php  接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
+   * 
+ */ + /** + *
  交易类型  trade_type  是 String(16)  JSAPI 取值如下:JSAPI,NATIVE,APP,详细说明见参数规定
+   * 
+ */ + /** + *
  商品ID  product_id  否 String(32)  12235413214070356458058 trade_type=NATIVE,此参数必传。此id为二维码中包含的商品ID,商户自行定义。
+   * 
+ */ + /** + *
  指定支付方式  limit_pay 否 String(32)  no_credit no_credit--指定不能使用信用卡支付
+   * 
+ */ + /** + *
  用户标识  openid  否 String(128) oUpF8uMuAJO_M2pxb1Q9zNjWeS6o  trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。openid如何获取,可参考【获取openid】。企业号请使用【企业号OAuth2.0接口】获取企业号内成员userid,再调用【企业号userid转openid接口】进行转换
+   * 
+ */ +} From b555cc37905ea822d3f9f7090bd1d8ee3422c0c0 Mon Sep 17 00:00:00 2001 From: BinaryWang Date: Mon, 26 Sep 2016 11:20:32 +0800 Subject: [PATCH 17/21] =?UTF-8?q?=E5=A2=9E=E5=8A=A0annotation=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E6=A0=87=E8=AF=86=E5=AD=97=E6=AE=B5=E6=98=AF=E5=90=A6?= =?UTF-8?q?=E5=BF=85=E5=A1=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../weixin/common/annotation/Required.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java new file mode 100644 index 00000000..9ed249da --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java @@ -0,0 +1,19 @@ +package me.chanjar.weixin.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 标识某个字段是否是必填的 + * + * Created by Binary Wang on 2016/9/25. + * @author binarywang (https://github.com/binarywang) + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Required { + +} \ No newline at end of file From c4838295e55f10c15ee6ef858f118dc3b591748f Mon Sep 17 00:00:00 2001 From: BinaryWang Date: Mon, 26 Sep 2016 11:21:20 +0800 Subject: [PATCH 18/21] add missing @Override --- .../me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java | 1 + 1 file changed, 1 insertion(+) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java index c7d451ef..8620cd84 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java @@ -23,6 +23,7 @@ public final class WxCardBuilder extends BaseBuilder { return this; } + @Override public WxMpCustomMessage build() { WxMpCustomMessage m = super.build(); m.setCardId(this.cardId); From 839ecadaa7c0c778c4566e68bd4d67b3e407d89b Mon Sep 17 00:00:00 2001 From: BinaryWang Date: Mon, 26 Sep 2016 12:34:37 +0800 Subject: [PATCH 19/21] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=96=B0=E7=9A=84?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E4=B8=8B=E5=8D=95=E6=8E=A5=E5=8F=A3=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E6=B7=BB=E5=8A=A0=E5=AF=B9=E6=8E=A5=E5=8F=A3=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E7=9A=84=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E6=9C=AA=E5=AF=B9=E5=AE=9E=E9=99=85=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E8=BF=9B=E8=A1=8C=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../util/http/SimplePostRequestExecutor.java | 6 + .../chanjar/weixin/mp/api/WxMpPayService.java | 7 +- .../mp/api/impl/WxMpPayServiceImpl.java | 272 ++++--- .../mp/bean/pay/WxMpPrepayIdResult.java | 124 ++++ .../weixin/mp/bean/pay/WxRedpackResult.java | 26 +- .../mp/bean/pay/WxSendRedpackRequest.java | 34 +- .../mp/bean/pay/WxUnifiedOrderRequest.java | 691 +++++++++++++++--- .../mp/bean/pay/WxUnifiedOrderResult.java | 155 ++++ .../mp/bean/result/WxMpPrepayIdResult.java | 128 ---- .../mp/api/impl/WxMpPayServiceImplTest.java | 20 +- 10 files changed, 1093 insertions(+), 370 deletions(-) create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java delete mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java index 3a137849..bdea8573 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java @@ -35,6 +35,12 @@ public class SimplePostRequestExecutor implements RequestExecutor")) { //xml格式输出直接返回 return responseContent; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java index 06cdde7d..dae03f43 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java @@ -6,10 +6,11 @@ import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback; import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; +import me.chanjar.weixin.mp.bean.pay.WxMpPrepayIdResult; import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest; -import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderResult; /** * 微信支付相关接口 @@ -48,9 +49,11 @@ public interface WxMpPayService { * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1) * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识" * 接口地址:https://api.mch.weixin.qq.com/pay/unifiedorder + * @throws WxErrorException * */ - WxMpPrepayIdResult unifiedOrder(WxUnifiedOrderRequest request); + WxUnifiedOrderResult unifiedOrder(WxUnifiedOrderRequest request) + throws WxErrorException; /** * 该接口调用“统一下单”接口,并拼装发起支付请求需要的参数 diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index 29d37238..e3e628c7 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -3,6 +3,7 @@ package me.chanjar.weixin.mp.api.impl; import java.io.IOException; import java.lang.reflect.Field; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; @@ -20,10 +21,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.MessageFormatter; +import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; +import me.chanjar.weixin.common.annotation.Required; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.Utf8ResponseHandler; @@ -32,9 +35,11 @@ import me.chanjar.weixin.mp.api.WxMpPayService; import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback; import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; +import me.chanjar.weixin.mp.bean.pay.WxMpPrepayIdResult; import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; -import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderResult; /** * Created by Binary Wang on 2016/7/28. @@ -43,10 +48,12 @@ import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult; */ public class WxMpPayServiceImpl implements WxMpPayService { + private static final List TRADE_TYPES = Lists.newArrayList("JSAPI", + "NATIVE", "APP"); private final Logger log = LoggerFactory.getLogger(WxMpPayServiceImpl.class); - private final String[] REQUIRED_ORDER_PARAMETERS = new String[]{"appid", - "mch_id", "body", "out_trade_no", "total_fee", "spbill_create_ip", - "notify_url", "trade_type"}; + private final String[] REQUIRED_ORDER_PARAMETERS = new String[] { "appid", + "mch_id", "body", "out_trade_no", "total_fee", "spbill_create_ip", + "notify_url", "trade_type" }; private HttpHost httpProxy; private WxMpServiceImpl wxMpService; @@ -58,13 +65,13 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override @Deprecated public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, - double amt, String body, String tradeType, String ip, - String callbackUrl) { + double amt, String body, String tradeType, String ip, + String callbackUrl) { Map packageParams = new HashMap<>(); packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -77,47 +84,48 @@ public class WxMpPayServiceImpl implements WxMpPayService { } @Override + @Deprecated public WxMpPrepayIdResult getPrepayId(final Map parameters) { final SortedMap packageParams = new TreeMap<>(parameters); packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("nonce_str", System.currentTimeMillis() + ""); checkParameters(packageParams); String sign = this.createSign(packageParams, - this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { request.append(String.format("<%s>%s", para.getKey(), - para.getValue(), para.getKey())); + para.getValue(), para.getKey())); } request.append(""); HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/pay/unifiedorder"); + "https://api.mch.weixin.qq.com/pay/unifiedorder"); if (this.httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { + .execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPrepayIdResult.class); return (WxMpPrepayIdResult) xstream.fromXML(responseContent); } catch (IOException e) { throw new RuntimeException("Failed to get prepay id due to IO exception.", - e); + e); } finally { httpPost.releaseConnection(); } @@ -127,33 +135,33 @@ public class WxMpPayServiceImpl implements WxMpPayService { for (String para : this.REQUIRED_ORDER_PARAMETERS) { if (!parameters.containsKey(para)) { throw new IllegalArgumentException( - "Reqiured argument '" + para + "' is missing."); + "Reqiured argument '" + para + "' is missing."); } } if ("JSAPI".equals(parameters.get("trade_type")) - && !parameters.containsKey("openid")) { + && !parameters.containsKey("openid")) { throw new IllegalArgumentException( - "Reqiured argument 'openid' is missing when trade_type is 'JSAPI'."); + "Reqiured argument 'openid' is missing when trade_type is 'JSAPI'."); } if ("NATIVE".equals(parameters.get("trade_type")) - && !parameters.containsKey("product_id")) { + && !parameters.containsKey("product_id")) { throw new IllegalArgumentException( - "Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'."); + "Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'."); } } @Override @Deprecated public Map getJsapiPayInfo(String openId, String outTradeNo, - double amt, String body, String ip, String callbackUrl) - throws WxErrorException { + double amt, String body, String ip, String callbackUrl) + throws WxErrorException { Map packageParams = new HashMap<>(); packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -168,13 +176,13 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override @Deprecated public Map getNativePayInfo(String productId, - String outTradeNo, double amt, String body, String ip, String callbackUrl) - throws WxErrorException { + String outTradeNo, double amt, String body, String ip, String callbackUrl) + throws WxErrorException { Map packageParams = new HashMap<>(); packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -188,27 +196,27 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public Map getPayInfo(Map parameters) - throws WxErrorException { + throws WxErrorException { WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(parameters); if (!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getReturn_code()) - || !"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { + || !"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { WxError error = new WxError(); error.setErrorCode(-1); error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code() - + ";return_msg:" + wxMpPrepayIdResult.getReturn_msg() - + ";result_code:" + wxMpPrepayIdResult.getResult_code() + ";err_code" - + wxMpPrepayIdResult.getErr_code() + ";err_code_des" - + wxMpPrepayIdResult.getErr_code_des()); + + ";return_msg:" + wxMpPrepayIdResult.getReturn_msg() + + ";result_code:" + wxMpPrepayIdResult.getResult_code() + ";err_code" + + wxMpPrepayIdResult.getErr_code() + ";err_code_des" + + wxMpPrepayIdResult.getErr_code_des()); throw new WxErrorException(error); } String prepayId = wxMpPrepayIdResult.getPrepay_id(); if (prepayId == null || prepayId.equals("")) { throw new RuntimeException( - String.format("Failed to get prepay id due to error code '%s'(%s).", - wxMpPrepayIdResult.getErr_code(), - wxMpPrepayIdResult.getErr_code_des())); + String.format("Failed to get prepay id due to error code '%s'(%s).", + wxMpPrepayIdResult.getErr_code(), + wxMpPrepayIdResult.getErr_code_des())); } Map payInfo = new HashMap<>(); @@ -223,21 +231,21 @@ public class WxMpPayServiceImpl implements WxMpPayService { } String finalSign = this.createSign(payInfo, - this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); payInfo.put("paySign", finalSign); return payInfo; } @Override public WxMpPayResult getJSSDKPayResult(String transactionId, - String outTradeNo) { + String outTradeNo) { String nonce_str = System.currentTimeMillis() + ""; SortedMap packageParams = new TreeMap<>(); packageParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); if (transactionId != null && !"".equals(transactionId.trim())) { packageParams.put("transaction_id", transactionId); @@ -245,40 +253,40 @@ public class WxMpPayServiceImpl implements WxMpPayService { packageParams.put("out_trade_no", outTradeNo); } else { throw new IllegalArgumentException( - "Either 'transactionId' or 'outTradeNo' must be given."); + "Either 'transactionId' or 'outTradeNo' must be given."); } packageParams.put("nonce_str", nonce_str); packageParams.put("sign", this.createSign(packageParams, - this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + this.wxMpService.getWxMpConfigStorage().getPartnerKey())); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { request.append(String.format("<%s>%s", para.getKey(), - para.getValue(), para.getKey())); + para.getValue(), para.getKey())); } request.append(""); HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/pay/orderquery"); + "https://api.mch.weixin.qq.com/pay/orderquery"); if (this.httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { + .execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPayResult.class); return (WxMpPayResult) xstream.fromXML(responseContent); } catch (IOException e) { throw new RuntimeException("Failed to query order due to IO exception.", - e); + e); } } @@ -297,66 +305,66 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public WxMpPayRefundResult refundPay(Map parameters) - throws WxErrorException { + throws WxErrorException { SortedMap refundParams = new TreeMap<>(parameters); refundParams.put("appid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); refundParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); refundParams.put("nonce_str", System.currentTimeMillis() + ""); refundParams.put("op_user_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); String sign = this.createSign(refundParams, - this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); refundParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : refundParams.entrySet()) { request.append(String.format("<%s>%s", para.getKey(), - para.getValue(), para.getKey())); + para.getValue(), para.getKey())); } request.append(""); HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/secapi/pay/refund"); + "https://api.mch.weixin.qq.com/secapi/pay/refund"); if (this.httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { + .execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxMpPayRefundResult.class); WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream - .fromXML(responseContent); + .fromXML(responseContent); if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) - || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { + || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { WxError error = new WxError(); error.setErrorCode(-1); error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() - + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() - + ";result_code:" + wxMpPayRefundResult.getResultCode() - + ";err_code" + wxMpPayRefundResult.getErrCode() + ";err_code_des" - + wxMpPayRefundResult.getErrCodeDes()); + + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() + + ";result_code:" + wxMpPayRefundResult.getResultCode() + + ";err_code" + wxMpPayRefundResult.getErrCode() + ";err_code_des" + + wxMpPayRefundResult.getErrCodeDes()); throw new WxErrorException(error); } return wxMpPayRefundResult; } catch (IOException e) { String message = MessageFormatter - .format("Exception happened when sending refund '{}'.", - request.toString()) - .getMessage(); + .format("Exception happened when sending refund '{}'.", + request.toString()) + .getMessage(); this.log.error(message, e); throw new WxErrorException( - WxError.newBuilder().setErrorMsg(message).build()); + WxError.newBuilder().setErrorMsg(message).build()); } finally { httpPost.releaseConnection(); } @@ -364,65 +372,67 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public boolean checkJSSDKCallbackDataSignature(Map kvm, - String signature) { + String signature) { return signature.equals(this.createSign(kvm, - this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + this.wxMpService.getWxMpConfigStorage().getPartnerKey())); } @Override @Deprecated public WxRedpackResult sendRedpack(Map parameters) - throws WxErrorException { + throws WxErrorException { SortedMap packageParams = new TreeMap<>(parameters); packageParams.put("wxappid", - this.wxMpService.getWxMpConfigStorage().getAppId()); + this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", - this.wxMpService.getWxMpConfigStorage().getPartnerId()); + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("nonce_str", System.currentTimeMillis() + ""); String sign = this.createSign(packageParams, - this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { request.append(String.format("<%s>%s", para.getKey(), - para.getValue(), para.getKey())); + para.getValue(), para.getKey())); } request.append(""); HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); + "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); if (this.httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { + .execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxRedpackResult.class); return (WxRedpackResult) xstream.fromXML(responseContent); } catch (IOException e) { String message = MessageFormatter - .format("Exception occured when sending redpack '{}'.", - request.toString()) - .getMessage(); + .format("Exception occured when sending redpack '{}'.", + request.toString()) + .getMessage(); this.log.error(message, e); - throw new WxErrorException(WxError.newBuilder().setErrorMsg(message).build()); + throw new WxErrorException( + WxError.newBuilder().setErrorMsg(message).build()); } finally { httpPost.releaseConnection(); } } @Override - public WxRedpackResult sendRedpack(WxSendRedpackRequest request) throws WxErrorException { + public WxRedpackResult sendRedpack(WxSendRedpackRequest request) + throws WxErrorException { XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxSendRedpackRequest.class); xstream.processAnnotations(WxRedpackResult.class); @@ -442,10 +452,13 @@ public class WxMpPayServiceImpl implements WxMpPayService { } String responseContent = this.wxMpService.post(url, xstream.toXML(request)); - WxRedpackResult redpackResult = (WxRedpackResult) xstream.fromXML(responseContent); - if("FAIL".equals(redpackResult.getResultCode())){ - throw new WxErrorException( - WxError.newBuilder().setErrorMsg(redpackResult.getErrCode() + ":" + redpackResult.getErrCodeDes()).build()); + WxRedpackResult redpackResult = (WxRedpackResult) xstream + .fromXML(responseContent); + if ("FAIL".equals(redpackResult.getResultCode())) { + throw new WxErrorException(WxError.newBuilder() + .setErrorMsg( + redpackResult.getErrCode() + ":" + redpackResult.getErrCodeDes()) + .build()); } return redpackResult; @@ -460,9 +473,10 @@ public class WxMpPayServiceImpl implements WxMpPayService { } try { - Field field = WxSendRedpackRequest.class.getDeclaredField(entry.getKey()); + Field field = bean.getClass().getDeclaredField(entry.getKey()); if (field.isAnnotationPresent(XStreamAlias.class)) { - result.put(field.getAnnotation(XStreamAlias.class).value(), reflect.get().toString()); + result.put(field.getAnnotation(XStreamAlias.class).value(), + reflect.get().toString()); } } catch (NoSuchFieldException | SecurityException e) { e.printStackTrace(); @@ -485,7 +499,8 @@ public class WxMpPayServiceImpl implements WxMpPayService { StringBuffer toSign = new StringBuffer(); for (String key : sortedMap.keySet()) { String value = packageParams.get(key); - if (null != value && !"".equals(value) && !"sign".equals(key) && !"key".equals(key)) { + if (null != value && !"".equals(value) && !"sign".equals(key) + && !"key".equals(key)) { toSign.append(key + "=" + value + "&"); } } @@ -495,4 +510,73 @@ public class WxMpPayServiceImpl implements WxMpPayService { return DigestUtils.md5Hex(toSign.toString()).toUpperCase(); } + @Override + public WxUnifiedOrderResult unifiedOrder(WxUnifiedOrderRequest request) + throws WxErrorException { + checkParameters(request); + + XStream xstream = XStreamInitializer.getInstance(); + xstream.processAnnotations(WxUnifiedOrderRequest.class); + xstream.processAnnotations(WxUnifiedOrderResult.class); + + request.setAppid(this.wxMpService.getWxMpConfigStorage().getAppId()); + request.setMchId(this.wxMpService.getWxMpConfigStorage().getPartnerId()); + request.setNonceStr(System.currentTimeMillis() + ""); + + String sign = this.createSign(xmlBean2Map(request), + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + request.setSign(sign); + + String url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; + + String responseContent = this.wxMpService.post(url, xstream.toXML(request)); + WxUnifiedOrderResult result = (WxUnifiedOrderResult) xstream + .fromXML(responseContent); + if ("FAIL".equals(result.getResultCode())) { + throw new WxErrorException(WxError.newBuilder() + .setErrorMsg(result.getErrCode() + ":" + result.getErrCodeDes()) + .build()); + } + + return result; + + } + + private void checkParameters(WxUnifiedOrderRequest request) { + + List nullFields = com.google.common.collect.Lists.newArrayList(); + for (Entry entry : Reflect.on(request).fields() + .entrySet()) { + Reflect reflect = entry.getValue(); + try { + Field field = request.getClass().getDeclaredField(entry.getKey()); + if (field.isAnnotationPresent(Required.class) + && reflect.get() == null) { + nullFields.add(entry.getKey()); + } + } catch (NoSuchFieldException | SecurityException e) { + e.printStackTrace(); + } + } + + if (!nullFields.isEmpty()) { + throw new IllegalArgumentException("必填字段[" + nullFields + "]必须提供值"); + } + + if (!TRADE_TYPES.contains(request.getTradeType())) { + throw new IllegalArgumentException( + "trade_type目前必须为" + TRADE_TYPES + "其中之一"); + + } + + if ("JSAPI".equals(request.getTradeType()) && request.getOpenid() == null) { + throw new IllegalArgumentException("当 trade_type是'JSAPI'时未指定openid"); + } + + if ("NATIVE".equals(request.getTradeType()) + && request.getProductId() == null) { + throw new IllegalArgumentException("当 trade_type是'NATIVE'时未指定product_id"); + } + } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java new file mode 100644 index 00000000..cff9d787 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java @@ -0,0 +1,124 @@ +package me.chanjar.weixin.mp.bean.pay; + +import java.io.Serializable; + +/** + *
+ * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
+ * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
+ * 
+ * + * @author chanjarster + */ +@Deprecated +public class WxMpPrepayIdResult implements Serializable { + private static final long serialVersionUID = -8970574397788396143L; + private String return_code; + private String return_msg; + private String appid; + private String mch_id; + private String nonce_str; + private String sign; + private String result_code; + private String prepay_id; + private String trade_type; + private String err_code; + private String err_code_des; + private String code_url; + + public String getReturn_code() { + return this.return_code; + } + + public void setReturn_code(String return_code) { + this.return_code = return_code; + } + + public String getReturn_msg() { + return this.return_msg; + } + + public void setReturn_msg(String return_msg) { + this.return_msg = return_msg; + } + + public String getAppid() { + return this.appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getMch_id() { + return this.mch_id; + } + + public void setMch_id(String mch_id) { + this.mch_id = mch_id; + } + + public String getNonce_str() { + return this.nonce_str; + } + + public void setNonce_str(String nonce_str) { + this.nonce_str = nonce_str; + } + + public String getSign() { + return this.sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getResult_code() { + return this.result_code; + } + + public void setResult_code(String result_code) { + this.result_code = result_code; + } + + public String getPrepay_id() { + return this.prepay_id; + } + + public void setPrepay_id(String prepay_id) { + this.prepay_id = prepay_id; + } + + public String getTrade_type() { + return this.trade_type; + } + + public void setTrade_type(String trade_type) { + this.trade_type = trade_type; + } + + public String getErr_code() { + return this.err_code; + } + + public void setErr_code(String err_code) { + this.err_code = err_code; + } + + public String getErr_code_des() { + return this.err_code_des; + } + + public void setErr_code_des(String err_code_des) { + this.err_code_des = err_code_des; + } + + public String getCode_url() { + return this.code_url; + } + + public void setCode_url(String code_url) { + this.code_url = code_url; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java index fa9ce561..297e07d7 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java @@ -19,32 +19,32 @@ public class WxRedpackResult implements Serializable { private static final long serialVersionUID = -4837415036337132073L; @XStreamAlias("return_code") - String returnCode; + private String returnCode; @XStreamAlias("return_msg") - String returnMsg; + private String returnMsg; @XStreamAlias("sign") - String sign; + private String sign; @XStreamAlias("result_code") - String resultCode; + private String resultCode; @XStreamAlias("err_code") - String errCode; + private String errCode; @XStreamAlias("err_code_des") - String errCodeDes; + private String errCodeDes; @XStreamAlias("mch_billno") - String mchBillno; + private String mchBillno; @XStreamAlias("mch_id") - String mchId; + private String mchId; @XStreamAlias("wxappid") - String wxappid; + private String wxappid; @XStreamAlias("re_openid") - String reOpenid; + private String reOpenid; @XStreamAlias("total_amount") - int totalAmount; + private int totalAmount; @XStreamAlias("send_time") - String sendTime; + private String sendTime; @XStreamAlias("send_listid") - String sendListid; + private String sendListid; public String getErrCode() { return this.errCode; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java index ccf84ae9..abe0d68f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java @@ -158,7 +158,7 @@ public class WxSendRedpackRequest { private String consumeMchId; public String getMchBillno() { - return mchBillno; + return this.mchBillno; } public void setMchBillno(String mchBillno) { @@ -166,7 +166,7 @@ public class WxSendRedpackRequest { } public String getSendName() { - return sendName; + return this.sendName; } public void setSendName(String sendName) { @@ -174,7 +174,7 @@ public class WxSendRedpackRequest { } public String getReOpenid() { - return reOpenid; + return this.reOpenid; } public void setReOpenid(String reOpenid) { @@ -182,7 +182,7 @@ public class WxSendRedpackRequest { } public Integer getTotalAmount() { - return totalAmount; + return this.totalAmount; } public void setTotalAmount(Integer totalAmount) { @@ -190,7 +190,7 @@ public class WxSendRedpackRequest { } public Integer getTotalNum() { - return totalNum; + return this.totalNum; } public void setTotalNum(Integer totalNum) { @@ -198,7 +198,7 @@ public class WxSendRedpackRequest { } public String getAmtType() { - return amtType; + return this.amtType; } public void setAmtType(String amtType) { @@ -206,7 +206,7 @@ public class WxSendRedpackRequest { } public String getWishing() { - return wishing; + return this.wishing; } public void setWishing(String wishing) { @@ -214,7 +214,7 @@ public class WxSendRedpackRequest { } public String getClientIp() { - return clientIp; + return this.clientIp; } public void setClientIp(String clientIp) { @@ -222,7 +222,7 @@ public class WxSendRedpackRequest { } public String getActName() { - return actName; + return this.actName; } public void setActName(String actName) { @@ -230,7 +230,7 @@ public class WxSendRedpackRequest { } public String getRemark() { - return remark; + return this.remark; } public void setRemark(String remark) { @@ -238,7 +238,7 @@ public class WxSendRedpackRequest { } public String getWxAppid() { - return wxAppid; + return this.wxAppid; } public void setWxAppid(String wxAppid) { @@ -246,7 +246,7 @@ public class WxSendRedpackRequest { } public String getMchId() { - return mchId; + return this.mchId; } public void setMchId(String mchId) { @@ -254,7 +254,7 @@ public class WxSendRedpackRequest { } public String getNonceStr() { - return nonceStr; + return this.nonceStr; } public void setNonceStr(String nonceStr) { @@ -262,7 +262,7 @@ public class WxSendRedpackRequest { } public String getSign() { - return sign; + return this.sign; } public void setSign(String sign) { @@ -270,7 +270,7 @@ public class WxSendRedpackRequest { } public String getSceneId() { - return sceneId; + return this.sceneId; } public void setSceneId(String sceneId) { @@ -278,7 +278,7 @@ public class WxSendRedpackRequest { } public String getRiskInfo() { - return riskInfo; + return this.riskInfo; } public void setRiskInfo(String riskInfo) { @@ -286,7 +286,7 @@ public class WxSendRedpackRequest { } public String getConsumeMchId() { - return consumeMchId; + return this.consumeMchId; } public void setConsumeMchId(String consumeMchId) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java index f1c77ff5..ccdfff90 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java @@ -1,197 +1,666 @@ package me.chanjar.weixin.mp.bean.pay; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + import com.thoughtworks.xstream.annotations.XStreamAlias; +import me.chanjar.weixin.common.annotation.Required; + /** - * 统一下单请求参数对象 - * Created by Binary Wang on 2016/9/25. + *
+ * 统一下单请求参数对象
+ * 参考文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
+ * 每个字段描述对应如下:
+ * 
  • 字段名 + *
  • 变量名 + *
  • 是否必填 + *
  • 类型 + *
  • 示例值 + *
  • 描述 + *
  • + * Created by Binary Wang on 2016/9/25. * @author binarywang (https://github.com/binarywang) */ @XStreamAlias("xml") public class WxUnifiedOrderRequest { + /** *
    -   * 公众账号ID 
    -   * appid 
    -   * 是 
    -   * String(32)  
    -   * wxd678efh567hg6787  
    +   * 公众账号ID
    +   * appid
    +   * 是
    +   * String(32)
    +   * wxd678efh567hg6787
        * 微信分配的公众账号ID(企业号corpid即为此appId)
        * 
    */ + @XStreamAlias("appid") + private String appid; + /** *
        * 商户号
    -   * mch_id  
    -   * 是 
    -   * String(32)  
    -   * 1230000109  
    +   * mch_id
    +   * 是
    +   * String(32)
    +   * 1230000109
        * 微信支付分配的商户号
        * 
    */ + @XStreamAlias("mch_id") + private String mchId; + /** - *
      
    -   * 设备号 
    -   * device_info 
    -   * 否 
    -   * String(32)  
    -   * 013467007045764 
    -   * 终端设备号(门店号或收银设备ID),注意:PC网页或公众号内支付请传"WEB"
    +   * 
    +   * 设备号
    +   * device_info
    +   * 否
    +   * String(32)
    +   * 013467007045764
    +   * 终端设备号(门店号或收银设备Id),注意:PC网页或公众号内支付请传"WEB"
        * 
    */ + @XStreamAlias("device_info") + private String deviceInfo; + /** - *
      
    -   * 随机字符串 
    -   * nonce_str 
    -   * 是 
    -   * String(32)  
    -   * 5K8264ILTKCH16CQ2502SI8ZNMTM67VS  
    +   * 
    +   * 随机字符串
    +   * nonce_str
    +   * 是
    +   * String(32)
    +   * 5K8264ILTKCH16CQ2502SI8ZNMTM67VS
        * 随机字符串,不长于32位。推荐随机数生成算法
        * 
    */ + @XStreamAlias("nonce_str") + private String nonceStr; + /** - *
      
    -   * 签名  
    -   * sign  
    +   * 
    +   * 签名
    +   * sign
        * 是
    -   *  String(32)  
    -   *  C380BEC2BFD727A4B6845133519F3AD6  
    -   *  签名,详见签名生成算法
    +   * String(32)
    +   * C380BEC2BFD727A4B6845133519F3AD6
    +   * 签名,详见签名生成算法
        * 
    */ + @XStreamAlias("sign") + private String sign; + /** - *
      
    -   * 商品描述  
    -   * body  
    +   * 
    +   * 商品描述
    +   * body
        * 是
    -   * String(128) 
    +   * String(128)
        * 腾讯充值中心-QQ会员充值
        * 商品简单描述,该字段须严格按照规范传递,具体请见参数规定
        * 
    */ + @Required + @XStreamAlias("body") + private String body; + /** - *
      
    -   * 商品详情  
    -   * detail  
    +   * 
    +   * 商品详情
    +   * detail
        * 否
    -   * String(6000) 
    +   * String(6000)
        *  {  "goods_detail":[
    -      {
    -      "goods_id":"iphone6s_16G",
    -      "wxpay_goods_id":"1001",
    -      "goods_name":"iPhone6s 16G",
    -      "goods_num":1,
    -      "price":528800,
    -      "goods_category":"123456",
    -      "body":"苹果手机"
    -      },
    -      {
    -      "goods_id":"iphone6s_32G",
    -      "wxpay_goods_id":"1002",
    -      "goods_name":"iPhone6s 32G",
    -      "quantity":1,
    -      "price":608800,
    -      "goods_category":"123789",
    -      "body":"苹果手机"
    -      }
    -      ]
    -      } 
    -              商品详细列表,使用Json格式,传输签名前请务必使用CDATA标签将JSON文本串保护起来。
    -        goods_detail []:
    -        └ goods_id String 必填 32 商品的编号
    -        └ wxpay_goods_id String 可选 32 微信支付定义的统一商品编号
    -        └ goods_name String 必填 256 商品名称
    -        └ goods_num Int 必填 商品数量
    -        └ price Int 必填 商品单价,单位为分
    -        └ goods_category String 可选 32 商品类目ID
    -        └ body String 可选 1000 商品描述信息
    -   * 
    - */ - /** - *
      
    -   * 附加数据  
    -   * attach  
    -   * 否 
    -   * String(127) 
    -   * 深圳分店 
    +    {
    +    "goods_id":"iphone6s_16G",
    +    "wxpay_goods_id":"1001",
    +    "goods_name":"iPhone6s 16G",
    +    "goods_num":1,
    +    "price":528800,
    +    "goods_category":"123456",
    +    "body":"苹果手机"
    +    },
    +    {
    +    "goods_id":"iphone6s_32G",
    +    "wxpay_goods_id":"1002",
    +    "goods_name":"iPhone6s 32G",
    +    "quantity":1,
    +    "price":608800,
    +    "goods_category":"123789",
    +    "body":"苹果手机"
    +    }
    +    ]
    +    }
    +            商品详细列表,使用Json格式,传输签名前请务必使用CDATA标签将JSON文本串保护起来。
    +      goods_detail []:
    +      └ goods_id String 必填 32 商品的编号
    +      └ wxpay_goods_id String 可选 32 微信支付定义的统一商品编号
    +      └ goods_name String 必填 256 商品名称
    +      └ goods_num Int 必填 商品数量
    +      └ price Int 必填 商品单价,单位为分
    +      └ goods_category String 可选 32 商品类目Id
    +      └ body String 可选 1000 商品描述信息
    +   * 
    + */ + @XStreamAlias("detail") + private String detail; + + /** + *
    +   * 附加数据
    +   * attach
    +   * 否
    +   * String(127)
    +   * 深圳分店
        *  附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
        * 
    */ + @XStreamAlias("attach") + private String attach; + /** - *
      
    +   * 
        * 商户订单号
    -   * out_trade_no   
    -   * 是 
    -   * String(32)  
    -   * 20150806125346  
    +   * out_trade_no
    +   * 是
    +   * String(32)
    +   * 20150806125346
        * 商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
        * 
    */ + @Required + @XStreamAlias("out_trade_no") + private String outTradeNo; + /** - *
      
    -   * 货币类型  
    -   * fee_type  
    -   * 否 
    -   * String(16)  
    -   * CNY 
    +   * 
    +   * 货币类型
    +   * fee_type
    +   * 否
    +   * String(16)
    +   * CNY
        * 符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
        * 
    */ + @XStreamAlias("fee_type") + private String feeType; + /** - *
      
    -   * 总金额 
    -   * total_fee 
    -   * 是 
    -   * Int 
    -   * 888 
    +   * 
    +   * 总金额
    +   * total_fee
    +   * 是
    +   * Int
    +   * 888
        * 订单总金额,单位为分,详见支付金额
        * 
    */ + @Required + @XStreamAlias("total_fee") + private Integer totalFee; + /** - *
      
    -   * 终端IP  
    -   * spbill_create_ip 
    -   * 是 
    -   * String(16)  
    -   * 123.12.12.123 
    +   * 
    +   * 终端IP
    +   * spbill_create_ip
    +   * 是
    +   * String(16)
    +   * 123.12.12.123
        * APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
        * 
    */ + @Required + @XStreamAlias("spbill_create_ip") + private String spbillCreateIp; + /** - *
      交易起始时间  time_start  否 String(14)  20091225091010  订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
    +   * 
    +   * 交易起始时间
    +   * time_start
    +   * 否
    +   * String(14)
    +   * 20091225091010
    +   * 订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
        * 
    */ + @XStreamAlias("time_start") + private String timeStart; + /** - *
      交易结束时间  time_expire 否 String(14)  20091227091010 
    -   * 
    - */ - /** - *
      订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则
    +   * 
    +   * 交易结束时间
    +   * time_expire
    +   * 否
    +   * String(14)
    +   * 20091227091010
    +   * 订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则
        *   注意:最短失效时间间隔必须大于5分钟
        * 
    */ + @XStreamAlias("time_expire") + private String timeExpire; + /** - *
      商品标记  goods_tag 否 String(32)  WXG 商品标记,代金券或立减优惠功能的参数,说明详见代金券或立减优惠
    +   * 
    +   * 商品标记
    +   * goods_tag
    +   * 否
    +   * String(32)
    +   * WXG
    +   * 商品标记,代金券或立减优惠功能的参数,说明详见代金券或立减优惠
        * 
    */ + @XStreamAlias("goods_tag") + private String goodsTag; + /** - *
      通知地址  notify_url  是 String(256) http://www.weixin.qq.com/wxpay/pay.php  接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
    +   * 
    +   * 通知地址
    +   * notify_url
    +   * 是
    +   * String(256)
    +   * http://www.weixin.qq.com/wxpay/pay.php
    +   * 接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
        * 
    */ + @Required + @XStreamAlias("notify_url") + private String notifyURL; + /** - *
      交易类型  trade_type  是 String(16)  JSAPI 取值如下:JSAPI,NATIVE,APP,详细说明见参数规定
    +   * 
    +   * 交易类型
    +   * trade_type
    +   * 是
    +   * String(16)
    +   * JSAPI
    +   * 取值如下:JSAPI,NATIVE,APP,详细说明见参数规定:
    +   * JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里
        * 
    */ + @Required + @XStreamAlias("trade_type") + private String tradeType; + /** - *
      商品ID  product_id  否 String(32)  12235413214070356458058 trade_type=NATIVE,此参数必传。此id为二维码中包含的商品ID,商户自行定义。
    +   * 
    +   * 商品Id
    +   * product_id
    +   * 否
    +   * String(32)
    +   * 12235413214070356458058
    +   * trade_type=NATIVE,此参数必传。此id为二维码中包含的商品Id,商户自行定义。
        * 
    */ + @XStreamAlias("product_id") + private String productId; + /** - *
      指定支付方式  limit_pay 否 String(32)  no_credit no_credit--指定不能使用信用卡支付
    +   * 
    +   * 指定支付方式
    +   * limit_pay
    +   * 否
    +   * String(32)
    +   * no_credit no_credit--指定不能使用信用卡支付
        * 
    */ + @XStreamAlias("limit_pay") + private String limitPay; + /** - *
      用户标识  openid  否 String(128) oUpF8uMuAJO_M2pxb1Q9zNjWeS6o  trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。openid如何获取,可参考【获取openid】。企业号请使用【企业号OAuth2.0接口】获取企业号内成员userid,再调用【企业号userid转openid接口】进行转换
    +   * 
    +   * 用户标识
    +   * openid
    +   * 否
    +   * String(128)
    +   * oUpF8uMuAJO_M2pxb1Q9zNjWeS6o
    +   * trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。
    +   * openid如何获取,可参考【获取openid】。
    +   * 企业号请使用【企业号OAuth2.0接口】获取企业号内成员userid,再调用【企业号userid转openid接口】进行转换
        * 
    */ + @XStreamAlias("openid") + private String openid; + + public String getAppid() { + return this.appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getMchId() { + return this.mchId; + } + + public void setMchId(String mchId) { + this.mchId = mchId; + } + + public String getDeviceInfo() { + return this.deviceInfo; + } + + public void setDeviceInfo(String deviceInfo) { + this.deviceInfo = deviceInfo; + } + + public String getNonceStr() { + return this.nonceStr; + } + + public void setNonceStr(String nonceStr) { + this.nonceStr = nonceStr; + } + + public String getSign() { + return this.sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getBody() { + return this.body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getDetail() { + return this.detail; + } + + public void setDetail(String detail) { + this.detail = detail; + } + + public String getAttach() { + return this.attach; + } + + public void setAttach(String attach) { + this.attach = attach; + } + + public String getOutTradeNo() { + return this.outTradeNo; + } + + public void setOutTradeNo(String outTradeNo) { + this.outTradeNo = outTradeNo; + } + + public String getFeeType() { + return this.feeType; + } + + public void setFeeType(String feeType) { + this.feeType = feeType; + } + + public Integer getTotalFee() { + return this.totalFee; + } + + public void setTotalFee(Integer totalFee) { + this.totalFee = totalFee; + } + + public String getSpbillCreateIp() { + return this.spbillCreateIp; + } + + public void setSpbillCreateIp(String spbillCreateIp) { + this.spbillCreateIp = spbillCreateIp; + } + + public String getTimeStart() { + return this.timeStart; + } + + public void setTimeStart(String timeStart) { + this.timeStart = timeStart; + } + + public String getTimeExpire() { + return this.timeExpire; + } + + public void setTimeExpire(String timeExpire) { + this.timeExpire = timeExpire; + } + + public String getGoodsTag() { + return this.goodsTag; + } + + public void setGoodsTag(String goodsTag) { + this.goodsTag = goodsTag; + } + + public String getNotifyURL() { + return this.notifyURL; + } + + public void setNotifyURL(String notifyURL) { + this.notifyURL = notifyURL; + } + + public String getTradeType() { + return this.tradeType; + } + + public void setTradeType(String tradeType) { + this.tradeType = tradeType; + } + + public String getProductId() { + return this.productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getLimitPay() { + return this.limitPay; + } + + public void setLimitPay(String limitPay) { + this.limitPay = limitPay; + } + + public String getOpenid() { + return this.openid; + } + + public void setOpenid(String openid) { + this.openid = openid; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } + + public static WxUnifiedOrderRequestBuilder builder() { + return new WxUnifiedOrderRequestBuilder(); + } + + public static class WxUnifiedOrderRequestBuilder { + private String appid; + private String mchId; + private String deviceInfo; + private String nonceStr; + private String sign; + private String body; + private String detail; + private String attach; + private String outTradeNo; + private String feeType; + private Integer totalFee; + private String spbillCreateIp; + private String timeStart; + private String timeExpire; + private String goodsTag; + private String notifyURL; + private String tradeType; + private String productId; + private String limitPay; + private String openid; + + public WxUnifiedOrderRequestBuilder appid(String appid) { + this.appid = appid; + return this; + } + + public WxUnifiedOrderRequestBuilder mchId(String mchId) { + this.mchId = mchId; + return this; + } + + public WxUnifiedOrderRequestBuilder deviceInfo(String deviceInfo) { + this.deviceInfo = deviceInfo; + return this; + } + + public WxUnifiedOrderRequestBuilder nonceStr(String nonceStr) { + this.nonceStr = nonceStr; + return this; + } + + public WxUnifiedOrderRequestBuilder sign(String sign) { + this.sign = sign; + return this; + } + + public WxUnifiedOrderRequestBuilder body(String body) { + this.body = body; + return this; + } + + public WxUnifiedOrderRequestBuilder detail(String detail) { + this.detail = detail; + return this; + } + + public WxUnifiedOrderRequestBuilder attach(String attach) { + this.attach = attach; + return this; + } + + public WxUnifiedOrderRequestBuilder outTradeNo(String outTradeNo) { + this.outTradeNo = outTradeNo; + return this; + } + + public WxUnifiedOrderRequestBuilder feeType(String feeType) { + this.feeType = feeType; + return this; + } + + public WxUnifiedOrderRequestBuilder totalFee(Integer totalFee) { + this.totalFee = totalFee; + return this; + } + + public WxUnifiedOrderRequestBuilder spbillCreateIp(String spbillCreateIp) { + this.spbillCreateIp = spbillCreateIp; + return this; + } + + public WxUnifiedOrderRequestBuilder timeStart(String timeStart) { + this.timeStart = timeStart; + return this; + } + + public WxUnifiedOrderRequestBuilder timeExpire(String timeExpire) { + this.timeExpire = timeExpire; + return this; + } + + public WxUnifiedOrderRequestBuilder goodsTag(String goodsTag) { + this.goodsTag = goodsTag; + return this; + } + + public WxUnifiedOrderRequestBuilder notifyURL(String notifyURL) { + this.notifyURL = notifyURL; + return this; + } + + public WxUnifiedOrderRequestBuilder tradeType(String tradeType) { + this.tradeType = tradeType; + return this; + } + + public WxUnifiedOrderRequestBuilder productId(String productId) { + this.productId = productId; + return this; + } + + public WxUnifiedOrderRequestBuilder limitPay(String limitPay) { + this.limitPay = limitPay; + return this; + } + + public WxUnifiedOrderRequestBuilder openid(String openid) { + this.openid = openid; + return this; + } + + public WxUnifiedOrderRequestBuilder from(WxUnifiedOrderRequest origin) { + this.appid(origin.appid); + this.mchId(origin.mchId); + this.deviceInfo(origin.deviceInfo); + this.nonceStr(origin.nonceStr); + this.sign(origin.sign); + this.body(origin.body); + this.detail(origin.detail); + this.attach(origin.attach); + this.outTradeNo(origin.outTradeNo); + this.feeType(origin.feeType); + this.totalFee(origin.totalFee); + this.spbillCreateIp(origin.spbillCreateIp); + this.timeStart(origin.timeStart); + this.timeExpire(origin.timeExpire); + this.goodsTag(origin.goodsTag); + this.notifyURL(origin.notifyURL); + this.tradeType(origin.tradeType); + this.productId(origin.productId); + this.limitPay(origin.limitPay); + this.openid(origin.openid); + return this; + } + + public WxUnifiedOrderRequest build() { + WxUnifiedOrderRequest m = new WxUnifiedOrderRequest(); + m.appid = this.appid; + m.mchId = this.mchId; + m.deviceInfo = this.deviceInfo; + m.nonceStr = this.nonceStr; + m.sign = this.sign; + m.body = this.body; + m.detail = this.detail; + m.attach = this.attach; + m.outTradeNo = this.outTradeNo; + m.feeType = this.feeType; + m.totalFee = this.totalFee; + m.spbillCreateIp = this.spbillCreateIp; + m.timeStart = this.timeStart; + m.timeExpire = this.timeExpire; + m.goodsTag = this.goodsTag; + m.notifyURL = this.notifyURL; + m.tradeType = this.tradeType; + m.productId = this.productId; + m.limitPay = this.limitPay; + m.openid = this.openid; + return m; + } + } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java new file mode 100644 index 00000000..18817461 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java @@ -0,0 +1,155 @@ +package me.chanjar.weixin.mp.bean.pay; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +/** + *
    + * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
    + * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
    + * 
    + * + * @author chanjarster + */ +@XStreamAlias("xml") +public class WxUnifiedOrderResult { + + @XStreamAlias("return_code") + private String returnCode; + + @XStreamAlias("return_msg") + private String returnMsg; + + @XStreamAlias("appid") + private String appid; + + @XStreamAlias("mch_id") + private String mchId; + + @XStreamAlias("nonce_str") + private String nonceStr; + + @XStreamAlias("sign") + private String sign; + + @XStreamAlias("result_code") + private String resultCode; + + @XStreamAlias("prepay_id") + private String prepayId; + + @XStreamAlias("trade_type") + private String tradeType; + + @XStreamAlias("err_code") + private String errCode; + + @XStreamAlias("err_code_des") + private String errCodeDes; + + @XStreamAlias("code_url") + private String codeURL; + + public String getReturnCode() { + return this.returnCode; + } + + public void setReturnCode(String returnCode) { + this.returnCode = returnCode; + } + + public String getReturnMsg() { + return this.returnMsg; + } + + public void setReturnMsg(String returnMsg) { + this.returnMsg = returnMsg; + } + + public String getAppid() { + return this.appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getMchId() { + return this.mchId; + } + + public void setMchId(String mchId) { + this.mchId = mchId; + } + + public String getNonceStr() { + return this.nonceStr; + } + + public void setNonceStr(String nonceStr) { + this.nonceStr = nonceStr; + } + + public String getSign() { + return this.sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public String getResultCode() { + return this.resultCode; + } + + public void setResultCode(String resultCode) { + this.resultCode = resultCode; + } + + public String getPrepayId() { + return this.prepayId; + } + + public void setPrepayId(String prepayId) { + this.prepayId = prepayId; + } + + public String getTradeType() { + return this.tradeType; + } + + public void setTradeType(String tradeType) { + this.tradeType = tradeType; + } + + public String getErrCode() { + return this.errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrCodeDes() { + return this.errCodeDes; + } + + public void setErrCodeDes(String errCodeDes) { + this.errCodeDes = errCodeDes; + } + + public String getCodeURL() { + return this.codeURL; + } + + public void setCodeURL(String codeURL) { + this.codeURL = codeURL; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java deleted file mode 100644 index e930fc13..00000000 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java +++ /dev/null @@ -1,128 +0,0 @@ -package me.chanjar.weixin.mp.bean.result; - -import java.io.Serializable; - -/** - *
    - * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
    - *
    - * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
    - *
    - * 
    - * - * @author chanjarster - */ -public class WxMpPrepayIdResult implements Serializable { - /** - * - */ - private static final long serialVersionUID = -8970574397788396143L; - private String return_code; - private String return_msg; - private String appid; - private String mch_id; - private String nonce_str; - private String sign; - private String result_code; - private String prepay_id; - private String trade_type; - private String err_code; - private String err_code_des; - private String code_url; - - public String getReturn_code() { - return this.return_code; - } - - public void setReturn_code(String return_code) { - this.return_code = return_code; - } - - public String getReturn_msg() { - return this.return_msg; - } - - public void setReturn_msg(String return_msg) { - this.return_msg = return_msg; - } - - public String getAppid() { - return this.appid; - } - - public void setAppid(String appid) { - this.appid = appid; - } - - public String getMch_id() { - return this.mch_id; - } - - public void setMch_id(String mch_id) { - this.mch_id = mch_id; - } - - public String getNonce_str() { - return this.nonce_str; - } - - public void setNonce_str(String nonce_str) { - this.nonce_str = nonce_str; - } - - public String getSign() { - return this.sign; - } - - public void setSign(String sign) { - this.sign = sign; - } - - public String getResult_code() { - return this.result_code; - } - - public void setResult_code(String result_code) { - this.result_code = result_code; - } - - public String getPrepay_id() { - return this.prepay_id; - } - - public void setPrepay_id(String prepay_id) { - this.prepay_id = prepay_id; - } - - public String getTrade_type() { - return this.trade_type; - } - - public void setTrade_type(String trade_type) { - this.trade_type = trade_type; - } - - public String getErr_code() { - return this.err_code; - } - - public void setErr_code(String err_code) { - this.err_code = err_code; - } - - public String getErr_code_des() { - return this.err_code_des; - } - - public void setErr_code_des(String err_code_des) { - this.err_code_des = err_code_des; - } - - public String getCode_url() { - return this.code_url; - } - - public void setCode_url(String code_url) { - this.code_url = code_url; - } -} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java index b17d1206..f6e990af 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java @@ -5,9 +5,12 @@ import org.testng.annotations.Test; import com.google.inject.Inject; +import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.ApiTestModule; import me.chanjar.weixin.mp.bean.pay.WxRedpackResult; import me.chanjar.weixin.mp.bean.pay.WxSendRedpackRequest; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest; +import me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderResult; /** * 测试支付相关接口 @@ -26,11 +29,6 @@ public class WxMpPayServiceImplTest { } - @Test - public void testGetPrepayId1() throws Exception { - - } - @Test public void testGetJsapiPayInfo() throws Exception { @@ -78,4 +76,16 @@ public class WxMpPayServiceImplTest { System.err.println(redpackResult); } + /** + * Test method for {@link me.chanjar.weixin.mp.api.impl.WxMpPayServiceImpl#unifiedOrder(me.chanjar.weixin.mp.bean.pay.WxUnifiedOrderRequest)}. + * @throws WxErrorException + */ + @Test + public void testUnifiedOrder() throws WxErrorException { + WxUnifiedOrderResult result = this.wxService.getPayService() + .unifiedOrder(WxUnifiedOrderRequest.builder().body("1111111") + .totalFee(1).spbillCreateIp("111111").notifyURL("111111") + .tradeType("JSAPI1").openid("122").outTradeNo("111111").build()); + System.err.println(result); + } } \ No newline at end of file From c538f6912db373fbeafffa5e2e5ca49d637e2c32 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Mon, 26 Sep 2016 18:43:30 +0800 Subject: [PATCH 20/21] Update README.md --- README.md | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index f061f5b0..4c090930 100644 --- a/README.md +++ b/README.md @@ -20,16 +20,16 @@ =========== ## 版本说明 -* 本项目定为每月发布一次正式版,版本号格式为X.X.0(如2.0.0,2.1.0等),月初或月底发布新版本,遇到重大问题需修复会及时提交新版本,欢迎大家随时提交Pull Request。 -* BUG修复和新特性一般会先发布成小版本作为临时版本(如2.0.1,2.0.2等,即尾号不为0,以区别于正式版)。 -* 目前最新版本号为 ![Maven Central](https://img.shields.io/maven-central/v/com.github.binarywang/weixin-java-parent.svg) ,也可以通过访问如下地址查看所有最新的版本: -- [【公众号】](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.github.binarywang%22%20AND%20a%3A%22weixin-java-mp%22) -- [【企业号】](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.github.binarywang%22%20AND%20a%3A%22weixin-java-cp%22) - +* 本项目定为每月发布一次正式版,版本号格式为X.X.0(如2.0.0,2.1.0等),月初或月底发布新版本,遇到重大问题需修复会及时提交新版本,欢迎大家随时提交Pull Request; +* BUG修复和新特性一般会先发布成小版本作为临时版本(如2.0.1,2.0.2等,即尾号不为0,以区别于正式版); +* 目前最新版本号为 ![Maven Central](https://img.shields.io/maven-central/v/com.github.binarywang/weixin-java-parent.svg) ,也可以通过访问链接[【公众号】](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.github.binarywang%22%20AND%20a%3A%22weixin-java-mp%22) [【企业号】](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.github.binarywang%22%20AND%20a%3A%22weixin-java-cp%22) +分别查看所有最新的版本。 ## Maven & Gradle * 公众号(订阅号、服务号): + +maven: ```xml com.github.binarywang @@ -37,12 +37,14 @@ 2.1.0 ``` - +gradle: ```groovy compile 'com.github.binarywang:weixin-java-mp:2.1.0' ``` * 企业号: + +maven: ```xml com.github.binarywang @@ -50,7 +52,7 @@ compile 'com.github.binarywang:weixin-java-mp:2.1.0' 2.1.0 ``` - +gradle: ```groovy compile 'com.github.binarywang:weixin-java-cp:2.1.0' ``` @@ -63,16 +65,14 @@ compile 'com.github.binarywang:weixin-java-cp:2.1.0' * https://git.coding.net/binarywang/weixin-java-tools.git -## 目前可参考的Demo项目: -* https://github.com/wechat-group/weixin-java-tools-springmvc -* https://github.com/wechat-group/weixin-mp-demo -* ===========以下为备份仓库,会保持跟主仓库同步 -* http://git.oschina.net/binary/weixin-mp-demo -* https://bitbucket.org/binarywang/weixin-mp-demo +## 目前可参考的Demo项目有两个: +1. https://github.com/wechat-group/weixin-mp-demo +1. https://github.com/wechat-group/weixin-java-tools-springmvc ## 关于代码贡献 +* 非常欢迎和感谢对本项目发起Pull Request的同学,本项目代码风格为使用2个空格代表一个Tab,因此在提交代码时请注意一下,否则很容易在IDE格式化代码后与原代码产生大量diff,这样会给其他人阅读代码带来极大的困扰。 +* 为了便于设置,本项目引入editorconfig插件,请使用eclipse的同学在贡献代码前安装相关插件,IntelliJ IDEA则自带支持,无需额外安装插件。 +* 本项目可以采用两种方式接受代码贡献: -* 非常欢迎和感谢对本项目发起Pull Request的同学,本项目可以采用两种方式接受代码贡献: -* 第一种就是基于[Git Flow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow)开发流程,因此在发起Pull Request的时候请选择develop分支。 -* 另外一种贡献代码的方式就是加入SDK Developers开发组,如果对自己的代码足够自信,可以随时提交代码,注意要随时进行单元测试,保证提交代码没有明显问题,具体加入方式,请咨询管理员。 -* 本项目代码风格为使用2个空格代表一个Tab,因此在提交代码时请注意一下,否则很容易在IDE格式化代码后与原代码产生大量diff,这样会给其他人阅读代码带来极大的困扰。 +1. 第一种就是基于[Git Flow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow)开发流程,因此在发起Pull Request的时候请选择develop分支。 +1. 另外一种贡献代码的方式就是加入SDK Developers开发组,如果对自己的代码足够自信,可以随时提交代码,注意要随时进行单元测试,保证提交代码没有明显问题,具体加入方式,请咨询管理员。 From dae8e40dc0c4b4eb0b089569e93b84a03ea5a3e3 Mon Sep 17 00:00:00 2001 From: BinaryWang Date: Mon, 26 Sep 2016 18:56:35 +0800 Subject: [PATCH 21/21] =?UTF-8?q?=E9=87=8D=E6=9E=84=E5=B7=B2=E6=9C=89?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chanjar/weixin/mp/api/WxMpPayService.java | 13 +- .../mp/api/impl/WxMpPayServiceImpl.java | 170 +++++------------- 2 files changed, 51 insertions(+), 132 deletions(-) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java index dae03f43..3a4128fe 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java @@ -30,20 +30,25 @@ public interface WxMpPayService { * @param tradeType 交易类型 JSAPI,NATIVE,APP,WAP * @param ip 发起支付的客户端IP * @param notifyUrl 通知地址 + * @throws WxErrorException * @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPrepayId(Map) instead */ @Deprecated - WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String notifyUrl); + WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, + String body, String tradeType, String ip, String notifyUrl) + throws WxErrorException; /** * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1) * 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识" * * @param parameters All required/optional parameters for weixin payment + * @throws WxErrorException * @deprecated use me.chanjar.weixin.mp.api.WxMpPayService.unifiedOrder(WxUnifiedOrderRequest) instead */ @Deprecated - WxMpPrepayIdResult getPrepayId(Map parameters); + WxMpPrepayIdResult getPrepayId(Map parameters) + throws WxErrorException; /** * 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1) @@ -98,9 +103,11 @@ public interface WxMpPayService { /** * 该接口提供所有微信支付订单的查询,当支付通知处理异常戒丢失的情冴,商户可以通过该接口查询订单支付状态。 * 详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2 + * @throws WxErrorException * */ - WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo); + WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) + throws WxErrorException; /** * 读取支付结果通知 diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index e3e628c7..b8ec8acb 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -1,6 +1,5 @@ package me.chanjar.weixin.mp.api.impl; -import java.io.IOException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; @@ -10,16 +9,9 @@ import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.codec.digest.DigestUtils; -import org.apache.http.Consts; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; import org.joor.Reflect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.slf4j.helpers.MessageFormatter; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -29,9 +21,9 @@ import com.thoughtworks.xstream.annotations.XStreamAlias; import me.chanjar.weixin.common.annotation.Required; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.Utf8ResponseHandler; import me.chanjar.weixin.common.util.xml.XStreamInitializer; import me.chanjar.weixin.mp.api.WxMpPayService; +import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.pay.WxMpPayCallback; import me.chanjar.weixin.mp.bean.pay.WxMpPayRefundResult; import me.chanjar.weixin.mp.bean.pay.WxMpPayResult; @@ -54,19 +46,17 @@ public class WxMpPayServiceImpl implements WxMpPayService { private final String[] REQUIRED_ORDER_PARAMETERS = new String[] { "appid", "mch_id", "body", "out_trade_no", "total_fee", "spbill_create_ip", "notify_url", "trade_type" }; - private HttpHost httpProxy; - private WxMpServiceImpl wxMpService; + private WxMpService wxMpService; - public WxMpPayServiceImpl(WxMpServiceImpl wxMpService) { + public WxMpPayServiceImpl(WxMpService wxMpService) { this.wxMpService = wxMpService; - this.httpProxy = wxMpService.getHttpProxy(); } @Override @Deprecated public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, - String callbackUrl) { + String callbackUrl) throws WxErrorException { Map packageParams = new HashMap<>(); packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); @@ -85,7 +75,8 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override @Deprecated - public WxMpPrepayIdResult getPrepayId(final Map parameters) { + public WxMpPrepayIdResult getPrepayId(final Map parameters) + throws WxErrorException { final SortedMap packageParams = new TreeMap<>(parameters); packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); @@ -106,29 +97,11 @@ public class WxMpPayServiceImpl implements WxMpPayService { request.append(""); - HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/pay/unifiedorder"); - if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); - httpPost.setConfig(config); - } - - StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); - httpPost.setEntity(entity); - try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); - XStream xstream = XStreamInitializer.getInstance(); - xstream.alias("xml", WxMpPrepayIdResult.class); - return (WxMpPrepayIdResult) xstream.fromXML(responseContent); - } catch (IOException e) { - throw new RuntimeException("Failed to get prepay id due to IO exception.", - e); - } finally { - httpPost.releaseConnection(); - } + String url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; + String responseContent = this.wxMpService.post(url, request.toString()); + XStream xstream = XStreamInitializer.getInstance(); + xstream.alias("xml", WxMpPrepayIdResult.class); + return (WxMpPrepayIdResult) xstream.fromXML(responseContent); } private void checkParameters(Map parameters) { @@ -238,7 +211,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { @Override public WxMpPayResult getJSSDKPayResult(String transactionId, - String outTradeNo) { + String outTradeNo) throws WxErrorException { String nonce_str = System.currentTimeMillis() + ""; SortedMap packageParams = new TreeMap<>(); @@ -267,27 +240,11 @@ public class WxMpPayServiceImpl implements WxMpPayService { } request.append(""); - HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/pay/orderquery"); - if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); - httpPost.setConfig(config); - } - - StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); - httpPost.setEntity(entity); - try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); - XStream xstream = XStreamInitializer.getInstance(); - xstream.alias("xml", WxMpPayResult.class); - return (WxMpPayResult) xstream.fromXML(responseContent); - } catch (IOException e) { - throw new RuntimeException("Failed to query order due to IO exception.", - e); - } + String url = "https://api.mch.weixin.qq.com/pay/orderquery"; + String responseContent = this.wxMpService.post(url, request.toString()); + XStream xstream = XStreamInitializer.getInstance(); + xstream.alias("xml", WxMpPayResult.class); + return (WxMpPayResult) xstream.fromXML(responseContent); } @Override @@ -325,49 +282,26 @@ public class WxMpPayServiceImpl implements WxMpPayService { } request.append(""); - HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/secapi/pay/refund"); - if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); - httpPost.setConfig(config); - } - - StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); - httpPost.setEntity(entity); - try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); - XStream xstream = XStreamInitializer.getInstance(); - xstream.processAnnotations(WxMpPayRefundResult.class); - WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream - .fromXML(responseContent); - - if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) - || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { - WxError error = new WxError(); - error.setErrorCode(-1); - error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() - + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() - + ";result_code:" + wxMpPayRefundResult.getResultCode() - + ";err_code" + wxMpPayRefundResult.getErrCode() + ";err_code_des" - + wxMpPayRefundResult.getErrCodeDes()); - throw new WxErrorException(error); - } + String url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; + String responseContent = this.wxMpService.post(url, request.toString()); + XStream xstream = XStreamInitializer.getInstance(); + xstream.processAnnotations(WxMpPayRefundResult.class); + WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream + .fromXML(responseContent); - return wxMpPayRefundResult; - } catch (IOException e) { - String message = MessageFormatter - .format("Exception happened when sending refund '{}'.", - request.toString()) - .getMessage(); - this.log.error(message, e); - throw new WxErrorException( - WxError.newBuilder().setErrorMsg(message).build()); - } finally { - httpPost.releaseConnection(); + if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) + || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { + WxError error = new WxError(); + error.setErrorCode(-1); + error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() + + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() + + ";result_code:" + wxMpPayRefundResult.getResultCode() + ";err_code" + + wxMpPayRefundResult.getErrCode() + ";err_code_des" + + wxMpPayRefundResult.getErrCodeDes()); + throw new WxErrorException(error); } + + return wxMpPayRefundResult; } @Override @@ -400,34 +334,12 @@ public class WxMpPayServiceImpl implements WxMpPayService { request.append(""); - HttpPost httpPost = new HttpPost( - "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); - if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) - .build(); - httpPost.setConfig(config); - } + String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; - StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); - httpPost.setEntity(entity); - try (CloseableHttpResponse response = this.wxMpService.getHttpclient() - .execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE - .handleResponse(response); - XStream xstream = XStreamInitializer.getInstance(); - xstream.processAnnotations(WxRedpackResult.class); - return (WxRedpackResult) xstream.fromXML(responseContent); - } catch (IOException e) { - String message = MessageFormatter - .format("Exception occured when sending redpack '{}'.", - request.toString()) - .getMessage(); - this.log.error(message, e); - throw new WxErrorException( - WxError.newBuilder().setErrorMsg(message).build()); - } finally { - httpPost.releaseConnection(); - } + String responseContent = this.wxMpService.post(url, request.toString()); + XStream xstream = XStreamInitializer.getInstance(); + xstream.processAnnotations(WxRedpackResult.class); + return (WxRedpackResult) xstream.fromXML(responseContent); } @Override @@ -544,7 +456,7 @@ public class WxMpPayServiceImpl implements WxMpPayService { private void checkParameters(WxUnifiedOrderRequest request) { - List nullFields = com.google.common.collect.Lists.newArrayList(); + List nullFields = Lists.newArrayList(); for (Entry entry : Reflect.on(request).fields() .entrySet()) { Reflect reflect = entry.getValue();