2
0
mirror of https://gitee.com/hotlcc/wechat4j.git synced 2026-01-15 15:21:56 +08:00

39 Commits

Author SHA1 Message Date
Allen
3749cdbc21 !14 升级版本号[0.2.4->0.2.5]
Merge pull request !14 from Allen/feature/20180914
2019-04-22 11:24:56 +08:00
Allen
7de2bae4cc [update] 1.调整了发送消息相关方法的名称;2.新增获取联系人头像数据的方法; 2019-04-22 11:22:58 +08:00
Allen
166db64b01 [update] 微信API文档修正 2019-04-18 17:11:43 +08:00
Allen
81ab8dd81c [update] 方法命名修改 2019-04-17 10:39:36 +08:00
Allen
433e342ea0 !13 [update] 新增视频消息支持
Merge pull request !13 from Allen/feature/20180914
2019-04-17 10:24:33 +08:00
Allen
c8f21dbdc9 [update] 新增视频消息发送 2019-04-17 10:23:39 +08:00
Allen
4facae51c9 !12 升级版本号[0.2.3->0.2.4]
Merge pull request !12 from Allen/feature/20180914
2019-04-17 10:21:18 +08:00
Allen
952040f6a6 [升级版本] 0.2.3 -> 0.2.4 2019-04-17 10:19:19 +08:00
Allen
a8a2b453ec [update] 新增视频消息发送 2019-04-17 10:18:22 +08:00
Allen
11f3b99524 [update] 日志框架使用方式变更 2019-04-16 16:51:55 +08:00
Allen
9302b2e68c [update] WebWeixinApi改为WebWeixinApiUtil工具类方式 2019-04-16 16:46:03 +08:00
Allen
53e7fedc6c !11 升级版本号[0.2.2->0.2.3]
Merge pull request !11 from Allen/feature/20180914
2019-04-09 11:42:30 +08:00
Allen
31f84b62bf 升级版本号[0.2.2->0.2.3] 2019-04-09 11:41:26 +08:00
Allen
c9b7c7c4bb !10 升级版本号[0.2.2->0.2.3]
Merge pull request !10 from Allen/feature/20180914
2019-04-09 11:38:40 +08:00
Allen
a98b21b23c 支持Anti996协议 2019-04-09 11:35:30 +08:00
Allen
9f36722bc4 更新 README.md 2019-03-31 00:56:54 +08:00
Allen
533f936ac0 !9 v0.2.2
Merge pull request !9 from Allen/feature/20180914
2018-09-19 17:02:15 +08:00
Allen
f0b1690023 提交代码:升级版本号[0.2.1->0.2.2] 2018-09-19 16:57:58 +08:00
Allen
743d40c847 提交代码:修复参数位置错误的验证bug 2018-09-19 16:57:07 +08:00
Allen
5c9aee686e !8 v0.2.1
Merge pull request !8 from Allen/feature/20180914
2018-09-18 14:43:15 +08:00
Allen
0d8b3c78e7 提交代码:升级版本号[0.2.0->0.2.1] 2018-09-18 14:40:46 +08:00
Allen
cf228920ee 提交代码:代码规范性调整 2018-09-18 14:39:55 +08:00
Allen
4eebb0ab10 提交代码:修改潜在bug 2018-09-14 21:48:43 +08:00
Allen
ce21807e3b 提交代码:bug修复 2018-09-14 20:55:12 +08:00
Allen
cba6b34a16 提交代码:bug修复 2018-09-14 20:48:48 +08:00
Allen
1c57501c76 !7 v0.2.0
Merge pull request !7 from Allen/feature/20180914
2018-09-14 16:30:30 +08:00
Allen
ed6a842b8f 提交代码:更新readme文档 2018-09-14 16:29:03 +08:00
Allen
8120000809 !6 v0.2.0
Merge pull request !6 from Allen/feature/20180914
2018-09-14 16:23:05 +08:00
Allen
97e67e28e1 提交代码:web微信api文档修改 2018-09-14 16:21:39 +08:00
Allen
80538def1a !5 v0.2.0
Merge pull request !5 from Allen/feature/20180914
2018-09-14 16:19:36 +08:00
Allen
c6d1ca83f3 提交代码:升级版本号[0.1.2->0.2.0] 2018-09-14 16:16:31 +08:00
Allen
ab094dad76 提交代码:更新web微信api文档 2018-09-14 16:15:35 +08:00
Allen
59a95df99a 提交代码:新增发送图片方法;调整发送文本方法的参数; 2018-09-14 16:15:00 +08:00
Allen
5995be80ba !4 v0.1.2
Merge pull request !4 from Allen/feature/20180914
2018-09-14 10:54:08 +08:00
Allen
0c6356a71a 提交代码:升级版本号[0.1.1->0.1.2] 2018-09-14 10:50:13 +08:00
Allen
76a2fa0dc1 提交代码:添加发送文本消息(根据多种名称)的方法 2018-09-14 10:49:24 +08:00
Allen
560d47bb85 !3 v0.1.1
Merge pull request !3 from Allen/feature/20180914
2018-09-14 10:24:01 +08:00
Allen
b1572e2bc7 提交代码:升级版本号[0.1.0->0.1.1] 2018-09-14 10:20:28 +08:00
Allen
329eb96602 提交代码:调整了test目录的logback.xml 2018-09-14 10:16:35 +08:00
32 changed files with 1593 additions and 805 deletions

View File

