Procházet zdrojové kódy

Merge pull request #3 from wechat-group/develop

合并代码
master
Jonk před 8 roky
committed by GitHub
rodič
revize
a5779a7493
58 změnil soubory, kde provedl 3273 přidání a 941 odebrání
  1. +30
    -31
      README.md
  2. +4
    -2
      build.gradle
  3. +20
    -0
      pom.xml
  4. binární
      res/github_id.png
  5. +19
    -0
      weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java
  6. +1
    -0
      weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java
  7. +0
    -34
      weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java
  8. +25
    -24
      weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java
  9. +0
    -2
      weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java
  10. +15
    -3
      weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java
  11. +7
    -2
      weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java
  12. +2
    -2
      weixin-java-mp/pom.xml
  13. +2
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java
  14. +26
    -75
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java
  15. +18
    -11
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java
  16. +51
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java
  17. +44
    -2
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java
  18. +11
    -45
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImpl.java
  19. +4
    -1
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java
  20. +16
    -15
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java
  21. +244
    -313
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java
  22. +30
    -17
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java
  23. +107
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java
  24. +87
    -6
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java
  25. +42
    -18
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java
  26. +1
    -3
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java
  27. +60
    -6
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java
  28. +32
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java
  29. +1
    -1
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayCallback.java
  30. +1
    -1
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayRefundResult.java
  31. +33
    -31
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayResult.java
  32. +124
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java
  33. +18
    -31
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java
  34. +296
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java
  35. +666
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java
  36. +155
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java
  37. +0
    -128
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java
  38. +560
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java
  39. +29
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java
  40. +84
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java
  41. +92
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java
  42. +15
    -10
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java
  43. +6
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java
  44. +4
    -46
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/ApiTestModule.java
  45. +2
    -2
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMassMessageAPITest.java
  46. +57
    -0
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxXmlMpInMemoryConfigStorage.java
  47. +3
    -2
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImplTest.java
  48. +3
    -3
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImplTest.java
  49. +38
    -51
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImplTest.java
  50. +37
    -5
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java
  51. +19
    -4
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImplTest.java
  52. +60
    -0
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImplTest.java
  53. +4
    -3
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserBlacklistServiceImplTest.java
  54. +3
    -2
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java
  55. +30
    -8
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImplTest.java
  56. +1
    -1
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java
  57. +33
    -0
      weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java
  58. +1
    -0
      weixin-java-mp/src/test/resources/test-config.sample.xml

+ 30
- 31
README.md Zobrazit soubor

@@ -1,35 +1,34 @@
# Weixin Java Tools 微信公众号/企业号开发Java SDK
## [![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://github.com/ellerbrock/open-source-badge/) ![Maven Central](https://img.shields.io/maven-central/v/com.github.binarywang/weixin-java-parent.svg) [![Build Status](https://travis-ci.org/binarywang/weixin-java-tools.svg?branch=develop)](https://travis-ci.org/binarywang/weixin-java-tools)
## [![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://github.com/ellerbrock/open-source-badge/) ![Maven Central](https://img.shields.io/maven-central/v/com.github.binarywang/weixin-java-parent.svg) [![Build Status](https://travis-ci.org/wechat-group/weixin-java-tools.svg?branch=develop)](https://travis-ci.org/wechat-group/weixin-java-tools)


### 声明:本项目Fork自chanjarster/weixin-java-tools,但由于原项目已停止维护,故单独维护和发布,且发布到maven上的groupId也会不同,详细信息见下文。
### 注意:
1. ***本项目Fork自chanjarster/weixin-java-tools,但由于原项目已停止维护,故单独维护和发布,且发布到maven上的groupId也会不同,详细信息见下文。***
1. ***自2.0.0版本以来,主要是公众号的接口调整比较大,主要是为了解决主接口类过于庞大不方便管理的问题,将接口实现代码按模块进行拆分。***
1. 最新更新:2016-08-31 发布2.1.0正式版!

### 最新更新:2.1.0版发布!!! on 2016-08-31
===========

#### ***自2.0.0版本以来,接口调整比较大,主要是公众号的调整,企业号无过多调整,主要是为了解决主接口类过于庞大不方便管理的问题,将接口实现代码按模块进行拆分。所以如果习惯于1.X.X版本的同学不想做过多更改的话,请慎重考虑升级到2.X.X版本.***
---
## 开发交流方式:
1. ***入群须知:为保证入群成员质量,请申请入群前,先Star本项目,然后在申请入群时,输入您的Github帐号ID,以便管理员核对,ID即你的github主页地址https://github.com/XXXX 中最后的部分XXXX的内容,或者在github网页右上角点击头像后查看Signed in as后方内容。***
1. QQ群:343954419 [![Join QQ Group](http://pub.idqqimg.com/wpa/images/group.png)](http://shang.qq.com/wpa/qunwpa?idkey=078f7a153d243853e24cf2b542e7a6ccbf2a592bc138080f84d11297f736ec46)
1. 微信群: 因二维码有时间限制,如有想加入微信群的,请入QQ群后咨询获取最新入群二维码;
1. 有功能需求或由于微信官方接口调整导致的代码问题,可以直接提出issue,便于讨论追踪问题;
1. 详细开发文档请看 [Wiki](https://github.com/wechat-group/weixin-java-tools/wiki)。

### 详细开发文档请看 [wiki](https://github.com/chanjarster/weixin-java-tools/wiki)。
===========
## 开发交流工具:
* 微信群: 因二维码有时间限制,如有想加入微信群的,请入QQ群后咨询获取最新入群二维码。
* QQ群:343954419 [![Join QQ Group](http://pub.idqqimg.com/wpa/images/group.png)](http://shang.qq.com/wpa/qunwpa?idkey=078f7a153d243853e24cf2b542e7a6ccbf2a592bc138080f84d11297f736ec46)
* ***注意:为保证入群成员质量,请申请入群前,先Star本项目,然后在申请入群时,输入您的Github帐号ID,以便管理员核对,ID即你的github主页地址https://github.com/XXXX 中最后的部分XXXX的内容,或者在github网页右上角点击头像查看,如下图Signed in as下方黄色标识内容即是:***
* ![github_id](https://raw.githubusercontent.com/wechat-group/weixin-java-tools/develop/res/github_id.png)
===========

## 版本说明
* 本项目定为每月发布一次正式版,版本号格式为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
<dependency>
<groupId>com.github.binarywang</groupId>
@@ -37,12 +36,14 @@
<version>2.1.0</version>
</dependency>
```
gradle:
```groovy
compile 'com.github.binarywang:weixin-java-mp:2.1.0'
```

* 企业号:

maven:
```xml
<dependency>
<groupId>com.github.binarywang</groupId>
@@ -50,7 +51,7 @@ compile 'com.github.binarywang:weixin-java-mp:2.1.0'
<version>2.1.0</version>
</dependency>
```
gradle:
```groovy
compile 'com.github.binarywang:weixin-java-cp:2.1.0'
```
@@ -63,16 +64,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开发组,如果对自己的代码足够自信,可以随时提交代码,注意要随时进行单元测试,保证提交代码没有明显问题,具体加入方式,请咨询管理员。

+ 4
- 2
build.gradle Zobrazit soubor

@@ -13,8 +13,8 @@ subprojects {

repositories {
mavenLocal()
maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
maven { url "http://central.maven.org/maven2" }
//maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
}


@@ -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'


+ 20
- 0
pom.xml Zobrazit soubor

@@ -51,6 +51,8 @@
<jodd-http.version>3.6.7</jodd-http.version>
<jedis.version>2.9.0</jedis.version>
<gson.version>2.7</gson.version>
<guava.version>19.0</guava.version>
<joor.version>0.9.6</joor.version>
<commons-lang3.version>3.4</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<commons-codec.version>1.10</commons-codec.version>
@@ -111,6 +113,14 @@
<version>${jedis.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>joor</artifactId>
</dependency>
</dependencies>

<dependencyManagement>
@@ -151,6 +161,16 @@
<version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>joor</artifactId>
<version>${joor.version}</version>
</dependency>
</dependencies>
</dependencyManagement>



binární
res/github_id.png Zobrazit soubor

Před Za
Šířka: 218  |  Výška: 119  |  Velikost: 3.9 KiB

+ 19
- 0
weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java Zobrazit soubor

@@ -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 {

}

+ 1
- 0
weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java Zobrazit soubor

@@ -30,6 +30,7 @@ public class WxConsts {
public static final String CUSTOM_MSG_MUSIC = "music";
public static final String CUSTOM_MSG_NEWS = "news";
public static final String CUSTOM_MSG_FILE = "file";
public static final String CUSTOM_MSG_WXCARD = "wxcard";
public static final String CUSTOM_MSG_TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service";
public static final String CUSTOM_MSG_SAFE_NO = "0";
public static final String CUSTOM_MSG_SAFE_YES = "1";


+ 0
- 34
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java Zobrazit soubor

@@ -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,33 +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 createSign(Map<String, String> packageParams,
String signKey) {
SortedMap<String, String> sortedMap = new TreeMap<>();
sortedMap.putAll(packageParams);
List<String> 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();


+ 25
- 24
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java Zobrazit soubor

@@ -1,11 +1,9 @@
package me.chanjar.weixin.common.util.http;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.common.util.fs.FileUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
@@ -14,14 +12,15 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;

import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.common.util.fs.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* 下载媒体文件请求执行器,请求的参数是String, 返回的结果是File
*
* 视频文件不支持下载
* @author Daniel Qian
*/
public class MediaDownloadRequestExecutor implements RequestExecutor<File, String> {
@@ -29,15 +28,12 @@ public class MediaDownloadRequestExecutor implements RequestExecutor<File, Strin
private File tmpDirFile;

public MediaDownloadRequestExecutor() {
super();
}

public MediaDownloadRequestExecutor(File tmpDirFile) {
super();
this.tmpDirFile = tmpDirFile;
}


@Override
public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException {
if (queryParam != null) {
@@ -59,20 +55,20 @@ public class MediaDownloadRequestExecutor implements RequestExecutor<File, Strin

Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
// 下载媒体文件出错
if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) {
// application/json; encoding=utf-8 下载媒体文件出错
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
throw new WxErrorException(WxError.fromJson(responseContent));
}
}
// 视频文件不支持下载
String fileName = getFileName(response);
if (StringUtils.isBlank(fileName)) {
return null;
}
String[] name_ext = fileName.split("\\.");
File localFile = FileUtils.createTmpFile(inputStream, name_ext[0], name_ext[1], this.tmpDirFile);
return localFile;
String[] nameAndExt = fileName.split("\\.");
return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], this.tmpDirFile);

} finally {
httpGet.releaseConnection();
@@ -80,13 +76,18 @@ public class MediaDownloadRequestExecutor implements RequestExecutor<File, Strin

}

protected String getFileName(CloseableHttpResponse response) {
private String getFileName(CloseableHttpResponse response) throws WxErrorException {
Header[] contentDispositionHeader = response.getHeaders("Content-disposition");
if(contentDispositionHeader == null || contentDispositionHeader.length == 0){
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
}

Pattern p = Pattern.compile(".*filename=\"(.*)\"");
Matcher m = p.matcher(contentDispositionHeader[0].getValue());
m.matches();
String fileName = m.group(1);
return fileName;
if(m.matches()){
return m.group(1);
}
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
}

}

+ 0
- 2
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java Zobrazit soubor

@@ -2,7 +2,6 @@ package me.chanjar.weixin.common.util.http;

import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
@@ -21,7 +20,6 @@ public interface RequestExecutor<T, E> {
* @param uri uri
* @param data 数据
* @throws WxErrorException
* @throws ClientProtocolException
* @throws IOException
*/
T execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, E data) throws WxErrorException, IOException;


+ 15
- 3
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java Zobrazit soubor

@@ -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,17 @@ public class SimplePostRequestExecutor implements RequestExecutor<String, String

try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
if (responseContent.isEmpty()) {
throw new WxErrorException(
WxError.newBuilder().setErrorCode(9999).setErrorMsg("无响应内容")
.build());
}

if (responseContent.startsWith("<xml>")) {
//xml格式输出直接返回
return responseContent;
}

WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);


+ 7
- 2
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java Zobrazit soubor

@@ -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;//防止将_转换成__
}
};
}
});


+ 2
- 2
weixin-java-mp/pom.xml Zobrazit soubor

@@ -1,7 +1,7 @@
<?xml version="1.0"?>
<project
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">
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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.github.binarywang</groupId>


+ 2
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java Zobrazit soubor

@@ -10,10 +10,12 @@ import java.io.IOException;
import java.io.InputStream;

/**
* <pre>
* Created by Binary Wang on 2016/7/21.
* 素材管理的相关接口,包括媒体管理的接口,
* 即以https://api.weixin.qq.com/cgi-bin/material
* 和 https://api.weixin.qq.com/cgi-bin/media开头的接口
* </pre>
*/
public interface WxMpMaterialService {



+ 26
- 75
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpPayService.java Zobrazit soubor

@@ -1,10 +1,17 @@
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.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.pay.WxUnifiedOrderResult;

/**
* 微信支付相关接口
* Created by Binary Wang on 2016/7/28.
@@ -12,77 +19,32 @@ import java.util.Map;
*/
public interface WxMpPayService {


/**
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"
*
* @param openId 支付人openId
* @param outTradeNo 商户端对应订单号
* @param amt 金额(单位元)
* @param body 商品描述
* @param tradeType 交易类型 JSAPI,NATIVE,APP,WAP
* @param ip 发起支付的客户端IP
* @param notifyUrl 通知地址
* @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPrepayId(Map<String, String>) instead
*/
@Deprecated
WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String notifyUrl);

/**
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"
* 接口地址:https://api.mch.weixin.qq.com/pay/unifiedorder
* @throws WxErrorException
*
* @param parameters All required/optional parameters for weixin payment
*/
WxMpPrepayIdResult getPrepayId(Map<String, String> parameters);
WxUnifiedOrderResult unifiedOrder(WxUnifiedOrderRequest request)
throws WxErrorException;

/**
* 该接口调用“统一下单”接口,并拼装发起支付请求需要的参数
* 详见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
*/
Map<String, String> getPayInfo(Map<String, String> parameters) throws WxErrorException;
Map<String, String> getPayInfo(WxUnifiedOrderRequest request) throws WxErrorException;

/**
* 该接口调用“统一下单”接口,并拼装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
* tradeType 交易类型 NATIVE (其他交易类型JSAPI,APP,WAP)
*
* @param productId 商户商品ID
* @param outTradeNo 商户端对应订单号
* @param amt 金额(单位元)
* @param body 商品描述
* @param ip 发起支付的客户端IP
* @param notifyUrl 通知地址
* @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPayInfo(Map<String, String>) instead
*/
@Deprecated
Map<String, String> 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
* tradeType 交易类型 JSAPI(其他交易类型NATIVE,APP,WAP)
*
* @param openId 支付人openId
* @param outTradeNo 商户端对应订单号
* @param amt 金额(单位元)
* @param body 商品描述
* @param ip 发起支付的客户端IP
* @param notifyUrl 通知地址
* @deprecated Use me.chanjar.weixin.mp.api.WxMpService.getPayInfo(Map<String, String>) instead
*/
@Deprecated
Map<String, String> getJsapiPayInfo(String openId, String outTradeNo, double amt, String body, String ip, String notifyUrl) throws WxErrorException;

/**
* 该接口提供所有微信支付订单的查询,当支付通知处理异常戒丢失的情冴,商户可以通过该接口查询订单支付状态。
* 详见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;

/**
* 读取支付结果通知
@@ -116,23 +78,12 @@ public interface WxMpPayService {

/**
* 发送微信红包给个人用户
* <p>
* 需要传入的必填参数如下:
* mch_billno//商户订单号
* send_name//商户名称
* re_openid//用户openid
* total_amount//红包总额
* total_num//红包发放总人数
* wishing//红包祝福语
* client_ip//服务器Ip地址
* act_name//活动名称
* remark //备注
* 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5
* <p>
* 使用现金红包功能需要在xml配置文件中额外设置:
* <partnerId></partnerId>微信商户平台ID
* <partnerKey></partnerKey>商户平台设置的API密钥
*
* <pre>
* 文档详见:
* 发送普通红包 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
* </pre>
*/
WxRedpackResult sendRedpack(Map<String, String> parameters) throws WxErrorException;
WxRedpackResult sendRedpack(WxSendRedpackRequest request) throws WxErrorException;

}

+ 18
- 11
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java Zobrazit soubor

@@ -302,28 +302,28 @@ public interface WxMpService {
WxMpKefuService getKefuService();

/**
* 返回素材相关接口方法实现类,以方便调用个其各种接口
* 返回素材相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpMaterialService
*/
WxMpMaterialService getMaterialService();

/**
* 返回菜单相关接口方法实现类,以方便调用个其各种接口
* 返回菜单相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpMenuService
*/
WxMpMenuService getMenuService();

/**
* 返回用户相关接口方法实现类,以方便调用个其各种接口
* 返回用户相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpUserService
*/
WxMpUserService getUserService();

/**
* 返回用户分组相关接口方法实现类,以方便调用个其各种接口
* 返回用户分组相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpGroupService
*/
@@ -331,44 +331,51 @@ public interface WxMpService {
WxMpGroupService getGroupService();

/**
* 返回用户标签相关接口方法实现类,以方便调用个其各种接口
* 返回用户标签相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpUserTagService
*/
WxMpUserTagService getUserTagService();

/**
* 返回二维码相关接口方法实现类,以方便调用个其各种接口
* 返回二维码相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpQrcodeService
*/
WxMpQrcodeService getQrcodeService();

/**
* 返回卡券相关接口方法实现类,以方便调用个其各种接口
* 返回卡券相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpCardService
*/
WxMpCardService getCardService();

/**
* 返回微信支付相关接口方法实现类,以方便调用个其各种接口
* 返回微信支付相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpPayService
*/
WxMpPayService getPayService();

/**
* 返回数据分析统计相关接口方法实现类,以方便调用个其各种接口
* 返回数据分析统计相关接口方法实现类对象,以方便调用个其各种接口
*
* @return WxMpDataCubeService
*/
WxMpDataCubeService getDataCubeService();

/**
* 返回用户黑名单管理相关接口的方法实现类,以方便调用其各种借
* 返回用户黑名单管理相关接口方法的实现类对象,以方便调用其各种接
*
* @return WxMpUserBlackListService
* @return WxMpUserBlacklistService
*/
WxMpUserBlacklistService getBlackListService();

/**
* 返回门店管理相关接口方法的实现类对象,以方便调用其各种接口
*
* @return WxMpStoreService
*/
WxMpStoreService getStoreService();
}

+ 51
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java Zobrazit soubor

@@ -0,0 +1,51 @@
package me.chanjar.weixin.mp.api;

import java.util.List;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.store.WxMpStoreBaseInfo;
import me.chanjar.weixin.mp.bean.store.WxMpStoreInfo;
import me.chanjar.weixin.mp.bean.store.WxMpStoreListResult;

/**
* 门店管理的相关接口代码
* @author binarywang(https://github.com/binarywang)
* Created by Binary Wang on 2016-09-23.
*/
public interface WxMpStoreService {
/**
* <pre>
* 创建门店
* 接口说明
* 创建门店接口是为商户提供创建自己门店数据的接口,门店数据字段越完整,商户页面展示越丰富,越能够吸引更多用户,并提高曝光度。
* 创建门店接口调用成功后会返回errcode 0、errmsg ok,但不会实时返回poi_id。
* 成功创建后,会生成poi_id,但该id不一定为最终id。门店信息会经过审核,审核通过后方可获取最终poi_id,该id为门店的唯一id,强烈建议自行存储审核通过后的最终poi_id,并为后续调用使用。
* 详情请见: <a href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444378120&token=&lang=zh_CN">微信门店接口</a>
* 接口格式: http://api.weixin.qq.com/cgi-bin/poi/addpoi?access_token=TOKEN
* </pre>
*
*/
void add(WxMpStoreBaseInfo request) throws WxErrorException;

/**
* <pre>
* 查询门店列表(指定查询起始位置和个数)
* 商户可以通过该接口,批量查询自己名下的门店list,并获取已审核通过的poi_id(所有状态均会返回poi_id,但该poi_id不一定为最终id)、商户自身sid 用于对应、商户名、分店名、地址字段。
* 详情请见: <a href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444378120&token=&lang=zh_CN">微信门店接口</a>
* </pre>
* @param begin 开始位置,0 即为从第一条开始查询
* @param limit 返回数据条数,最大允许50,默认为20
* @throws WxErrorException
*/
WxMpStoreListResult list(int begin, int limit) throws WxErrorException;

/**
* <pre>
* 查询门店列表(所有)
* 商户可以通过该接口,批量查询自己名下的门店list,并获取已审核通过的poi_id(所有状态均会返回poi_id,但该poi_id不一定为最终id)、商户自身sid 用于对应、商户名、分店名、地址字段。
* 详情请见: <a href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444378120&token=&lang=zh_CN">微信门店接口</a>
* </pre>
* @throws WxErrorException
*/
List<WxMpStoreInfo> listAll() throws WxErrorException;
}

+ 44
- 2
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java Zobrazit soubor

@@ -1,10 +1,11 @@
package me.chanjar.weixin.mp.api;

import java.util.List;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.tag.WxTagListUser;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;

import java.util.List;

/**
* 用户标签管理相关接口
* Created by Binary Wang on 2016/9/2.
@@ -55,4 +56,45 @@ public interface WxMpUserTagService {
*/
Boolean tagDelete(Integer id) throws WxErrorException;

/**
* <pre>
* 获取标签下粉丝列表
* 详情请见:<a href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">用户标签管理</a>
* 接口url格式: https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=ACCESS_TOKEN
* </pre>
*
*/
WxTagListUser tagListUser(Integer tagId, String nextOpenid) throws WxErrorException;

/**
* <pre>
* 批量为用户打标签
* 详情请见:<a href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">用户标签管理</a>
* 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=ACCESS_TOKEN
* </pre>
*
*/
boolean batchTagging(Integer tagId, String[] openids) throws WxErrorException;

/**
* <pre>
* 批量为用户取消标签
* 详情请见:<a href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">用户标签管理</a>
* 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=ACCESS_TOKEN
* </pre>
*
*/
boolean batchUntagging(Integer tagId, String[] openids) throws WxErrorException;


/**
* <pre>
* 获取用户身上的标签列表
* 详情请见:<a href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">用户标签管理</a>
* 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=ACCESS_TOKEN
* </pre>
*
*/
List<Integer> userTagList(String openid) throws WxErrorException;

}

+ 11
- 45
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImpl.java Zobrazit soubor

@@ -1,13 +1,6 @@
package me.chanjar.weixin.mp.api.impl;

import java.io.File;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;

import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
@@ -17,15 +10,15 @@ import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpCustomMessage;
import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfAccountRequest;
import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfSessionRequest;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfList;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfMsgList;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfOnlineList;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionGetResult;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionList;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfSessionWaitCaseList;
import me.chanjar.weixin.mp.bean.kefu.result.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Date;

/**
*
*
* @author Binary Wang
*
*/
@@ -33,6 +26,7 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
protected final Logger log = LoggerFactory
.getLogger(WxMpKefuServiceImpl.class);
private static final String API_URL_PREFIX = "https://api.weixin.qq.com/customservice";
private static final String API_URL_PREFIX_WITH_CGI_BIN = "https://api.weixin.qq.com/cgi-bin/customservice";
private WxMpService wxMpService;

public WxMpKefuServiceImpl(WxMpService wxMpService) {
@@ -44,26 +38,20 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send";
String responseContent = this.wxMpService.post(url, message.toJson());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, message.toJson(),
responseContent);
return true;
}

@Override
public WxMpKfList kfList() throws WxErrorException {
String url = API_URL_PREFIX + "/getkflist";
String url = API_URL_PREFIX_WITH_CGI_BIN + "/getkflist";
String responseContent = this.wxMpService.get(url, null);
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, null,
responseContent);
return WxMpKfList.fromJson(responseContent);
}

@Override
public WxMpKfOnlineList kfOnlineList() throws WxErrorException {
String url = API_URL_PREFIX + "/getonlinekflist";
String url = API_URL_PREFIX_WITH_CGI_BIN + "/getonlinekflist";
String responseContent = this.wxMpService.get(url, null);
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, null,
responseContent);
return WxMpKfOnlineList.fromJson(responseContent);
}

@@ -72,8 +60,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
throws WxErrorException {
String url = API_URL_PREFIX + "/kfaccount/add";
String responseContent = this.wxMpService.post(url, request.toJson());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, request.toJson(),
responseContent);
return true;
}

@@ -82,8 +68,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
throws WxErrorException {
String url = API_URL_PREFIX + "/kfaccount/update";
String responseContent = this.wxMpService.post(url, request.toJson());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, request.toJson(),
responseContent);
return true;
}

@@ -91,8 +75,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
public boolean kfAccountInviteWorker(WxMpKfAccountRequest request) throws WxErrorException {
String url = API_URL_PREFIX + "/kfaccount/inviteworker";
String responseContent = this.wxMpService.post(url, request.toJson());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, request.toJson(),
responseContent);
return true;
}

@@ -102,9 +84,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
String url = API_URL_PREFIX + "/kfaccount/uploadheadimg?kf_account=" + kfAccount;
WxMediaUploadResult responseContent = this.wxMpService
.execute(new MediaUploadRequestExecutor(), url, imgFile);
this.log.debug("\nurl:{}\nparams:{}&file:{}\nresponse:{}", url, kfAccount,
imgFile.getAbsolutePath(),
responseContent);
return true;
}

@@ -112,8 +91,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
public boolean kfAccountDel(String kfAccount) throws WxErrorException {
String url = API_URL_PREFIX + "/kfaccount/del?kf_account=" + kfAccount;
String responseContent = this.wxMpService.get(url, null);
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, null,
responseContent);
return true;
}

@@ -123,8 +100,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
WxMpKfSessionRequest request = new WxMpKfSessionRequest(kfAccount, openid);
String url = API_URL_PREFIX + "/kfsession/create";
String responseContent = this.wxMpService.post(url, request.toJson());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, request.toJson(),
responseContent);
return true;
}

@@ -134,8 +109,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
WxMpKfSessionRequest request = new WxMpKfSessionRequest(kfAccount, openid);
String url = API_URL_PREFIX + "/kfsession/close";
String responseContent = this.wxMpService.post(url, request.toJson());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, request.toJson(),
responseContent);
return true;
}

@@ -144,8 +117,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
throws WxErrorException {
String url = API_URL_PREFIX + "/kfsession/getsession?openid=" + openid;
String responseContent = this.wxMpService.get(url, null);
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, null,
responseContent);
return WxMpKfSessionGetResult.fromJson(responseContent);
}

@@ -154,8 +125,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
throws WxErrorException {
String url = API_URL_PREFIX + "/kfsession/getsessionlist?kf_account=" + kfAccount;
String responseContent = this.wxMpService.get(url, null);
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, null,
responseContent);
return WxMpKfSessionList.fromJson(responseContent);
}

@@ -164,8 +133,6 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
throws WxErrorException {
String url = API_URL_PREFIX + "/kfsession/getwaitcase";
String responseContent = this.wxMpService.get(url, null);
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, null,
responseContent);
return WxMpKfSessionWaitCaseList.fromJson(responseContent);
}

@@ -188,8 +155,7 @@ public class WxMpKefuServiceImpl implements WxMpKefuService {
param.addProperty("number", number); //number 每次获取条数,最多10000条

String responseContent = this.wxMpService.post(url, param.toString());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, param.toString(),
responseContent);

return WxMpKfMsgList.fromJson(responseContent);
}



+ 4
- 1
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java Zobrazit soubor

@@ -50,7 +50,10 @@ public class WxMpMaterialServiceImpl implements WxMpMaterialService {
@Override
public File mediaDownload(String media_id) throws WxErrorException {
String url = MEDIA_API_URL_PREFIX + "/get";
return this.wxMpService.execute(new MediaDownloadRequestExecutor(this.wxMpService.getWxMpConfigStorage().getTmpDirFile()), url, "media_id=" + media_id);
return this.wxMpService.execute(
new MediaDownloadRequestExecutor(this.wxMpService.getWxMpConfigStorage().getTmpDirFile()),
url,
"media_id=" + media_id);
}

@Override


+ 16
- 15
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java Zobrazit soubor

@@ -5,8 +5,6 @@ import org.slf4j.LoggerFactory;

import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor;
import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor;
import me.chanjar.weixin.mp.api.WxMpMenuService;
import me.chanjar.weixin.mp.api.WxMpService;

@@ -15,7 +13,8 @@ import me.chanjar.weixin.mp.api.WxMpService;
*/
public class WxMpMenuServiceImpl implements WxMpMenuService {
private static final String API_URL_PREFIX = "https://api.weixin.qq.com/cgi-bin/menu";
private static Logger log = LoggerFactory.getLogger(WxMpMenuServiceImpl.class);
private static Logger log = LoggerFactory
.getLogger(WxMpMenuServiceImpl.class);

private WxMpService wxMpService;

@@ -25,36 +24,37 @@ public class WxMpMenuServiceImpl implements WxMpMenuService {

@Override
public void menuCreate(WxMenu menu) throws WxErrorException {
String menuJson = menu.toJson();
String url = API_URL_PREFIX + "/create";
String menuJson = menu.toJson();
String url = API_URL_PREFIX + "/create";
if (menu.getMatchRule() != null) {
url = API_URL_PREFIX + "/addconditional";
}
log.trace("开始创建菜单:{}", menuJson);
String result = this.wxMpService.execute(new SimplePostRequestExecutor(), url,menuJson);
}

log.debug("开始创建菜单:{}", menuJson);

String result = this.wxMpService.post(url, menuJson);
log.debug("创建菜单:{},结果:{}", menuJson, result);
}

@Override
public void menuDelete() throws WxErrorException {
String url = API_URL_PREFIX + "/delete";
String result = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, null);
String result = this.wxMpService.get(url, null);
log.debug("删除菜单结果:{}", result);
}

@Override
public void menuDelete(String menuid) throws WxErrorException {
String url = API_URL_PREFIX + "/delconditional";
String result = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, "menuid=" + menuid);
log.debug("根据MeunId({})删除菜单结果:{}", menuid,result);
String result = this.wxMpService.get(url, "menuid=" + menuid);
log.debug("根据MeunId({})删除菜单结果:{}", menuid, result);
}

@Override
public WxMenu menuGet() throws WxErrorException {
String url = API_URL_PREFIX + "/get";
try {
String resultContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, null);
String resultContent = this.wxMpService.get(url, null);
return WxMenu.fromJson(resultContent);
} catch (WxErrorException e) {
// 46003 不存在的菜单数据
@@ -69,11 +69,12 @@ public class WxMpMenuServiceImpl implements WxMpMenuService {
public WxMenu menuTryMatch(String userid) throws WxErrorException {
String url = API_URL_PREFIX + "/trymatch";
try {
String resultContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, "user_id=" + userid);
String resultContent = this.wxMpService.get(url, "user_id=" + userid);
return WxMenu.fromJson(resultContent);
} catch (WxErrorException e) {
// 46003 不存在的菜单数据 46002 不存在的菜单版本
if (e.getError().getErrorCode() == 46003 || e.getError().getErrorCode() == 46002) {
if (e.getError().getErrorCode() == 46003
|| e.getError().getErrorCode() == 46002) {
return null;
}
throw e;


+ 244
- 313
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java Zobrazit soubor

@@ -1,28 +1,38 @@
package me.chanjar.weixin.mp.api.impl;

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;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.joor.Reflect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.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.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.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;
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.pay.WxUnifiedOrderResult;

/**
* Created by Binary Wang on 2016/7/28.
@@ -31,198 +41,25 @@ import java.util.TreeMap;
*/
public class WxMpPayServiceImpl implements WxMpPayService {

private static final List<String> 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 HttpHost httpProxy;
private WxMpServiceImpl wxMpService;
private WxMpService wxMpService;

public WxMpPayServiceImpl(WxMpServiceImpl wxMpService) {
public WxMpPayServiceImpl(WxMpService wxMpService) {
this.wxMpService = wxMpService;
this.httpProxy = wxMpService.getHttpProxy();
}

@Override
public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo,
double amt, String body, String tradeType, String ip,
String callbackUrl) {
Map<String, String> packageParams = new HashMap<>();
packageParams.put("appid",
this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo);
packageParams.put("total_fee", (int) (amt * 100) + "");
packageParams.put("spbill_create_ip", ip);
packageParams.put("notify_url", callbackUrl);
packageParams.put("trade_type", tradeType);
packageParams.put("openid", openId);

return getPrepayId(packageParams);
}

@Override
public WxMpPrepayIdResult getPrepayId(final Map<String, String> parameters) {
final SortedMap<String, String> packageParams = new TreeMap<>(parameters);
packageParams.put("appid",
this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("nonce_str", System.currentTimeMillis() + "");
checkParameters(packageParams);

String sign = WxCryptUtil.createSign(packageParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey());
packageParams.put("sign", sign);

StringBuilder request = new StringBuilder("<xml>");
for (Map.Entry<String, String> para : packageParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(),
para.getValue(), para.getKey()));
}

request.append("</xml>");

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();
}
}

private void checkParameters(Map<String, String> parameters) {
for (String para : this.REQUIRED_ORDER_PARAMETERS) {
if (!parameters.containsKey(para)) {
throw new IllegalArgumentException(
"Reqiured argument '" + para + "' is missing.");
}
}

if ("JSAPI".equals(parameters.get("trade_type"))
&& !parameters.containsKey("openid")) {
throw new IllegalArgumentException(
"Reqiured argument 'openid' is missing when trade_type is 'JSAPI'.");
}

if ("NATIVE".equals(parameters.get("trade_type"))
&& !parameters.containsKey("product_id")) {
throw new IllegalArgumentException(
"Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'.");
}
}

@Override
public Map<String, String> getJsapiPayInfo(String openId, String outTradeNo,
double amt, String body, String ip, String callbackUrl)
throws WxErrorException {
Map<String, String> packageParams = new HashMap<>();
packageParams.put("appid",
this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo);
packageParams.put("total_fee", (int) (amt * 100) + "");
packageParams.put("spbill_create_ip", ip);
packageParams.put("notify_url", callbackUrl);
packageParams.put("trade_type", "JSAPI");
packageParams.put("openid", openId);

return getPayInfo(packageParams);
}

@Override
public Map<String, String> getNativePayInfo(String productId,
String outTradeNo, double amt, String body, String ip, String callbackUrl)
throws WxErrorException {
Map<String, String> packageParams = new HashMap<>();
packageParams.put("appid",
this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo);
packageParams.put("total_fee", (int) (amt * 100) + "");
packageParams.put("spbill_create_ip", ip);
packageParams.put("notify_url", callbackUrl);
packageParams.put("trade_type", "NATIVE");
packageParams.put("product_id", productId);

return getPayInfo(packageParams);
}

@Override
public Map<String, String> getPayInfo(Map<String, String> parameters)
throws WxErrorException {
WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(parameters);

if (!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getReturn_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());
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()));
}

Map<String, String> payInfo = new HashMap<>();
payInfo.put("appId", this.wxMpService.getWxMpConfigStorage().getAppId());
// 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
payInfo.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
payInfo.put("nonceStr", System.currentTimeMillis() + "");
payInfo.put("package", "prepay_id=" + prepayId);
payInfo.put("signType", "MD5");
if ("NATIVE".equals(parameters.get("trade_type"))) {
payInfo.put("codeUrl", wxMpPrepayIdResult.getCode_url());
}

String finalSign = WxCryptUtil.createSign(payInfo,
this.wxMpService.getWxMpConfigStorage().getPartnerKey());
payInfo.put("paySign", finalSign);
return payInfo;
}

@Override
public WxMpPayResult getJSSDKPayResult(String transactionId,
String outTradeNo) {
String outTradeNo) throws WxErrorException {
String nonce_str = System.currentTimeMillis() + "";

SortedMap<String, String> 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);
@@ -230,41 +67,25 @@ 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", WxCryptUtil.createSign(packageParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey()));
packageParams.put("sign", this.createSign(packageParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey()));

StringBuilder request = new StringBuilder("<xml>");
for (Map.Entry<String, String> para : packageParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(),
para.getValue(), para.getKey()));
para.getValue(), para.getKey()));
}
request.append("</xml>");

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
@@ -282,127 +103,237 @@ public class WxMpPayServiceImpl implements WxMpPayService {

@Override
public WxMpPayRefundResult refundPay(Map<String, String> parameters)
throws WxErrorException {
throws WxErrorException {
SortedMap<String, String> 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());
String sign = WxCryptUtil.createSign(refundParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey());
this.wxMpService.getWxMpConfigStorage().getPartnerId());
String sign = this.createSign(refundParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey());
refundParams.put("sign", sign);

StringBuilder request = new StringBuilder("<xml>");
for (Map.Entry<String, String> para : refundParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(),
para.getValue(), para.getKey()));
para.getValue(), para.getKey()));
}
request.append("</xml>");

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);
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);

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);
}

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);
return wxMpPayRefundResult;
}

@Override
public boolean checkJSSDKCallbackDataSignature(Map<String, String> kvm,
String signature) {
return signature.equals(this.createSign(kvm,
this.wxMpService.getWxMpConfigStorage().getPartnerKey()));
}

@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());
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/mmpaymkttransfers/sendredpack";
if (request.getAmtType() != null) {
//裂变红包
url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack";
}

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());
}

return redpackResult;
}

private Map<String, String> xmlBean2Map(Object bean) {
Map<String, String> result = Maps.newHashMap();
for (Entry<String, Reflect> entry : Reflect.on(bean).fields().entrySet()) {
Reflect reflect = entry.getValue();
if (reflect.get() == null) {
continue;
}

try {
Field field = bean.getClass().getDeclaredField(entry.getKey());
if (field.isAnnotationPresent(XStreamAlias.class)) {
result.put(field.getAnnotation(XStreamAlias.class).value(),
reflect.get().toString());
}
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}

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();
}

return result;
}

@Override
public boolean checkJSSDKCallbackDataSignature(Map<String, String> kvm,
String signature) {
return signature.equals(WxCryptUtil.createSign(kvm,
this.wxMpService.getWxMpConfigStorage().getPartnerKey()));
/**
* 微信公众号支付签名算法(详见:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3)
* @param packageParams 原始参数
* @param signKey 加密Key(即 商户Key)
* @return 签名字符串
*/
private String createSign(Map<String, String> packageParams, String signKey) {
SortedMap<String, String> 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();
}

@Override
public WxRedpackResult sendRedpack(Map<String, String> parameters)
throws WxErrorException {
SortedMap<String, String> packageParams = new TreeMap<>(parameters);
packageParams.put("wxappid",
this.wxMpService.getWxMpConfigStorage().getAppId());
packageParams.put("mch_id",
this.wxMpService.getWxMpConfigStorage().getPartnerId());
packageParams.put("nonce_str", System.currentTimeMillis() + "");
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());
}

String sign = WxCryptUtil.createSign(packageParams,
this.wxMpService.getWxMpConfigStorage().getPartnerKey());
packageParams.put("sign", sign);
return result;

StringBuilder request = new StringBuilder("<xml>");
for (Map.Entry<String, String> para : packageParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(),
para.getValue(), para.getKey()));
}

private void checkParameters(WxUnifiedOrderRequest request) {

List<String> nullFields = Lists.newArrayList();
for (Entry<String, Reflect> 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();
}
}

request.append("</xml>");
if (!nullFields.isEmpty()) {
throw new IllegalArgumentException("必填字段[" + nullFields + "]必须提供值");
}

if (!TRADE_TYPES.contains(request.getTradeType())) {
throw new IllegalArgumentException(
"trade_type目前必须为" + TRADE_TYPES + "其中之一");

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);
}

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();
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");
}
}

@Override
public Map<String, String> getPayInfo(WxUnifiedOrderRequest request) throws WxErrorException {
WxUnifiedOrderResult unifiedOrderResult = this.unifiedOrder(request);

if (!"SUCCESS".equalsIgnoreCase(unifiedOrderResult.getReturnCode())
|| !"SUCCESS".equalsIgnoreCase(unifiedOrderResult.getResultCode())) {
throw new WxErrorException(WxError.newBuilder().setErrorCode(-1)
.setErrorMsg("return_code:" + unifiedOrderResult.getReturnCode() + ";return_msg:"
+ unifiedOrderResult.getReturnMsg() + ";result_code:" + unifiedOrderResult.getResultCode() + ";err_code"
+ unifiedOrderResult.getErrCode() + ";err_code_des" + unifiedOrderResult.getErrCodeDes())
.build());
}

String prepayId = unifiedOrderResult.getPrepayId();
if (StringUtils.isBlank(prepayId)) {
throw new RuntimeException(String.format("Failed to get prepay id due to error code '%s'(%s).",
unifiedOrderResult.getErrCode(), unifiedOrderResult.getErrCodeDes()));
}

Map<String, String> payInfo = new HashMap<>();
payInfo.put("appId", this.wxMpService.getWxMpConfigStorage().getAppId());
// 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
payInfo.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
payInfo.put("nonceStr", System.currentTimeMillis() + "");
payInfo.put("package", "prepay_id=" + prepayId);
payInfo.put("signType", "MD5");
if ("NATIVE".equals(request.getTradeType())) {
payInfo.put("codeUrl", unifiedOrderResult.getCodeURL());
}

String finalSign = this.createSign(payInfo, this.wxMpService.getWxMpConfigStorage().getPartnerKey());
payInfo.put("paySign", finalSign);
return payInfo;
}

}

+ 30
- 17
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java Zobrazit soubor

@@ -1,9 +1,23 @@
package me.chanjar.weixin.mp.api.impl;

import java.io.IOException;

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.HttpGet;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.result.WxError;
@@ -28,6 +42,7 @@ import me.chanjar.weixin.mp.api.WxMpMenuService;
import me.chanjar.weixin.mp.api.WxMpPayService;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpStoreService;
import me.chanjar.weixin.mp.api.WxMpUserBlacklistService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.api.WxMpUserTagService;
@@ -44,18 +59,6 @@ import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpSemanticQueryResult;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
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.HttpGet;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class WxMpServiceImpl implements WxMpService {

@@ -93,6 +96,8 @@ public class WxMpServiceImpl implements WxMpService {

private WxMpPayService payService = new WxMpPayServiceImpl(this);

private WxMpStoreService storeService = new WxMpStoreServiceImpl(this);

private WxMpDataCubeService dataCubeService = new WxMpDataCubeServiceImpl(this);

private WxMpUserBlacklistService blackListService = new WxMpUserBlacklistServiceImpl(this);
@@ -252,9 +257,8 @@ public class WxMpServiceImpl implements WxMpService {
@Override
public String templateSend(WxMpTemplateMessage templateMessage) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send";
String responseContent = execute(new SimplePostRequestExecutor(), url, templateMessage.toJson());
JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent);
final JsonObject jsonObject = tmpJsonElement.getAsJsonObject();
String responseContent = this.post(url, templateMessage.toJson());
final JsonObject jsonObject = JSON_PARSER.parse(responseContent).getAsJsonObject();
if (jsonObject.get("errcode").getAsInt() == 0){
return jsonObject.get("msgid").getAsString();
}
@@ -421,7 +425,9 @@ public class WxMpServiceImpl implements WxMpService {
int retryTimes = 0;
do {
try {
return executeInternal(executor, uri, data);
T result = executeInternal(executor, uri, data);
this.log.debug("\n[URL]: {}\n[PARAMS]: {}\n[RESPONSE]: {}",uri, data, result);
return result;
} catch (WxErrorException e) {
WxError error = e.getError();
/**
@@ -465,9 +471,11 @@ public class WxMpServiceImpl implements WxMpService {
if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001) {
// 强制设置wxMpConfigStorage它的access token过期了,这样在下一次请求里就会刷新access token
this.configStorage.expireAccessToken();
return execute(executor, uri, data);
return this.execute(executor, uri, data);
}
if (error.getErrorCode() != 0) {
this.log.error("\n[URL]: {}\n[PARAMS]: {}\n[RESPONSE]: {}", uri, data,
error);
throw new WxErrorException(error);
}
return null;
@@ -586,4 +594,9 @@ public class WxMpServiceImpl implements WxMpService {
return this.blackListService;
}

@Override
public WxMpStoreService getStoreService() {
return this.storeService;
}

}

+ 107
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java Zobrazit soubor

@@ -0,0 +1,107 @@
package me.chanjar.weixin.mp.api.impl;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map.Entry;

import org.joor.Reflect;

import com.google.common.collect.Lists;
import com.google.gson.JsonObject;

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.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpStoreService;
import me.chanjar.weixin.mp.bean.store.WxMpStoreBaseInfo;
import me.chanjar.weixin.mp.bean.store.WxMpStoreInfo;
import me.chanjar.weixin.mp.bean.store.WxMpStoreListResult;

/**
* Created by Binary Wang on 2016/9/26.
* @author binarywang (https://github.com/binarywang)
*
*/
public class WxMpStoreServiceImpl implements WxMpStoreService {
private static final String API_BASE_URL = "http://api.weixin.qq.com/cgi-bin/poi";

private WxMpService wxMpService;

public WxMpStoreServiceImpl(WxMpService wxMpService) {
this.wxMpService = wxMpService;
}

@Override
public void add(WxMpStoreBaseInfo request) throws WxErrorException {
checkParameters(request);

String url = API_BASE_URL + "/addpoi";
String response = this.wxMpService.post(url, request.toJson());
WxError wxError = WxError.fromJson(response);
if (wxError.getErrorCode() != 0) {
throw new WxErrorException(wxError);
}
}

private void checkParameters(WxMpStoreBaseInfo request) {
List<String> nullFields = Lists.newArrayList();
for (Entry<String, Reflect> 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 + "]必须提供值");
}

}

@Override
public WxMpStoreListResult list(int begin, int limit)
throws WxErrorException {
String url = API_BASE_URL + "/getpoilist";
JsonObject params = new JsonObject();
params.addProperty("begin", begin);
params.addProperty("limit", limit);
String response = this.wxMpService.post(url, params.toString());

WxError wxError = WxError.fromJson(response);
if (wxError.getErrorCode() != 0) {
throw new WxErrorException(wxError);
}

return WxMpStoreListResult.fromJson(response);
}

@Override
public List<WxMpStoreInfo> listAll() throws WxErrorException {
int limit = 50;
WxMpStoreListResult list = this.list(0, limit);
List<WxMpStoreInfo> stores = list.getBusinessList();
if (list.getTotalCount() > limit) {
int begin = limit;
WxMpStoreListResult followingList = this.list(begin, limit);
while (followingList.getBusinessList().size() > 0) {
stores.addAll(followingList.getBusinessList());
begin += limit;
if (begin >= list.getTotalCount()) {
break;
}
followingList = this.list(begin, limit);
}
}

return stores;
}

}

+ 87
- 6
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java Zobrazit soubor

@@ -1,17 +1,21 @@
package me.chanjar.weixin.mp.api.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserTagService;
import me.chanjar.weixin.mp.bean.tag.WxTagListUser;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
*
@@ -92,4 +96,81 @@ public class WxMpUserTagServiceImpl implements WxMpUserTagService {

throw new WxErrorException(wxError);
}

@Override
public WxTagListUser tagListUser(Integer tagId, String nextOpenid) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/user/tag/get";

JsonObject json = new JsonObject();
json.addProperty("tagid", tagId);
json.addProperty("next_openid", StringUtils.trimToEmpty(nextOpenid));

String responseContent = this.wxMpService.post(url, json.toString());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, json.toString(),
responseContent);
return WxTagListUser.fromJson(responseContent);
}

@Override
public boolean batchTagging(Integer tagId, String[] openids) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging";

JsonObject json = new JsonObject();
json.addProperty("tagid", tagId);
JsonArray openidArrayJson = new JsonArray();
for (String openid : openids) {
openidArrayJson.add(openid);
}
json.add("openid_list", openidArrayJson);

String responseContent = this.wxMpService.post(url, json.toString());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, json.toString(),
responseContent);
WxError wxError = WxError.fromJson(responseContent);
if (wxError.getErrorCode() == 0) {
return true;
}

throw new WxErrorException(wxError);
}

@Override
public boolean batchUntagging(Integer tagId, String[] openids) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging";

JsonObject json = new JsonObject();
json.addProperty("tagid", tagId);
JsonArray openidArrayJson = new JsonArray();
for (String openid : openids) {
openidArrayJson.add(openid);
}
json.add("openid_list", openidArrayJson);

String responseContent = this.wxMpService.post(url, json.toString());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, json.toString(),
responseContent);
WxError wxError = WxError.fromJson(responseContent);
if (wxError.getErrorCode() == 0) {
return true;
}

throw new WxErrorException(wxError);
}

@Override
public List<Integer> userTagList(String openid) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/tags/getidlist";

JsonObject json = new JsonObject();
json.addProperty("openid", openid);

String responseContent = this.wxMpService.post(url, json.toString());
this.log.debug("\nurl:{}\nparams:{}\nresponse:{}", url, json.toString(),
responseContent);

return WxMpGsonBuilder.create().fromJson(
new JsonParser().parse(responseContent).getAsJsonObject().get("tagid_list"),
new TypeToken<List<Integer>>() {
}.getType());
}
}

+ 42
- 18
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java Zobrazit soubor

@@ -1,12 +1,18 @@
package me.chanjar.weixin.mp.bean;

import me.chanjar.weixin.mp.bean.custombuilder.*;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import me.chanjar.weixin.mp.bean.custombuilder.ImageBuilder;
import me.chanjar.weixin.mp.bean.custombuilder.MusicBuilder;
import me.chanjar.weixin.mp.bean.custombuilder.NewsBuilder;
import me.chanjar.weixin.mp.bean.custombuilder.TextBuilder;
import me.chanjar.weixin.mp.bean.custombuilder.VideoBuilder;
import me.chanjar.weixin.mp.bean.custombuilder.VoiceBuilder;
import me.chanjar.weixin.mp.bean.custombuilder.WxCardBuilder;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

/**
* 客服消息
* @author chanjarster
@@ -14,7 +20,7 @@ import java.util.List;
*/
public class WxMpCustomMessage implements Serializable {
private static final long serialVersionUID = -9196732086954365246L;
private String toUser;
private String msgType;
private String content;
@@ -25,8 +31,9 @@ public class WxMpCustomMessage implements Serializable {
private String musicUrl;
private String hqMusicUrl;
private String kfAccount;
private String cardId;
private List<WxArticle> articles = new ArrayList<>();
public String getToUser() {
return this.toUser;
}
@@ -36,7 +43,7 @@ public class WxMpCustomMessage implements Serializable {
public String getMsgType() {
return this.msgType;
}
/**
* <pre>
* 请使用
@@ -46,6 +53,7 @@ public class WxMpCustomMessage implements Serializable {
* {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_MUSIC}
* {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_VIDEO}
* {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_NEWS}
* {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_WXCARD}
* </pre>
* @param msgType
*/
@@ -94,24 +102,33 @@ public class WxMpCustomMessage implements Serializable {
public void setHqMusicUrl(String hqMusicUrl) {
this.hqMusicUrl = hqMusicUrl;
}

public String getCardId() {
return this.cardId;
}

public void setCardId(String cardId) {
this.cardId = cardId;
}

public List<WxArticle> getArticles() {
return this.articles;
}
public void setArticles(List<WxArticle> articles) {
this.articles = articles;
}
public String toJson() {
return WxMpGsonBuilder.INSTANCE.create().toJson(this);
}
public static class WxArticle {
private String title;
private String description;
private String url;
private String picUrl;
public String getTitle() {
return this.title;
}
@@ -136,9 +153,9 @@ public class WxMpCustomMessage implements Serializable {
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
}
/**
* 获得文本消息builder
*/
@@ -159,34 +176,41 @@ public class WxMpCustomMessage implements Serializable {
public static VoiceBuilder VOICE() {
return new VoiceBuilder();
}
/**
* 获得视频消息builder
*/
public static VideoBuilder VIDEO() {
return new VideoBuilder();
}
/**
* 获得音乐消息builder
*/
public static MusicBuilder MUSIC() {
return new MusicBuilder();
}
/**
* 获得图文消息builder
*/
public static NewsBuilder NEWS() {
return new NewsBuilder();
}


/**
* 获得卡券消息builder
*/
public static WxCardBuilder WXCARD() {
return new WxCardBuilder();
}

public String getKfAccount() {
return this.kfAccount;
}
public void setKfAccount(String kfAccount) {
this.kfAccount = kfAccount;
}
}

+ 1
- 3
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java Zobrazit soubor

@@ -7,9 +7,6 @@ import java.io.Serializable;
*/
public class WxMpTemplateData implements Serializable {

/**
*
*/
private static final long serialVersionUID = 6301835292940277870L;
private String name;
private String value;
@@ -48,6 +45,7 @@ public class WxMpTemplateData implements Serializable {
public String getColor() {
return this.color;
}

public void setColor(String color) {
this.color = color;
}


+ 60
- 6
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java Zobrazit soubor

@@ -1,17 +1,14 @@
package me.chanjar.weixin.mp.bean;

import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class WxMpTemplateMessage implements Serializable {
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

/**
*
*/
public class WxMpTemplateMessage implements Serializable {
private static final long serialVersionUID = 5063374783759519418L;

private String toUser;
private String templateId;
private String url;
@@ -65,4 +62,61 @@ public class WxMpTemplateMessage implements Serializable {
public String toJson() {
return WxMpGsonBuilder.INSTANCE.create().toJson(this);
}

public static WxMpTemplateMessageBuilder builder() {
return new WxMpTemplateMessageBuilder();
}

public static class WxMpTemplateMessageBuilder {
private String toUser;
private String templateId;
private String url;
private String topColor;
private List<WxMpTemplateData> data = new ArrayList<>();

public WxMpTemplateMessageBuilder toUser(String toUser) {
this.toUser = toUser;
return this;
}

public WxMpTemplateMessageBuilder templateId(String templateId) {
this.templateId = templateId;
return this;
}

public WxMpTemplateMessageBuilder url(String url) {
this.url = url;
return this;
}

public WxMpTemplateMessageBuilder topColor(String topColor) {
this.topColor = topColor;
return this;
}

public WxMpTemplateMessageBuilder data(List<WxMpTemplateData> data) {
this.data = data;
return this;
}

public WxMpTemplateMessageBuilder from(WxMpTemplateMessage origin) {
this.toUser(origin.toUser);
this.templateId(origin.templateId);
this.url(origin.url);
this.topColor(origin.topColor);
this.data(origin.data);
return this;
}

public WxMpTemplateMessage build() {
WxMpTemplateMessage m = new WxMpTemplateMessage();
m.toUser = this.toUser;
m.templateId = this.templateId;
m.url = this.url;
m.topColor = this.topColor;
m.data = this.data;
return m;
}
}

}

+ 32
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/WxCardBuilder.java Zobrazit soubor

@@ -0,0 +1,32 @@
package me.chanjar.weixin.mp.bean.custombuilder;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.bean.WxMpCustomMessage;

/**
* 卡券消息builder
* <pre>
* 用法: WxMpCustomMessage m = WxMpCustomMessage.WXCARD().cardId(...).toUser(...).build();
* </pre>
* @author mgcnrx11
*
*/
public final class WxCardBuilder extends BaseBuilder<WxCardBuilder> {
private String cardId;

public WxCardBuilder() {
this.msgType = WxConsts.CUSTOM_MSG_WXCARD;
}

public WxCardBuilder cardId(String cardId) {
this.cardId = cardId;
return this;
}

@Override
public WxMpCustomMessage build() {
WxMpCustomMessage m = super.build();
m.setCardId(this.cardId);
return m;
}
}

weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java → weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayCallback.java Zobrazit soubor

@@ -1,4 +1,4 @@
package me.chanjar.weixin.mp.bean.result;
package me.chanjar.weixin.mp.bean.pay;

import java.io.Serializable;


weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java → weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayRefundResult.java Zobrazit soubor

@@ -1,4 +1,4 @@
package me.chanjar.weixin.mp.bean.result;
package me.chanjar.weixin.mp.bean.pay;

import java.io.Serializable;


weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java → weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPayResult.java Zobrazit soubor

@@ -1,7 +1,10 @@
package me.chanjar.weixin.mp.bean.result;
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;

/**
* <pre>
* 查询订单支付状态返回的结果
@@ -13,9 +16,11 @@ import java.io.Serializable;
* @author ukid
*/
public class WxMpPayResult implements Serializable {
/**
*
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}

private static final long serialVersionUID = -570934170727777190L;
private String return_code;
@@ -41,6 +46,16 @@ public class WxMpPayResult implements Serializable {
private String out_trade_no;
private String attach;
private String time_end;
/**
* 现金支付金额 cash_fee 是 Int 100 现金支付金额订单现金支付金额,详见支付金额
*/
private String cash_fee;
/**
* 现金支付货币类型 cash_fee_type 否
*
*/
private String cash_fee_type;

public String getReturn_code() {
return this.return_code;
@@ -226,32 +241,19 @@ public class WxMpPayResult implements Serializable {
this.trade_state_desc = trade_state_desc;
}

@Override
public String toString() {
return "WxMpPayResult{" +
"return_code=" + this.return_code +
", return_msg='" + this.return_msg + '\'' +
", appid='" + this.appid + '\'' +
", mch_id='" + this.mch_id + '\'' +
", nonce_str='" + this.nonce_str + '\'' +
", sign='" + this.sign + '\'' +
", result_code='" + this.result_code + '\'' +
", err_code='" + this.err_code + '\'' +
", err_code_des='" + this.err_code_des + '\'' +
", trade_state=" + this.trade_state +
", trade_state_desc=" + this.trade_state_desc +
", device_info='" + this.device_info + '\'' +
", openid='" + this.openid + '\'' +
", is_subscribe='" + this.is_subscribe + '\'' +
", trade_type='" + this.trade_type + '\'' +
", bank_type='" + this.bank_type + '\'' +
", total_fee='" + this.total_fee + '\'' +
", coupon_fee='" + this.coupon_fee + '\'' +
", fee_type='" + this.fee_type + '\'' +
", transaction_id='" + this.transaction_id + '\'' +
", out_trade_no='" + this.out_trade_no + '\'' +
", attach='" + this.attach + '\'' +
", time_end='" + this.time_end + '\'' +
'}';
public String getCash_fee() {
return this.cash_fee;
}

public void setCash_fee(String cash_fee) {
this.cash_fee = cash_fee;
}

public String getCash_fee_type() {
return this.cash_fee_type;
}

public void setCash_fee_type(String cash_fee_type) {
this.cash_fee_type = cash_fee_type;
}
}

+ 124
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxMpPrepayIdResult.java Zobrazit soubor

@@ -0,0 +1,124 @@
package me.chanjar.weixin.mp.bean.pay;

import java.io.Serializable;

/**
* <pre>
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
* </pre>
*
* @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;
}
}

weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java → weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxRedpackResult.java Zobrazit soubor

@@ -1,7 +1,10 @@
package me.chanjar.weixin.mp.bean.result;
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,38 +16,35 @@ import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("xml")
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;
@@ -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);
}
}

+ 296
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequest.java Zobrazit soubor

@@ -0,0 +1,296 @@
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
* 详见<a href="https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3">签名生成算法</a>
*/
@XStreamAlias("sign")
private String sign;

/**
* <pre>
* scene_id
* 场景id
* PRODUCT_1:商品促销
* PRODUCT_2:抽奖
* PRODUCT_3:虚拟物品兑奖
* PRODUCT_4:企业内部福利
* PRODUCT_5:渠道分润
* PRODUCT_6:保险回馈
* PRODUCT_7:彩票派奖
* PRODUCT_8:税务刮奖
* 非必填字段
* </pre>
*/
@XStreamAlias("scene_id")
private String sceneId;

/**
* <pre>
* risk_info
* 活动信息
* posttime:用户操作的时间戳
* mobile:业务系统账号的手机号,国家代码-手机号。不需要+号
* deviceid :mac 地址或者设备唯一标识
* clientversion :用户操作的客户端版本
* 把值为非空的信息用key=value进行拼接,再进行urlencode
* urlencode(posttime=xx&mobile=xx&deviceid=xx)
* 非必填字段
* </pre>
*/
@XStreamAlias("risk_info")
private String riskInfo;

/**
* <pre>
* consume_mch_id
* 资金授权商户号
* 资金授权商户号
* 服务商替特约商户发放时使用
* 非必填字段
* </pre>
*/
@XStreamAlias("consume_mch_id")
private String consumeMchId;

public String getMchBillno() {
return this.mchBillno;
}

public void setMchBillno(String mchBillno) {
this.mchBillno = mchBillno;
}

public String getSendName() {
return this.sendName;
}

public void setSendName(String sendName) {
this.sendName = sendName;
}

public String getReOpenid() {
return this.reOpenid;
}

public void setReOpenid(String reOpenid) {
this.reOpenid = reOpenid;
}

public Integer getTotalAmount() {
return this.totalAmount;
}

public void setTotalAmount(Integer totalAmount) {
this.totalAmount = totalAmount;
}

public Integer getTotalNum() {
return this.totalNum;
}

public void setTotalNum(Integer totalNum) {
this.totalNum = totalNum;
}

public String getAmtType() {
return this.amtType;
}

public void setAmtType(String amtType) {
this.amtType = amtType;
}

public String getWishing() {
return this.wishing;
}

public void setWishing(String wishing) {
this.wishing = wishing;
}

public String getClientIp() {
return this.clientIp;
}

public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}

public String getActName() {
return this.actName;
}

public void setActName(String actName) {
this.actName = actName;
}

public String getRemark() {
return this.remark;
}

public void setRemark(String remark) {
this.remark = remark;
}

public String getWxAppid() {
return this.wxAppid;
}

public void setWxAppid(String wxAppid) {
this.wxAppid = wxAppid;
}

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 getSceneId() {
return this.sceneId;
}

public void setSceneId(String sceneId) {
this.sceneId = sceneId;
}

public String getRiskInfo() {
return this.riskInfo;
}

public void setRiskInfo(String riskInfo) {
this.riskInfo = riskInfo;
}

public String getConsumeMchId() {
return this.consumeMchId;
}

public void setConsumeMchId(String consumeMchId) {
this.consumeMchId = consumeMchId;
}

}

+ 666
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderRequest.java Zobrazit soubor

@@ -0,0 +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;

/**
* <pre>
* 统一下单请求参数对象
* 参考文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
* 每个字段描述对应如下:
* <li>字段名
* <li>变量名
* <li>是否必填
* <li>类型
* <li>示例值
* <li>描述
* </pre>
* Created by Binary Wang on 2016/9/25.
* @author binarywang (https://github.com/binarywang)
*/
@XStreamAlias("xml")
public class WxUnifiedOrderRequest {

/**
* <pre>
* 公众账号ID
* appid
* 是
* String(32)
* wxd678efh567hg6787
* 微信分配的公众账号ID(企业号corpid即为此appId)
* </pre>
*/
@XStreamAlias("appid")
private String appid;

/**
* <pre>
* 商户号
* mch_id
* 是
* String(32)
* 1230000109
* 微信支付分配的商户号
* </pre>
*/
@XStreamAlias("mch_id")
private String mchId;

/**
* <pre>
* 设备号
* device_info
* 否
* String(32)
* 013467007045764
* 终端设备号(门店号或收银设备Id),注意:PC网页或公众号内支付请传"WEB"
* </pre>
*/
@XStreamAlias("device_info")
private String deviceInfo;

/**
* <pre>
* 随机字符串
* nonce_str
* 是
* String(32)
* 5K8264ILTKCH16CQ2502SI8ZNMTM67VS
* 随机字符串,不长于32位。推荐随机数生成算法
* </pre>
*/
@XStreamAlias("nonce_str")
private String nonceStr;

/**
* <pre>
* 签名
* sign
* 是
* String(32)
* C380BEC2BFD727A4B6845133519F3AD6
* 签名,详见签名生成算法
* </pre>
*/
@XStreamAlias("sign")
private String sign;

/**
* <pre>
* 商品描述
* body
* 是
* String(128)
* 腾讯充值中心-QQ会员充值
* 商品简单描述,该字段须严格按照规范传递,具体请见参数规定
* </pre>
*/
@Required
@XStreamAlias("body")
private String body;

/**
* <pre>
* 商品详情
* 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 商品描述信息
* </pre>
*/
@XStreamAlias("detail")
private String detail;

/**
* <pre>
* 附加数据
* attach
* 否
* String(127)
* 深圳分店
* 附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
* </pre>
*/
@XStreamAlias("attach")
private String attach;

/**
* <pre>
* 商户订单号
* out_trade_no
* 是
* String(32)
* 20150806125346
* 商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
* </pre>
*/
@Required
@XStreamAlias("out_trade_no")
private String outTradeNo;

/**
* <pre>
* 货币类型
* fee_type
* 否
* String(16)
* CNY
* 符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
* </pre>
*/
@XStreamAlias("fee_type")
private String feeType;

/**
* <pre>
* 总金额
* total_fee
* 是
* Int
* 888
* 订单总金额,单位为分,详见支付金额
* </pre>
*/
@Required
@XStreamAlias("total_fee")
private Integer totalFee;

/**
* <pre>
* 终端IP
* spbill_create_ip
* 是
* String(16)
* 123.12.12.123
* APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
* </pre>
*/
@Required
@XStreamAlias("spbill_create_ip")
private String spbillCreateIp;

/**
* <pre>
* 交易起始时间
* time_start
* 否
* String(14)
* 20091225091010
* 订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
* </pre>
*/
@XStreamAlias("time_start")
private String timeStart;

/**
* <pre>
* 交易结束时间
* time_expire
* 否
* String(14)
* 20091227091010
* 订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则
* 注意:最短失效时间间隔必须大于5分钟
* </pre>
*/
@XStreamAlias("time_expire")
private String timeExpire;

/**
* <pre>
* 商品标记
* goods_tag
* 否
* String(32)
* WXG
* 商品标记,代金券或立减优惠功能的参数,说明详见代金券或立减优惠
* </pre>
*/
@XStreamAlias("goods_tag")
private String goodsTag;

/**
* <pre>
* 通知地址
* notify_url
* 是
* String(256)
* http://www.weixin.qq.com/wxpay/pay.php
* 接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
* </pre>
*/
@Required
@XStreamAlias("notify_url")
private String notifyURL;

/**
* <pre>
* 交易类型
* trade_type
* 是
* String(16)
* JSAPI
* 取值如下:JSAPI,NATIVE,APP,详细说明见参数规定:
* JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里
* </pre>
*/
@Required
@XStreamAlias("trade_type")
private String tradeType;

/**
* <pre>
* 商品Id
* product_id
* 否
* String(32)
* 12235413214070356458058
* trade_type=NATIVE,此参数必传。此id为二维码中包含的商品Id,商户自行定义。
* </pre>
*/
@XStreamAlias("product_id")
private String productId;

/**
* <pre>
* 指定支付方式
* limit_pay
* 否
* String(32)
* no_credit no_credit--指定不能使用信用卡支付
* </pre>
*/
@XStreamAlias("limit_pay")
private String limitPay;

/**
* <pre>
* 用户标识
* openid
* 否
* String(128)
* oUpF8uMuAJO_M2pxb1Q9zNjWeS6o
* trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。
* openid如何获取,可参考【获取openid】。
* 企业号请使用【企业号OAuth2.0接口】获取企业号内成员userid,再调用【企业号userid转openid接口】进行转换
* </pre>
*/
@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;
}
}

}

+ 155
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/pay/WxUnifiedOrderResult.java Zobrazit soubor

@@ -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;

/**
* <pre>
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
* </pre>
*
* @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);
}
}

+ 0
- 128
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java Zobrazit soubor

@@ -1,128 +0,0 @@
package me.chanjar.weixin.mp.bean.result;

import java.io.Serializable;

/**
* <pre>
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"返回的结果
*
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
*
* </pre>
*
* @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;
}
}

+ 560
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java Zobrazit soubor

@@ -0,0 +1,560 @@
package me.chanjar.weixin.mp.bean.store;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;

import me.chanjar.weixin.common.annotation.Required;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

/**
* 门店基础信息
* @author binarywang(https://github.com/binarywang)
* Created by Binary Wang on 2016-09-23.
*/
public class WxMpStoreBaseInfo {
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}

public String toJson() {
JsonElement base_info = WxMpGsonBuilder.create().toJsonTree(this);
JsonObject jsonObject = new JsonObject();
jsonObject.add("base_info", base_info);
JsonObject business = new JsonObject();
business.add("business", jsonObject);
return business.toString();
}

public static class WxMpStorePhoto {
/**
* 照片url
*/
@SerializedName("photo_url")
private String photoUrl;
}

/**
* sid
* 商户自己的id,用于后续审核通过收到poi_id 的通知时,做对应关系。请商户自己保证唯一识别性
*/
@SerializedName("sid")
private String sid;

/**
* business_name
* 门店名称(仅为商户名,如:国美、麦当劳,不应包含地区、地址、分店名等信息,错误示例:北京国美)
* 不能为空,15个汉字或30个英文字符内
*/
@Required
@SerializedName("business_name")
private String businessName;

/**
* branch_name
* 分店名称(不应包含地区信息,不应与门店名有重复,错误示例:北京王府井店)
* 10个字以内
*/
@Required
@SerializedName("branch_name")
private String branchName;

/**
* province
* 门店所在的省份(直辖市填城市名,如:北京市)
* 10个字以内
*/
@Required
@SerializedName("province")
private String province;

/**
* city
* 门店所在的城市
* 10个字以内
*/
@Required
@SerializedName("city")
private String city;

/**
* district
* 门店所在地区
* 10个字以内
*/
@Required
@SerializedName("district")
private String district;

/**
* address
* 门店所在的详细街道地址(不要填写省市信息)
* (东莞等没有“区”行政区划的城市,该字段可不必填写。其余城市必填。)
*/
@Required
@SerializedName("address")
private String address;

/**
* telephone
* 门店的电话(纯数字,区号、分机号均由“-”隔开)
*/
@Required
@SerializedName("telephone")
private String telephone;

/**
* categories
* 门店的类型(不同级分类用“,”隔开,如:美食,川菜,火锅。详细分类参见附件:微信门店类目表)
*/
@Required
@SerializedName("categories")
private String[] categories;

/**
* offsetType
* 坐标类型,1 为火星坐标(目前只能选1)
*/
@Required
@SerializedName("offset_type")
private Integer offsetType = 1;

/**
* longitude
* 门店所在地理位置的经度
*/
@Required
@SerializedName("longitude")
private BigDecimal longitude;

/**
* latitude
* 门店所在地理位置的纬度(经纬度均为火星坐标,最好选用腾讯地图标记的坐标)
*/
@Required
@SerializedName("latitude")
private BigDecimal latitude;

/**
* photo_list
* 图片列表,url 形式,可以有多张图片,尺寸为 640*340px。必须为上一接口生成的url。
* 图片内容不允许与门店不相关,不允许为二维码、员工合照(或模特肖像)、营业执照、无门店正门的街景、地图截图、公交地铁站牌、菜单截图等
*/
@SerializedName("photo_list")
private List<WxMpStorePhoto> photos;

/**
* recommend
* 推荐品,餐厅可为推荐菜;酒店为推荐套房;景点为推荐游玩景点等,针对自己行业的推荐内容
* 200字以内
*/
@SerializedName("recommend")
private String recommend;

/**
* special
* 特色服务,如免费wifi,免费停车,送货上门等商户能提供的特色功能或服务
*/
@SerializedName("special")
private String special;

/**
* introduction
* 商户简介,主要介绍商户信息等
* 300字以内
*/
@SerializedName("introduction")
private String introduction;

/**
* open_time
* 营业时间,24 小时制表示,用“-”连接,如 8:00-20:00
*/
@SerializedName("open_time")
private String openTime;

/**
* avg_price
* 人均价格,大于0 的整数
*/
@SerializedName("avg_price")
private Integer avgPrice;

/**
* 门店是否可用状态。1 表示系统错误、2 表示审核中、3 审核通过、4 审核驳回。当该字段为1、2、4 状态时,poi_id 为空
*/
@SerializedName("available_state")
private Integer availableState;

/**
* 扩展字段是否正在更新中。1 表示扩展字段正在更新中,尚未生效,不允许再次更新; 0 表示扩展字段没有在更新中或更新已生效,可以再次更新
*/
@SerializedName("update_status")
private Integer updateStatus;

/**
* 门店poi id
*/
@SerializedName("poi_id")
private String poiId;

public String getSid() {
return this.sid;
}

public void setSid(String sid) {
this.sid = sid;
}

public String getBusinessName() {
return this.businessName;
}

public void setBusinessName(String businessName) {
this.businessName = businessName;
}

public String getBranchName() {
return this.branchName;
}

public void setBranchName(String branchName) {
this.branchName = branchName;
}

public String getProvince() {
return this.province;
}

public void setProvince(String province) {
this.province = province;
}

public String getCity() {
return this.city;
}

public void setCity(String city) {
this.city = city;
}

public String getDistrict() {
return this.district;
}

public void setDistrict(String district) {
this.district = district;
}

public String getAddress() {
return this.address;
}

public void setAddress(String address) {
this.address = address;
}

public String getTelephone() {
return this.telephone;
}

public void setTelephone(String telephone) {
this.telephone = telephone;
}

public String[] getCategories() {
return this.categories;
}

public void setCategories(String[] categories) {
this.categories = categories;
}

public Integer getOffsetType() {
return this.offsetType;
}

public void setOffsetType(Integer offsetType) {
this.offsetType = offsetType;
}

public BigDecimal getLongitude() {
return this.longitude;
}

public void setLongitude(BigDecimal longitude) {
this.longitude = longitude;
}

public BigDecimal getLatitude() {
return this.latitude;
}

public void setLatitude(BigDecimal latitude) {
this.latitude = latitude;
}

public List<WxMpStorePhoto> getPhotos() {
return this.photos;
}

public void setPhotos(List<WxMpStorePhoto> photos) {
this.photos = photos;
}

public String getRecommend() {
return this.recommend;
}

public void setRecommend(String recommend) {
this.recommend = recommend;
}

public String getSpecial() {
return this.special;
}

public void setSpecial(String special) {
this.special = special;
}

public String getIntroduction() {
return this.introduction;
}

public void setIntroduction(String introduction) {
this.introduction = introduction;
}

public String getOpenTime() {
return this.openTime;
}

public void setOpenTime(String openTime) {
this.openTime = openTime;
}

public Integer getAvgPrice() {
return this.avgPrice;
}

public void setAvgPrice(Integer avgPrice) {
this.avgPrice = avgPrice;
}

public Integer getAvailableState() {
return this.availableState;
}

public void setAvailableState(Integer availableState) {
this.availableState = availableState;
}

public Integer getUpdateStatus() {
return this.updateStatus;
}

public void setUpdateStatus(Integer updateStatus) {
this.updateStatus = updateStatus;
}

public String getPoiId() {
return this.poiId;
}

public void setPoiId(String poiId) {
this.poiId = poiId;
}

public static WxMpStoreBaseInfoBuilder builder() {
return new WxMpStoreBaseInfoBuilder();
}

public static class WxMpStoreBaseInfoBuilder {
private String sid;
private String businessName;
private String branchName;
private String province;
private String city;
private String district;
private String address;
private String telephone;
private String[] categories;
private Integer offsetType;
private BigDecimal longitude;
private BigDecimal latitude;
private List<WxMpStorePhoto> photos;
private String recommend;
private String special;
private String introduction;
private String openTime;
private Integer avgPrice;
private Integer availableState;
private Integer updateStatus;
private String poiId;

public WxMpStoreBaseInfoBuilder sid(String sid) {
this.sid = sid;
return this;
}

public WxMpStoreBaseInfoBuilder businessName(String businessName) {
this.businessName = businessName;
return this;
}

public WxMpStoreBaseInfoBuilder branchName(String branchName) {
this.branchName = branchName;
return this;
}

public WxMpStoreBaseInfoBuilder province(String province) {
this.province = province;
return this;
}

public WxMpStoreBaseInfoBuilder city(String city) {
this.city = city;
return this;
}

public WxMpStoreBaseInfoBuilder district(String district) {
this.district = district;
return this;
}

public WxMpStoreBaseInfoBuilder address(String address) {
this.address = address;
return this;
}

public WxMpStoreBaseInfoBuilder telephone(String telephone) {
this.telephone = telephone;
return this;
}

public WxMpStoreBaseInfoBuilder categories(String[] categories) {
this.categories = categories;
return this;
}

public WxMpStoreBaseInfoBuilder offsetType(Integer offsetType) {
this.offsetType = offsetType;
return this;
}

public WxMpStoreBaseInfoBuilder longitude(BigDecimal longitude) {
this.longitude = longitude;
return this;
}

public WxMpStoreBaseInfoBuilder latitude(BigDecimal latitude) {
this.latitude = latitude;
return this;
}

public WxMpStoreBaseInfoBuilder photos(List<WxMpStorePhoto> photos) {
this.photos = photos;
return this;
}

public WxMpStoreBaseInfoBuilder recommend(String recommend) {
this.recommend = recommend;
return this;
}

public WxMpStoreBaseInfoBuilder special(String special) {
this.special = special;
return this;
}

public WxMpStoreBaseInfoBuilder introduction(String introduction) {
this.introduction = introduction;
return this;
}

public WxMpStoreBaseInfoBuilder openTime(String openTime) {
this.openTime = openTime;
return this;
}

public WxMpStoreBaseInfoBuilder avgPrice(Integer avgPrice) {
this.avgPrice = avgPrice;
return this;
}

public WxMpStoreBaseInfoBuilder availableState(Integer availableState) {
this.availableState = availableState;
return this;
}

public WxMpStoreBaseInfoBuilder updateStatus(Integer updateStatus) {
this.updateStatus = updateStatus;
return this;
}

public WxMpStoreBaseInfoBuilder poiId(String poiId) {
this.poiId = poiId;
return this;
}

public WxMpStoreBaseInfoBuilder from(WxMpStoreBaseInfo origin) {
this.sid(origin.sid);
this.businessName(origin.businessName);
this.branchName(origin.branchName);
this.province(origin.province);
this.city(origin.city);
this.district(origin.district);
this.address(origin.address);
this.telephone(origin.telephone);
this.categories(origin.categories);
this.offsetType(origin.offsetType);
this.longitude(origin.longitude);
this.latitude(origin.latitude);
this.photos(origin.photos);
this.recommend(origin.recommend);
this.special(origin.special);
this.introduction(origin.introduction);
this.openTime(origin.openTime);
this.avgPrice(origin.avgPrice);
this.availableState(origin.availableState);
this.updateStatus(origin.updateStatus);
this.poiId(origin.poiId);
return this;
}

public WxMpStoreBaseInfo build() {
WxMpStoreBaseInfo m = new WxMpStoreBaseInfo();
m.sid = this.sid;
m.businessName = this.businessName;
m.branchName = this.branchName;
m.province = this.province;
m.city = this.city;
m.district = this.district;
m.address = this.address;
m.telephone = this.telephone;
m.categories = this.categories;
m.offsetType = this.offsetType;
m.longitude = this.longitude;
m.latitude = this.latitude;
m.photos = this.photos;
m.recommend = this.recommend;
m.special = this.special;
m.introduction = this.introduction;
m.openTime = this.openTime;
m.avgPrice = this.avgPrice;
m.availableState = this.availableState;
m.updateStatus = this.updateStatus;
m.poiId = this.poiId;
return m;
}
}

}

+ 29
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java Zobrazit soubor

@@ -0,0 +1,29 @@
/**
* Copyright(c) 2011-2016 by UCredit Inc.
* All Rights Reserved
*/
package me.chanjar.weixin.mp.bean.store;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.google.gson.annotations.SerializedName;

public class WxMpStoreInfo {
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}

@SerializedName("base_info")
private WxMpStoreBaseInfo baseInfo;

public WxMpStoreBaseInfo getBaseInfo() {
return this.baseInfo;
}

public void setBaseInfo(WxMpStoreBaseInfo baseInfo) {
this.baseInfo = baseInfo;
}

}

+ 84
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java Zobrazit soubor

@@ -0,0 +1,84 @@
package me.chanjar.weixin.mp.bean.store;

import java.util.List;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.google.gson.annotations.SerializedName;

import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

/**
* 门店列表结果类
* @author binarywang(https://github.com/binarywang)
* Created by Binary Wang on 2016-09-27.
*
*/
public class WxMpStoreListResult {
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}

public static WxMpStoreListResult fromJson(String json) {
return WxMpGsonBuilder.create().fromJson(json, WxMpStoreListResult.class);
}

/**
* 错误码,0为正常
*/
@SerializedName("errcode")
private Integer errCode;

/**
* 错误信息
*/
@SerializedName("errmsg")
private String errMsg;

/**
* 门店信息列表
*/
@SerializedName("business_list")
private List<WxMpStoreInfo> businessList;

/**
* 门店信息总数
*/
@SerializedName("total_count")
private Integer totalCount;

public Integer getTotalCount() {
return this.totalCount;
}

public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}

public Integer getErrCode() {
return this.errCode;
}

public void setErrCode(Integer errCode) {
this.errCode = errCode;
}

public String getErrMsg() {
return this.errMsg;
}

public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}

public List<WxMpStoreInfo> getBusinessList() {
return this.businessList;
}

public void setBusinessList(List<WxMpStoreInfo> businessList) {
this.businessList = businessList;
}

}

+ 92
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java Zobrazit soubor

@@ -0,0 +1,92 @@
package me.chanjar.weixin.mp.bean.tag;

import com.google.gson.annotations.SerializedName;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.util.List;

/**
* 获取标签下粉丝列表的结果对象
* @author binarywang(https://github.com/binarywang)
* Created by Binary Wang on 2016-09-19.
*/
public class WxTagListUser {

public static WxTagListUser fromJson(String json) {
return WxMpGsonBuilder.create().fromJson(json,WxTagListUser.class);
}

public String toJson() {
return WxMpGsonBuilder.create().toJson(this);
}

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}

/**
*"count":2,这次获取的粉丝数量
*/
@SerializedName("count")
private Integer count;

/**
*"data" 粉丝列表
*/
@SerializedName("data")
private WxTagListUserData data;

/**
*"next_openid" 拉取列表最后一个用户的openid
*/
@SerializedName("next_openid")
private String nextOpenid;

public Integer getCount() {
return count;
}

public void setCount(Integer count) {
this.count = count;
}

public WxTagListUserData getData() {
return data;
}

public void setData(WxTagListUserData data) {
this.data = data;
}

public String getNextOpenid() {
return nextOpenid;
}

public void setNextOpenid(String nextOpenid) {
this.nextOpenid = nextOpenid;
}

public static class WxTagListUserData {
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}

/**
* openid 列表
*/
@SerializedName("openid")
private List<String> openidList;

public List<String> getOpenidList() {
return openidList;
}

public void setOpenidList(List<String> openidList) {
this.openidList = openidList;
}
}
}

+ 15
- 10
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java Zobrazit soubor

@@ -24,27 +24,32 @@ import java.io.IOException;
public class MediaImgUploadRequestExecutor implements RequestExecutor<WxMediaImgUploadResult, File> {
@Override
public WxMediaImgUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File data) throws WxErrorException, IOException {
if (data == null) {
throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build());
}

HttpPost httpPost = new HttpPost(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(config);
}
if (data != null) {
HttpEntity entity = MultipartEntityBuilder
.create()
.addBinaryBody("media", data)
.setMode(HttpMultipartMode.RFC6532)
.build();
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
}
HttpEntity entity = MultipartEntityBuilder
.create()
.addBinaryBody("media", data)
.setMode(HttpMultipartMode.RFC6532)
.build();
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}

return WxMediaImgUploadResult.fromJson(responseContent);
}
}
}
}

+ 6
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java Zobrazit soubor

@@ -75,6 +75,12 @@ public class WxMpCustomMessageGsonAdapter implements JsonSerializer<WxMpCustomMe
newsJsonObject.add("articles", articleJsonArray);
messageJson.add("news", newsJsonObject);
}

if (WxConsts.CUSTOM_MSG_WXCARD.equals(message.getMsgType())) {
JsonObject wxcard = new JsonObject();
wxcard.addProperty("card_id", message.getCardId());
messageJson.add("wxcard", wxcard);
}
if (StringUtils.isNotBlank(message.getKfAccount())){
JsonObject newsJsonObject = new JsonObject();


+ 4
- 46
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/ApiTestModule.java Zobrazit soubor

@@ -3,15 +3,12 @@ package me.chanjar.weixin.mp.api;
import java.io.IOException;
import java.io.InputStream;

import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.commons.lang3.builder.ToStringBuilder;

import com.google.inject.Binder;
import com.google.inject.Module;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;

import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

public class ApiTestModule implements Module {

@@ -19,8 +16,8 @@ public class ApiTestModule implements Module {
public void configure(Binder binder) {
try (InputStream is1 = ClassLoader
.getSystemResourceAsStream("test-config.xml")) {
WxXmlMpInMemoryConfigStorage config = fromXml(
WxXmlMpInMemoryConfigStorage.class, is1);
WxXmlMpInMemoryConfigStorage config = this
.fromXml(WxXmlMpInMemoryConfigStorage.class, is1);
WxMpServiceImpl wxService = new WxMpServiceImpl();
wxService.setWxMpConfigStorage(config);

@@ -32,50 +29,11 @@ public class ApiTestModule implements Module {
}

@SuppressWarnings("unchecked")
public static <T> T fromXml(Class<T> clazz, InputStream is) {
private <T> T fromXml(Class<T> clazz, InputStream is) {
XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", clazz);
xstream.processAnnotations(clazz);
return (T) xstream.fromXML(is);
}

@XStreamAlias("xml")
public static class WxXmlMpInMemoryConfigStorage
extends WxMpInMemoryConfigStorage {

private String openid;
private String kfAccount;
private String qrconnectRedirectUrl;

public String getOpenid() {
return this.openid;
}

public void setOpenid(String openid) {
this.openid = openid;
}

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}

public String getKfAccount() {
return this.kfAccount;
}

public void setKfAccount(String kfAccount) {
this.kfAccount = kfAccount;
}

public String getQrconnectRedirectUrl() {
return this.qrconnectRedirectUrl;
}

public void setQrconnectRedirectUrl(String qrconnectRedirectUrl) {
this.qrconnectRedirectUrl = qrconnectRedirectUrl;
}

}

}

+ 2
- 2
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMassMessageAPITest.java Zobrazit soubor

@@ -36,7 +36,7 @@ public class WxMpMassMessageAPITest {
@Test
public void testTextMassOpenIdsMessageSend() throws WxErrorException {
// 发送群发消息
ApiTestModule.WxXmlMpInMemoryConfigStorage configProvider = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService
WxXmlMpInMemoryConfigStorage configProvider = (WxXmlMpInMemoryConfigStorage) this.wxService
.getWxMpConfigStorage();
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MASS_MSG_TEXT);
@@ -53,7 +53,7 @@ public class WxMpMassMessageAPITest {
public void testMediaMassOpenIdsMessageSend(String massMsgType,
String mediaId) throws WxErrorException {
// 发送群发消息
ApiTestModule.WxXmlMpInMemoryConfigStorage configProvider = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService
WxXmlMpInMemoryConfigStorage configProvider = (WxXmlMpInMemoryConfigStorage) this.wxService
.getWxMpConfigStorage();
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(massMsgType);


+ 57
- 0
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxXmlMpInMemoryConfigStorage.java Zobrazit soubor

@@ -0,0 +1,57 @@
/**
* Copyright(c) 2011-2016 by UCredit Inc.
* All Rights Reserved
*/
package me.chanjar.weixin.mp.api;

import org.apache.commons.lang3.builder.ToStringBuilder;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("xml")
public class WxXmlMpInMemoryConfigStorage
extends WxMpInMemoryConfigStorage {

private String openid;
private String kfAccount;
private String qrconnectRedirectUrl;
private String templateId;

public String getOpenid() {
return this.openid;
}

public void setOpenid(String openid) {
this.openid = openid;
}

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}

public String getKfAccount() {
return this.kfAccount;
}

public void setKfAccount(String kfAccount) {
this.kfAccount = kfAccount;
}

public String getQrconnectRedirectUrl() {
return this.qrconnectRedirectUrl;
}

public void setQrconnectRedirectUrl(String qrconnectRedirectUrl) {
this.qrconnectRedirectUrl = qrconnectRedirectUrl;
}

public String getTemplateId() {
return this.templateId;
}

public void setTemplateId(String templateId) {
this.templateId = templateId;
}

}

+ 3
- 2
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImplTest.java Zobrazit soubor

@@ -3,6 +3,7 @@ package me.chanjar.weixin.mp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.ApiTestModule;
import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.bean.WxMpGroup;
import org.testng.Assert;
import org.testng.annotations.Guice;
@@ -48,13 +49,13 @@ public class WxMpGroupServiceImplTest {
}

public void testGroupQueryUserGroup() throws WxErrorException {
ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage();
WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage();
long groupid = this.wxService.getGroupService().userGetGroup(configStorage.getOpenid());
Assert.assertTrue(groupid != -1l);
}

public void testGroupMoveUser() throws WxErrorException {
ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage();
WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage();
this.wxService.getGroupService().userUpdateGroup(configStorage.getOpenid(), this.wxService.getGroupService().groupGet().get(3).getId());
}



+ 3
- 3
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImplTest.java Zobrazit soubor

@@ -14,7 +14,7 @@ import com.google.inject.Inject;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.ApiTestModule;
import me.chanjar.weixin.mp.api.ApiTestModule.WxXmlMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.bean.WxMpCustomMessage;
import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfAccountRequest;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfInfo;
@@ -38,7 +38,7 @@ public class WxMpKefuServiceImplTest {
protected WxMpServiceImpl wxService;

public void testSendCustomMessage() throws WxErrorException {
ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService
WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService
.getWxMpConfigStorage();
WxMpCustomMessage message = new WxMpCustomMessage();
message.setMsgType(WxConsts.CUSTOM_MSG_TEXT);
@@ -50,7 +50,7 @@ public class WxMpKefuServiceImplTest {
}

public void testSendCustomMessageWithKfAccount() throws WxErrorException {
ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService
WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService
.getWxMpConfigStorage();
WxMpCustomMessage message = new WxMpCustomMessage();
message.setMsgType(WxConsts.CUSTOM_MSG_TEXT);


+ 38
- 51
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImplTest.java Zobrazit soubor

@@ -1,26 +1,6 @@
package me.chanjar.weixin.mp.api.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

import com.google.inject.Inject;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
@@ -29,11 +9,17 @@ import me.chanjar.weixin.mp.api.ApiTestModule;
import me.chanjar.weixin.mp.bean.WxMpMaterial;
import me.chanjar.weixin.mp.bean.WxMpMaterialArticleUpdate;
import me.chanjar.weixin.mp.bean.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.result.WxMpMaterialCountResult;
import me.chanjar.weixin.mp.bean.result.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.result.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.result.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpMaterialVideoInfoResult;
import me.chanjar.weixin.mp.bean.result.*;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static org.junit.Assert.*;

/**
* 素材管理相关接口的测试
@@ -48,7 +34,7 @@ public class WxMpMaterialServiceImplTest {
@Inject
protected WxMpServiceImpl wxService;

private Map<String, Map<String, Object>> media_ids = new LinkedHashMap<>();
private Map<String, Map<String, Object>> mediaIds = new LinkedHashMap<>();
// 缩略图的id,测试上传图文使用
private String thumbMediaId = "";
// 单图文消息media_id
@@ -59,7 +45,7 @@ public class WxMpMaterialServiceImplTest {
private WxMpMaterialCountResult wxMaterialCountResultBeforeTest;

@DataProvider
public Object[][] uploadMedia() {
public Object[][] mediaFiles() {
return new Object[][] {
new Object[] { WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, "mm.jpeg" },
new Object[] { WxConsts.MEDIA_VOICE, WxConsts.FILE_MP3, "mm.mp3" },
@@ -68,7 +54,7 @@ public class WxMpMaterialServiceImplTest {
};
}

@Test(dataProvider = "uploadMedia")
@Test(dataProvider = "mediaFiles")
public void testUploadMaterial(String mediaType, String fileType, String fileName) throws WxErrorException, IOException {
if (this.wxMaterialCountResultBeforeTest == null) {
this.wxMaterialCountResultBeforeTest = this.wxService.getMaterialService()
@@ -104,7 +90,7 @@ public class WxMpMaterialServiceImplTest {
materialInfo.put("media_id", res.getMediaId());
materialInfo.put("length", tempFile.length());
materialInfo.put("filename", tempFile.getName());
this.media_ids.put(res.getMediaId(), materialInfo);
this.mediaIds.put(res.getMediaId(), materialInfo);

System.out.println(res);
}
@@ -172,18 +158,18 @@ public class WxMpMaterialServiceImplTest {
}

@Test(dependsOnMethods = {"testMaterialCount"}, dataProvider = "downloadMaterial")
public void testDownloadMaterial(String media_id) throws WxErrorException, IOException {
Map<String, Object> materialInfo = this.media_ids.get(media_id);
public void testDownloadMaterial(String mediaId) throws WxErrorException, IOException {
Map<String, Object> materialInfo = this.mediaIds.get(mediaId);
assertNotNull(materialInfo);
String filename = materialInfo.get("filename").toString();
if (filename.endsWith(".mp3") || filename.endsWith(".jpeg")) {
try (InputStream inputStream = this.wxService.getMaterialService()
.materialImageOrVoiceDownload(media_id)) {
.materialImageOrVoiceDownload(mediaId)) {
assertNotNull(inputStream);
}
}
if (filename.endsWith("mp4")) {
WxMpMaterialVideoInfoResult wxMaterialVideoInfoResult = this.wxService.getMaterialService().materialVideoInfo(media_id);
WxMpMaterialVideoInfoResult wxMaterialVideoInfoResult = this.wxService.getMaterialService().materialVideoInfo(mediaId);
assertNotNull(wxMaterialVideoInfoResult);
assertNotNull(wxMaterialVideoInfoResult.getDownUrl());
}
@@ -260,9 +246,9 @@ public class WxMpMaterialServiceImplTest {

@DataProvider
public Object[][] downloadMaterial() {
Object[][] params = new Object[this.media_ids.size()][];
Object[][] params = new Object[this.mediaIds.size()][];
int index = 0;
for (String mediaId : this.media_ids.keySet()) {
for (String mediaId : this.mediaIds.keySet()) {
params[index] = new Object[]{mediaId};
index++;
}
@@ -272,7 +258,7 @@ public class WxMpMaterialServiceImplTest {
@DataProvider
public Iterator<Object[]> allTestMaterial() {
List<Object[]> params = new ArrayList<>();
for (String mediaId : this.media_ids.keySet()) {
for (String mediaId : this.mediaIds.keySet()) {
params.add(new Object[]{mediaId});
}
params.add(new Object[]{this.singleNewsMediaId});
@@ -281,8 +267,8 @@ public class WxMpMaterialServiceImplTest {
}

// 以下为media接口的测试
private List<String> mediaIds = new ArrayList<>();
@Test(dataProvider="uploadMedia")
private List<String> mediaIdsToDownload = new ArrayList<>();
@Test(dataProvider="mediaFiles")
public void testUploadMedia(String mediaType, String fileType, String fileName) throws WxErrorException, IOException {
try(InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName)){
WxMediaUploadResult res = this.wxService.getMaterialService().mediaUpload(mediaType, fileType, inputStream);
@@ -290,31 +276,32 @@ public class WxMpMaterialServiceImplTest {
assertNotNull(res.getCreatedAt());
assertTrue(res.getMediaId() != null || res.getThumbMediaId() != null);

if (res.getMediaId() != null) {
this.mediaIds.add(res.getMediaId());
if (res.getMediaId() != null && !mediaType.equals(WxConsts.MEDIA_VIDEO)) {
//video 不支持下载,所以不加入
this.mediaIdsToDownload.add(res.getMediaId());
}

if (res.getThumbMediaId() != null) {
this.mediaIds.add(res.getThumbMediaId());
this.mediaIdsToDownload.add(res.getThumbMediaId());
}

System.out.println(res);
}
}

@Test(dependsOnMethods = { "testUploadMedia" }, dataProvider="downloadMedia")
public void testDownloadMedia(String media_id) throws WxErrorException {
File file = this.wxService.getMaterialService().mediaDownload(media_id);
assertNotNull(file);
System.out.println(file.getAbsolutePath());
}

@DataProvider
public Object[][] downloadMedia() {
Object[][] params = new Object[this.mediaIds.size()][];
for (int i = 0; i < this.mediaIds.size(); i++) {
params[i] = new Object[] { this.mediaIds.get(i) };
Object[][] params = new Object[this.mediaIdsToDownload.size()][];
for (int i = 0; i < this.mediaIdsToDownload.size(); i++) {
params[i] = new Object[] { this.mediaIdsToDownload.get(i) };
}
return params;
}

@Test(dependsOnMethods = { "testUploadMedia" }, dataProvider="downloadMedia")
public void testDownloadMedia(String mediaId) throws WxErrorException {
File file = this.wxService.getMaterialService().mediaDownload(mediaId);
assertNotNull(file);
System.out.println(file.getAbsolutePath());
}
}

+ 37
- 5
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImplTest.java Zobrazit soubor

@@ -1,19 +1,32 @@
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.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.ApiTestModule;
import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage;
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;

/**
* 测试支付相关接口
* Created by Binary Wang on 2016/7/28.
* @author binarywang (https://github.com/binarywang)
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxMpPayServiceImplTest {
@Test
public void testGetPrepayId() throws Exception {

}
@Inject
protected WxMpServiceImpl wxService;

@Test
public void testGetPrepayId1() throws Exception {
public void testGetPrepayId() throws Exception {

}

@@ -54,7 +67,26 @@ public class WxMpPayServiceImplTest {

@Test
public void testSendRedpack() throws Exception {

WxSendRedpackRequest request = new WxSendRedpackRequest();
request.setActName("abc");
request.setClientIp("aaa");
request.setMchBillno("aaaa");
request
.setReOpenid(((WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage()).getOpenid());
WxRedpackResult redpackResult = this.wxService.getPayService().sendRedpack(request);
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("JSAPI").openid("122").outTradeNo("111111").build());
System.err.println(result);
}
}

+ 19
- 4
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImplTest.java Zobrazit soubor

@@ -1,5 +1,8 @@
package me.chanjar.weixin.mp.api.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
@@ -7,8 +10,11 @@ import org.testng.annotations.Test;
import com.google.inject.Inject;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.ApiTestModule;
import me.chanjar.weixin.mp.api.ApiTestModule.WxXmlMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.bean.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.WxMpTemplateMessage;

@Test
@Guice(modules = ApiTestModule.class)
@@ -82,9 +88,18 @@ public class WxMpServiceImplTest {
Assert.fail("Not yet implemented");
}

@Test
public void testTemplateSend() {
Assert.fail("Not yet implemented");
@Test(invocationCount = 100, threadPoolSize = 30)
public void testTemplateSend() throws WxErrorException {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService
.getWxMpConfigStorage();
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(configStorage.getOpenid())
.templateId(configStorage.getTemplateId()).build();
templateMessage.addWxMpTemplateData(
new WxMpTemplateData("first", dateFormat.format(new Date())));
this.wxService.templateSend(templateMessage);
}

@Test


+ 60
- 0
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImplTest.java Zobrazit soubor

@@ -0,0 +1,60 @@
/**
* Copyright(c) 2011-2016 by UCredit Inc.
* All Rights Reserved
*/
package me.chanjar.weixin.mp.api.impl;

import static org.junit.Assert.assertNotNull;

import java.math.BigDecimal;
import java.util.List;

import org.testng.annotations.Guice;
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.store.WxMpStoreBaseInfo;
import me.chanjar.weixin.mp.bean.store.WxMpStoreInfo;
import me.chanjar.weixin.mp.bean.store.WxMpStoreListResult;

/**
* @author 王彬 (Binary Wang)
*
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxMpStoreServiceImplTest {
@Inject
private WxMpServiceImpl wxMpService;

/**
* Test method for {@link me.chanjar.weixin.mp.api.impl.WxMpStoreServiceImpl#add(me.chanjar.weixin.mp.bean.store.WxMpStoreBaseInfo)}.
* @throws WxErrorException
*/
public void testAdd() throws WxErrorException {
this.wxMpService.getStoreService()
.add(WxMpStoreBaseInfo.builder().businessName("haha").branchName("abc")
.province("aaa").district("aaa").telephone("122").address("abc")
.categories(new String[] { "美食,江浙菜" })
.longitude(new BigDecimal("115.32375"))
.latitude(new BigDecimal("25.097486")).city("aaa").offsetType(1)
.build());
}

public void testList() throws WxErrorException {
WxMpStoreListResult result = this.wxMpService.getStoreService().list(0, 10);
assertNotNull(result);
System.err.println(result);
}

public void testListAll() throws WxErrorException {
List<WxMpStoreInfo> list = this.wxMpService.getStoreService().listAll();
assertNotNull(list);
System.err.println(list.size());
System.err.println(list);
}

}

+ 4
- 3
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserBlacklistServiceImplTest.java Zobrazit soubor

@@ -1,6 +1,7 @@
package me.chanjar.weixin.mp.api.impl;

import me.chanjar.weixin.mp.api.ApiTestModule;
import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.bean.result.WxMpUserBlacklistGetResult;
import org.testng.Assert;
import org.testng.annotations.Guice;
@@ -21,7 +22,7 @@ public class WxMpUserBlacklistServiceImplTest {

@Test
public void testGetBlacklist() throws Exception {
ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService
WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService
.getWxMpConfigStorage();
WxMpUserBlacklistGetResult wxMpUserBlacklistGetResult = this.wxService.getBlackListService().getBlacklist(configStorage.getOpenid());
Assert.assertNotNull(wxMpUserBlacklistGetResult);
@@ -33,7 +34,7 @@ public class WxMpUserBlacklistServiceImplTest {

@Test
public void testPushToBlacklist() throws Exception {
ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService
WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService
.getWxMpConfigStorage();
List<String> openidList = new ArrayList<>();
openidList.add(configStorage.getOpenid());
@@ -42,7 +43,7 @@ public class WxMpUserBlacklistServiceImplTest {

@Test
public void testPullFromBlacklist() throws Exception {
ApiTestModule.WxXmlMpInMemoryConfigStorage configStorage = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService
WxXmlMpInMemoryConfigStorage configStorage = (WxXmlMpInMemoryConfigStorage) this.wxService
.getWxMpConfigStorage();
List<String> openidList = new ArrayList<>();
openidList.add(configStorage.getOpenid());


+ 3
- 2
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java Zobrazit soubor

@@ -8,6 +8,7 @@ import com.google.inject.Inject;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.ApiTestModule;
import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;

@@ -25,12 +26,12 @@ public class WxMpUserServiceImplTest {
protected WxMpServiceImpl wxService;

public void testUserUpdateRemark() throws WxErrorException {
ApiTestModule.WxXmlMpInMemoryConfigStorage configProvider = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage();
WxXmlMpInMemoryConfigStorage configProvider = (WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage();
this.wxService.getUserService().userUpdateRemark(configProvider.getOpenid(), "测试备注名");
}

public void testUserInfo() throws WxErrorException {
ApiTestModule.WxXmlMpInMemoryConfigStorage configProvider = (ApiTestModule.WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage();
WxXmlMpInMemoryConfigStorage configProvider = (WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage();
WxMpUser user = this.wxService.getUserService().userInfo(configProvider.getOpenid(), null);
Assert.assertNotNull(user);
System.out.println(user);


+ 30
- 8
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImplTest.java Zobrazit soubor

@@ -1,15 +1,15 @@
package me.chanjar.weixin.mp.api.impl;

import java.util.List;

import com.google.inject.Inject;
import me.chanjar.weixin.mp.api.ApiTestModule;
import me.chanjar.weixin.mp.api.WxXmlMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.bean.tag.WxTagListUser;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;
import org.testng.Assert;
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.tag.WxUserTag;
import java.util.List;

/**
*
@@ -22,7 +22,7 @@ public class WxMpUserTagServiceImplTest {
@Inject
protected WxMpServiceImpl wxService;

private Integer tagId;
private Integer tagId = 2;

@Test
public void testTagCreate() throws Exception {
@@ -55,4 +55,26 @@ public class WxMpUserTagServiceImplTest {
Assert.assertTrue(res);
}

}
@Test
public void testTagListUser() throws Exception {
WxTagListUser res = this.wxService.getUserTagService().tagListUser(this.tagId, null);
System.out.println(res);
Assert.assertNotNull(res);
}

@Test
public void testBatchUntagging() throws Exception {
String[] openids = new String[]{((WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage()).getOpenid()};
boolean res = this.wxService.getUserTagService().batchUntagging(this.tagId, openids);
System.out.println(res);
Assert.assertTrue(res);
}

@Test
public void testUserTagList() throws Exception {
List<Integer> res = this.wxService.getUserTagService().userTagList(
((WxXmlMpInMemoryConfigStorage) this.wxService.getWxMpConfigStorage()).getOpenid());
System.out.println(res);
Assert.assertNotNull(res);
}
}

+ 1
- 1
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/WxRedpackResultTest.java Zobrazit soubor

@@ -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 {



+ 33
- 0
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/pay/WxSendRedpackRequestTest.java Zobrazit soubor

@@ -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<String, Reflect> 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());
}
}

}

}

+ 1
- 0
weixin-java-mp/src/test/resources/test-config.sample.xml Zobrazit soubor

@@ -6,6 +6,7 @@
<accessToken>可以不填写</accessToken>
<expiresTime>可以不填写</expiresTime>
<openid>某个加你公众号的用户的openId</openid>
<templateId>模版消息的模版ID</templateId>
<oauth2redirectUri>网页授权获取用户信息回调地址</oauth2redirectUri>
<qrconnectRedirectUrl>网页应用授权登陆回调地址</qrconnectRedirectUrl>
<kfAccount>完整客服账号,格式为:账号前缀@公众号微信号</kfAccount>


Načítá se…
Zrušit
Uložit