@@ -6,11 +6,9 @@
码云主页:[https://gitee.com/hotlcc](https://gitee.com/hotlcc)
[![gitee](https://img.shields.io/badge/gitee-%40hotlcc-green.svg)](https://gitee.com/hotlcc)
[![gitee](https://img.shields.io/badge/github-%40hotlcc-blank.svg)](https://github.com/hotlcc)
[![toutiao](https://img.shields.io/badge/toutiao-%40Allen-red.svg)](https://www.toutiao.com/c/user/3341863552/#mid=51655113888)
[![@Allen on weibo](https://img.shields.io/badge/weibo-%40Allen-orange.svg)](https://weibo.com/hotloveu?is_hot=1)
[![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](http://www.apache.org/licenses/LICENSE-2.0.html)
[![License](https://img.shields.io/badge/license-Anti%20996-4EB1BA.svg)](https://raw.githubusercontent.com/996icu/996.ICU/master/LICENSE_CN)
<a href="https://996.icu"><img src="https://img.shields.io/badge/link-996.icu-red.svg"></a>
## Web微信API文档
@@ -19,10 +17,8 @@
## 简单使用
```java
WebWeixinApi api = new WebWeixinApi();
// 实例化微信客户端
Wechat wechat = new Wechat();
wechat.setWebWeixinApi(api);
// 自动登录
wechat.autoLogin();
```
@@ -33,14 +29,50 @@ wechat.autoLogin();
```java
// 通过userName发送文本消息
public JSONObject sendText(String content, String userName);
// 通过昵称发送消息
public JSONObject sendTextToNickName(String content, String nickName);
// 通过备注名发送消息
public JSONObject sendTextToRemarkName(String content, String remarkName);
JSONObject sendText(String content, String userName);
// 通过昵称发送文本消息
JSONObject sendTextToNickName(String content, String nickName);
// 通过备注名发送文本消息
JSONObject sendTextToRemarkName(String content, String remarkName);
// 发送文本消息(根据多种名称)
JSONObject sendText(String userName, String nickName, String remarkName, String content);
```
> 目前仅支持发送文本消息,更多消息类型支持尽请期待。
### 图片消息
```java
// 通过userName发送图片消息
JSONObject sendImage(String userName, byte[] mediaData, String mediaName, ContentType contentType);
JSONObject sendImage(String userName, File image);
// 通过昵称发送图片消息
JSONObject sendImageToNickName(String nickName, byte[] mediaData, String mediaName, ContentType contentType);
JSONObject sendImageToNickName(String nickName, File image);
// 通过备注名发送图片消息
JSONObject sendImageToRemarkName(String remarkName, byte[] mediaData, String mediaName, ContentType contentType);
JSONObject sendImageToRemarkName(String remarkName, File image);
// 发送图片消息(根据多种名称)
JSONObject sendImage(String userName, String nickName, String remarkName, byte[] mediaData, String mediaName, ContentType contentType);
JSONObject sendImage(String userName, String nickName, String remarkName, File image);
```
### 视频消息
```java
// 通过userName发送视频消息
JSONObject sendVideo(String userName, byte[] mediaData, String mediaName, ContentType contentType);
JSONObject sendVideo(String userName, File video);
// 通过昵称发送视频消息
JSONObject sendVideoToNickName(String nickName, byte[] mediaData, String mediaName, ContentType contentType);
JSONObject sendVideoToNickName(String nickName, File video);
// 通过备注名发送视频消息
JSONObject sendVideoToRemarkName(String remarkName, byte[] mediaData, String mediaName, ContentType contentType);
JSONObject sendVideoToRemarkName(String remarkName, File video);
// 发送视频消息(根据多种名称)
JSONObject sendVideo(String userName, String nickName, String remarkName, byte[] mediaData, String mediaName, ContentType contentType);
JSONObject sendVideo(String userName, String nickName, String remarkName, File video);
```
> 更多消息类型支持尽请期待。
## 消息处理器

View File

@@ -158,7 +158,7 @@ URL参数分析
FORM表单参数分析
|数名|示例值|描述|
|数名|示例值|描述|
|---|---|---|
|sid||登录时获取的;|
|uin||登录时获取的;|
@@ -924,7 +924,7 @@ POST参数分析
- 10002撤回消息
- SyncKey会暂存起来作为下一次请求的参数。
### 4.2、发送消息
### 4.2、发送文本消息
打开一个聊天界面,向好友发送一条消息,会发现产生如下 POST 请求:
@@ -996,3 +996,128 @@ POST参数分析
```
https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json
```
若文件较小则只会产生一个该请求若文件较大则会产生多个该请求。多个请求表示以分片的方式发送文件数据分片大小约为524288。
FORM表单参数分析
|参数名|示例值|描述|
|---|---|---|
|~~id~~|WU_FILE_0|页面文件组件ID非必须|
|~~name~~|bd00c8eed5c2cd522e69f38317b46903.jpg|文件名;非必须;|
|~~type~~|image/jpeg|文件的MimeType非必须|
|~~lastModifieDate~~||文件最后修改时间;非必须;|
|~~size~~|99785|文件大小;非必须;|
|chunks|3|文件分片数量;文件较大需要分片时必须;|
|chunk|0|文件分片序号从0开始文件较大需要分片时必须|
|mediatype|pic|文件类型图片为pic视频为video其它文件为doc必须|
|uploadmediarequest||JSON字符串必须|
|webwx_data_ticket||cookie中的数据必须|
|pass_ticket||登录时获取的;必须;|
|filename||文件二进制数据;必须;|
uploadmediarequest结构示例
```json
{
"UploadType": 2,
"BaseRequest": {
"Uin": 1245,
"Sid": "zxaODbK4ed",
"Skey": "@crypt_4f399da_3c7a87e93b7872bce",
"DeviceID": "e69688819413"
},
"ClientMediaId": 153686311,
"TotalLen": 87508,
"StartPos": 0,
"DataLen": 87508,
"MediaType": 4,
"FromUserName": "@6feb88ee01067121479f686",
"ToUserName": "@6feb88ee0106f67121479f686",
"FileMd5": "717d1dbb9833c7cdbdd09ac"
}
```
服务端返回数据:
```json
{
"BaseResponse": {
"Ret": 0,
"ErrMsg": ""
},
"MediaId": "@crypt_17ab5.................39bd9cfa9ab",
"StartPos": 99785,
"CDNThumbImgHeight": 56,
"CDNThumbImgWidth": 100,
"EncryFileName": "bd00c8e.....38317b46903.jpg"
}
```
上传成功后返回数据中会有MediaId如果是分片上传的则最后一个请求会返回MediaId。
### 4.4、发送图片消息
发送图片后紧接着4.3的是如下POST请求
```
https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket=xFAjPcq0eXh.......TYHHdHgVL52eHo%253D
```
URL参数分析
|数名|示例值|描述|
|---|---|---|
|pass_ticket|xFAjPcq0eXh.......TYHHdHgVL52eHo%253D|同前面获取的;|
POST的数据JSON
```json
{
"BaseRequest": {
"Uin": 16...245,
"Sid": "KvCP..../TNqh8",
"Skey": "@crypt_4fb399da......9f1b3d997c4b5eef82",
"DeviceID": "e2825...3652448"
},
"Msg": {
"Type": 3,
"MediaId": "@crypt_17ab5.................39bd9cfa9ab",
"Content": "",
"FromUserName": "@3641f45.......69bed57642",
"ToUserName": "@3641f454....9bed57642",
"LocalID": "153691....0527",
"ClientMsgId": "1536....390527"
},
"Scene": 0
}
```
POST参数分析
|Key|示例值|描述|
|---|---|---|
|BaseRequest||同上;|
|Msg.ClientMsgId||同LocalID|
|Msg.Content||消息内容消息为媒体时该值为媒体ID。|
|Msg.FromUserName||发送用户;|
|Msg.LocalID||13位时间戳+4位随机数|
|Msg.ToUserName||接收用户;|
|Msg.Type|3|消息类型同3.1中接收的消息类型;|
|Msg.MediaId||4.3接口中返回的MediaId|
|Scene|0|固定值;|
服务端返回数据:
```json
{
"BaseResponse": {
"Ret": 0,
"ErrMsg": ""
},
"MsgID": "28832......8291836",
"LocalID": "1536.....54390527"
}
```
Web微信发送图片需要先调4.3的接口将媒体文件上传到服务器然后再调4.4的接口发送图片的相关信息。

View File

@@ -6,7 +6,7 @@
<groupId>com.hotlcc</groupId>
<artifactId>wechat4j</artifactId>
<version>0.1.0</version>
<version>0.2.5</version>
<name>wechat4j</name>
<description>Wechat client for Java.</description>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
package com.hotlcc.wechat4j.enums;
import lombok.AllArgsConstructor;
/**
* 微信退出类型
*
* @author Allen
*/
@AllArgsConstructor
public enum ExitType {
ERROR_EXIT("错误退出"),
LOCAL_EXIT("本地退出"),
REMOTE_EXIT("远程退出");
private String desc;
}

View File

@@ -1,17 +0,0 @@
package com.hotlcc.wechat4j.enums;
/**
* 微信退出类型
*/
public enum ExitTypeEnum {
ERROR_EXIT("错误导致退出"),
LOCAL_EXIT("本次手动退出"),
REMOTE_EXIT("远程操作退出");
private String desc;
ExitTypeEnum(String desc) {
this.desc = desc;
}
}

View File

@@ -1,26 +1,23 @@
package com.hotlcc.wechat4j.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 等待确认登录的tip
*
* @author https://gitee.com/hotlcc
* @author Allen
*/
public enum LoginTipEnum {
@SuppressWarnings("unused")
@Getter
@AllArgsConstructor
public enum LoginTip {
TIP_0(0, "扫码登录"),
TIP_1(1, "确认登录");
private int code;
private String desc;
LoginTipEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
@Override
public String toString() {
return code + "";

View File

@@ -0,0 +1,22 @@
package com.hotlcc.wechat4j.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author Allen
* @version 1.0
* @date 2019/4/17 9:51
*/
@Getter
@AllArgsConstructor
public enum MediaType {
PICTURE(4, "pic"),
VIDEO(4, "video");
public static String REQUEST_KEY = "mediatype";
public static String REQUEST_JSON_KEY = "MediaType";
private Integer code;
private String value;
}

View File

@@ -1,11 +1,17 @@
package com.hotlcc.wechat4j.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 消息类型enum
*
* @author https://gitee.com/hotlcc
* @author Allen
*/
public enum MsgTypeEnum {
@SuppressWarnings({"unused"})
@AllArgsConstructor
@Getter
public enum MsgType {
TEXT_MSG(1, "文本消息"),
IMAGE_MSG(3, "图片消息"),
VOICE_MSG(34, "语音消息"),
@@ -25,19 +31,6 @@ public enum MsgTypeEnum {
SYSTEM_MSG(10000, "系统消息"),
WITHDRAW_MSG(10002, "撤回消息");
MsgTypeEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
private int code;
private String desc;
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}

View File

@@ -0,0 +1,35 @@
package com.hotlcc.wechat4j.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 操作系统enum
*
* @author Allen
*/
@Getter
@AllArgsConstructor
public enum OperatingSystem {
DARWIN("darwin"),
WINDOWS("windows"),
LINUX("linux"),
MAC_OS("mac"),
OTHER("other");
private String value;
public static OperatingSystem currentOperatingSystem() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains(OperatingSystem.DARWIN.getValue())) {
return OperatingSystem.DARWIN;
} else if (osName.contains(OperatingSystem.WINDOWS.getValue())) {
return OperatingSystem.WINDOWS;
} else if (osName.contains(OperatingSystem.LINUX.getValue())) {
return OperatingSystem.LINUX;
} else if (osName.contains(OperatingSystem.MAC_OS.getValue())) {
return OperatingSystem.MAC_OS;
}
return OperatingSystem.OTHER;
}
}

View File

@@ -1,38 +0,0 @@
package com.hotlcc.wechat4j.enums;
/**
* 操作系统enum
*
* @author https://gitee.com/hotlcc
*/
public enum OperatingSystemEnum {
DARWIN("darwin"),
WINDOWS("windows"),
LINUX("linux"),
MAC_OS("mac"),
OTHER("other");
private String value;
public String getValue() {
return value;
}
OperatingSystemEnum(String value) {
this.value = value;
}
public static OperatingSystemEnum currentOperatingSystem() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.indexOf(OperatingSystemEnum.DARWIN.getValue()) >= 0) {
return OperatingSystemEnum.DARWIN;
} else if (osName.indexOf(OperatingSystemEnum.WINDOWS.getValue()) >= 0) {
return OperatingSystemEnum.WINDOWS;
} else if (osName.indexOf(OperatingSystemEnum.LINUX.getValue()) >= 0) {
return OperatingSystemEnum.LINUX;
} else if (osName.indexOf(OperatingSystemEnum.MAC_OS.getValue()) >= 0) {
return OperatingSystemEnum.MAC_OS;
}
return OperatingSystemEnum.OTHER;
}
}

View File

@@ -1,6 +1,16 @@
package com.hotlcc.wechat4j.enums;
public enum RetcodeEnum {
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Ret代码
*
* @author Allen
*/
@AllArgsConstructor
@Getter
public enum Retcode {
RECODE_0(0, "正常"),
RECODE_1100(1100, "失败/登出微信"),
RECODE_1101(1101, "从其它设备登录微信");
@@ -8,18 +18,9 @@ public enum RetcodeEnum {
private int code;
private String desc;
RetcodeEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public static RetcodeEnum valueOf(int code) {
RetcodeEnum[] es = values();
for (RetcodeEnum e : es) {
public static Retcode valueOf(int code) {
Retcode[] es = values();
for (Retcode e : es) {
if (e.code == code) {
return e;
}

View File

@@ -1,6 +1,14 @@
package com.hotlcc.wechat4j.enums;
public enum SelectorEnum {
import lombok.AllArgsConstructor;
/**
* Selector代码
*
* @author Allen
*/
@AllArgsConstructor
public enum Selector {
SELECTOR_0(0, "正常"),
SELECTOR_2(2, "有新消息"),
SELECTOR_4(4, "目前发现修改了联系人备注会出现"),
@@ -10,18 +18,9 @@ public enum SelectorEnum {
private int code;
private String desc;
SelectorEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public static SelectorEnum valueOf(int code) {
SelectorEnum[] es = values();
for (SelectorEnum e : es) {
public static Selector valueOf(int code) {
Selector[] es = values();
for (Selector e : es) {
if (e.code == code) {
return e;
}

View File

@@ -1,39 +1,41 @@
package com.hotlcc.wechat4j.handler;
import com.hotlcc.wechat4j.Wechat;
import com.hotlcc.wechat4j.enums.ExitTypeEnum;
import com.hotlcc.wechat4j.enums.ExitType;
/**
* 退出事件处理器
*
* @author Allen
*/
public interface ExitEventHandler {
/**
* 针对所有类型的退出事件
*
* @param wechat
* @param type
* @param t
* @param wechat 微信客户端
* @param type 退出类型
* @param t 异常
*/
void handleAllType(Wechat wechat, ExitTypeEnum type, Throwable t);
void handleAllType(Wechat wechat, ExitType type, Throwable t);
/**
* 针对错误导致的退出事件
*
* @param wechat
* @param wechat 微信客户端
*/
void handleErrorExitEvent(Wechat wechat);
/**
* 针对远程人为导致的退出事件
*
* @param wechat
* @param wechat 微信客户端
*/
void handleRemoteExitEvent(Wechat wechat);
/**
* 针对本地任务导致的退出事件
*
* @param wechat
* @param wechat 微信客户端
*/
void handleLocalExitEvent(Wechat wechat);
}

View File

@@ -4,14 +4,16 @@ import com.hotlcc.wechat4j.Wechat;
import com.hotlcc.wechat4j.model.ReceivedMsg;
/**
* 接收消息处理器
* 接收消息的消息处理器
*
* @author Allen
*/
public interface ReceivedMsgHandler {
/**
* 处理所有类型的消息
*
* @param wechat
* @param msg
* @param wechat 微信客户端
* @param msg 接收的消息
*/
void handleAllType(Wechat wechat, ReceivedMsg msg);
}

View File

@@ -1,15 +1,26 @@
package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* AppInfo
*
* @author Allen
*/
@Getter
public final class AppInfo {
@Setter
public final class AppInfo implements Serializable {
private static final long serialVersionUID = 1L;
private AppInfo() {
}
@@ -22,10 +33,7 @@ public final class AppInfo {
if (info == null) {
return null;
}
AppInfo appInfo = new AppInfo();
appInfo.type = info.getInteger("Type");
appInfo.appID = info.getString("AppID");
return appInfo;
return JSON.toJavaObject(info, AppInfo.class);
}
public static List<AppInfo> valueOf(JSONArray infos) {

View File

@@ -5,12 +5,18 @@ import com.hotlcc.wechat4j.util.WechatUtil;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* 基本请求模型
*
* @author Allen
*/
@Getter
@Setter
public class BaseRequest {
public class BaseRequest implements Serializable {
private static final long serialVersionUID = 1L;
public BaseRequest() {
}

View File

@@ -0,0 +1,17 @@
package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
/**
* 媒体消息
*
* @author Allen
*/
@Getter
@Setter
public class MediaMessage extends WxMessage {
@JSONField(name = "MediaId")
private String mediaId;
}

View File

@@ -1,15 +1,21 @@
package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Getter
public final class ReceivedMsg {
@Setter
public final class ReceivedMsg implements Serializable {
private static final long serialVersionUID = 1L;
private ReceivedMsg() {
}
@@ -75,37 +81,7 @@ public final class ReceivedMsg {
return null;
}
ReceivedMsg receivedMsg = new ReceivedMsg();
receivedMsg.subMsgType = msg.getInteger("SubMsgType");
receivedMsg.voiceLength = msg.getLong("VoiceLength");
receivedMsg.fileName = msg.getString("FileName");
receivedMsg.imgHeight = msg.getLong("ImgHeight");
receivedMsg.toUserName = msg.getString("ToUserName");
receivedMsg.hasProductId = msg.getLong("HasProductId");
receivedMsg.imgStatus = msg.getInteger("ImgStatus");
receivedMsg.url = msg.getString("Url");
receivedMsg.imgWidth = msg.getInteger("ImgWidth");
receivedMsg.forwardFlag = msg.getInteger("ForwardFlag");
receivedMsg.status = msg.getInteger("Status");
receivedMsg.ticket = msg.getString("Ticket");
receivedMsg.recommendInfo = com.hotlcc.wechat4j.model.RecommendInfo.valueOf(msg.getJSONObject("RecommendInfo"));
receivedMsg.createTime = msg.getLong("CreateTime");
receivedMsg.newMsgId = msg.getLong("NewMsgId");
receivedMsg.msgType = msg.getInteger("MsgType");
receivedMsg.encryFileName = msg.getString("EncryFileName");
receivedMsg.msgId = msg.getString("MsgId");
receivedMsg.statusNotifyCode = msg.getInteger("StatusNotifyCode");
receivedMsg.appInfo = com.hotlcc.wechat4j.model.AppInfo.valueOf(msg.getJSONObject("AppInfo"));
receivedMsg.playLength = msg.getLong("PlayLength");
receivedMsg.mediaId = msg.getString("MediaId");
receivedMsg.content = msg.getString("Content");
receivedMsg.statusNotifyUserName = msg.getString("StatusNotifyUserName");
receivedMsg.fromUserName = msg.getString("FromUserName");
receivedMsg.oriContent = msg.getString("OriContent");
receivedMsg.fileSize = msg.getString("FileSize");
return receivedMsg;
return JSON.toJavaObject(msg, ReceivedMsg.class);
}
public static List<ReceivedMsg> valueOf(JSONArray msgs) {

View File

@@ -1,15 +1,26 @@
package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* RecommendInfo
*
* @author Allen
*/
@Getter
public final class RecommendInfo {
@Setter
public final class RecommendInfo implements Serializable {
private static final long serialVersionUID = 1L;
private RecommendInfo() {
}
@@ -47,24 +58,7 @@ public final class RecommendInfo {
return null;
}
RecommendInfo recommendInfo = new RecommendInfo();
recommendInfo.ticket = info.getString("Ticket");
recommendInfo.userName = info.getString("UserName");
recommendInfo.sex = info.getInteger("Sex");
recommendInfo.attrStatus = info.getInteger("AttrStatus");
recommendInfo.city = info.getString("City");
recommendInfo.nickName = info.getString("NickName");
recommendInfo.scene = info.getInteger("Scene");
recommendInfo.province = info.getString("Province");
recommendInfo.content = info.getString("Content");
recommendInfo.alias = info.getString("Alias");
recommendInfo.signature = info.getString("Signature");
recommendInfo.opCode = info.getInteger("OpCode");
recommendInfo.qqNum = info.getLong("QQNum");
recommendInfo.verifyFlag = info.getInteger("VerifyFlag");
return recommendInfo;
return JSON.toJavaObject(info, RecommendInfo.class);
}
public static List<RecommendInfo> valueOf(JSONArray infos) {

View File

@@ -1,18 +1,26 @@
package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 微信用户信息
*
* @author Allen
*/
@Getter
public final class UserInfo {
@Setter
public final class UserInfo implements Serializable {
private static final long serialVersionUID = 1L;
private UserInfo() {
}
@@ -84,41 +92,7 @@ public final class UserInfo {
return null;
}
UserInfo userInfo = new UserInfo();
userInfo.uin = info.getLong("Uin");
userInfo.nickName = info.getString("NickName");
userInfo.headImgUrl = info.getString("HeadImgUrl");
userInfo.contactFlag = info.getInteger("ContactFlag");
userInfo.memberCount = info.getInteger("MemberCount");
userInfo.memberList = valueOf(info.getJSONArray("MemberList"));
userInfo.remarkName = info.getString("RemarkName");
userInfo.hideInputBarFlag = info.getInteger("HideInputBarFlag");
userInfo.sex = info.getInteger("Sex");
userInfo.signature = info.getString("Signature");
userInfo.verifyFlag = info.getInteger("VerifyFlag");
userInfo.ownerUin = info.getLong("OwnerUin");
userInfo.pyInitial = info.getString("PYInitial");
userInfo.pyQuanPin = info.getString("PYQuanPin");
userInfo.remarkPYInitial = info.getString("RemarkPYInitial");
userInfo.remarkPYQuanPin = info.getString("RemarkPYQuanPin");
userInfo.starFriend = info.getInteger("StarFriend");
userInfo.appAccountFlag = info.getInteger("AppAccountFlag");
userInfo.statues = info.getInteger("Statues");
userInfo.attrStatus = info.getInteger("AttrStatus");
userInfo.province = info.getString("Province");
userInfo.city = info.getString("City");
userInfo.alias = info.getString("Alias");
userInfo.snsFlag = info.getInteger("SnsFlag");
userInfo.uniFriend = info.getInteger("UniFriend");
userInfo.displayName = info.getString("DisplayName");
userInfo.chatRoomId = info.getLong("ChatRoomId");
userInfo.keyWord = info.getString("KeyWord");
userInfo.encryChatRoomId = info.getString("EncryChatRoomId");
userInfo.isOwner = info.getInteger("IsOwner");
userInfo.userName = info.getString("UserName");
return userInfo;
return JSON.toJavaObject(info, UserInfo.class);
}
public static List<UserInfo> valueOf(JSONArray infos) {

View File

@@ -4,12 +4,18 @@ import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* 要发送的消息
*
* @author Allen
*/
@Getter
@Setter
public class WxMessage {
public class WxMessage implements Serializable {
private static final long serialVersionUID = 1L;
@JSONField(name = "ClientMsgId")
private String clientMsgId;
@JSONField(name = "Content")

View File

@@ -1,14 +1,23 @@
package com.hotlcc.wechat4j.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
/**
* 通用工具类
*
* @author Allen
*/
@Slf4j
public final class CommonUtil {
private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);
private CommonUtil() {
}
/**
* 睡眠线程
*
* @param millis 时间
* @param nanos nanos
*/
public static void threadSleep(long millis, int nanos) {
try {
Thread.sleep(millis, nanos);
@@ -17,6 +26,11 @@ public final class CommonUtil {
}
}
/**
* 睡眠线程
*
* @param millis 时间
*/
public static void threadSleep(long millis) {
try {
Thread.sleep(millis);

View File

@@ -0,0 +1,82 @@
package com.hotlcc.wechat4j.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import javax.activation.MimetypesFileTypeMap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 文件工具类
*
* @author Allen
*/
@Slf4j
public final class FileUtil {
private FileUtil() {
}
/**
* 从文件中获取二进制数据
*
* @param file 文件
* @return 二进制数据
*/
public static byte[] getBytes(File file) {
if (file == null) {
throw new IllegalArgumentException("参数file不能为null");
}
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
try {
fis = new FileInputStream(file);
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.flush();
baos.close();
fis.close();
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取文件的ContentType
*
* @param file 文件
* @return ContentType
*/
public static ContentType getContentType(File file) {
String mimeType = new MimetypesFileTypeMap().getContentType(file);
ContentType contentType = ContentType.parse(mimeType);
return contentType;
}
}

View File

@@ -1,15 +1,18 @@
package com.hotlcc.wechat4j.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Properties工具类
*
* @author Allen
*/
@Slf4j
public final class PropertiesUtil {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private PropertiesUtil() {
}
@@ -33,7 +36,7 @@ public final class PropertiesUtil {
is = PropertiesUtil.class.getClassLoader().getResourceAsStream(path);
prop.load(is);
} catch (Exception e) {
logger.error("Loading properties file \"" + path + "\" error.", e);
log.error("Loading properties file \"" + path + "\" error.", e);
} finally {
if (is != null) {
try {

View File

@@ -6,9 +6,8 @@ import com.google.zxing.NotFoundException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.hotlcc.wechat4j.enums.OperatingSystemEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hotlcc.wechat4j.enums.OperatingSystem;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
@@ -16,25 +15,22 @@ import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 二维码工具类
*
* @author Allen
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@Slf4j
public final class QRCodeUtil {
private static Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);
private QRCodeUtil() {
}
/**
* 从BitMatrix中得到boolean矩阵不去除周围空白部分
*
* @return
* @return 得到的boolean矩阵
*/
private static boolean[][] toBoolMatrix(BitMatrix matrix) {
return toBoolMatrix(matrix, false);
@@ -43,9 +39,9 @@ public final class QRCodeUtil {
/**
* 从BitMatrix中得到boolean矩阵
*
* @param matrix
* @param matrix BitMatrix
* @param noMargin 是否去除周围空白
* @return
* @return 得到的boolean矩阵
*/
private static boolean[][] toBoolMatrix(BitMatrix matrix, boolean noMargin) {
int width = matrix.getWidth();
@@ -60,8 +56,8 @@ public final class QRCodeUtil {
right = width - br[1] - 1;
}
boolean[][] m = new boolean[height - top - bottom][width - left - right];
for (int h = 0 + top, i = 0; h < height - bottom; h++, i++) {
for (int w = 0 + left, j = 0; w < width - right; w++, j++) {
for (int h = top, i = 0; h < height - bottom; h++, i++) {
for (int w = left, j = 0; w < width - right; w++, j++) {
m[i][j] = matrix.get(w, h);
}
}
@@ -71,8 +67,8 @@ public final class QRCodeUtil {
/**
* 将矩阵逆时针转90度
*
* @param matrix
* @return
* @param matrix 旋转前的矩阵
* @return 旋转后的矩阵
*/
private static boolean[][] reverseMatrix(boolean[][] matrix) {
if (matrix == null) {
@@ -95,15 +91,14 @@ public final class QRCodeUtil {
/**
* 从boolMatrix左上角判断二维码定位标记的大小
*
* @param boolMatrix
* @return
* @param boolMatrix bool矩阵
* @return 定位标记大小
*/
private static int getBitCharSize(boolean[][] boolMatrix) {
int a = 0, b = 0;
out:
for (int i = 0, len = boolMatrix.length; i < len; i++) {
for (boolean[] boolArr : boolMatrix) {
boolean find = false;
boolean[] boolArr = boolMatrix[i];
for (int i2 = 0, len2 = boolArr.length; i2 < len2; i2++) {
if (!find && boolArr[i2]) {
find = true;
@@ -122,59 +117,62 @@ public final class QRCodeUtil {
/**
* 从boolMatrix判断bit-char占位比
*
* @param boolMatrix
* @return
* @param boolMatrix bool矩阵
* @return 占位比
*/
private static int getBitCharRatio(boolean[][] boolMatrix) {
int[] size = new int[4];
int len = 4;
// 找出四个角的占位数
int[] size = new int[len];
size[0] = getBitCharSize(boolMatrix);
for (int i = 1; i < 4; i++) {
for (int i = 1; i < len; i++) {
boolMatrix = reverseMatrix(boolMatrix);
size[i] = getBitCharSize(boolMatrix);
}
Map<Integer, Integer> map = new HashMap<>();
// 统计每个占位数出现的次数
int[] num = new int[len];
for (int i = 0; i < len; i++) {
int n = 0;
for (int s : size) {
Integer count = map.get(s);
if (count == null) {
map.put(s, 1);
} else {
map.put(s, count + 1);
if (s == size[i]) {
n++;
}
}
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
Integer k = null, v = null;
int flag = 0;
for (Map.Entry<Integer, Integer> entry : entrySet) {
if (flag++ == 0) {
k = entry.getKey();
v = entry.getValue();
continue;
num[i] = n;
}
if (entry.getValue() > v) {
k = entry.getKey();
v = entry.getValue();
// 找出最多的次数
int maxNum = num[0];
for (int i = 1; i < len; i++) {
maxNum = Math.max(maxNum, num[i]);
}
// 找出出现次数最多的占位数
int s = 0;
for (int i = 0; i < len; i++) {
if (num[i] == maxNum) {
s = size[i];
}
}
return k.intValue() / 7;
return s / 7;
}
/**
* 将二维码图片转为字符矩阵
*
* @param image
* @return
* @param image 二维码图片
* @param onStr 实体字符串
* @param offStr 空白字符串
* @return 字符矩阵
*/
public static String toCharMatrix(BufferedImage image, String onStr, String offStr) {
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BitMatrix matrix = null;
BitMatrix matrix;
try {
matrix = binarizer.getBlackMatrix();
boolean[][] boolMatrix = toBoolMatrix(matrix, true);
int ratio = getBitCharRatio(boolMatrix);
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
for (int i = 0, len = boolMatrix.length; i < len; i += ratio) {
boolean[] boolArr = boolMatrix[i];
for (int i2 = 0, len2 = boolArr.length; i2 < len2; i2 += ratio) {
@@ -192,8 +190,8 @@ public final class QRCodeUtil {
/**
* 将二维码图片转为字符矩阵
*
* @param image
* @return
* @param image 二维码图片
* @return 字符矩阵
*/
public static String toCharMatrix(BufferedImage image) {
return toCharMatrix(image, " ", "██");
@@ -202,8 +200,10 @@ public final class QRCodeUtil {
/**
* 将二维码图片转为字符矩阵
*
* @param data
* @return
* @param data 二维码图片的字节数据
* @param onStr 实体字符串
* @param offStr 空白字符串
* @return 字符矩阵
*/
public static String toCharMatrix(byte[] data, String onStr, String offStr) {
ByteArrayInputStream bais = null;
@@ -228,8 +228,8 @@ public final class QRCodeUtil {
/**
* 将二维码图片转为字符矩阵
*
* @param data
* @return
* @param data 二维码图片的字节数据
* @return 字符矩阵
*/
public static String toCharMatrix(byte[] data) {
return toCharMatrix(data, " ", "██");
@@ -238,8 +238,8 @@ public final class QRCodeUtil {
/**
* 将二维码图片数据写入到临时文件
*
* @param data
* @return
* @param data 二维码图片的字节数据
* @return 字符矩阵
*/
public static File writeToTempFile(byte[] data) {
FileOutputStream fos = null;
@@ -250,7 +250,7 @@ public final class QRCodeUtil {
fos.flush();
return tmp;
} catch (IOException e) {
logger.error("二维码写入临时文件异常", e);
log.error("二维码写入临时文件异常", e);
throw new RuntimeException(e);
} finally {
if (fos != null) {
@@ -266,12 +266,12 @@ public final class QRCodeUtil {
/**
* 打开二维码图片
*
* @param data
* @param data 二维码图片的字节数据
*/
public static void openQRCodeImage(byte[] data) {
OperatingSystemEnum os = OperatingSystemEnum.currentOperatingSystem();
Runtime runtime = null;
File tmp = null;
OperatingSystem os = OperatingSystem.currentOperatingSystem();
Runtime runtime;
File tmp;
switch (os) {
case WINDOWS:
runtime = Runtime.getRuntime();

View File

@@ -5,6 +5,11 @@ import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.UUID;
/**
* 字符串工具类
*
* @author Allen
*/
public final class StringUtil {
private StringUtil() {
}

View File

@@ -1,13 +1,13 @@
package com.hotlcc.wechat4j.api;
package com.hotlcc.wechat4j.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hotlcc.wechat4j.enums.LoginTipEnum;
import com.hotlcc.wechat4j.enums.LoginTip;
import com.hotlcc.wechat4j.enums.MediaType;
import com.hotlcc.wechat4j.model.BaseRequest;
import com.hotlcc.wechat4j.model.MediaMessage;
import com.hotlcc.wechat4j.model.WxMessage;
import com.hotlcc.wechat4j.util.PropertiesUtil;
import com.hotlcc.wechat4j.util.StringUtil;
import com.hotlcc.wechat4j.util.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
@@ -22,14 +22,11 @@ import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.stringtemplate.v4.ST;
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -39,21 +36,33 @@ import java.util.regex.Pattern;
*
* @author Allen
*/
@SuppressWarnings("Duplicates")
public class WebWeixinApi {
private static Logger logger = LoggerFactory.getLogger(WebWeixinApi.class);
@SuppressWarnings({"Duplicates", "unused"})
@Slf4j
public final class WebWeixinApiUtil {
private WebWeixinApiUtil() {
}
//预编译正则匹配
/**
* 预编译正则匹配
*/
private static Pattern PATTERN_UUID_1 = Pattern.compile("window.QRLogin.code = (\\d+);");
private static Pattern PATTERN_UUID_2 = Pattern.compile("window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";");
private static Pattern PATTERN_REDIRECT_URI_1 = Pattern.compile("window.code=(\\d+);");
private static Pattern PATTERN_REDIRECT_URI_2 = Pattern.compile("window.code=(\\d+);\\s*window.redirect_uri=\"(\\S+?)\";");
private static Pattern PATTERN_REDIRECT_URI_3 = Pattern.compile("http(s*)://wx(\\d*)\\.qq\\.com\\/");
private static Pattern PATTERN_REDIRECT_URI_3 = Pattern.compile("http(s*)://wx(\\d*)\\.qq\\.com/");
/**
* 上传媒体文件分片大小
*/
private static final int UPLOAD_MEDIA_FILE_CHUNK_SIZE = 524288;
/**
* 获取微信uuid
*
* @param httpClient http客户端
* @return 返回数据
*/
public JSONObject getWxUuid(HttpClient httpClient) {
public static JSONObject getWxUuid(HttpClient httpClient) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.uuid_url"))
.add("appid", PropertiesUtil.getProperty("webwx.appid"))
@@ -98,7 +107,7 @@ public class WebWeixinApi {
return result;
} catch (Exception e) {
logger.error("获取uuid异常", e);
log.error("获取uuid异常", e);
return null;
}
}
@@ -106,9 +115,11 @@ public class WebWeixinApi {
/**
* 获取二维码
*
* @param uuid
* @param httpClient http客户端
* @param uuid uuid
* @return 二维码图片字节数据
*/
public byte[] getQR(HttpClient httpClient,
public static byte[] getQR(HttpClient httpClient,
String uuid) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.qrcode_url"))
@@ -132,7 +143,7 @@ public class WebWeixinApi {
return data;
} catch (Exception e) {
logger.error("获取二维码异常", e);
log.error("获取二维码异常", e);
return null;
}
}
@@ -140,10 +151,13 @@ public class WebWeixinApi {
/**
* 获取跳转uri等待扫码认证
*
* @return
* @param httpClient http客户端
* @param tip 登录tip
* @param uuid uuid
* @return 返回数据
*/
public JSONObject getRedirectUri(HttpClient httpClient,
LoginTipEnum tip,
public static JSONObject getRedirectUri(HttpClient httpClient,
LoginTip tip,
String uuid) {
try {
long millis = System.currentTimeMillis();
@@ -201,7 +215,7 @@ public class WebWeixinApi {
return result;
} catch (Exception e) {
logger.error("获取跳转uri异常", e);
log.error("获取跳转uri异常", e);
return null;
}
}
@@ -209,8 +223,12 @@ public class WebWeixinApi {
/**
* 获取登录认证码
* 此方法执行后其它web端微信pc端都会下线
*
* @param httpClient http客户端
* @param redirectUri 调整uri
* @return 返回数据
*/
public JSONObject getLoginCode(HttpClient httpClient,
public static JSONObject getLoginCode(HttpClient httpClient,
String redirectUri) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.newlogin_url"))
@@ -229,32 +247,34 @@ public class WebWeixinApi {
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8);
JSONObject result = JSONObject.parseObject(XML.toJSONObject(res).toString()).getJSONObject("error");
return result;
return JSONObject.parseObject(XML.toJSONObject(res).toString()).getJSONObject("error");
} catch (Exception e) {
logger.error("获取登录认证码异常", e);
log.error("获取登录认证码异常", e);
return null;
}
}
/**
* 退出登录
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param baseRequest BaseRequest
*/
public void logout(HttpClient httpClient,
public static void logout(HttpClient httpClient,
String urlVersion,
BaseRequest BaseRequest) {
BaseRequest baseRequest) {
try {
List<NameValuePair> pairList = new ArrayList<>();
pairList.add(new BasicNameValuePair("sid", BaseRequest.getSid()));
pairList.add(new BasicNameValuePair("uin", BaseRequest.getUin()));
pairList.add(new BasicNameValuePair("sid", baseRequest.getSid()));
pairList.add(new BasicNameValuePair("uin", baseRequest.getUin()));
//分两步进行
for (int i = 0; i <= 1; i++) {
String url = new ST(PropertiesUtil.getProperty("webwx-url.logout_url"))
.add("urlVersion", urlVersion)
.add("type", i)
.add("skey", StringUtil.encodeURL(BaseRequest.getSkey(), Consts.UTF_8.name()))
.add("skey", StringUtil.encodeURL(baseRequest.getSkey(), Consts.UTF_8.name()))
.render();
HttpPost httpPost = new HttpPost(url);
@@ -266,18 +286,22 @@ public class WebWeixinApi {
httpClient.execute(httpPost);
}
} catch (Exception e) {
logger.error("退出登录异常", e);
log.error("退出登录异常", e);
}
}
/**
* push登录
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param wxuin uin
* @return 返回数据
*/
public JSONObject pushLogin(HttpClient httpClient,
public static JSONObject pushLogin(HttpClient httpClient,
String urlVersion,
String wxuin) {
try {
long millis = System.currentTimeMillis();
String url = new ST(PropertiesUtil.getProperty("webwx-url.pushlogin_url"))
.add("urlVersion", urlVersion)
.add("uin", wxuin)
@@ -297,22 +321,28 @@ public class WebWeixinApi {
return JSONObject.parseObject(res);
} catch (Exception e) {
logger.error("push登录异常", e);
log.error("push登录异常", e);
return null;
}
}
/**
* 获取初始化数据
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @return 返回数据
*/
public JSONObject webWeixinInit(HttpClient httpClient,
public static JSONObject webWeixinInit(HttpClient httpClient,
String urlVersion,
String passticket,
BaseRequest BaseRequest) {
BaseRequest baseRequest) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxinit_url"))
.add("urlVersion", urlVersion)
.add("pass_ticket", passticket)
.add("pass_ticket", StringUtil.encodeURL(passticket, Consts.UTF_8.name()))
.add("r", System.currentTimeMillis() / 1252L)
.render();
@@ -320,7 +350,7 @@ public class WebWeixinApi {
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", BaseRequest);
paramJson.put("BaseRequest", baseRequest);
HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8);
httpPost.setEntity(paramEntity);
@@ -335,7 +365,7 @@ public class WebWeixinApi {
return JSONObject.parseObject(res);
} catch (Exception e) {
logger.error("获取初始化数据异常", e);
log.error("获取初始化数据异常", e);
return null;
}
}
@@ -343,24 +373,29 @@ public class WebWeixinApi {
/**
* 开启消息状态通知
*
* @return
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param loginUserName 当前登录账号用户名
* @return 返回数据
*/
public JSONObject statusNotify(HttpClient httpClient,
public static JSONObject statusNotify(HttpClient httpClient,
String urlVersion,
String passticket,
BaseRequest BaseRequest,
BaseRequest baseRequest,
String loginUserName) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.statusnotify_url"))
.add("urlVersion", urlVersion)
.add("pass_ticket", passticket)
.add("pass_ticket", StringUtil.encodeURL(passticket, Consts.UTF_8.name()))
.render();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", BaseRequest);
paramJson.put("BaseRequest", baseRequest);
paramJson.put("ClientMsgId", System.currentTimeMillis());
paramJson.put("Code", 3);
paramJson.put("FromUserName", loginUserName);
@@ -379,28 +414,34 @@ public class WebWeixinApi {
return JSONObject.parseObject(res);
} catch (Exception e) {
logger.error("开启消息状态通知异常", e);
log.error("开启消息状态通知异常", e);
return null;
}
}
/**
* 服务端状态同步心跳
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param baseRequest BaseRequest
* @param syncKeyList SyncKeyList
* @return 返回数据
*/
public JSONObject syncCheck(HttpClient httpClient,
public static JSONObject syncCheck(HttpClient httpClient,
String urlVersion,
BaseRequest BaseRequest,
JSONArray SyncKeyList) {
BaseRequest baseRequest,
JSONArray syncKeyList) {
try {
long millis = System.currentTimeMillis();
String url = new ST(PropertiesUtil.getProperty("webwx-url.synccheck_url"))
.add("urlVersion", urlVersion)
.add("r", millis)
.add("skey", StringUtil.encodeURL(BaseRequest.getSkey(), Consts.UTF_8.name()))
.add("sid", BaseRequest.getSid())
.add("uin", BaseRequest.getUin())
.add("skey", StringUtil.encodeURL(baseRequest.getSkey(), Consts.UTF_8.name()))
.add("sid", baseRequest.getSid())
.add("uin", baseRequest.getUin())
.add("deviceid", WechatUtil.createDeviceID())
.add("synckey", StringUtil.encodeURL(WechatUtil.syncKeyListToString(SyncKeyList), Consts.UTF_8.name()))
.add("synckey", StringUtil.encodeURL(WechatUtil.syncKeyListToString(syncKeyList), Consts.UTF_8.name()))
.add("_", millis)
.render();
@@ -432,15 +473,21 @@ public class WebWeixinApi {
return result;
} catch (Exception e) {
logger.error("服务端状态同步异常", e);
log.error("服务端状态同步异常", e);
return null;
}
}
/**
* 获取全部联系人列表
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param skey skey
* @return 返回数据
*/
public JSONObject getContact(HttpClient httpClient,
public static JSONObject getContact(HttpClient httpClient,
String urlVersion,
String passticket,
String skey) {
@@ -465,18 +512,25 @@ public class WebWeixinApi {
return JSONObject.parseObject(res);
} catch (Exception e) {
logger.error("获取全部联系人列表异常", e);
log.error("获取全部联系人列表异常", e);
return null;
}
}
/**
* 批量获取指定用户信息
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param batchContactList 联系人列表
* @return 返回数据
*/
public JSONObject batchGetContact(HttpClient httpClient,
public static JSONObject batchGetContact(HttpClient httpClient,
String urlVersion,
String passticket,
BaseRequest BaseRequest,
BaseRequest baseRequest,
JSONArray batchContactList) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.batchgetcontact_url"))
@@ -489,7 +543,7 @@ public class WebWeixinApi {
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", BaseRequest);
paramJson.put("BaseRequest", baseRequest);
paramJson.put("Count", batchContactList.size());
paramJson.put("List", batchContactList);
HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8);
@@ -506,33 +560,76 @@ public class WebWeixinApi {
return JSONObject.parseObject(res);
} catch (Exception e) {
logger.error("批量获取指定联系人信息异常", e);
log.error("批量获取指定联系人信息异常", e);
return null;
}
}
/**
* 获取联系人头像
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param username 用户名
* @return 头像图片数据
*/
public static byte[] getContactHeadImg(HttpClient httpClient,
String urlVersion,
String username) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxgetheadimg_url"))
.add("urlVersion", urlVersion)
.add("seq", System.currentTimeMillis())
.add("username", username)
.render();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK != statusCode) {
throw new RuntimeException("响应失败(" + statusCode + ")");
}
HttpEntity entity = response.getEntity();
byte[] headImgData = EntityUtils.toByteArray(entity);
return headImgData;
} catch (Exception e) {
log.error("获取联系人头像图片异常", e);
return null;
}
}
/**
* 从服务端同步新数据
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param syncKey syncKey
* @return 返回数据
*/
public JSONObject webWxSync(HttpClient httpClient,
public static JSONObject webWxSync(HttpClient httpClient,
String urlVersion,
String passticket,
BaseRequest BaseRequest,
JSONObject SyncKey) {
BaseRequest baseRequest,
JSONObject syncKey) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsync_url"))
.add("urlVersion", urlVersion)
.add("skey", BaseRequest.getSkey())
.add("sid", BaseRequest.getSid())
.add("pass_ticket", passticket)
.add("skey", baseRequest.getSkey())
.add("sid", baseRequest.getSid())
.add("pass_ticket", StringUtil.encodeURL(passticket, Consts.UTF_8.name()))
.render();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", BaseRequest);
paramJson.put("SyncKey", SyncKey);
paramJson.put("BaseRequest", baseRequest);
paramJson.put("SyncKey", syncKey);
HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8);
httpPost.setEntity(paramEntity);
@@ -547,15 +644,22 @@ public class WebWeixinApi {
return JSONObject.parseObject(res);
} catch (Exception e) {
logger.error("从服务端同步新数据异常", e);
log.error("从服务端同步新数据异常", e);
return null;
}
}
/**
* 发送消息
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param message 消息
* @return 返回数据
*/
public JSONObject sendMsg(HttpClient httpClient,
public static JSONObject sendMsg(HttpClient httpClient,
String urlVersion,
String passticket,
BaseRequest baseRequest,
@@ -563,7 +667,7 @@ public class WebWeixinApi {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsendmsg_url"))
.add("urlVersion", urlVersion)
.add("pass_ticket", passticket)
.add("pass_ticket", StringUtil.encodeURL(passticket, Consts.UTF_8.name()))
.render();
HttpPost httpPost = new HttpPost(url);
@@ -585,134 +689,82 @@ public class WebWeixinApi {
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8);
JSONObject result = JSONObject.parseObject(res);
return result;
return JSONObject.parseObject(res);
} catch (Exception e) {
logger.error("发送消息异常", e);
log.error("发送消息异常", e);
return null;
}
}
/**
* 上传媒体文件
* 上传媒体文件(支持大文件自动分片上传)
*
* @return
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param fromUserName 发送者用户名
* @param toUserName 接受者用户名
* @param dataTicket dataTicket
* @param mediaData 媒体文件二进制数据
* @param mediaName 媒体文件名称
* @param contentType 媒体文件类型
* @param mediaType 媒体类型
* @return 返回数据
*/
public JSONObject uploadMedia(HttpClient httpClient,
String urlVersion,
String passticket,
BaseRequest BaseRequest,
String FromUserName,
String ToUserName,
String dataTicket,
byte[] data,
String fileName,
ContentType contentType) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.uploadmedia_url"))
.add("urlVersion", urlVersion)
.render();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", ContentType.MULTIPART_FORM_DATA.toString());
long millis = System.currentTimeMillis();
JSONObject uploadmediarequest = new JSONObject();
uploadmediarequest.put("UploadType", 2);
uploadmediarequest.put("BaseRequest", BaseRequest);
uploadmediarequest.put("ClientMediaId", millis);
uploadmediarequest.put("TotalLen", data.length);
uploadmediarequest.put("StartPos", 0);
uploadmediarequest.put("DataLen", data.length);
uploadmediarequest.put("MediaType", 4);
uploadmediarequest.put("FromUserName", FromUserName);
uploadmediarequest.put("ToUserName", ToUserName);
uploadmediarequest.put("FileMd5", DigestUtils.md5(data));
HttpEntity paramEntity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addTextBody("id", StringUtil.getUuid(), ContentType.TEXT_PLAIN)
.addTextBody("name", fileName, ContentType.TEXT_PLAIN)
.addTextBody("type", contentType.getMimeType(), ContentType.TEXT_PLAIN)
.addTextBody("lastModifieDate", millis + "", ContentType.TEXT_PLAIN)
.addTextBody("size", data.length + "", ContentType.TEXT_PLAIN)
.addTextBody("mediatype", WechatUtil.getMediatype(contentType.getMimeType()), ContentType.TEXT_PLAIN)
.addTextBody("uploadmediarequest", uploadmediarequest.toJSONString(), ContentType.TEXT_PLAIN)
.addTextBody("webwx_data_ticket", dataTicket, ContentType.TEXT_PLAIN)
.addTextBody("pass_ticket", passticket, ContentType.TEXT_PLAIN)
.addBinaryBody("filename", data, contentType, fileName)
.build();
httpPost.setEntity(paramEntity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK != statusCode) {
throw new RuntimeException("响应失败(" + statusCode + ")");
}
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8);
JSONObject result = JSONObject.parseObject(res);
return result;
} catch (Exception e) {
logger.error("上传媒体文件异常", e);
return null;
}
}
/**
* 上传媒体文件
*
* @return
*/
public JSONObject uploadMedia(HttpClient httpClient,
public static JSONObject uploadMedia(HttpClient httpClient,
String urlVersion,
String passticket,
BaseRequest baseRequest,
String fromUserName,
String toUserName,
String dataTicket,
File file) {
byte[] mediaData,
String mediaName,
ContentType contentType,
MediaType mediaType) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.uploadmedia_url"))
.add("urlVersion", urlVersion)
.render();
long millis = System.currentTimeMillis();
int mediaLength = mediaData.length;
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", ContentType.MULTIPART_FORM_DATA.toString());
long millis = System.currentTimeMillis();
String contentTypeStr = new MimetypesFileTypeMap().getContentType(file);
ContentType contentType = ContentType.parse(contentTypeStr);
JSONObject uploadmediarequest = new JSONObject();
uploadmediarequest.put("UploadType", 2);
uploadmediarequest.put("BaseRequest", baseRequest);
uploadmediarequest.put("ClientMediaId", millis);
uploadmediarequest.put("TotalLen", file.length());
uploadmediarequest.put("TotalLen", mediaLength);
uploadmediarequest.put("StartPos", 0);
uploadmediarequest.put("DataLen", file.length());
uploadmediarequest.put("MediaType", 4);
uploadmediarequest.put("DataLen", mediaLength);
uploadmediarequest.put(MediaType.REQUEST_JSON_KEY, mediaType.getCode());
uploadmediarequest.put("FromUserName", fromUserName);
uploadmediarequest.put("ToUserName", toUserName);
uploadmediarequest.put("FileMd5", DigestUtils.md5(new FileInputStream(file)));
uploadmediarequest.put("FileMd5", DigestUtils.md5Hex(mediaData));
// 分片数量
int chunks = new BigDecimal(mediaLength).divide(new BigDecimal(UPLOAD_MEDIA_FILE_CHUNK_SIZE), 0, BigDecimal.ROUND_UP).intValue();
JSONObject result = null;
for (int chunk = 0; chunk < chunks; chunk++) {
int from = chunk * UPLOAD_MEDIA_FILE_CHUNK_SIZE;
int to = (chunk + 1) * UPLOAD_MEDIA_FILE_CHUNK_SIZE;
to = Math.min(to, mediaLength);
byte[] temp = Arrays.copyOfRange(mediaData, from, to);
HttpEntity paramEntity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addTextBody("id", StringUtil.getUuid(), ContentType.TEXT_PLAIN)
.addTextBody("name", file.getName(), ContentType.TEXT_PLAIN)
.addTextBody("type", contentTypeStr, ContentType.TEXT_PLAIN)
.addTextBody("lastModifieDate", millis + "", ContentType.TEXT_PLAIN)
.addTextBody("size", file.length() + "", ContentType.TEXT_PLAIN)
.addTextBody("mediatype", WechatUtil.getMediatype(contentType.getMimeType()), ContentType.TEXT_PLAIN)
.addTextBody("chunks", String.valueOf(chunks))
.addTextBody("chunk", String.valueOf(chunk))
.addTextBody(MediaType.REQUEST_KEY, mediaType.getValue(), ContentType.TEXT_PLAIN)
.addTextBody("uploadmediarequest", uploadmediarequest.toJSONString(), ContentType.TEXT_PLAIN)
.addTextBody("webwx_data_ticket", dataTicket, ContentType.TEXT_PLAIN)
.addTextBody("pass_ticket", passticket, ContentType.TEXT_PLAIN)
.addBinaryBody("filename", file, contentType, file.getName())
.addBinaryBody("filename", temp, contentType, mediaName)
.build();
httpPost.setEntity(paramEntity);
@@ -725,11 +777,115 @@ public class WebWeixinApi {
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8);
JSONObject result = JSONObject.parseObject(res);
result = JSONObject.parseObject(res);
if (result == null) {
break;
}
JSONObject baseResponse = result.getJSONObject("BaseResponse");
if (baseResponse == null) {
break;
}
int ret = baseResponse.getIntValue("Ret");
if (ret != 0) {
break;
}
}
return result;
} catch (Exception e) {
logger.error("上传媒体文件异常", e);
log.error("上传媒体文件异常", e);
return null;
}
}
/**
* 发送图片消息
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param message 消息
* @return 返回数据
*/
public static JSONObject sendImageMsg(HttpClient httpClient,
String urlVersion,
String passticket,
BaseRequest baseRequest,
MediaMessage message) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsendmsgimg_url"))
.add("urlVersion", urlVersion)
.add("pass_ticket", StringUtil.encodeURL(passticket, Consts.UTF_8.name()))
.render();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", baseRequest);
paramJson.put("Msg", message);
paramJson.put("Scene", 0);
HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8);
httpPost.setEntity(paramEntity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK != statusCode) {
throw new RuntimeException("响应失败(" + statusCode + ")");
}
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8);
return JSONObject.parseObject(res);
} catch (Exception e) {
log.error("发送图片消息异常", e);
return null;
}
}
/**
* 发送视频消息
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param baseRequest BaseRequest
* @param message 消息
* @return 返回数据
*/
public static JSONObject sendVideoMsg(HttpClient httpClient,
String urlVersion,
BaseRequest baseRequest,
MediaMessage message) {
try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsendvideomsg_url"))
.add("urlVersion", urlVersion)
.render();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", baseRequest);
paramJson.put("Msg", message);
paramJson.put("Scene", 0);
HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8);
httpPost.setEntity(paramEntity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK != statusCode) {
throw new RuntimeException("响应失败(" + statusCode + ")");
}
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8);
return JSONObject.parseObject(res);
} catch (Exception e) {
log.error("发送视频消息异常", e);
return null;
}
}

View File

@@ -4,6 +4,11 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.RandomStringUtils;
/**
* 微信工具类
*
* @author Allen
*/
public final class WechatUtil {
private WechatUtil() {
}
@@ -14,7 +19,7 @@ public final class WechatUtil {
/**
* 创建一个设备ID
*
* @return
* @return 设备ID
*/
public static String createDeviceID() {
return "e" + RandomStringUtils.random(15, STRING_CHARS_1);
@@ -23,7 +28,7 @@ public final class WechatUtil {
/**
* 创建一个消息ID
*
* @return
* @return 消息ID
*/
public static String createMsgId() {
return System.currentTimeMillis() + RandomStringUtils.random(4, STRING_CHARS_2);
@@ -32,8 +37,8 @@ public final class WechatUtil {
/**
* 把SyncKeyList转为字符串格式
*
* @param SyncKeyList
* @return
* @param SyncKeyList SyncKeyList
* @return 字符串
*/
public static String syncKeyListToString(JSONArray SyncKeyList) {
if (SyncKeyList == null) {
@@ -51,21 +56,4 @@ public final class WechatUtil {
}
return synckey.toString();
}
/**
* 根据ContentType得到微信上传所需的mediatype
*
* @param contentType
* @return
*/
public static String getMediatype(String contentType) {
if (contentType == null) {
return "doc";
}
if (contentType.indexOf("image") >= 0) {
return "pic";
} else {
return "doc";
}
}
}

View File

@@ -1,3 +1,6 @@
# 0、全局
## 0.1、Web微信host
webwx-url.webwxhost_url=https://wx<urlVersion>.qq.com
# 1、登录
## 1.1、获取微信uuid
webwx-url.uuid_url=https://login.wx.qq.com/jslogin?appid=<appid>&fun=new&lang=zh_CN&_=<_>
@@ -23,6 +26,8 @@ webwx-url.synccheck_url=https://webpush.wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bi
webwx-url.getcontact_url=https://wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=zh_CN&pass_ticket=<pass_ticket>&r=<r>&seq=0&skey=<skey>
## 3.2、批量获取指定联系人列表
webwx-url.batchgetcontact_url=https://wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r=<r>&lang=zh_CN&pass_ticket=<pass_ticket>
## 3.3、获取联系人头像
webwx-url.webwxgetheadimg_url=https://wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxgetheadimg?seq=<seq>&username=<username>
# 4、收发消息
## 4.1、从服务端拉取新消息
webwx-url.webwxsync_url=https://wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxsync?sid=<sid>&skey=<skey>&pass_ticket=<pass_ticket>
@@ -30,3 +35,7 @@ webwx-url.webwxsync_url=https://wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxs
webwx-url.webwxsendmsg_url=https://wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?pass_ticket=<pass_ticket>
## 4.3、上传媒体文件
webwx-url.uploadmedia_url=https://file.wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json
## 4.4、发送图片消息
webwx-url.webwxsendmsgimg_url=https://wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket=<pass_ticket>
## 4.5、发送视频消息
webwx-url.webwxsendvideomsg_url=https://wx<urlVersion>.qq.com/cgi-bin/mmwebwx-bin/webwxsendvideomsg?fun=async&f=json

View File

@@ -1,15 +1,24 @@
import com.alibaba.fastjson.JSONObject;
import com.hotlcc.wechat4j.Wechat;
import com.hotlcc.wechat4j.api.WebWeixinApi;
import com.hotlcc.wechat4j.handler.ReceivedMsgHandler;
import com.hotlcc.wechat4j.model.ReceivedMsg;
import com.hotlcc.wechat4j.model.UserInfo;
import com.hotlcc.wechat4j.util.CommonUtil;
import com.hotlcc.wechat4j.util.StringUtil;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestClass {
public static void main(String[] args) {
WebWeixinApi api = new WebWeixinApi();
Wechat wechat = new Wechat();
wechat.setWebWeixinApi(api);
private Wechat wechat;
@Before
public void initAndLogin() {
wechat = new Wechat();
wechat.addReceivedMsgHandler(new ReceivedMsgHandler() {
@Override
public void handleAllType(Wechat wechat, ReceivedMsg msg) {
@@ -18,6 +27,46 @@ public class TestClass {
System.out.println(name + ": " + msg.getContent());
}
});
wechat.autoLogin();
}
public void testSendText() {
JSONObject result = wechat.sendTextToUserName(null, "这是消息内容");
System.out.println(result);
}
public void testSendImage() {
File file = null;
JSONObject result = null;
file = new File("C:\\Users\\Administrator\\Pictures\\壁纸\\9e5f4981099bcf351e0ec18c3654aced.jpg");
result = wechat.sendImageToUserName(null, file);
file = new File("C:\\Users\\Administrator\\Videos\\手机QQ视频_20190416170016.mp4");
result = wechat.sendVideoToUserName(null, file);
System.out.println(result);
while (true) CommonUtil.threadSleep(5000);
}
@Test
public void testGetImageData() {
byte[] data = wechat.getContactHeadImgByUserName(null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream("D:\\a.jpg");
fos.write(data);
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@@ -1,11 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="30 second">
<property name="APP_NAME" value="emall-admin"/>
<property name="LOG_DIRECTORY" value="${user.home}/logs/${APP_NAME}/"/>
<property name="FILE_SIZE" value="20MB"/>
<property name="MAX_HISTORY" value="100"/>
<property name="TOTAL_SIZE" value="1GB"/>
<property name="APP_NAME" value="wechat4j"/>
<property name="LOG_LEVEL" value="INFO"/>
<!-- 控制台打印 -->
@@ -15,145 +11,8 @@
</encoder>
</appender>
<!-- INFO 输入到文件,按文件大小 -->
<appender name="INFO-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${LOG_DIRECTORY}/info.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIRECTORY}%d/info%i.log</fileNamePattern>
<maxHistory>${MAX_HISTORY}</maxHistory>
<maxFileSize>${FILE_SIZE}</maxFileSize>
<totalSizeCap>${TOTAL_SIZE}</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %m%n</pattern>
</encoder>
</appender>
<!-- ERROR 输入到文件,按文件大小 -->
<appender name="ERROR-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %m%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${LOG_DIRECTORY}/error.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIRECTORY}%d/error%i.log</fileNamePattern>
<maxHistory>${MAX_HISTORY}</maxHistory>
<maxFileSize>${FILE_SIZE}</maxFileSize>
<totalSizeCap>${TOTAL_SIZE}</totalSizeCap>
</rollingPolicy>
</appender>
<!-- WARN 输入到文件,按文件大小 -->
<appender name="WARN-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %m%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${LOG_DIRECTORY}/warn.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIRECTORY}%d/warn%i.log</fileNamePattern>
<maxHistory>${MAX_HISTORY}</maxHistory>
<maxFileSize>${FILE_SIZE}</maxFileSize>
<totalSizeCap>${TOTAL_SIZE}</totalSizeCap>
</rollingPolicy>
</appender>
<!-- DEBUG 输入到文件,按文件大小 -->
<appender name="DEBUG-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %m%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${LOG_DIRECTORY}/debug.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIRECTORY}%d/debug%i.log</fileNamePattern>
<maxHistory>${MAX_HISTORY}</maxHistory>
<maxFileSize>${FILE_SIZE}</maxFileSize>
</rollingPolicy>
</appender>
<!-- TRACE 输入到文件,按日期和文件大小 -->
<appender name="TRACE-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %m%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACE</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${LOG_DIRECTORY}/trace.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIRECTORY}%d/trace%i.log</fileNamePattern>
<maxHistory>${MAX_HISTORY}</maxHistory>
<maxFileSize>${FILE_SIZE}</maxFileSize>
</rollingPolicy>
</appender>
<appender name="${APP_NAME}" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %m%n</pattern>
</encoder>
<!-- 过滤日志级别 -->
<!--<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>-->
<file>${LOG_DIRECTORY}/${APP_NAME}.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIRECTORY}%d/${APP_NAME}%i.log</fileNamePattern>
<maxHistory>${MAX_HISTORY}</maxHistory>
<maxFileSize>${FILE_SIZE}</maxFileSize>
</rollingPolicy>
</appender>
<!-- 包级别的日志 additivity="false" -->
<logger name="com.aaron.springcloud.consumer.controller" additivity="false">
<level value="{LOG_LEVEL}"/>
<appender-ref ref="${APP_NAME}"/>
<!-- 还是要输出到控制台中-->
<appender-ref ref="STDOUT"/>
</logger>
<!-- org包下面设置日志级别为Error-->
<!--<logger name="org" level="ERROR"/>-->
<!-- org包下面设置日志级别为Error-->
<!--<logger name="com.netflix" level="ERROR"/>-->
<!-- Logger 根目录 -->
<root level="${LOG_LEVEL}">
<appender-ref ref="STDOUT"/>
<!--<appender-ref ref="ERROR-OUT"/>
<appender-ref ref="WARN-OUT"/>
<appender-ref ref="INFO-OUT"/>
<appender-ref ref="DEBUG-OUT"/>
<appender-ref ref="TRACE-OUT"/>-->
</root>
</configuration>