repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMinishopImageUploadResult.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMinishopImageUploadResult.java | package me.chanjar.weixin.common.bean.result;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.Data;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
@Data
public class WxMinishopImageUploadResult implements Serializable {
private static final long serialVersionUID = 330834334738622332L;
private String errcode;
private String errmsg;
private WxMinishopPicFileResult picFile;
public static WxMinishopImageUploadResult fromJson(String json) {
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
WxMinishopImageUploadResult result = new WxMinishopImageUploadResult();
result.setErrcode(jsonObject.get(WxConsts.ERR_CODE).getAsNumber().toString());
if (result.getErrcode().equals("0")) {
WxMinishopPicFileResult picFileResult = new WxMinishopPicFileResult();
JsonObject picObject = jsonObject.get("pic_file").getAsJsonObject();
JsonElement mediaId = picObject.get("media_id");
picFileResult.setMediaId(mediaId==null ? "" : mediaId.getAsString());
JsonElement payMediaId = picObject.get("pay_media_id");
picFileResult.setPayMediaId(payMediaId==null ? "" : payMediaId.getAsString());
JsonElement tempImgUrl = picObject.get("temp_img_url");
picFileResult.setTempImgUrl(tempImgUrl==null ? "" : tempImgUrl.getAsString());
result.setPicFile(picFileResult);
}
return result;
}
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMinishopPicFileCustomizeResult.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMinishopPicFileCustomizeResult.java | package me.chanjar.weixin.common.bean.result;
import lombok.Data;
import java.io.Serializable;
@Data
public class WxMinishopPicFileCustomizeResult implements Serializable {
private String mediaId;
private String tempImgUrl;
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java | package me.chanjar.weixin.common.bean.result;
import java.io.Serializable;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
/**
*
* @author Daniel Qian
*/
@Data
public class WxMediaUploadResult implements Serializable {
private static final long serialVersionUID = 330834334738622341L;
private String url;
private String type;
private String mediaId;
private String thumbMediaId;
private long createdAt;
public static WxMediaUploadResult fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxMediaUploadResult.class);
}
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/imgproc/WxImgProcAiCropResult.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/imgproc/WxImgProcAiCropResult.java | package me.chanjar.weixin.common.bean.imgproc;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
import java.util.List;
/**
* @author Theo Nie
*/
@Data
public class WxImgProcAiCropResult implements Serializable {
private static final long serialVersionUID = -6470673963772979463L;
@SerializedName("img_size")
private ImgSize imgSize;
@SerializedName("results")
private List<Results> results;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
public static WxImgProcAiCropResult fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxImgProcAiCropResult.class);
}
@Data
public static class ImgSize implements Serializable {
private static final long serialVersionUID = -6470673963772979463L;
@SerializedName("w")
private int w;
@SerializedName("h")
private int h;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
@Data
public static class Results implements Serializable {
private static final long serialVersionUID = -6470673963772979463L;
@SerializedName("crop_left")
private int cropLeft;
@SerializedName("crop_top")
private int cropTop;
@SerializedName("crop_right")
private int cropRight;
@SerializedName("crop_bottom")
private int cropBottom;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/imgproc/WxImgProcSuperResolutionResult.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/imgproc/WxImgProcSuperResolutionResult.java | package me.chanjar.weixin.common.bean.imgproc;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
/**
* 图片高清化返回结果
* @author Theo Nie
*/
@Data
public class WxImgProcSuperResolutionResult implements Serializable {
private static final long serialVersionUID = 8007440280170407021L;
@SerializedName("media_id")
private String mediaId;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
public static WxImgProcSuperResolutionResult fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxImgProcSuperResolutionResult.class);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/imgproc/WxImgProcQrCodeResult.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/imgproc/WxImgProcQrCodeResult.java | package me.chanjar.weixin.common.bean.imgproc;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
import java.util.List;
/**
* 二维码/条码识别返回结果
*
* @author Theo Nie
*/
@Data
public class WxImgProcQrCodeResult implements Serializable {
private static final long serialVersionUID = -1194154790100866123L;
@SerializedName("img_size")
private ImgSize imgSize;
@SerializedName("code_results")
private List<CodeResults> codeResults;
@Data
public static class ImgSize implements Serializable {
private static final long serialVersionUID = -8847603245514017839L;
@SerializedName("w")
private int w;
@SerializedName("h")
private int h;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
@Data
public static class CodeResults implements Serializable {
private static final long serialVersionUID = -6138135951229076759L;
@SerializedName("type_name")
private String typeName;
@SerializedName("data")
private String data;
@SerializedName("pos")
private Pos pos;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
@Data
public static class Pos implements Serializable {
private static final long serialVersionUID = 7754894061212819602L;
@SerializedName("left_top")
private Coordinate leftTop;
@SerializedName("right_top")
private Coordinate rightTop;
@SerializedName("right_bottom")
private Coordinate rightBottom;
@SerializedName("left_bottom")
private Coordinate leftBottom;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
@Data
public static class Coordinate implements Serializable {
private static final long serialVersionUID = 8930443668927359677L;
@SerializedName("x")
private int x;
@SerializedName("y")
private int y;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
}
}
public static WxImgProcQrCodeResult fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxImgProcQrCodeResult.class);
}
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java | package me.chanjar.weixin.common.bean.menu;
import java.io.Serializable;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
/**
* menu rule.
*
* @author Daniel Qian
*/
@Data
public class WxMenuRule implements Serializable {
private static final long serialVersionUID = -4587181819499286670L;
/**
* 变态的微信接口,反序列化时这里反人类的使用和序列化时不一样的名字.
*/
@SerializedName(value = "tag_id", alternate = "group_id")
private String tagId;
private String sex;
private String country;
private String province;
private String city;
@SerializedName("client_platform_type")
private String clientPlatformType;
private String language;
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java | package me.chanjar.weixin.common.bean.menu;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
/**
* 菜单(公众号和企业号共用的).
*
* @author Daniel Qian
*/
@Data
public class WxMenu implements Serializable {
private static final long serialVersionUID = -7083914585539687746L;
private List<WxMenuButton> buttons = new ArrayList<>();
private WxMenuRule matchRule;
/**
* 要用 http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html 格式来反序列化
* 相比 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html 的格式,外层多套了一个menu
*/
public static WxMenu fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxMenu.class);
}
/**
* 要用 http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html 格式来反序列化
* 相比 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html 的格式,外层多套了一个menu
*/
public static WxMenu fromJson(InputStream is) {
return WxGsonBuilder.create()
.fromJson(new InputStreamReader(is, StandardCharsets.UTF_8), WxMenu.class);
}
public String toJson() {
return WxGsonBuilder.create().toJson(this);
}
@Override
public String toString() {
return this.toJson();
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java | package me.chanjar.weixin.common.bean.menu;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
/**
* menu button.
*
* @author Daniel Qian
*/
@Data
public class WxMenuButton implements Serializable {
private static final long serialVersionUID = -1070939403109776555L;
/**
* <pre>
* 菜单的响应动作类型.
* view表示网页类型,
* click表示点击类型,
* miniprogram表示小程序类型
* </pre>
*/
private String type;
/**
* 菜单标题,不超过16个字节,子菜单不超过60个字节.
*/
private String name;
/**
* <pre>
* 菜单KEY值,用于消息接口推送,不超过128字节.
* click等点击类型必须
* </pre>
*/
private String key;
/**
* <pre>
* 网页链接.
* 用户点击菜单可打开链接,不超过1024字节。type为miniprogram时,不支持小程序的老版本客户端将打开本url。
* view、miniprogram类型必须
* </pre>
*/
private String url;
/**
* <pre>
* 调用新增永久素材接口返回的合法media_id.
* media_id类型和view_limited类型必须
* </pre>
*/
@SerializedName("media_id")
private String mediaId;
/**
* <pre>
* 调用发布图文接口获得的article_id.
* article_id类型和article_view_limited类型必须
* </pre>
*/
@SerializedName("article_id")
private String articleId;
/**
* <pre>
* 小程序的appid.
* miniprogram类型必须
* </pre>
*/
@SerializedName("appid")
private String appId;
/**
* <pre>
* 小程序的页面路径.
* miniprogram类型必须
* </pre>
*/
@SerializedName("pagepath")
private String pagePath;
@SerializedName("sub_button")
private List<WxMenuButton> subButtons = new ArrayList<>();
@Override
public String toString() {
return WxGsonBuilder.create().toJson(this);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/subscribemsg/CategoryData.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/subscribemsg/CategoryData.java | package me.chanjar.weixin.common.bean.subscribemsg;
import lombok.Data;
import java.io.Serializable;
/**
* .
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
* created on 2021-01-27
*/
@Data
public class CategoryData implements Serializable {
private static final long serialVersionUID = -5935548352317679892L;
private int id;
private String name;
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/subscribemsg/PubTemplateTitleListResult.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/subscribemsg/PubTemplateTitleListResult.java | package me.chanjar.weixin.common.bean.subscribemsg;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
import java.util.List;
/**
* @author ArBing
*/
@Data
public class PubTemplateTitleListResult implements Serializable {
private static final long serialVersionUID = -7718911668757837527L;
private int count;
private List<TemplateItem> data;
public static PubTemplateTitleListResult fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, PubTemplateTitleListResult.class);
}
@Data
public static class TemplateItem implements Serializable {
private static final long serialVersionUID = 6888726696879905332L;
private Integer type;
private Integer tid;
private String categoryId;
private String title;
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/subscribemsg/TemplateInfo.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/subscribemsg/TemplateInfo.java | package me.chanjar.weixin.common.bean.subscribemsg;
import lombok.Data;
import java.io.Serializable;
/**
* .
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
* created on 2021-01-27
*/
@Data
public class TemplateInfo implements Serializable {
private static final long serialVersionUID = 6971785763573992264L;
private String priTmplId;
private String title;
private String content;
private String example;
private int type;
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/subscribemsg/PubTemplateKeyword.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/subscribemsg/PubTemplateKeyword.java | package me.chanjar.weixin.common.bean.subscribemsg;
import lombok.Data;
import java.io.Serializable;
/**
* .
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
* created on 2021-01-27
*/
@Data
public class PubTemplateKeyword implements Serializable {
private static final long serialVersionUID = -1100641668859815647L;
private int kid;
private String name;
private String example;
private String rule;
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/enums/WxType.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/enums/WxType.java | package me.chanjar.weixin.common.enums;
/**
* <pre>
* 微信类型枚举.
* Created by BinaryWang on 2018/5/14.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
public enum WxType {
/**
* 企业微信.
*/
CP,
/**
* 微信公众号.
*/
MP,
/**
* 微信小程序.
*/
MiniApp,
/**
* 微信开放平台.
*/
Open,
/**
* 微信支付.
*/
Pay,
/**
* 微信视频号
*/
Channel,
;
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-common/src/main/java/me/chanjar/weixin/common/enums/TicketType.java | weixin-java-common/src/main/java/me/chanjar/weixin/common/enums/TicketType.java | package me.chanjar.weixin.common.enums;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* <pre>
* ticket类型枚举
* Created by Binary Wang on 2018/11/18.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Getter
@RequiredArgsConstructor
public enum TicketType {
/**
* jsapi
*/
JSAPI("jsapi"),
/**
* sdk
*/
SDK("2"),
/**
* 微信卡券
*/
WX_CARD("wx_card");
/**
* type代码
*/
private final String code;
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapterTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapterTest.java | package me.chanjar.weixin.cp.util.json;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <pre>
*
* Created by Binary Wang on 2018/9/16.
* </pre>
*
* @author BinaryWang
*/
public class WxCpUserGsonAdapterTest {
/**
* Test deserialize.
*/
@Test
public void testDeserialize() {
final String userJson = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"userid\": \"zhangsan\",\n" +
" \"name\": \"李四\",\n" +
" \"department\": [1, 2],\n" +
" \"order\": [1, 2],\n" +
" \"position\": \"后台工程师\",\n" +
" \"mobile\": \"15913215421\",\n" +
" \"gender\": \"1\",\n" +
" \"email\": \"zhangsan@gzdev.com\",\n" +
" \"isleader\": 1,\n" +
" \"avatar\": \"http://wx.qlogo" +
".cn/mmopen/ajNVdqHZLLA3WJ6DSZUfiakYe37PKnQhBIeOQBO4czqrnZDS79FH5Wm5m4X69TBicnHFlhiafvDwklOpZeXYQQ2icg/0\",\n" +
" \"telephone\": \"020-123456\",\n" +
" \"address\": \"广州市海珠区新港中路\"," +
" \"enable\": 1,\n" +
" \"alias\": \"jackzhang\",\n" +
" \"extattr\": {\n" +
" \"attrs\": [\n" +
" {\n" +
" \"type\": 0,\n" +
" \"name\": \"文本名称\",\n" +
" \"text\": {\n" +
" \"value\": \"文本\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\": 1,\n" +
" \"name\": \"网页名称\",\n" +
" \"web\": {\n" +
" \"url\": \"http://www.test.com\",\n" +
" \"title\": \"标题\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }," +
" \"status\": 1,\n" +
" \"qr_code\": \"https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=xxx\",\n" +
" \"external_position\": \"高级产品经理\",\n" +
" \"external_profile\": {\n" +
" \"external_corp_name\": \"企业简称\",\n" +
" \"external_attr\": [\n" +
" {\n" +
" \"type\": 0,\n" +
" \"name\": \"文本名称\",\n" +
" \"text\": {\n" +
" \"value\": \"文本\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\": 1,\n" +
" \"name\": \"网页名称\",\n" +
" \"web\": {\n" +
" \"url\": \"http://www.test.com\",\n" +
" \"title\": \"标题\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\": 2,\n" +
" \"name\": \"测试app\",\n" +
" \"miniprogram\": {\n" +
" \"appid\": \"wx8bd8012614784fake\",\n" +
" \"pagepath\": \"/index\",\n" +
" \"title\": \"my miniprogram\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }" +
"}";
final WxCpUser user = WxCpUser.fromJson(userJson);
assertThat(user).isNotNull();
assertThat(user.getOrders()).isNotEmpty();
assertThat(user.getOrders()).hasSize(2);
assertThat(user.getOrders()[0]).isEqualTo(1);
assertThat(user.getOrders()[1]).isEqualTo(2);
assertThat(user.getAddress()).isEqualTo("广州市海珠区新港中路");
assertThat(user.getAlias()).isEqualTo("jackzhang");
assertThat(user.getExtAttrs()).isNotEmpty();
final WxCpUser.Attr extraAttr1 = user.getExtAttrs().get(0);
assertThat(extraAttr1.getType()).isEqualTo(0);
assertThat(extraAttr1.getName()).isEqualTo("文本名称");
assertThat(extraAttr1.getTextValue()).isEqualTo("文本");
final WxCpUser.Attr extraAttr2 = user.getExtAttrs().get(1);
assertThat(extraAttr2.getType()).isEqualTo(1);
assertThat(extraAttr2.getName()).isEqualTo("网页名称");
assertThat(extraAttr2.getWebTitle()).isEqualTo("标题");
assertThat(extraAttr2.getWebUrl()).isEqualTo("http://www.test.com");
assertThat(user.getExternalPosition()).isEqualTo("高级产品经理");
assertThat(user.getExternalCorpName()).isEqualTo("企业简称");
assertThat(user.getExternalAttrs()).isNotEmpty();
final WxCpUser.ExternalAttribute externalAttr1 = user.getExternalAttrs().get(0);
assertThat(externalAttr1.getType()).isEqualTo(0);
assertThat(externalAttr1.getName()).isEqualTo("文本名称");
assertThat(externalAttr1.getValue()).isEqualTo("文本");
final WxCpUser.ExternalAttribute externalAttr2 = user.getExternalAttrs().get(1);
assertThat(externalAttr2.getType()).isEqualTo(1);
assertThat(externalAttr2.getName()).isEqualTo("网页名称");
assertThat(externalAttr2.getUrl()).isEqualTo("http://www.test.com");
assertThat(externalAttr2.getTitle()).isEqualTo("标题");
final WxCpUser.ExternalAttribute externalAttr3 = user.getExternalAttrs().get(2);
assertThat(externalAttr3.getType()).isEqualTo(2);
assertThat(externalAttr3.getName()).isEqualTo("测试app");
assertThat(externalAttr3.getAppid()).isEqualTo("wx8bd8012614784fake");
assertThat(externalAttr3.getPagePath()).isEqualTo("/index");
assertThat(externalAttr3.getTitle()).isEqualTo("my miniprogram");
}
/**
* Test serialize.
*/
@Test
public void testSerialize() {
WxCpUser user = new WxCpUser();
user.setOrders(new Integer[]{1, 2});
user.addExtAttr(WxCpUser.Attr.builder()
.type(0)
.name("文本名称")
.textValue("文本")
.build());
user.addExternalAttr(WxCpUser.ExternalAttribute.builder()
.type(0)
.name("文本名称")
.value("文本")
.build());
user.addExternalAttr(WxCpUser.ExternalAttribute.builder()
.type(1)
.name("网页名称")
.url("http://www.test.com")
.title("标题")
.build());
user.addExternalAttr(WxCpUser.ExternalAttribute.builder()
.type(2)
.name("测试app")
.appid("wx8bd80126147df384")
.pagePath("/index")
.title("my miniprogram")
.build());
assertThat(user.toJson()).isEqualTo("{\"order\":[1,2]," +
"\"extattr\":{\"attrs\":[{\"type\":0,\"name\":\"文本名称\",\"text\":{\"value\":\"文本\"}}]}," +
"\"external_profile\":{\"external_attr\":" +
"[{\"type\":0,\"name\":\"文本名称\",\"text\":{\"value\":\"文本\"}}," +
"{\"type\":1,\"name\":\"网页名称\",\"web\":{\"url\":\"http://www.test.com\",\"title\":\"标题\"}}," +
"{\"type\":2,\"name\":\"测试app\"," +
"\"miniprogram\":{\"appid\":\"wx8bd80126147df384\",\"pagepath\":\"/index\",\"title\":\"my miniprogram\"}}]}}");
}
/**
* Test directLeader empty array serialization.
* This test verifies that empty directLeader arrays are included in JSON as "direct_leader":[]
* instead of being omitted, which is required for WeChat Work API to reset user direct leaders.
*/
@Test
public void testDirectLeaderEmptyArraySerialization() {
WxCpUser user = new WxCpUser();
user.setUserId("testuser");
user.setName("Test User");
// Test with empty array - should be serialized as "direct_leader":[]
user.setDirectLeader(new String[]{});
String json = user.toJson();
assertThat(json).contains("\"direct_leader\":[]");
// Test with null - should not include direct_leader field
user.setDirectLeader(null);
json = user.toJson();
assertThat(json).doesNotContain("direct_leader");
// Test with non-empty array - should be serialized normally
user.setDirectLeader(new String[]{"leader1", "leader2"});
json = user.toJson();
assertThat(json).contains("\"direct_leader\":[\"leader1\",\"leader2\"]");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapterForPrivatizedVersionTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapterForPrivatizedVersionTest.java | package me.chanjar.weixin.cp.util.json;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <pre>
* 企业微信(私有化版本getUser兼容测试)
* </pre>
*
* @author 庄壮壮
* @since 2020 -06-16 09:36
*/
public class WxCpUserGsonAdapterForPrivatizedVersionTest {
/**
* Test deserialize.
*/
@Test
public void testDeserialize() {
final String userJson = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"userid\": \"zhangsan\",\n" +
" \"name\": \"李四\",\n" +
" \"department\": [1, 2],\n" +
" \"order\": [2, 10],\n" +
" \"position\": \"后台工程师1\",\n" +
" \"positions\": [\"后台工程师1\",\"后台工程师2\"],\n" +
" \"mobile\": \"15913215421\",\n" +
" \"hide_mobile\": 0,\n" +
" \"gender\": \"1\",\n" +
" \"email\": \"zhangsan@gzdev.com\",\n" +
" \"is_leader_in_dept\": [1, 0],\n" +
" \"avatar\": \"http://wx.qlogo" +
".cn/mmopen/ajNVdqHZLLA3WJ6DSZUfiakYe37PKnQhBIeOQBO4czqrnZDS79FH5Wm5m4X69TBicnHFlhiafvDwklOpZeXYQQ2icg/0\",\n" +
" \"telephone\": \"020-123456\",\n" +
" \"english_name\": \"jackzhang\",\n" +
" \"extattr\": {\"attrs\":[{\"name\":\"爱好\",\"value\":\"旅游\"},{\"name\":\"卡号\",\"value\":\"1234567234\"}]},\n" +
" \"status\": 1,\n" +
" \"enable\": 0,\n" +
" \"qr_code\": \"https://wwlocal.qq.com/wework_admin/userQRCode?vcode=vc2140a8b3c6207c74&lvc" +
"=vcf6f1acfdc4b45088\"\n" +
"}";
final WxCpUser user = WxCpUser.fromJson(userJson);
assertThat(user).isNotNull();
// test order
assertThat(user.getOrders()).isNotEmpty();
assertThat(user.getOrders().length).isEqualTo(2);
assertThat(user.getOrders()[0]).isEqualTo(2);
assertThat(user.getOrders()[1]).isEqualTo(10);
// test english name
assertThat(user.getEnglishName()).isEqualTo("jackzhang");
// test extattrs
assertThat(user.getExtAttrs()).isNotEmpty();
final WxCpUser.Attr extraAttr1 = user.getExtAttrs().get(0);
assertThat(extraAttr1.getName()).isEqualTo("爱好");
assertThat(extraAttr1.getTextValue()).isEqualTo("旅游");
final WxCpUser.Attr extraAttr2 = user.getExtAttrs().get(1);
assertThat(extraAttr2.getName()).isEqualTo("卡号");
assertThat(extraAttr2.getTextValue()).isEqualTo("1234567234");
// test position
assertThat(user.getPosition()).isEqualTo("后台工程师1");
// test positions
assertThat(user.getPositions()).isNotEmpty();
assertThat(user.getPositions().length).isEqualTo(2);
assertThat(user.getPositions()[0]).isEqualTo("后台工程师1");
assertThat(user.getPositions()[1]).isEqualTo("后台工程师2");
}
/**
* Test serialize.
*/
@Test
public void testSerialize() {
WxCpUser user = new WxCpUser();
user.setOrders(new Integer[]{1, 2});
user.setPositions(new String[]{"后台工程师1", "后台工程师2"});
user.setEnglishName("jackson");
WxCpUser.Attr attr1 = new WxCpUser.Attr();
attr1.setName("爱好").setTextValue("旅游");
WxCpUser.Attr attr2 = new WxCpUser.Attr();
attr2.setName("卡号").setTextValue("1234567234");
user.addExtAttr(attr1);
user.addExtAttr(attr2);
assertThat(user.toJson()).isEqualTo("{\"order\":[1,2],\"positions\":[\"后台工程师1\",\"后台工程师2\"]," +
"\"english_name\":\"jackson\",\"extattr\":{\"attrs\":[{\"name\":\"爱好\",\"value\":\"旅游\"},{\"name\":\"卡号\"," +
"\"value\":\"1234567234\"}]},\"external_profile\":{}}");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtilTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtilTest.java | package me.chanjar.weixin.cp.util.crypto;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
/**
* The type Wx cp crypt util test.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-06-11
*/
public class WxCpCryptUtilTest {
/**
* Test.
*/
@Test
public void test() {
String encodingAesKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";
final byte[] commonsCodec = Base64.decodeBase64(encodingAesKey + "=");
final byte[] guava = java.util.Base64.getDecoder().decode(StringUtils.remove(encodingAesKey, " "));
final byte[] guava1 = java.util.Base64.getDecoder().decode(StringUtils.remove(encodingAesKey + "=", " "));
assertEquals(commonsCodec, guava);
assertEquals(guava1, guava);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpServiceApacheHttpClientImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpServiceApacheHttpClientImplTest.java | package me.chanjar.weixin.cp.tp.service.impl;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.redis.RedissonWxRedisOps;
import me.chanjar.weixin.cp.bean.WxCpProviderToken;
import me.chanjar.weixin.cp.bean.WxCpTpCorpId2OpenCorpId;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.AbstractWxCpTpInRedisConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedisTemplateConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedissonConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* 测试用参数请在自己的企业微信第三方开发者后台查找匹配
* 如果测试不过,请检查redis中是否存在微信定期推送的suite_ticket
*
* @author zhangq <zhangq002@gmail.com>
*/
public class WxCpTpServiceApacheHttpClientImplTest {
/**
* The constant API_URL.
*/
public static final String API_URL = "https://qyapi.weixin.qq.com";
/**
* The constant SUITE_ID.
*/
public static final String SUITE_ID = "xxxxxx";
/**
* The constant SUITE_SECRET.
*/
public static final String SUITE_SECRET = "xxxxxx";
/**
* The constant TOKEN.
*/
public static final String TOKEN = "xxxxxx";
/**
* The constant AES_KEY.
*/
public static final String AES_KEY = "xxxxxx";
/**
* The constant PROVIDER_CORP_ID.
*/
public static final String PROVIDER_CORP_ID = "xxxxxx";
/**
* The constant PROVIDER_SECRET.
*/
public static final String PROVIDER_SECRET = "xxxxxx";
/**
* The constant REDIS_ADDR.
*/
public static final String REDIS_ADDR = "redis://xxx.xxx.xxx.xxx:6379";
/**
* The constant REDIS_PASSWD.
*/
public static final String REDIS_PASSWD = "xxxxxx";
private static final String AUTH_CORP_ID = "xxxxxx";
private static final String PERMANENT_CODE = "xxxxxx";
private WxCpTpService wxCpTpService;
/**
* Sets up.
*/
@BeforeMethod
public void setUp() {
wxCpTpService = new WxCpTpServiceApacheHttpClientImpl();
wxCpTpService.setWxCpTpConfigStorage(wxCpTpConfigStorage());
}
/**
* Wx cp tp config storage wx cp tp config storage.
*
* @return the wx cp tp config storage
*/
public WxCpTpConfigStorage wxCpTpConfigStorage() {
WxCpTpRedissonConfigImpl wxCpTpRedissonConfig=new WxCpTpRedissonConfigImpl(redissonClient(),"");
wxCpTpRedissonConfig.setBaseApiUrl(API_URL);
wxCpTpRedissonConfig.setSuiteId(SUITE_ID);
wxCpTpRedissonConfig.setSuiteSecret(SUITE_SECRET);
wxCpTpRedissonConfig.setToken(TOKEN);
wxCpTpRedissonConfig.setEncodingAESKey(AES_KEY);
wxCpTpRedissonConfig.setCorpId(PROVIDER_CORP_ID);
wxCpTpRedissonConfig.setProviderSecret(PROVIDER_SECRET);
return wxCpTpRedissonConfig;
}
/**
* Redisson client redisson client.
*
* @return the redisson client
*/
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer().setAddress(REDIS_ADDR).setConnectTimeout(10 * 1000).setDatabase(6)
.setPassword(REDIS_PASSWD).setConnectionMinimumIdleSize(2).setConnectionPoolSize(2);
return Redisson.create(config);
}
/**
* Test get suite access token entity.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetSuiteAccessTokenEntity() throws WxErrorException {
wxCpTpService.getWxCpTpConfigStorage().expireSuiteAccessToken();
WxAccessToken suiteAccessTokenEntity = wxCpTpService.getSuiteAccessTokenEntity(true);
System.out.println("suiteAccessTokenEntity:" + suiteAccessTokenEntity);
Assert.assertTrue(
StringUtils.isNotBlank(suiteAccessTokenEntity.getAccessToken()) && suiteAccessTokenEntity.getExpiresIn() > 0);
suiteAccessTokenEntity = wxCpTpService.getSuiteAccessTokenEntity();
System.out.println("suiteAccessTokenEntity:" + suiteAccessTokenEntity);
Assert.assertTrue(
StringUtils.isNotBlank(suiteAccessTokenEntity.getAccessToken()) && suiteAccessTokenEntity.getExpiresIn() > 0);
}
/**
* Test get wx cp provider token entity.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetWxCpProviderTokenEntity() throws WxErrorException {
wxCpTpService.getWxCpTpConfigStorage().expireProviderToken();
WxCpProviderToken providerToken = wxCpTpService.getWxCpProviderTokenEntity(true);
System.out.println("providerToken:" + providerToken);
Assert
.assertTrue(StringUtils.isNotBlank(providerToken.getProviderAccessToken()) && providerToken.getExpiresIn() > 0);
providerToken = wxCpTpService.getWxCpProviderTokenEntity();
System.out.println("providerToken:" + providerToken);
Assert
.assertTrue(StringUtils.isNotBlank(providerToken.getProviderAccessToken()) && providerToken.getExpiresIn() > 0);
}
/**
* Test get corp token.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCorpToken() throws WxErrorException {
wxCpTpService.getWxCpTpConfigStorage().expireAccessToken(AUTH_CORP_ID);
WxAccessToken accessToken = wxCpTpService.getCorpToken(AUTH_CORP_ID, PERMANENT_CODE, true);
System.out.println("accessToken:" + accessToken);
accessToken = wxCpTpService.getCorpToken(AUTH_CORP_ID, PERMANENT_CODE);
System.out.println("accessToken:" + accessToken);
}
/**
* Test get auth corp js api ticket.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetAuthCorpJsApiTicket() throws WxErrorException {
wxCpTpService.getWxCpTpConfigStorage().expireAuthCorpJsApiTicket(AUTH_CORP_ID);
String authCorpJsApiTicket = wxCpTpService.getAuthCorpJsApiTicket(AUTH_CORP_ID, true);
System.out.println("authCorpJsApiTicket:" + authCorpJsApiTicket);
authCorpJsApiTicket = wxCpTpService.getAuthCorpJsApiTicket(AUTH_CORP_ID);
System.out.println("authCorpJsApiTicket:" + authCorpJsApiTicket);
}
/**
* Test get suite js api ticket.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetSuiteJsApiTicket() throws WxErrorException {
wxCpTpService.getWxCpTpConfigStorage().expireAuthSuiteJsApiTicket(AUTH_CORP_ID);
String suiteJsApiTicket = wxCpTpService.getSuiteJsApiTicket(AUTH_CORP_ID, true);
System.out.println("suiteJsApiTicket:" + suiteJsApiTicket);
suiteJsApiTicket = wxCpTpService.getSuiteJsApiTicket(AUTH_CORP_ID);
System.out.println("suiteJsApiTicket:" + suiteJsApiTicket);
}
@Test
public void testCorpId2OpenCorpId() throws WxErrorException {
WxCpTpCorpId2OpenCorpId openCorpId = wxCpTpService.corpId2OpenCorpId("wpVIkfEAAAu2wGiOEeNMQ69afwLM6BbA");
System.out.println("openCorpId:" + openCorpId);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpOrderServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpOrderServiceImplTest.java | package me.chanjar.weixin.cp.tp.service.impl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.order.WxCpTpOrderDetails;
import me.chanjar.weixin.cp.bean.order.WxCpTpOrderListGetResult;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpTpDefaultConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpOrderService;
import org.apache.commons.lang3.time.DateUtils;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.GET_ORDER;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.GET_ORDER_LIST;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import static org.testng.Assert.*;
/**
* 应用版本付费订单相关接口测试
*/
public class WxCpTpOrderServiceImplTest {
@Mock
private WxCpTpServiceApacheHttpClientImpl wxCpTpService;
private WxCpTpConfigStorage configStorage;
private WxCpTpOrderService wxCpTpOrderService;
/**
* Sets up.
*/
@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
configStorage = new WxCpTpDefaultConfigImpl();
when(wxCpTpService.getWxCpTpConfigStorage()).thenReturn(configStorage);
wxCpTpOrderService = new WxCpTpOrderServiceImpl(wxCpTpService);
}
/**
* 获取订单详情
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetOrder() throws WxErrorException {
String orderId = "2018091822ks1sd3s";
String result = "" +
"{\n" +
" \"errcode\" : 0,\n" +
" \"errmsg\" : \"ok\",\n" +
" \"orderid\" : \"2018091822ks1sd3s\",\n" +
" \"order_status\" : 1,\n" +
" \"order_type\" : 1,\n" +
" \"paid_corpid\" : \"wwfedd7e5291d63aaa\",\n" +
" \"operator_id\" : \"zhangsan\",\n" +
" \"suiteid\" : \"wx67cce113441ccaaa\",\n" +
" \"appid\" : 1,\n" +
" \"edition_id\" : \"RLS65535\",\n" +
" \"edition_name\" : \"协同版\",\n" +
" \"price\" : 100,\n" +
" \"user_count\" : 1000,\n" +
" \"order_period\": 365,\n" +
" \"order_time\" : 1533702999,\n" +
" \"paid_time\" : 1533702910,\n" +
" \"begin_time\" : 1533702910,\n" +
" \"end_time\" : 1553515904,\n" +
" \"order_from\" : 1,\n" +
" \"operator_corpid\" : \"wwfedd7e5292d63aaa\",\n" +
" \"service_share_amount\" : 60,\n" +
" \"platform_share_amount\" : 10,\n" +
" \"dealer_share_amount\" : 30,\n" +
" \"dealer_corp_info\":\n" +
" {\n" +
" \"corpid\": \"xxxx\",\n" +
" \"corp_name\": \"name\"\n" +
" }\n" +
" }";
String url = configStorage.getApiUrl(GET_ORDER);
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
final WxCpTpOrderDetails orderDetails = wxCpTpOrderService.getOrder(orderId);
assertNotNull(orderDetails);
assertEquals(orderDetails.getOrderId(), orderId);
}
/**
* 获取订单列表
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetOrderList() throws WxErrorException {
String orderId = "2018091822ks1sd3s";
Date startTime = new Date();
Date endTime = DateUtils.addDays(startTime, 5);
Integer testMode = 0;
String result = "" +
" {\n" +
" \"errcode\" : 0,\n" +
" \"errmsg\" : \"ok\",\n" +
" \"order_list\": [\n" +
" {\n" +
" \"orderid\" : \"2018091822ks1sd3s\",\n" +
" \"order_status\" : 1,\n" +
" \"order_type\" : 1,\n" +
" \"paid_corpid\" : \"wwfedd7e5292d63aaa\",\n" +
" \"operator_id\" : \"zhangsan\",\n" +
" \"suiteid\" : \"wx67cce113441cc7a6\",\n" +
" \"appid\" : 1,\n" +
" \"edition_id\" : \"RLS65535\",\n" +
" \"edition_name\" : \"协同版\",\n" +
" \"price\" : 100,\n" +
" \"user_count\" : 1000,\n" +
" \"order_period\": 365,\n" +
" \"order_time\" : 1533702999,\n" +
" \"paid_time\" : 1533702910,\n" +
" \"begin_time\" : 1533702910,\n" +
" \"end_time\" : 1553515904,\n" +
" \"order_from\" : 1,\n" +
" \"operator_corpid\" : \"wwfedd7e5292d63aaa\",\n" +
" \"service_share_amount\" : 60,\n" +
" \"platform_share_amount\" : 10,\n" +
" \"dealer_share_amount\" : 30,\n" +
" \"dealer_corp_info\":\n" +
" {\n" +
" \"corpid\": \"xxxx\",\n" +
" \"corp_name\": \"name\"\n" +
" }\n" +
" }]\n" +
" }";
String url = configStorage.getApiUrl(GET_ORDER_LIST);
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
final WxCpTpOrderListGetResult orderList = wxCpTpOrderService.getOrderList(startTime, endTime, testMode);
assertNotNull(orderList);
final List<WxCpTpOrderDetails> detailsList = orderList.getOrderList();
assertTrue(Objects.nonNull(detailsList) && !detailsList.isEmpty());
assertEquals(detailsList.get(0).getOrderId(), orderId);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpLicenseServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpLicenseServiceImplTest.java | package me.chanjar.weixin.cp.tp.service.impl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.license.*;
import me.chanjar.weixin.cp.bean.license.account.*;
import me.chanjar.weixin.cp.bean.license.order.*;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpTpDefaultConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpLicenseService;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.*;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.License.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* 许可证账号服务测试
*
* @author Totoro created on 2022/6/27 16:34
*/
public class WxCpTpLicenseServiceImplTest {
@Mock
private WxCpTpServiceApacheHttpClientImpl wxCpTpService;
private WxCpTpConfigStorage configStorage;
private WxCpTpLicenseService wxCpTpLicenseService;
/**
* Sets up.
*/
@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
configStorage = new WxCpTpDefaultConfigImpl();
when(wxCpTpService.getWxCpTpConfigStorage()).thenReturn(configStorage);
wxCpTpLicenseService = new WxCpTpLicenseServiceImpl(wxCpTpService);
}
/**
* Test crate new order.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testCrateNewOrder() throws WxErrorException {
String orderId = "OASFNAISFASFA252462";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"order_id\": \"OASFNAISFASFA252462\"\n" +
"}";
String url =
configStorage.getApiUrl(CREATE_NEW_ORDER) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpTpLicenseNewOrderRequest orderRequest = WxCpTpLicenseNewOrderRequest.builder()
.accountCount(WxCpTpLicenseAccountCount.builder().baseCount(5).externalContactCount(6).build())
.buyerUserId("test")
.corpId("test")
.accountDuration(WxCpTpLicenseAccountDuration.builder().months(5).build())
.build();
final WxCpTpLicenseCreateOrderResp newOrder = wxCpTpLicenseService.createNewOrder(orderRequest);
assertNotNull(newOrder);
assertEquals(newOrder.getOrderId(), orderId);
}
/**
* Test create renew order job.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testCreateRenewOrderJob() throws WxErrorException {
String jobId = "test123456";
String result = "{\n" +
" \"errcode\":0,\n" +
" \"errmsg\":\"ok\",\n" +
" \"jobid\":\"test123456\",\n" +
" \"invalid_account_list\":[\n" +
" {\n" +
" \"errcode\":1,\n" +
" \"errmsg\":\"error\",\n" +
" \"userid\":\"userid1\",\n" +
" \"type\":1\n" +
" },\n" +
" {\n" +
" \"errcode\":0,\n" +
" \"errmsg\":\"ok\",\n" +
" \"userid\":\"userid2\",\n" +
" \"type\":1\n" +
" }\n" +
" ]\n" +
"}";
String url =
configStorage.getApiUrl(CREATE_RENEW_ORDER_JOB) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
List<WxCpTpLicenseBaseAccount> accountList = new ArrayList<>();
accountList.add(WxCpTpLicenseBaseAccount.builder().type(1).userid("userid1").build());
accountList.add(WxCpTpLicenseBaseAccount.builder().type(1).userid("userid2").build());
WxCpTpLicenseRenewOrderJobRequest orderJobRequest = WxCpTpLicenseRenewOrderJobRequest.builder()
.jobId("test123456")
.accountList(accountList).build();
final WxCpTpLicenseRenewOrderJobResp renewOrderJob = wxCpTpLicenseService.createRenewOrderJob(orderJobRequest);
assertNotNull(renewOrderJob);
assertEquals(renewOrderJob.getJobId(), jobId);
assertEquals(renewOrderJob.getInvalidAccountList().size(), accountList.size());
}
/**
* Test submit renew order job.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSubmitRenewOrderJob() throws WxErrorException {
String orderId = "test5915231";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"order_id\": \"test5915231\"\n" +
"}";
String url =
configStorage.getApiUrl(SUBMIT_ORDER_JOB) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpTpLicenseRenewOrderRequest renewOrderRequest = WxCpTpLicenseRenewOrderRequest.builder()
.jobId("test123456")
.accountDuration(WxCpTpLicenseAccountDuration.builder().months(5).build())
.buyerUserId("test")
.build();
WxCpTpLicenseCreateOrderResp createOrderResp = wxCpTpLicenseService.submitRenewOrder(renewOrderRequest);
assertNotNull(createOrderResp);
assertEquals(createOrderResp.getOrderId(), orderId);
}
/**
* Test get order list.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetOrderList() throws WxErrorException {
String nextCursor = "DSGAKAFA4524";
String orderId = "test123";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"next_cursor\":\"DSGAKAFA4524\",\n" +
"\t\"has_more\":1,\n" +
"\t\"order_list\":[\n" +
"\t\t{\n" +
"\t\t\t\"order_id\":\"test123\",\n" +
"\t\t\t\"order_type\":1\n" +
"\t\t}\n" +
"\t]\n" +
"}";
String url = configStorage.getApiUrl(LIST_ORDER) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpTpLicenseOrderListResp orderList = wxCpTpLicenseService.getOrderList("test", new Date(), new Date(), null, 10);
assertNotNull(orderList);
assertEquals(orderList.getNextCursor(), nextCursor);
assertEquals(orderList.getOrderList().get(0).getOrderId(), orderId);
}
/**
* Test get order.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetOrder() throws WxErrorException {
String corpId = "ASFASF4254";
String orderId = "FASASIFJ9W125234";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"order\":{\n" +
"\t\t\"order_id\":\"FASASIFJ9W125234\",\n" +
"\t\t\"order_type\":1,\n" +
"\t\t\"order_status\":1,\n" +
"\t\t\"corpid\":\"ASFASF4254\",\n" +
"\t\t\"price\":10000,\n" +
"\t\t\"account_count\":{\n" +
"\t \t \"base_count\":100,\n" +
" \t \"external_contact_count\":100\n" +
"\t },\n" +
"\t\t \"account_duration\":\n" +
" \t\t {\n" +
"\t \t \t\"months\":2\n" +
" \t \t \t},\n" +
"\t\t\"create_time\":150000000,\n" +
"\t \"pay_time\":1550000000\n" +
"\t}\n" +
"}";
String url = configStorage.getApiUrl(GET_ORDER) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpTpLicenseOrderInfoResp orderInfo = wxCpTpLicenseService.getOrderInfo(orderId);
assertNotNull(orderInfo);
assertNotNull(orderInfo.getOrder());
assertEquals(orderInfo.getOrder().getOrderId(), orderId);
assertEquals(orderInfo.getOrder().getCorpId(), corpId);
}
/**
* Test get order account.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetOrderAccount() throws WxErrorException {
String orderId = "ASFASF4254";
String activeCode = "FASASIFJ9W125234";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"next_cursor\": \"ASFASF4254\",\n" +
"\t\"has_more\":1,\n" +
"\t\"account_list\":[\n" +
"\t\t{\n" +
"\t\t\t\"active_code\": \"FASASIFJ9W125234\",\n" +
"\t\t\t\"userid\":\"XXX\",\n" +
"\t\t\t\"type\": 1\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"active_code\": \"code2\",\n" +
"\t\t\t\"userid\":\"XXX\",\n" +
"\t\t\t\"type\": 2\n" +
"\t\t}\n" +
"\t]\n" +
"}";
String url =
configStorage.getApiUrl(LIST_ORDER_ACCOUNT) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpTpLicenseOrderAccountListResp orderAccountList = wxCpTpLicenseService.getOrderAccountList(orderId, 10, null);
assertNotNull(orderAccountList);
assertNotNull(orderAccountList.getAccountList());
assertEquals(orderAccountList.getAccountList().get(0).getActiveCode(), activeCode);
}
/**
* Test active account.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testActiveAccount() throws WxErrorException {
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\"\n" +
"}";
String url =
configStorage.getApiUrl(ACTIVE_ACCOUNT) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpBaseResp wxCpBaseResp = wxCpTpLicenseService.activeCode("123456", "123456", "123456");
assertNotNull(wxCpBaseResp);
}
/**
* Test batch active account.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testBatchActiveAccount() throws WxErrorException {
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"active_result\":[\n" +
"\t{\n" +
"\t\t\"active_code\" : \"aASFINAJOFASF\",\n" +
"\t\t\"userid\": \"SAGASGSD\",\n" +
"\t\t\"errcode\":0\n" +
"\t},\n" +
"\t{\n" +
"\t\t\"active_code\" : \"ASDEGAFAd\",\n" +
"\t\t\"userid\": \"dsfafD\",\n" +
"\t\t\"errcode\":0\n" +
"\t}]\n" +
"}";
String url =
configStorage.getApiUrl(BATCH_ACTIVE_ACCOUNT) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
List<WxCpTpLicenseActiveAccount> accountList = new ArrayList<>();
accountList.add(WxCpTpLicenseActiveAccount.builder().userid("SAGASGSD").activeCode("aASFINAJOFASF").build());
accountList.add(WxCpTpLicenseActiveAccount.builder().userid("dsfafD").activeCode("ASDEGAFAd").build());
WxCpTpLicenseBatchActiveResultResp wxCpTpLicenseBatchActiveResultResp = wxCpTpLicenseService.batchActiveCode(
"123456", accountList);
assertNotNull(wxCpTpLicenseBatchActiveResultResp);
assertEquals(wxCpTpLicenseBatchActiveResultResp.getActiveResults().size(), accountList.size());
assertEquals(wxCpTpLicenseBatchActiveResultResp.getActiveResults().get(0).getActiveCode(), "aASFINAJOFASF");
}
/**
* Test get active info by code.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetActiveInfoByCode() throws WxErrorException {
String activeCode = "asgasfasfa";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"active_info\": {\n" +
"\t\t\"active_code\": \"asgasfasfa\",\n" +
"\t\t\"type\": 1,\n" +
"\t\t\"status\": 1,\n" +
"\t\t\"userid\": \"asfasgasg\",\n" +
"\t\t\"create_time\":1640966400,\n" +
"\t\t\"active_time\": 1640966400,\n" +
"\t\t\"expire_time\":1640966400\n" +
"\t}\n" +
"}";
String url =
configStorage.getApiUrl(GET_ACTIVE_INFO_BY_CODE) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpTpLicenseCodeInfoResp activeInfoByCode = wxCpTpLicenseService.getActiveInfoByCode("123456", "safasg");
assertNotNull(activeInfoByCode);
assertEquals(activeInfoByCode.getActiveCodeInfo().getActiveCode(), activeCode);
}
/**
* Test get active info by user.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetActiveInfoByUser() throws WxErrorException {
String activeCode = "asfaisfhiuaw";
String userid = "asfasgasga";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"active_status\": 1,\n" +
"\t\"active_info_list\": \n" +
"\t[\n" +
"\t\t {\n" +
"\t\t\t\"active_code\": \"asfaisfhiuaw\",\n" +
"\t\t\t\"type\": 1,\n" +
"\t\t\t\"userid\": \"asfasgasga\",\n" +
"\t\t\t\"active_time\": 1640966400,\n" +
"\t\t\t\"expire_time\":1640966400\n" +
" \t \t },\n" +
" {\n" +
"\t\t\t\"active_code\": \"gasdawsd\",\n" +
"\t\t\t\"type\": 2,\n" +
"\t\t\t\"userid\": \"asdfasfasf\",\n" +
"\t\t\t\"active_time\":1640966400,\n" +
"\t\t\t\"expire_time\":1640966400\n" +
"\t\t }\n" +
" ]\n" +
"}";
String url =
configStorage.getApiUrl(GET_ACTIVE_INFO_BY_USER) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpTpLicenseActiveInfoByUserResp activeInfoByUser = wxCpTpLicenseService.getActiveInfoByUser("123456", userid);
assertNotNull(activeInfoByUser);
assertEquals(activeInfoByUser.getActiveStatus().intValue(), 1);
assertEquals(activeInfoByUser.getActiveInfoList().get(0).getActiveCode(), activeCode);
}
/**
* Test batch get active info by user.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testBatchGetActiveInfoByUser() throws WxErrorException {
String activeCode = "asgasgasgas";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"active_info_list\": [\n" +
"\t\t{\n" +
"\t\t\t\"active_code\": \"asgasgasgas\",\n" +
"\t\t\t\"type\": 1,\n" +
"\t\t\t\"status\": 1,\n" +
"\t\t\t\"userid\": \"gadfFDF\",\n" +
"\t\t\t\"create_time\":1640966400,\n" +
"\t\t\t\"active_time\": 1640966400,\n" +
"\t\t\t\"expire_time\":1640966400\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"active_code\": \"awsgdgasdasd\",\n" +
"\t\t\t\"type\": 2,\n" +
"\t\t\t\"status\": 1,\n" +
"\t\t\t\"userid\": \"SGASRDASGAQ\",\n" +
"\t\t\t\"create_time\":1640966400,\n" +
"\t\t\t\"active_time\": 1640966400,\n" +
"\t\t\t\"expire_time\":1640966400\n" +
"\t\t}\n" +
"\t],\n" +
"\t\"invalid_active_code_list\":[\"fasgasga\"]\n" +
"}";
String url =
configStorage.getApiUrl(BATCH_GET_ACTIVE_INFO_BY_CODE) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
Set<String> codes = new HashSet<>();
codes.add("asgasgasgas");
codes.add("awsgdgasdasd");
codes.add("fasgasga");
WxCpTpLicenseBatchCodeInfoResp codeInfoResp = wxCpTpLicenseService.batchGetActiveInfoByCode(codes, "asfasfas");
assertNotNull(codeInfoResp);
assertEquals(codeInfoResp.getActiveCodeInfoList().size(), codes.size() - 1);
assertNotNull(codeInfoResp.getInvalidActiveCodeList());
}
/**
* Test get corp account list.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCorpAccountList() throws WxErrorException {
String nextCursor = "asfasdfas";
String userid = "asdasdasd";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"next_cursor\":\"asfasdfas\",\n" +
"\t\"has_more\":1,\n" +
"\t\"account_list\":[\n" +
"\t\t{\n" +
"\t\t\t\"userid\": \"asdasdasd\",\n" +
"\t\t\t\"type\": 1,\n" +
"\t\t\t\"expire_time\":1500000000,\n" +
"\t\t\t\"active_time\":1500000000\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"userid\": \"asgasgasdasd\",\n" +
"\t\t\t\"type\": 1,\n" +
"\t\t\t\"expire_time\":1500000000,\n" +
"\t\t\t\"active_time\":1500000000\n" +
"\t\t}\n" +
"\t]\n" +
"}";
String url =
configStorage.getApiUrl(LIST_ACTIVED_ACCOUNT) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
WxCpTpLicenseCorpAccountListResp accountList = wxCpTpLicenseService.getCorpAccountList("123456", 10, null);
assertNotNull(accountList);
assertNotNull(accountList.getOrderList());
assertEquals(accountList.getNextCursor(), nextCursor);
assertEquals(accountList.getOrderList().get(0).getUserid(), userid);
}
/**
* Test batch transfer license.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testBatchTransferLicense() throws WxErrorException {
String handoverUserid = "dazdasfasf";
String takeoverUserid = "asfasfasf";
String result = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"transfer_result\":[\n" +
"\t{\n" +
"\t\t\"handover_userid\":\"dazdasfasf\",\n" +
"\t\t\"takeover_userid\":\"asfasfasf\",\n" +
"\t\t\"errcode\":0\n" +
"\t}]\n" +
"}";
String url =
configStorage.getApiUrl(BATCH_TRANSFER_LICENSE) + "?provider_access_token=" + wxCpTpService.getWxCpProviderToken();
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
List<WxCpTpLicenseTransfer> transferList = new ArrayList<>();
transferList.add(WxCpTpLicenseTransfer.builder().handoverUserId(handoverUserid).takeoverUserId(takeoverUserid).build());
WxCpTpLicenseBatchTransferResp licenseBatchTransferResp = wxCpTpLicenseService.batchTransferLicense("123456",
transferList);
assertNotNull(licenseBatchTransferResp);
assertNotNull(licenseBatchTransferResp.getTransferResult());
assertEquals(licenseBatchTransferResp.getTransferResult().size(), transferList.size());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpEditionServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpEditionServiceImplTest.java | package me.chanjar.weixin.cp.tp.service.impl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpTpProlongTryResult;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpTpDefaultConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpEditionService;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.PROLONG_TRY;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* 应用版本付费版本相关接口测试
*/
public class WxCpTpEditionServiceImplTest {
@Mock
private WxCpTpServiceApacheHttpClientImpl wxCpTpService;
private WxCpTpConfigStorage configStorage;
private WxCpTpEditionService wxCpTpEditionService;
/**
* Sets up.
*/
@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
configStorage = new WxCpTpDefaultConfigImpl();
when(wxCpTpService.getWxCpTpConfigStorage()).thenReturn(configStorage);
wxCpTpEditionService = new WxCpTpEditionServiceImpl(wxCpTpService);
}
/**
* 延长试用期
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testProlongTry() throws WxErrorException {
String buyerCorpId = "wx7da9abf8ac62baaa";
Integer prolongDays = 7;
String appId = "1";
Long tryEndTime = 1565152189L;
String result = "" +
" {\n" +
" \"errcode\" : 0,\n" +
" \"errmsg\" : \"ok\",\n" +
" \"try_end_time\" : 1565152189\n" +
" }";
String url = configStorage.getApiUrl(PROLONG_TRY);
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
final WxCpTpProlongTryResult prolongTryResult = wxCpTpEditionService.prolongTry(buyerCorpId, prolongDays, appId);
assertNotNull(prolongTryResult);
assertEquals(prolongTryResult.getTryEndTime(), tryEndTime);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/BaseWxCpTpServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/BaseWxCpTpServiceImplTest.java | package me.chanjar.weixin.cp.tp.service.impl;
import com.google.gson.JsonObject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.redis.RedissonWxRedisOps;
import me.chanjar.weixin.cp.bean.WxCpTpAuthInfo;
import me.chanjar.weixin.cp.bean.WxCpTpCorp;
import me.chanjar.weixin.cp.bean.WxCpTpPermanentCodeInfo;
import me.chanjar.weixin.cp.bean.WxTpCustomizedAuthUrl;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpTpDefaultConfigImpl;
import me.chanjar.weixin.cp.config.impl.AbstractWxCpTpInRedisConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedisTemplateConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedissonConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import org.mockito.Mockito;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.GET_AUTH_INFO;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tp.GET_PERMANENT_CODE;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 测试代码.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2019-08-18
*/
public class BaseWxCpTpServiceImplTest {
private final WxCpTpService tpService = Mockito.spy(new WxCpTpServiceApacheHttpClientImpl());
/**
* The constant PROVIDER_CORP_ID.
*/
public static final String PROVIDER_CORP_ID = "xxxxxx";
/**
* The constant PROVIDER_SECRET.
*/
public static final String PROVIDER_SECRET = "xxxxxx";
/**
* The constant REDIS_ADDR.
*/
public static final String REDIS_ADDR = "redis://xxx.xxx.xxx.xxx:6379";
/**
* The constant REDIS_PASSWD.
*/
public static final String REDIS_PASSWD = "xxxxxx";
private WxCpTpService wxCpTpService;
/**
* Sets up.
*/
@BeforeMethod
public void setUp() {
wxCpTpService = new WxCpTpServiceApacheHttpClientImpl();
wxCpTpService.setWxCpTpConfigStorage(wxCpTpConfigStorage());
}
/**
* Wx cp tp config storage wx cp tp config storage.
*
* @return the wx cp tp config storage
*/
public WxCpTpConfigStorage wxCpTpConfigStorage() {
WxCpTpRedissonConfigImpl wxCpTpRedissonConfig=new WxCpTpRedissonConfigImpl(redissonClient(),"");
wxCpTpRedissonConfig.setCorpId(PROVIDER_CORP_ID);
wxCpTpRedissonConfig.setProviderSecret(PROVIDER_SECRET);
return wxCpTpRedissonConfig;
}
/**
* Redisson client redisson client.
*
* @return the redisson client
*/
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer().setAddress(REDIS_ADDR).setConnectTimeout(10 * 1000).setDatabase(6)
.setPassword(REDIS_PASSWD).setConnectionMinimumIdleSize(2).setConnectionPoolSize(2);
return Redisson.create(config);
}
/**
* Test check signature.
*/
@Test
public void testCheckSignature() {
}
/**
* Test get suite access token.
*/
@Test
public void testGetSuiteAccessToken() {
}
/**
* Test get suite ticket.
*/
@Test
public void testGetSuiteTicket() {
}
/**
* Test test get suite ticket.
*/
@Test
public void testTestGetSuiteTicket() {
}
/**
* Test js code 2 session.
*/
@Test
public void testJsCode2Session() {
}
/**
* Test get corp token.
*/
@Test
public void testGetCorpToken() {
}
/**
* Test get permanent code.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetPermanentCode() throws WxErrorException {
String returnJson = "{\n" +
" \"errcode\":0 ,\n" +
" \"errmsg\":\"ok\" ,\n" +
" \"access_token\": \"xxxxxx\", \n" +
" \"expires_in\": 7200, \n" +
" \"permanent_code\": \"xxxx\", \n" +
" \"dealer_corp_info\": \n" +
" {\n" +
" \"corpid\": \"xxxx\",\n" +
" \"corp_name\": \"name\"\n" +
" },\n" +
" \"auth_corp_info\": \n" +
" {\n" +
" \"corpid\": \"xxxx\",\n" +
" \"corp_name\": \"name\",\n" +
" \"corp_type\": \"verified\",\n" +
" \"corp_square_logo_url\": \"yyyyy\",\n" +
" \"corp_user_max\": 50,\n" +
" \"corp_agent_max\": 30,\n" +
" \"corp_full_name\":\"full_name\",\n" +
" \"verified_end_time\":1431775834,\n" +
" \"subject_type\": 1,\n" +
" \"corp_wxqrcode\": \"zzzzz\",\n" +
" \"corp_scale\": \"1-50人\",\n" +
" \"corp_industry\": \"IT服务\",\n" +
" \"corp_sub_industry\": \"计算机软件/硬件/信息服务\",\n" +
" \"location\":\"广东省广州市\"\n" +
" },\n" +
" \"auth_info\":\n" +
" {\n" +
" \"agent\" :\n" +
" [\n" +
" {\n" +
" \"agentid\":1,\n" +
" \"name\":\"NAME\",\n" +
" \"round_logo_url\":\"xxxxxx\",\n" +
" \"square_logo_url\":\"yyyyyy\",\n" +
" \"appid\":1,\n" +
" \"privilege\":\n" +
" {\n" +
" \"level\":1,\n" +
" \"allow_party\":[1,2,3],\n" +
" \"allow_user\":[\"zhansan\",\"lisi\"],\n" +
" \"allow_tag\":[1,2,3],\n" +
" \"extra_party\":[4,5,6],\n" +
" \"extra_user\":[\"wangwu\"],\n" +
" \"extra_tag\":[4,5,6]\n" +
" }\n" +
" },\n" +
" {\n" +
" \"agentid\":2,\n" +
" \"name\":\"NAME2\",\n" +
" \"round_logo_url\":\"xxxxxx\",\n" +
" \"square_logo_url\":\"yyyyyy\",\n" +
" \"appid\":5\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"auth_user_info\":\n" +
" {\n" +
" \"userid\":\"aa\",\n" +
" \"name\":\"xxx\",\n" +
" \"avatar\":\"http://xxx\"\n" +
" }\n" +
"}\n";
final WxCpTpConfigStorage configStorage = new WxCpTpDefaultConfigImpl();
tpService.setWxCpTpConfigStorage(configStorage);
JsonObject jsonObject = new JsonObject();
String authCode = "";
jsonObject.addProperty("auth_code", authCode);
Mockito.doReturn(returnJson).when(tpService).post(configStorage.getApiUrl(GET_PERMANENT_CODE),
jsonObject.toString());
final WxCpTpCorp tpCorp = tpService.getPermanentCode(authCode);
assertThat(tpCorp.getPermanentCode()).isEqualTo("xxxx");
final WxCpTpPermanentCodeInfo tpPermanentCodeInfo = tpService.getPermanentCodeInfo(authCode);
assertThat(tpPermanentCodeInfo.getAuthInfo().getAgents().get(0).getAgentId()).isEqualTo(1);
}
/**
* Test get permanent code info.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetPermanentCodeInfo() throws WxErrorException {
String returnJson = "{\n" +
" \"access_token\": \"u6SoEWyrEmworJ1uNzddbiXh42mCLNU_mdd6b01Afo2LKmyi-WdaaYqhEGFZjB1RGZ" +
"-rhjLcAJ86ger7b7Q0gowSw9iIDR8dm49aVH_MztzmQttP3XFG7np1Dxs_VQkVwhhRmfRpEonAmK1_JWIFqayJXXiPUS3LsFd3tWpE7rxmsRa7Ev2ml2htbRp_qGUjtFTErKoDsnNGSka6_RqFPA\", \n" +
" \"expires_in\": 7200, \n" +
" \"permanent_code\": \"lMLlxss77ntxzuEl1i1_AQ3-6-cvqMLYs209YNWVruk\", \n" +
" \"auth_corp_info\": {\n" +
" \"corpid\": \"xxxcorpid\", \n" +
" \"corp_name\": \"xxxx有限公司\", \n" +
" \"corp_type\": \"unverified\", \n" +
" \"corp_round_logo_url\": \"http://p.qpic" +
".cn/pic_wework/3777001839/4046834be7a5f2711feaaa3cc4e691e1bcb1e526cb4544b5/0\", \n" +
" \"corp_square_logo_url\": \"https://p.qlogo" +
".cn/bizmail/EsvsszIt9hJrjrx8QKXuIs0iczdnV4icaPibLIViaukn1iazCay8L1UXtibA/0\", \n" +
" \"corp_user_max\": 200, \n" +
" \"corp_agent_max\": 300, \n" +
" \"corp_wxqrcode\": \"http://p.qpic" +
".cn/pic_wework/211781738/a9af41a60af7519775dd7ac846a4942979dc4a14b8bb2c72/0\", \n" +
" \"corp_full_name\": \"xxxx有限公司\", \n" +
" \"subject_type\": 1, \n" +
" \"corp_scale\": \"1-50人\", \n" +
" \"corp_industry\": \"生活服务\", \n" +
" \"corp_sub_industry\": \"租赁和商务服务\", \n" +
" \"location\": \"北京市\"\n" +
" }, \n" +
" \"auth_info\": {\n" +
" \"agent\": [\n" +
" {\n" +
" \"agentid\": 1000012, \n" +
" \"name\": \"xxxxx\", \n" +
" \"square_logo_url\": \"http://wx.qlogo" +
".cn/mmhead/Q3auHgzwzM4ZCtdxicN8ghMOtTv7M7rLPKmeZ3amic00btdwbNmicaW3Q/0\", \n" +
" \"privilege\": {\n" +
" \"level\": 1, \n" +
" \"allow_party\": [ ], \n" +
" \"allow_user\": [\n" +
" \"yuanqixun\"\n" +
" ], \n" +
" \"allow_tag\": [ ], \n" +
" \"extra_party\": [ ], \n" +
" \"extra_user\": [ ], \n" +
" \"extra_tag\": [ ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" }, \n" +
" \"auth_user_info\": {\n" +
" \"userid\": \"yuanqixun\", \n" +
" \"name\": \"袁启勋\", \n" +
" \"avatar\": \"http://wework.qpic.cn/bizmail/ZYqy8EswiaFyPnk7gy7eiafoicz3TL35f4bAvCf2eSe6RVYSK7aPDFxcw/0" +
"\"\n" +
" },\n" +
" \"edition_info\":\n" +
" {\n" +
" \"agent\" :\n" +
" [\n" +
" {\n" +
" \"agentid\":1,\n" +
" \"edition_id\":\"RLS65535\",\n" +
" \"edition_name\":\"协同版\",\n" +
" \"app_status\":3,\n" +
" \"user_limit\":200,\n" +
" \"expired_time\":1541990791\n" +
" },\n" +
" {\n" +
" \"agentid\":1,\n" +
" \"edition_id\":\"RLS65535\",\n" +
" \"edition_name\":\"协同版\",\n" +
" \"app_status\":3,\n" +
" \"user_limit\":200,\n" +
" \"expired_time\":1541990791,\n" +
" \"is_virtual_version\":false,\n" +
" \"is_shared_from_other_corp\":true\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
final WxCpTpConfigStorage configStorage = new WxCpTpDefaultConfigImpl();
tpService.setWxCpTpConfigStorage(configStorage);
JsonObject jsonObject = new JsonObject();
String authCode = "";
jsonObject.addProperty("auth_code", authCode);
Mockito.doReturn(returnJson).when(tpService).post(configStorage.getApiUrl(GET_PERMANENT_CODE),
jsonObject.toString());
final WxCpTpPermanentCodeInfo tpPermanentCodeInfo = tpService.getPermanentCodeInfo(authCode);
assertThat(tpPermanentCodeInfo.getAuthInfo().getAgents().get(0).getAgentId()).isEqualTo(1000012);
Assert.assertNotNull(tpPermanentCodeInfo.getAuthInfo().getAgents().get(0).getSquareLogoUrl());
Assert.assertNotNull(tpPermanentCodeInfo.getAuthCorpInfo().getCorpSquareLogoUrl());
final WxCpTpPermanentCodeInfo.EditionInfo editionInfo = tpPermanentCodeInfo.getEditionInfo();
Assert.assertNotNull(editionInfo);
final List<WxCpTpPermanentCodeInfo.Agent> editionInfoAgents = editionInfo.getAgents();
Assert.assertTrue(Objects.nonNull(editionInfoAgents) && !editionInfoAgents.isEmpty());
Assert.assertNotNull(editionInfoAgents.get(0).getExpiredTime());
}
/**
* Test get auth info.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetAuthInfo() throws WxErrorException {
String returnJson = "{\n" +
" \"errcode\":0 ,\n" +
" \"errmsg\":\"ok\" ,\n" +
" \"dealer_corp_info\": \n" +
" {\n" +
" \"corpid\": \"xxxx\",\n" +
" \"corp_name\": \"name\"\n" +
" },\n" +
" \"auth_corp_info\": \n" +
" {\n" +
" \"corpid\": \"xxxx\",\n" +
" \"corp_name\": \"name\",\n" +
" \"corp_type\": \"verified\",\n" +
" \"corp_square_logo_url\": \"yyyyy\",\n" +
" \"corp_user_max\": 50,\n" +
" \"corp_agent_max\": 30,\n" +
" \"corp_full_name\":\"full_name\",\n" +
" \"verified_end_time\":1431775834,\n" +
" \"subject_type\": 1,\n" +
" \"corp_wxqrcode\": \"zzzzz\",\n" +
" \"corp_scale\": \"1-50人\",\n" +
" \"corp_industry\": \"IT服务\",\n" +
" \"corp_sub_industry\": \"计算机软件/硬件/信息服务\",\n" +
" \"location\":\"广东省广州市\"\n" +
" },\n" +
" \"auth_info\":\n" +
" {\n" +
" \"agent\" :\n" +
" [\n" +
" {\n" +
" \"agentid\":1,\n" +
" \"name\":\"NAME\",\n" +
" \"round_logo_url\":\"xxxxxx\",\n" +
" \"square_logo_url\":\"yyyyyy\",\n" +
" \"appid\":1,\n" +
" \"privilege\":\n" +
" {\n" +
" \"level\":1,\n" +
" \"allow_party\":[1,2,3],\n" +
" \"allow_user\":[\"zhansan\",\"lisi\"],\n" +
" \"allow_tag\":[1,2,3],\n" +
" \"extra_party\":[4,5,6],\n" +
" \"extra_user\":[\"wangwu\"],\n" +
" \"extra_tag\":[4,5,6]\n" +
" }\n" +
" },\n" +
" {\n" +
" \"agentid\":2,\n" +
" \"name\":\"NAME2\",\n" +
" \"round_logo_url\":\"xxxxxx\",\n" +
" \"square_logo_url\":\"yyyyyy\",\n" +
" \"appid\":5\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"edition_info\":\n" +
" {\n" +
" \"agent\" :\n" +
" [\n" +
" {\n" +
" \"agentid\":1,\n" +
" \"edition_id\":\"RLS65535\",\n" +
" \"edition_name\":\"协同版\",\n" +
" \"app_status\":3,\n" +
" \"user_limit\":200,\n" +
" \"expired_time\":1541990791,\n" +
" \"is_virtual_version\":false,\n" +
" \"is_shared_from_other_corp\":true\n" +
" },\n" +
" {\n" +
" \"agentid\":1,\n" +
" \"edition_id\":\"RLS65535\",\n" +
" \"edition_name\":\"协同版\",\n" +
" \"app_status\":3,\n" +
" \"user_limit\":200,\n" +
" \"expired_time\":1541990791,\n" +
" \"is_virtual_version\":false,\n" +
" \"is_shared_from_other_corp\":true\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n";
final WxCpTpConfigStorage configStorage = new WxCpTpDefaultConfigImpl();
tpService.setWxCpTpConfigStorage(configStorage);
JsonObject jsonObject = new JsonObject();
String authCorpId = "xxxxx";
String permanentCode = "xxxxx";
jsonObject.addProperty("auth_corpid", authCorpId);
jsonObject.addProperty("permanent_code", permanentCode);
Mockito.doReturn(returnJson).when(tpService).post(configStorage.getApiUrl(GET_AUTH_INFO), jsonObject.toString());
WxCpTpAuthInfo authInfo = tpService.getAuthInfo(authCorpId, permanentCode);
Assert.assertNotNull(authInfo.getAuthCorpInfo().getCorpId());
final WxCpTpAuthInfo.EditionInfo editionInfo = authInfo.getEditionInfo();
Assert.assertNotNull(editionInfo);
final List<WxCpTpAuthInfo.Agent> editionInfoAgents = editionInfo.getAgents();
Assert.assertTrue(Objects.nonNull(editionInfoAgents) && !editionInfoAgents.isEmpty());
Assert.assertNotNull(editionInfoAgents.get(0).getExpiredTime());
}
/**
* Test get.
*/
@Test
public void testGet() {
}
/**
* Test post.
*/
@Test
public void testPost() {
}
/**
* Test execute.
*/
@Test
public void testExecute() {
}
/**
* Test execute internal.
*/
@Test
public void testExecuteInternal() {
}
/**
* Test set wx cp tp config storage.
*/
@Test
public void testSetWxCpTpConfigStorage() {
}
/**
* Test set retry sleep millis.
*/
@Test
public void testSetRetrySleepMillis() {
}
/**
* Test set max retry times.
*/
@Test
public void testSetMaxRetryTimes() {
}
/**
* Test get tmp dir file.
*/
@Test
public void testGetTmpDirFile() {
}
/**
* Test set tmp dir file.
*/
@Test
public void testSetTmpDirFile() {
}
/**
* Test get request http.
*/
@Test
public void testGetRequestHttp() {
}
@Test
public void testGetCustomizedAuthUrl() throws WxErrorException {
String state = "test";
List<String> templateIdList = Arrays.asList("");
final WxTpCustomizedAuthUrl customizedAuthUrl = wxCpTpService.getCustomizedAuthUrl(state, templateIdList);
Assert.assertNotNull(customizedAuthUrl);
Assert.assertEquals((long) customizedAuthUrl.getErrcode(), 0);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpTagServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/tp/service/impl/WxCpTpTagServiceImplTest.java | package me.chanjar.weixin.cp.tp.service.impl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpTpTag;
import me.chanjar.weixin.cp.bean.WxCpTpTagAddOrRemoveUsersResult;
import me.chanjar.weixin.cp.bean.WxCpTpTagGetResult;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpTpDefaultConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpTagService;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.collections.CollectionUtils;
import java.util.Arrays;
import java.util.List;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Tag.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.when;
import static org.testng.Assert.*;
/**
* 企业微信-第三方开发-标签管理相关测试
*
* @author zhangq
* @since 2021 /2/15 9:14
*/
public class WxCpTpTagServiceImplTest {
@Mock
private WxCpTpServiceApacheHttpClientImpl wxCpTpService;
private WxCpTpConfigStorage configStorage;
private WxCpTpTagService wxCpTpTagService;
/**
* Sets up.
*/
@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
configStorage = new WxCpTpDefaultConfigImpl();
when(wxCpTpService.getWxCpTpConfigStorage()).thenReturn(configStorage);
wxCpTpTagService = new WxCpTpTagServiceImpl(wxCpTpService);
}
/**
* Test create.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testCreate() throws WxErrorException {
String url = configStorage.getApiUrl(TAG_CREATE);
String tagName = "test_tag_name";
int tagId = 12;
String result = "{\"errcode\":0,\"errmsg\":\"created\",\"tagid\":12}";
when(wxCpTpService.post(eq(url), any(String.class))).thenReturn(result);
assertEquals(wxCpTpTagService.create(tagName, tagId), String.valueOf(tagId));
}
/**
* Test list all.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testListAll() throws WxErrorException {
String url = configStorage.getApiUrl(TAG_LIST);
String result = "{\"errcode\":0,\"errmsg\":\"ok\",\"taglist\":[{\"tagid\":1,\"tagname\":\"a\"},{\"tagid\":2," +
"\"tagname\":\"b\"}]}";
when(wxCpTpService.get(eq(url), anyString())).thenReturn(result);
List<WxCpTpTag> wxCpTpTags = wxCpTpTagService.listAll();
assertNotNull(wxCpTpTags);
assertTrue(CollectionUtils.hasElements(wxCpTpTags));
assertEquals(wxCpTpTags.get(0).getTagId(), "1");
assertEquals(wxCpTpTags.get(1).getTagName(), "b");
}
/**
* Test get.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGet() throws WxErrorException {
String tagId = "anyTagId";
String url = String.format(configStorage.getApiUrl(TAG_GET), tagId);
String result = "{\"errcode\":0,\"errmsg\":\"ok\",\"tagname\":\"乒乓球协会\",\"userlist\":[{\"userid\":\"zhangsan\"," +
"\"name\":\"李四\"}],\"partylist\":[2]}";
when(wxCpTpService.get(eq(url), anyString())).thenReturn(result);
WxCpTpTagGetResult getResult = wxCpTpTagService.get(tagId);
assertEquals(getResult.getTagname(), "乒乓球协会");
assertEquals((int) getResult.getPartylist().get(0), 2);
assertEquals(getResult.getUserlist().get(0).getUserId(), "zhangsan");
}
/**
* Test add users 2 tag.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testAddUsers2Tag() throws WxErrorException {
String tagId = "anyTagId";
String url = configStorage.getApiUrl(TAG_ADD_TAG_USERS);
// 成功时返回对象
String success = "{\"errcode\":0,\"errmsg\":\"ok\"}";
when(wxCpTpService.post(eq(url), anyString())).thenReturn(success);
WxCpTpTagAddOrRemoveUsersResult postResult = wxCpTpTagService
.addUsers2Tag(tagId, Arrays.asList("usr1", "usr2"), Arrays.asList("dept1", "dept2"));
assertEquals((int) postResult.getErrCode(), 0);
assertNull(postResult.getInvalidParty());
assertNull(postResult.getInvalidUsers());
// 部分失败时返回对象
String partFailure = "{\"errcode\":0,\"errmsg\":\"ok\",\"invalidlist\":\"usr1|usr2\",\"invalidparty\":[2,3,4]}";
when(wxCpTpService.post(eq(url), anyString())).thenReturn(partFailure);
postResult = wxCpTpTagService.addUsers2Tag(tagId, Arrays.asList("usr1", "usr2"), Arrays.asList("dept1", "dept2"));
assertEquals((int) postResult.getErrCode(), 0);
assertEquals(postResult.getInvalidUserList().size(), 2);
assertEquals(postResult.getInvalidUserList().get(1), "usr2");
assertEquals(postResult.getInvalidParty().length, 3);
assertEquals(postResult.getInvalidParty()[1], "3");
// 全部失败时返回对象
String allFailure = "{\"errcode\":40070,\"errmsg\":\"all list invalid \"}";
when(wxCpTpService.post(eq(url), anyString())).thenReturn(allFailure);
postResult = wxCpTpTagService.addUsers2Tag(tagId, Arrays.asList("usr1", "usr2"), Arrays.asList("dept1", "dept2"));
assertEquals((int) postResult.getErrCode(), 40070);
assertNull(postResult.getInvalidParty());
assertNull(postResult.getInvalidUsers());
}
/**
* Test remove users from tag.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testRemoveUsersFromTag() throws WxErrorException {
String tagId = "anyTagId";
String url = configStorage.getApiUrl(TAG_DEL_TAG_USERS);
// 成功时返回对象
String success = "{\"errcode\":0,\"errmsg\":\"ok\"}";
when(wxCpTpService.post(eq(url), anyString())).thenReturn(success);
WxCpTpTagAddOrRemoveUsersResult postResult = wxCpTpTagService
.removeUsersFromTag(tagId, Arrays.asList("usr1", "usr2"), Arrays.asList("dept1", "dept2"));
assertEquals((int) postResult.getErrCode(), 0);
assertNull(postResult.getInvalidParty());
assertNull(postResult.getInvalidUsers());
// 部分失败时返回对象
String partFailure = "{\"errcode\":0,\"errmsg\":\"ok\",\"invalidlist\":\"usr1|usr2\",\"invalidparty\":[2,3,4]}";
when(wxCpTpService.post(eq(url), anyString())).thenReturn(partFailure);
postResult = wxCpTpTagService.removeUsersFromTag(tagId, Arrays.asList("usr1", "usr2"), Arrays.asList("dept1",
"dept2"));
assertEquals((int) postResult.getErrCode(), 0);
assertEquals(postResult.getInvalidUserList().size(), 2);
assertEquals(postResult.getInvalidUserList().get(1), "usr2");
assertEquals(postResult.getInvalidParty().length, 3);
assertEquals(postResult.getInvalidParty()[1], "3");
// 全部失败时返回对象
String allFailure = "{\"errcode\":40070,\"errmsg\":\"all list invalid \"}";
when(wxCpTpService.post(eq(url), anyString())).thenReturn(allFailure);
postResult = wxCpTpTagService.removeUsersFromTag(tagId, Arrays.asList("usr1", "usr2"), Arrays.asList("dept1",
"dept2"));
assertEquals((int) postResult.getErrCode(), 40070);
assertNull(postResult.getInvalidParty());
assertNull(postResult.getInvalidUsers());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java | package me.chanjar.weixin.cp.api;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import java.io.IOException;
import java.io.InputStream;
/**
* The type Api test module.
*/
@Slf4j
public class ApiTestModule implements Module {
private static final String TEST_CONFIG_XML = "test-config.xml";
/**
* The Config.
*/
protected WxXmlCpInMemoryConfigStorage config;
private static <T> T fromXml(Class<T> clazz, InputStream is) {
XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", clazz);
xstream.processAnnotations(clazz);
return (T) xstream.fromXML(is);
}
@Override
public void configure(Binder binder) {
try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(TEST_CONFIG_XML)) {
if (inputStream == null) {
throw new WxRuntimeException("测试配置文件【" + TEST_CONFIG_XML + "】未找到,请参照test-config-sample.xml文件生成");
}
config = fromXml(WxXmlCpInMemoryConfigStorage.class, inputStream);
WxCpService wxService = new WxCpServiceImpl();
wxService.setWxCpConfigStorage(config);
binder.bind(WxCpService.class).toInstance(wxService);
binder.bind(WxXmlCpInMemoryConfigStorage.class).toInstance(config);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* The type Wx xml cp in memory config storage.
*/
@Data
@EqualsAndHashCode(callSuper = true)
@XStreamAlias("xml")
public static class WxXmlCpInMemoryConfigStorage extends WxCpDefaultConfigImpl {
private static final long serialVersionUID = -4521839921547374822L;
/**
* The User id.
*/
protected String userId;
/**
* The Department id.
*/
protected String departmentId;
/**
* The Tag id.
*/
protected String tagId;
/**
* The External user id.
*/
protected String externalUserId;
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpOaWeDriveServiceTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpOaWeDriveServiceTest.java | package me.chanjar.weixin.cp.api;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.oa.wedrive.*;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.demo.WxCpDemoInMemoryConfigStorage;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
/**
* 微盘测试类.
* 官方文档:https://developer.work.weixin.qq.com/document/path/93654
*
* @author Wang_Wong
*/
@Slf4j
public class WxCpOaWeDriveServiceTest {
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService cpService;
/**
* Test.
*
* @throws Exception the exception
*/
@Test
public void test() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(inputStream);
wxCpConfigStorage = config;
cpService = new WxCpServiceImpl();
cpService.setWxCpConfigStorage(config);
String createSpace = "{\"userid\":\"USERID\",\"space_name\":\"SPACE_NAME\",\"auth_info\":[{\"type\":1," +
"\"userid\":\"USERID\",\"auth\":2},{\"type\":2,\"departmentid\":2,\"auth\":1}]}";
WxCpSpaceCreateRequest wxCpSpaceCreateRequest = WxCpSpaceCreateRequest.fromJson(createSpace);
log.info(wxCpSpaceCreateRequest.toJson());
String uId = "WangKai";
String spId = "s.ww45d3e188865aca30.652091685u4h";
// 空间的文件id
String fileId = "s.ww45d3e188865aca30.652091685u4h_f.652344507ysDL";
String fileId2 = "s.ww45d3e188865aca30.652091685u4h_f.652696024TU4P";
/*
* 获取分享链接
*/
WxCpFileShare fileShare = cpService.getOaWeDriveService().fileShare(fileId2);
log.info("获取分享链接返回结果为:{}", fileShare.toJson());
/*
* 分享设置
*/
WxCpBaseResp fileSetting = cpService.getOaWeDriveService().fileSetting(fileId2, 2, 1);
log.info("分享设置返回结果为:{}", fileSetting.toJson());
/*
* 删除指定人
*/
WxCpFileAclDelRequest aclDelRequest = new WxCpFileAclDelRequest();
aclDelRequest.setUserId(uId);
aclDelRequest.setFileId(fileId2);
ArrayList<WxCpFileAclDelRequest.AuthInfo> aclDelList = Lists.newArrayList();
WxCpFileAclDelRequest.AuthInfo aclDelAuthInfo = new WxCpFileAclDelRequest.AuthInfo();
aclDelAuthInfo.setType(1);
aclDelAuthInfo.setUserId(uId);
aclDelList.add(aclDelAuthInfo);
aclDelRequest.setAuthInfo(aclDelList);
WxCpBaseResp aclDel = cpService.getOaWeDriveService().fileAclDel(aclDelRequest);
log.info("删除指定人返回结果为:{}", aclDel.toJson());
/*
* 新增指定人
*/
WxCpFileAclAddRequest fileAclAdd = new WxCpFileAclAddRequest();
fileAclAdd.setUserId(uId);
fileAclAdd.setFileId(fileId2);
var authInfoData = new WxCpFileAclAddRequest.AuthInfo();
authInfoData.setType(1);
authInfoData.setAuth(1);
authInfoData.setUserId(uId);
ArrayList<WxCpFileAclAddRequest.AuthInfo> authList = Lists.newArrayList();
authList.add(authInfoData);
fileAclAdd.setAuthInfo(authList);
WxCpBaseResp result = cpService.getOaWeDriveService().fileAclAdd(fileAclAdd);
log.info("返回结果为:{}", result.toJson());
/*
* 删除文件
*/
ArrayList<String> fileIds = Lists.newArrayList();
fileIds.add(fileId);
WxCpBaseResp fileDelete = cpService.getOaWeDriveService().fileDelete(fileIds);
log.info("删除文件数据为:{}", fileDelete.toJson());
/*
文件信息
*/
WxCpFileInfo fileInfo = cpService.getOaWeDriveService().fileInfo(fileId);
log.info("fileInfo数据为:{}", fileInfo.toJson());
/*
移动文件
*/
WxCpFileMoveRequest fileMoveRequest = new WxCpFileMoveRequest();
fileMoveRequest.setFatherId(spId);
fileMoveRequest.setReplace(true);
fileMoveRequest.setFileId(new String[]{fileId});
WxCpFileMove fileMove = cpService.getOaWeDriveService().fileMove(fileMoveRequest);
log.info("fileMove数据为:{}", fileMove.toJson());
/*
新建文件/微文档
*/
WxCpFileCreate fileCreate = cpService.getOaWeDriveService().fileCreate(spId, spId, 3, "新建微文档1");
log.info("新建文件/微文档:{}", fileCreate.toJson());
/*
下载文件
*/
WxCpFileDownload fileDownload = cpService.getOaWeDriveService().fileDownload(uId, fileId);
log.info("下载文件为:{}", fileDownload.toJson());
/*
上传文件
*/
WxCpFileUploadRequest fileUploadRequest = new WxCpFileUploadRequest();
fileUploadRequest.setSpaceId(spId);
fileUploadRequest.setFatherId(spId);
fileUploadRequest.setFileName("第一个文件");
// 将文件转成base64字符串
File file = new File("D:/info.log.2022-05-07.0.log");
// File file = new File("D:/16.png");
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
String encodeBase64Content = Base64.getEncoder().encodeToString(buffer);
fileUploadRequest.setFileBase64Content(encodeBase64Content);
WxCpFileUpload fileUpload = cpService.getOaWeDriveService().fileUpload(fileUploadRequest);
log.info("上传文件为:{}", fileUpload.toJson());
/*
重命名文件
*/
WxCpFileRename fileRename = cpService.getOaWeDriveService().fileRename(fileUpload.getFileId(), "新的名字呢");
log.info("重命名文件:{}", fileRename.toJson());
/*
获取文件列表
*/
WxCpFileListRequest fileListRequest = new WxCpFileListRequest();
fileListRequest.setSpaceId(spId);
fileListRequest.setFatherId(spId);
fileListRequest.setSortType(1);
fileListRequest.setStart(0);
fileListRequest.setLimit(100);
WxCpFileList fileList = cpService.getOaWeDriveService().fileList(fileListRequest);
log.info("获取文件列表为:{}", fileList.toJson());
/*
* 权限管理
*/
WxCpSpaceSettingRequest spaceSettingRequest = new WxCpSpaceSettingRequest();
spaceSettingRequest.setUserId(uId);
spaceSettingRequest.setSpaceId(spId);
// spaceSettingRequest.setEnableWatermark(false);
spaceSettingRequest.setAddMemberOnlyAdmin(true);
spaceSettingRequest.setEnableShareUrl(false);
spaceSettingRequest.setShareUrlNoApprove(true);
spaceSettingRequest.setShareUrlNoApproveDefaultAuth(2);
WxCpBaseResp spaceSetting = cpService.getOaWeDriveService().spaceSetting(spaceSettingRequest);
log.info("权限管理信息为:{}", spaceSetting.toJson());
/*
* 获取邀请链接
*/
WxCpSpaceShare spaceShare = cpService.getOaWeDriveService().spaceShare(spId);
log.info("获取邀请链接信息为:{}", spaceShare.toJson());
/*
* 获取空间信息
*/
WxCpSpaceInfo data = cpService.getOaWeDriveService().spaceInfo(spId);
log.info("获取空间信息为:{}", data.toJson());
/*
* 移除成员/部门
*/
WxCpSpaceAclDelRequest spaceAclDelRequest = new WxCpSpaceAclDelRequest();
spaceAclDelRequest.setUserId(uId);
spaceAclDelRequest.setSpaceId(spId);
// 被移除的空间成员信息
WxCpSpaceAclDelRequest.AuthInfo delAuthInfo = new WxCpSpaceAclDelRequest.AuthInfo();
delAuthInfo.setType(1);
delAuthInfo.setUserId("MiaoMiu99");
List<WxCpSpaceAclDelRequest.AuthInfo> delAuthInfoList = new ArrayList<>();
delAuthInfoList.add(delAuthInfo);
spaceAclDelRequest.setAuthInfo(delAuthInfoList);
WxCpBaseResp spaceAclDel = cpService.getOaWeDriveService().spaceAclDel(spaceAclDelRequest);
log.info("移除成员/部门,返回数据为:{}", spaceAclDel.toJson());
/*
* 添加成员/部门
* https://developer.work.weixin.qq.com/document/path/93656
*/
WxCpSpaceAclAddRequest spaceAclAddRequest = new WxCpSpaceAclAddRequest();
spaceAclAddRequest.setUserId(uId);
spaceAclAddRequest.setSpaceId(spId);
List<WxCpSpaceAclAddRequest.AuthInfo> authInfoList = new ArrayList<>();
// 被添加的空间成员信息
WxCpSpaceAclAddRequest.AuthInfo authInfo = new WxCpSpaceAclAddRequest.AuthInfo();
authInfo.setAuth(2);
authInfo.setType(1);
authInfo.setUserId("MiaoMiu99");
authInfoList.add(authInfo);
spaceAclAddRequest.setAuthInfo(authInfoList);
WxCpBaseResp wxCpBaseResp = cpService.getOaWeDriveService().spaceAclAdd(spaceAclAddRequest);
log.info("添加成员/部门,返回数据为:{}", wxCpBaseResp.toJson());
/*
* 获取空间信息
*/
WxCpSpaceInfo spaceInfo = cpService.getOaWeDriveService().spaceInfo("s.ww45d3e188865aca30.652091685u4h");
log.info("获取空间信息,spaceInfo信息为:{}", spaceInfo.toJson());
/*
* 新建空间
*/
WxCpSpaceCreateRequest request = new WxCpSpaceCreateRequest();
request.setUserId("WangKai");
request.setSpaceName("测试云盘Three");
WxCpSpaceCreateData spaceCreateData = cpService.getOaWeDriveService().spaceCreate(request);
log.info("空间id为:{}", spaceCreateData.getSpaceId()); //
log.info(spaceCreateData.toJson());
/*
* 重命名空间
*/
WxCpSpaceRenameRequest wxCpSpaceRenameRequest = new WxCpSpaceRenameRequest();
wxCpSpaceRenameRequest.setUserId("WangKai");
wxCpSpaceRenameRequest.setSpaceId(spaceCreateData.getSpaceId());
wxCpSpaceRenameRequest.setSpaceName("测试云盘Four");
WxCpBaseResp baseResp = cpService.getOaWeDriveService().spaceRename(wxCpSpaceRenameRequest);
log.info("重命名成功:{}", baseResp.toJson());
/*
* 解散空间
*/
WxCpBaseResp thisResp = cpService.getOaWeDriveService().spaceDismiss(spaceCreateData.getSpaceId());
log.info("解散成功:{}", thisResp.toJson());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModuleWithMockServer.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModuleWithMockServer.java | package me.chanjar.weixin.cp.api;
import com.google.inject.Binder;
/**
* 带mock server 的test module.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-08-30
*/
public class ApiTestModuleWithMockServer extends ApiTestModule {
/**
* The constant mockServerPort.
*/
public static final int mockServerPort = 8080;
@Override
public void configure(Binder binder) {
super.configure(binder);
super.config.setBaseApiUrl("http://localhost:" + mockServerPort);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/TestConstants.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/TestConstants.java | package me.chanjar.weixin.cp.api;
/**
* <pre>
* 仅供测试使用的一些常量
* Created by Binary Wang on 2017-3-9.
* </pre>
*/
public class TestConstants {
/**
* The constant FILE_JPG.
*/
///////////////////////
// 文件类型
///////////////////////
public static final String FILE_JPG = "jpeg";
/**
* The constant FILE_MP3.
*/
public static final String FILE_MP3 = "mp3";
/**
* The constant FILE_AMR.
*/
public static final String FILE_AMR = "amr";
/**
* The constant FILE_MP4.
*/
public static final String FILE_MP4 = "mp4";
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMsgAuditTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMsgAuditTest.java | package me.chanjar.weixin.cp.api;
import com.google.common.collect.Lists;
import com.tencent.wework.Finance;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.XmlUtils;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.msgaudit.*;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.demo.WxCpDemoInMemoryConfigStorage;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.*;
/**
* 企业微信会话内容存档测试类.
* <a href="https://developer.work.weixin.qq.com/document/path/91360">官方文档</a>
*
* @author <a href="https://github.com/0katekate0">Wang_Wong</a>
* created on 2022-01-17
*/
@Slf4j
public class WxCpMsgAuditTest {
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService cpService;
/**
* Test.
*/
// com.binarywang.spring.starter.wxjava.cp.config.WxCpServiceAutoConfiguration
// WxCpServiceImpl.getAccessToken()
@BeforeTest
private void initCpService() {
if (cpService == null) {
InputStream inputStream = ClassLoader.getSystemResourceAsStream("test-config.xml");
wxCpConfigStorage = WxCpDemoInMemoryConfigStorage.fromXml(inputStream);
cpService = new WxCpServiceImpl();
cpService.setWxCpConfigStorage(this.wxCpConfigStorage);
}
}
@Test
public void test() throws Exception {
/*
* 客户同意进行聊天内容存档事件回调
* 配置了客户联系功能的成员添加外部联系人同意进行聊天内容存档时,回调该事件。
*
* https://developer.work.weixin.qq.com/document/path/92005
*/
String msgAuditApprovedXml = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[change_external_contact]]></Event>\n" +
"\t<ChangeType><![CDATA[msg_audit_approved]]></ChangeType>\n" +
"\t<UserID><![CDATA[zhangsan]]></UserID>\n" +
"\t<ExternalUserID><![CDATA[woAJ2GCAAABiuyujaWJHDDGi0mACHAAA]]></ExternalUserID>\n" +
"\t<WelcomeCode><![CDATA[WELCOMECODE]]></WelcomeCode>\n" +
"</xml>";
final WxCpXmlMessage msgAuditApprovedXmlMsg = XStreamTransformer.fromXml(WxCpXmlMessage.class, msgAuditApprovedXml);
msgAuditApprovedXmlMsg.setAllFieldsMap(XmlUtils.xml2Map(msgAuditApprovedXml));
log.info("msgAuditApprovedXmlMsg:{}", WxCpGsonBuilder.create().toJson(msgAuditApprovedXmlMsg));
/*
* 产生会话回调事件
* 为了提升企业会话存档的使用性能,降低无效的轮询次数。
* 当企业收到或发送新消息时,企业微信可以以事件的形式推送到企业指定的url。回调间隔为15秒,在15秒内若有消息则触发回调,若无消息则不会触发回调。
*
* https://developer.work.weixin.qq.com/document/path/95039
*/
String msgAuditNotifyXml = "<xml>\n" +
" <ToUserName><![CDATA[CorpID]]></ToUserName>\n" +
" <FromUserName><![CDATA[sys]]></FromUserName> \n" +
" <CreateTime>1629101687</CreateTime>\n" +
" <MsgType><![CDATA[event]]></MsgType>\n" +
" <AgentID>2000004</AgentID>\n" +
" <Event><![CDATA[msgaudit_notify]]></Event>\n" +
"</xml>";
final WxCpXmlMessage msgAuditNotifyXmlMsg = XStreamTransformer.fromXml(WxCpXmlMessage.class, msgAuditNotifyXml);
msgAuditNotifyXmlMsg.setAllFieldsMap(XmlUtils.xml2Map(msgAuditNotifyXml));
log.info("msgAuditNotifyXmlMsg:{}", WxCpGsonBuilder.create().toJson(msgAuditNotifyXmlMsg));
/*
* 增加变更事件类型:产生会话回调事件
*/
String msgauditNotify = WxCpConsts.EventType.MSGAUDIT_NOTIFY;
/*
* 仔细配置:
* <xml>
* <corpId>ww45xxx88865xxx</corpId>
* <corpSecret>xIpum7Yt4NMXcyxdzcQ2l_46BG4QIQDR57MhA45ebIw</corpSecret> // secret
* <agentId>200000</agentId> // 会话存档的应用id
* <token></token> // 回调配置的token
* <aesKey></aesKey> // 回调配置的EncodingAESKey
*
* // 企业微信会话存档
* // 1、会话存档私钥,最好去除前缀和换行,如下所示!
* // 2、仔细配置windows以及linux环境sdk路径
* <msgAuditPriKey>MIxxx893B2pggd1r95T8k2QxxxxbD6xxxxmXsskn
* +5XunyR1WJlJGqgi0OMVGYvSfkNb9kD50fM21CGLcN1y4miL9fVNBIsvJmIUeJCNS8TioAVGFvh2EgzjqTR1gH</msgAuditPriKey>
* <msgAuditLibPath>/www/osfile/libcrypto-1_1-x64.dll,libssl-1_1-x64.dll,libcurl-x64.dll,WeWorkFinanceSdk.dll,
* libWeWorkFinanceSdk_Java.so</msgAuditLibPath>
* </xml>
*
* 注意:最好先配置lib开头的系统库,再配置sdk类库,配置绝对路径,最好配置为linux路径
* Windows:
* <msgAuditLibPath>D:/WorkSpace/libcrypto-1_1-x64.dll,libssl-1_1-x64.dll,libcurl-x64.dll,WeWorkFinanceSdk.dll,
* libWeWorkFinanceSdk_Java.so</msgAuditLibPath>
* Linux:
* <msgAuditLibPath>/www/osfile/work_msg_storage/libcrypto-1_1-x64.dll,libssl-1_1-x64.dll,libcurl-x64.dll,
* WeWorkFinanceSdk.dll,libWeWorkFinanceSdk_Java.so</msgAuditLibPath>
*
*
* yml配置(支持多个corpId):
* wx:
* cp:
* appConfigs:
* - agentId: 10001 #客户联系
* corpId: xxxxxxxxxxx
* secret: T5fTj1n-sBAT4rKNW5c9IYNfPdXZxxxxxxxxxxx
* token: 2bSNqTcLtxxxxxxxxxxx
* aesKey: AXazu2Xyw44SNY1x8go2phn9p9B2xxxxxxxxxxx
* - agentId: 10002 #会话内容存档
* corpId: xxxxxxxxxxx
* secret: xIpum7Yt4NMXcyxdzcQ2l_46BG4Qxxxxxxxxxxx
* token:
* aesKey:
* msgAuditPriKey: MIxxx893B2pggd1r95T8k2QxxxxbD6xxxxmXsskn
* +5XunyR1WJlJGqgi0OMVGYvSfkNb9kD50fM21CGLcN1y4miL9fVNBIsvJmIUeJCNS8TioAVGFvh2EgzjqTR1gHxxx
* msgAuditLibPath: /www/osfile/libcrypto-1_1-x64.dll,libssl-1_1-x64.dll,libcurl-x64.dll,WeWorkFinanceSdk
* .dll,libWeWorkFinanceSdk_Java.so
*
*
* 在线生成非对称加密公钥私钥对:
* http://web.chacuo.net/netrsakeypair
*
*
* 或者可以在linux上使用如下命令生成公钥私钥对:
* openssl genrsa -out private_key.pem 2048
* openssl rsa -in private_key.pem -pubout -out public_key.pem
* /
/*
* 建议放到redis,本次请求获取消息记录开始的seq值。首次访问填写0,非首次使用上次企业微信返回的最大seq。允许从任意seq重入拉取。
*/
long seq = 0L;
/*
* 图片,语音,视频,表情,文件,音频存档消息,音频共享文档消息调用 获取媒体消息
*/
List<String> mediaType = Arrays.asList(WxCpConsts.MsgAuditMediaType.IMAGE,
WxCpConsts.MsgAuditMediaType.VOICE, WxCpConsts.MsgAuditMediaType.VIDEO,
WxCpConsts.MsgAuditMediaType.EMOTION, WxCpConsts.MsgAuditMediaType.FILE,
WxCpConsts.MsgAuditMediaType.MEETING_VOICE_CALL, WxCpConsts.MsgAuditMediaType.VOIP_DOC_SHARE);
// 模拟多次拉取数据,根据seq拉取
for (int i = 0; i < 3; i++) {
// 本次请求获取消息记录开始的seq值。首次访问填写0,非首次使用上次企业微信返回的最大seq。允许从任意seq重入拉取。
WxCpChatDatas chatDatas = cpService.getMsgAuditService().getChatDatas(seq, 10L, null, null, 1000L);
if (chatDatas != null && chatDatas.getChatData().size() > 0) {
List<WxCpChatDatas.WxCpChatData> chatdata = chatDatas.getChatData();
Iterator<WxCpChatDatas.WxCpChatData> iterator = chatdata.iterator();
while (iterator.hasNext()) {
WxCpChatDatas.WxCpChatData chatData = iterator.next();
seq = chatData.getSeq();
// 数据
// String msgId = chatData.getMsgId();
// String encryptChatMsg = chatData.getEncryptChatMsg();
// String encryptRandomKey = chatData.getEncryptRandomKey();
// Integer publickeyVer = chatData.getPublickeyVer();
// 获取明文数据
final String chatPlainText = cpService.getMsgAuditService().getChatPlainText(chatDatas.getSdk(), chatData, 2);
final WxCpChatModel wxCpChatModel = WxCpChatModel.fromJson(chatPlainText);
log.info("明文数据为:{}", wxCpChatModel.toJson());
// 获取消息数据
// https://developer.work.weixin.qq.com/document/path/91774
final WxCpChatModel decryptData = cpService.getMsgAuditService().getDecryptData(chatDatas.getSdk(),
chatData, 2);
log.info("获取消息数据为:{}", decryptData.toJson());
/*
* 注意:
* 根据上面返回的文件类型来获取媒体文件,
* 不同的文件类型,拼接好存放文件的绝对路径,写入文件流,获取媒体文件。(拼接绝对文件路径的原因,以便上传到腾讯云或阿里云对象存储)
*
* 目标文件绝对路径+实际文件名,比如:/usr/local/file/20220114/474f866b39d10718810d55262af82662.gif
*/
String path = "/usr/local/file/";
String msgType = decryptData.getMsgType();
if (mediaType.contains(decryptData.getMsgType())) {
// 文件后缀
String suffix = "";
// 文件名md5
String md5Sum = "";
// sdkFileId
String sdkFileId = "";
switch (msgType) {
case WxCpConsts.MsgAuditMediaType.IMAGE:
suffix = WxCpConsts.MsgAuditMediaType.MsgAuditSuffix.JPG;
md5Sum = decryptData.getImage().getMd5Sum();
sdkFileId = decryptData.getImage().getSdkFileId();
break;
case WxCpConsts.MsgAuditMediaType.VOICE:
suffix = WxCpConsts.MsgAuditMediaType.MsgAuditSuffix.AMR;
md5Sum = decryptData.getVoice().getMd5Sum();
sdkFileId = decryptData.getVoice().getSdkFileId();
break;
case WxCpConsts.MsgAuditMediaType.VIDEO:
suffix = WxCpConsts.MsgAuditMediaType.MsgAuditSuffix.MP4;
md5Sum = decryptData.getVideo().getMd5Sum();
sdkFileId = decryptData.getVideo().getSdkFileId();
break;
case WxCpConsts.MsgAuditMediaType.EMOTION:
md5Sum = decryptData.getEmotion().getMd5Sum();
sdkFileId = decryptData.getEmotion().getSdkFileId();
int type = decryptData.getEmotion().getType();
switch (type) {
case 1:
suffix = WxCpConsts.MsgAuditMediaType.MsgAuditSuffix.GIF;
break;
case 2:
suffix = WxCpConsts.MsgAuditMediaType.MsgAuditSuffix.PNG;
break;
default:
return;
}
break;
case WxCpConsts.MsgAuditMediaType.FILE:
md5Sum = decryptData.getFile().getMd5Sum();
suffix = "." + decryptData.getFile().getFileExt();
sdkFileId = decryptData.getFile().getSdkFileId();
break;
// 音频存档消息
case WxCpConsts.MsgAuditMediaType.MEETING_VOICE_CALL:
md5Sum = decryptData.getVoiceId();
sdkFileId = decryptData.getMeetingVoiceCall().getSdkFileId();
for (WxCpChatModel.MeetingVoiceCall.DemoFileData demofiledata :
decryptData.getMeetingVoiceCall().getDemoFileData()) {
String demoFileDataFileName = demofiledata.getFileName();
suffix = demoFileDataFileName.substring(demoFileDataFileName.lastIndexOf(".") + 1);
}
break;
// 音频共享文档消息
case WxCpConsts.MsgAuditMediaType.VOIP_DOC_SHARE:
md5Sum = decryptData.getVoipId();
WxCpFileItem docShare = decryptData.getVoipDocShare();
String fileName = docShare.getFileName();
suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
break;
default:
return;
}
/*
* 拉取媒体文件
*
* 注意:
* 1、根据上面返回的文件类型,拼接好存放文件的绝对路径即可。此时绝对路径写入文件流,来达到获取媒体文件的目的。
* 2、拉取完媒体文件之后,此时文件已经存在绝对路径,可以通过mq异步上传到对象存储
* 3、比如可以上传到阿里云oss或者腾讯云cos
*/
String targetPath = path + md5Sum + suffix;
cpService.getMsgAuditService().getMediaFile(chatDatas.getSdk(), sdkFileId, null, null, 1000L, targetPath);
}
}
}
// 注意:
// 当此批次数据拉取完毕后,应释放此次sdk
log.info("释放sdk {}", chatDatas.getSdk());
Finance.DestroySdk(chatDatas.getSdk());
}
/*
* 文本
*/
// String text = "{\"msgid\":\"CAQQluDa4QUY0On2rYSAgAMgzPrShAE=\",\"action\":\"send\",\"from\":\"XuJinSheng\",
// \"tolist\":[\"icefog\"],\"roomid\":\"\",\"msgtime\":1547087894783,\"msgtype\":\"text\",
// \"text\":{\"content\":\"test\"}}";
String text = "{\"msgid\":\"CAQQluDa4QUY0On2rYSAgAMgzPrShAE=\",\"action\":\"send\",\"from\":\"XuJinSheng\"," +
"\"tolist\":[\"icefog\"],\"roomid\":\"\",\"msgtime\":1547087894783,\"msgtype\":\"text\"," +
"\"text\":{\"content\":\"这是一条引用/回复消息:\\\"\\n------\\n@nick777\"}}";
WxCpChatModel modelText = WxCpChatModel.fromJson(text);
log.info("数据为:" + modelText.toJson());
/*
* 图片
*/
String image = "{\"msgid\":\"CAQQvPnc4QUY0On2rYSAgAMgooLa0Q8=\",\"action\":\"send\",\"from\":\"XuJinSheng\"," +
"\"tolist\":[\"icefog\"],\"roomid\":\"\",\"msgtime\":0,\"msgtype\":\"image\"," +
"\"image\":{\"md5sum\":\"50de8e5ae8ffe4f1df7a93841f71993a\",\"filesize\":70961," +
"\"sdkfileid" +
"\":\"CtYBMzA2OTAyMDEwMjA0NjIzMDYwMDIwMTAwMDIwNGI3ZmU0MDZlMDIwMzBmNTliMTAyMDQ1YzliNTQ3NzAyMDQ1YzM3M2NiYzA0MjQ2NjM0MzgzNTM0NjEzNTY1MmQzNDYxMzQzODJkMzQzMTYxNjEyZDM5NjEzOTM2MmQ2MTM2NjQ2NDY0NjUzMDY2NjE2NjM1MzcwMjAxMDAwMjAzMDExNTQwMDQxMDUwZGU4ZTVhZThmZmU0ZjFkZjdhOTM4NDFmNzE5OTNhMDIwMTAyMDIwMTAwMDQwMBI4TkRkZk1UWTRPRGcxTVRBek1ETXlORFF6TWw4eE9UUTVOamN6TkRZMlh6RTFORGN4TWpNNU1ERT0aIGEwNGQwYWUyM2JlYzQ3NzQ5MjZhNWZjMjk0ZTEyNTkz\"}}";
WxCpChatModel modelImage = WxCpChatModel.fromJson(image);
log.info("数据为:" + modelImage.toJson());
/*
* 撤回消息
*/
String revoke = "{\"msgid\":\"15775510700152506326_1603875615\",\"action\":\"recall\",\"from\":\"kenshin\"," +
"\"tolist\":[\"wmUu0zBgAALV7ZymkcMyxvbTe8YdWxxA\"],\"roomid\":\"\",\"msgtime\":1603875615723," +
"\"msgtype\":\"revoke\",\"revoke\":{\"pre_msgid\":\"14822339130656386894_1603875600\"}}";
WxCpChatModel modelRevoke = WxCpChatModel.fromJson(revoke);
log.info("数据为:" + modelRevoke.toJson());
/*
* 同意会话聊天内容
*/
String agree = "{\"msgid\":\"8891446340739254950_1603875826\",\"action\":\"send\"," +
"\"from\":\"wmGAgeDQAAvQeaTqWwkMTxGMkvI7OOuQ\",\"tolist\":[\"kenshin\"],\"roomid\":\"\"," +
"\"msgtime\":1603875826656,\"msgtype\":\"agree\",\"agree\":{\"userid\":\"wmGAgeDQAAvQeaTqWwkMTxGMkvI7OOuQ\"," +
"\"agree_time\":1603875826656}}";
String disagree = "{\"msgid\":\"17972321270926900092_1603875944\",\"action\":\"send\"," +
"\"from\":\"wmErxtDgAA9AW32YyyuYRimKr7D1KWlw\",\"tolist\":[\"kenshin\"],\"roomid\":\"\"," +
"\"msgtime\":1603875944122,\"msgtype\":\"disagree\"," +
"\"disagree\":{\"userid\":\"wmErxtDgAA9AW32YyyuYRimKr7D1KWlw\",\"disagree_time\":1603875944122}}";
WxCpChatModel modelAgree = WxCpChatModel.fromJson(agree);
WxCpChatModel modelDisagree = WxCpChatModel.fromJson(disagree);
log.info("数据为:" + modelAgree.toJson());
log.info("数据为:" + modelDisagree.toJson());
/*
* 语音
*/
String voice = "{\"msgid\":\"10958372969718811103_1603875609\",\"action\":\"send\"," +
"\"from\":\"wmGAgeDQAAdBjb8CK4ieMPRm7Cqm-9VA\",\"tolist\":[\"kenshin\"],\"roomid\":\"\"," +
"\"msgtime\":1603875609704,\"msgtype\":\"voice\",\"voice\":{\"md5sum\":\"9db09c7fa627c9e53f17736c786a74d5\"," +
"\"voice_size\":6810,\"play_length\":10," +
"\"sdkfileid" +
"\":\"kcyZjZqOXhETGYxajB2Zkp5Rk8zYzh4RVF3ZzZGdXlXNWRjMUoxVGZxbzFTTDJnQ2YxL0NraVcxUUJNK3VUamhEVGxtNklCbjZmMEEwSGRwN0h2cU1GQTU1MDRSMWdTSmN3b25ZMkFOeG5hMS90Y3hTQ0VXRlVxYkR0Ymt5c3JmV2VVcGt6UlNXR1ZuTFRWVGtudXVldDRjQ3hscDBrMmNhMFFXVnAwT3Y5NGVqVGpOcWNQV2wrbUJwV01TRm9xWmNDRVVrcFY5Nk9OUS9GbXIvSmZvOVVZZjYxUXBkWnMvUENkVFQxTHc2N0drb2pJT0FLZnhVekRKZ1FSNDU3ZnZtdmYvTzZDOG9DRXl2SUNIOHc9PRI0TkRkZk56ZzRNVE13TVRjMk5qQTRNak0yTmw4ek5qRTVOalExTjE4eE5qQXpPRGMxTmpBNRogNzM3MDY2NmM2YTc5Njg3NDdhNzU3NDY0NzY3NTY4NjY=\"}}";
WxCpChatModel modelVoice = WxCpChatModel.fromJson(voice);
log.info("数据为:" + modelVoice.toJson());
/*
* 视频
*/
String video = "{\"msgid\":\"17955920891003447432_1603875627\",\"action\":\"send\",\"from\":\"kenshin\"," +
"\"tolist\":[\"wmGAgeDQAAHuRJbt4ZQI_1cqoQcf41WQ\"],\"roomid\":\"\",\"msgtime\":1603875626823," +
"\"msgtype\":\"video\",\"video\":{\"md5sum\":\"d06fc80c01d6fbffcca3b229ba41eac6\",\"filesize\":15169724," +
"\"play_length\":108," +
"\"sdkfileid" +
"\":\"MzAzMjYxMzAzNTYzMzgzMjMyMzQwMjAxMDAwMjA0MDBlNzc4YzAwNDEwZDA2ZmM4MGMwMWQ2ZmJmZmNjYTNiMjI5YmE0MWVhYzYwMjAxMDQwMjAxMDAwNDAwEjhORGRmTVRZNE9EZzFNREEyTlRjM056QXpORjgxTWpZeE9USTBOek5mTVRZd016ZzNOVFl5Tnc9PRogNTIzNGQ1NTQ5N2RhNDM1ZDhlZTU5ODk4NDQ4NzRhNDk=\"}}";
WxCpChatModel modelVideo = WxCpChatModel.fromJson(video);
log.info("数据为:" + modelVideo.toJson());
/*
* 名片
*/
String card = "{\"msgid\":\"13714216591700685558_1603875680\",\"action\":\"send\",\"from\":\"kenshin\"," +
"\"tolist\":[\"wmGAgeDQAAy2Dtr0F8aK4dTuatfm-5Rg\"],\"roomid\":\"\",\"msgtime\":1603875680377," +
"\"msgtype\":\"card\",\"card\":{\"corpname\":\"微信联系人\",\"userid\":\"wmGAgeDQAAGjFmfnP7A3j2JxQDdLNhSw\"}}";
WxCpChatModel modelCard = WxCpChatModel.fromJson(card);
log.info("数据为:" + modelCard.toJson());
/*
* 位置
*/
String location = "{\"msgid\":\"2641513858500683770_1603876152\",\"action\":\"send\",\"from\":\"icefog\"," +
"\"tolist\":[\"wmN6etBgAA0sbJ3invMvRxPQDFoq9uWA\"],\"roomid\":\"\",\"msgtime\":1603876152141," +
"\"msgtype\":\"location\",\"location\":{\"longitude\":116.586285899,\"latitude\":39.911125799," +
"\"address\":\"北京市xxx区xxx路xxx大厦x座\",\"title\":\"xxx管理中心\",\"zoom\":15}}";
WxCpChatModel modelLocation = WxCpChatModel.fromJson(location);
log.info("数据为:" + modelLocation.toJson());
/*
* 表情
*/
String emotion = "{\"msgid\":\"6623217619416669654_1603875612\",\"action\":\"send\",\"from\":\"icef\"," +
"\"tolist\":[\"wmErxtDgAAhteCglUZH2kUt3rq431qmg\"],\"roomid\":\"\",\"msgtime\":1603875611148," +
"\"msgtype\":\"emotion\",\"emotion\":{\"type\":1,\"width\":290,\"height\":290,\"imagesize\":962604," +
"\"md5sum\":\"94c2b0bba52cc456cb8221b248096612\"," +
"\"sdkfileid\":\"4eE1ESTVNalE1TnprMFh6RTJNRE00TnpVMk1UST0aIDc0NzI2NjY1NzE3NTc0Nzg2ZDZlNzg2YTY5NjY2MTYx\"}}";
WxCpChatModel modelEmotion = WxCpChatModel.fromJson(emotion);
log.info("数据为:" + modelEmotion.toJson());
/*
* 文件
*/
String file = "{\"msgid\":\"18039699423706571225_1603875608\",\"action\":\"send\",\"from\":\"kens\"," +
"\"tolist\":[\"wmErxtDgAArDlFIhf76O6w4GxU81al8w\"],\"roomid\":\"\",\"msgtime\":1603875608214," +
"\"msgtype\":\"file\",\"file\":{\"md5sum\":\"18e93fc2ea884df23b3d2d3b8667b9f0\",\"filename\":\"资料.docx\"," +
"\"fileext\":\"docx\",\"filesize\":18181," +
"\"sdkfileid" +
"\":\"E4ODRkZjIzYjNkMmQzYjg2NjdiOWYwMDIwMTA1MDIwMTAwMDQwMBI4TkRkZk1UWTRPRGcxTURrek9UZzBPVEF6TTE4eE1EUXpOVGcxTlRVNVh6RTJNRE00TnpVMk1EZz0aIDMwMzkzMzY0NjEzNjM3NjY2NDY1NjMzNjYxMzIzNzYx\"}}";
WxCpChatModel modelFile = WxCpChatModel.fromJson(file);
log.info("数据为:" + modelFile.toJson());
/*
* 链接
*/
String link = "{\"msgid\":\"11788441727514772650_1603875624\",\"action\":\"send\",\"from\":\"kenshin\"," +
"\"tolist\":[\"0000726\"],\"roomid\":\"\",\"msgtime\":1603875624476,\"msgtype\":\"link\"," +
"\"link\":{\"title\":\"邀请你加入群聊\",\"description\":\"技术支持群,进入可查看详情\",\"link_url\":\"https://work.weixin.qq" +
".com/wework_admin/external_room/join/exceed?vcode=xxx\",\"image_url\":\"https://wework.qpic.cn/wwpic/xxx/0\"}}";
WxCpChatModel modelLink = WxCpChatModel.fromJson(link);
log.info("数据为:" + modelLink.toJson());
/*
* 小程序消息
*/
String weapp = "{\"msgid\":\"11930598857592605935_1603875608\",\"action\":\"send\",\"from\":\"kens\"," +
"\"tolist\":[\"wmGAgeDQAAsgQetTQGqRbMxrkodpM3fA\"],\"roomid\":\"\",\"msgtime\":1603875608691," +
"\"msgtype\":\"weapp\",\"weapp\":{\"title\":\"开始聊天前请仔细阅读服务须知事项\",\"description\":\"客户需同意存档聊天记录\"," +
"\"username\":\"xxx@app\",\"displayname\":\"服务须知\"}}";
WxCpChatModel modelWeapp = WxCpChatModel.fromJson(weapp);
log.info("数据为:" + modelWeapp.toJson());
/*
* 会话记录消息
*/
String chatrecord = "{\"msgid\":\"11354299838102555191_1603875658\",\"action\":\"send\",\"from\":\"ken\"," +
"\"tolist\":[\"icef\"],\"roomid\":\"\",\"msgtime\":1603875657905,\"msgtype\":\"chatrecord\"," +
"\"chatrecord\":{\"title\":\"群聊\",\"item\":[{\"type\":\"ChatRecordText\",\"msgtime\":1603875610," +
"\"content\":\"{\\\"content\\\":\\\"test\\\"}\",\"from_chatroom\":false},{\"type\":\"ChatRecordText\"," +
"\"msgtime\":1603875620,\"content\":\"{\\\"content\\\":\\\"test2\\\"}\",\"from_chatroom\":false}]}}";
WxCpChatModel modelChatRecord = WxCpChatModel.fromJson(chatrecord);
log.info("数据为:" + modelChatRecord.toJson());
/*
* 填表消息
*/
String collect = "{\"msgid\":\"2500536226619379797_1576034482\",\"action\":\"send\",\"from\":\"nick\"," +
"\"tolist\":[\"XuJinSheng\",\"15108264797\"],\"roomid\":\"wrjc7bDwYAOAhf9quEwRRxyyoMm0QAAA\"," +
"\"msgtime\":1576034482344,\"msgtype\":\"collect\",\"collect\":{\"room_name\":\"这是一个群\",\"creator\":\"nick\"," +
"\"create_time\":\"2019-12-11 11:21:22\",\"title\":\"这是填表title\",\"details\":[{\"id\":1,\"ques\":\"表项1,文本\"," +
"\"type\":\"Text\"},{\"id\":2,\"ques\":\"表项2,数字\",\"type\":\"Number\"},{\"id\":3,\"ques\":\"表项3,日期\"," +
"\"type\":\"Date\"},{\"id\":4,\"ques\":\"表项4,时间\",\"type\":\"Time\"}]}}";
WxCpChatModel modelCollect = WxCpChatModel.fromJson(collect);
log.info("数据为:" + modelCollect.toJson());
/*
* 红包消息
*/
String redpacket = "{\"msgid\":\"333590477316965370_1603877439\",\"action\":\"send\",\"from\":\"kens\"," +
"\"tolist\":[\"1000000444696\"],\"roomid\":\"\",\"msgtime\":1603877439038,\"msgtype\":\"redpacket\"," +
"\"redpacket\":{\"type\":1,\"wish\":\"恭喜发财,大吉大利\",\"totalcnt\":1,\"totalamount\":3000}}";
WxCpChatModel modelRedpacket = WxCpChatModel.fromJson(redpacket);
log.info("数据为:" + modelRedpacket.toJson());
/*
* 会议邀请信息
*/
String meeting = "{\"msgid\":\"5935786683775673543_1603877328\",\"action\":\"send\",\"from\":\"ken\"," +
"\"tolist\":[\"icef\",\"test\"],\"roomid\":\"wr2vOpDgAAN4zVWKbS\",\"msgtime\":1603877328914," +
"\"msgtype\":\"meeting\",\"meeting\":{\"topic\":\"夕会\",\"starttime\":1603877400,\"endtime\":1603881000," +
"\"address\":\"\",\"remarks\":\"\",\"meetingtype\":102,\"meetingid\":1210342560,\"status\":1}}";
WxCpChatModel modelMeeting = WxCpChatModel.fromJson(meeting);
log.info("数据为:" + modelMeeting.toJson());
/*
* 切换企业日志
*/
String switchlog = "{\"msgid\":\"125289002219525886280\",\"action\":\"switch\",\"time\":1554119421840," +
"\"user\":\"XuJinSheng\"}";
WxCpChatModel modelSwitchLog = WxCpChatModel.fromJson(switchlog);
log.info("数据为:" + modelSwitchLog.toJson());
/*
* 在线文档消息
*/
String docMsg = "{\"msgid\":\"9732089160923053207_1603877765\",\"action\":\"send\",\"from\":\"ken\"," +
"\"tolist\":[\"icef\",\"test\"],\"roomid\":\"wrJawBCQAAStr3jxVxEH\",\"msgtime\":1603877765291," +
"\"msgtype\":\"docmsg\",\"doc\":{\"title\":\"测试&演示客户\",\"doc_creator\":\"test\",\"link_url\":\"https://doc" +
".weixin.qq.com/txdoc/excel?docid=xxx\"}}";
WxCpChatModel modelDocMsg = WxCpChatModel.fromJson(docMsg);
log.info("数据为:" + modelDocMsg.toJson());
/*
* MarkDown格式消息
*/
String markDown = "{\"msgid\":\"7546287934688259248_1603875715\",\"action\":\"send\",\"from\":\"ken\"," +
"\"tolist\":[\"icef\",\"test\"],\"roomid\":\"wr0SfLCgAAgCaCPeM33UNe\",\"msgtime\":1603875715782," +
"\"msgtype\":\"markdown\",\"info\":{\"content\":\"请前往系统查看,谢谢。\"}}";
WxCpChatModel modelMarkDown = WxCpChatModel.fromJson(markDown);
log.info("数据为:" + modelMarkDown.toJson());
/*
* 图文消息
*/
String news = "{\"msgid\":\"118732825779547782215\",\"action\":\"send\",\"from\":\"kens\",\"tolist\":[\"icef\"," +
"\"test\"],\"roomid\":\"wrErxtDgAA0jgXE5\",\"msgtime\":1603876045165,\"msgtype\":\"news\"," +
"\"info\":{\"item\":[{\"title\":\"service \",\"description\":\"test\",\"url\":\"http://xxx\"," +
"\"picurl\":\"https://www.qq.com/xxx.jpg\"}]}}";
WxCpChatModel modelNews = WxCpChatModel.fromJson(news);
log.info("数据为:" + modelNews.toJson());
/*
* 日程消息
*/
String calendar = "{\"msgid\":\"2345881211604379705_1603877680\",\"action\":\"send\",\"from\":\"ken\"," +
"\"tolist\":[\"icef\",\"test\"],\"roomid\":\"wr2LO0CAAAFrTZCGWWAxBA\",\"msgtime\":1603877680795," +
"\"msgtype\":\"calendar\",\"calendar\":{\"title\":\"xxx业绩复盘会\",\"creatorname\":\"test\"," +
"\"attendeename\":[\"aaa\",\"bbb\"],\"starttime\":1603882800,\"endtime\":1603886400,\"place\":\"\"," +
"\"remarks\":\"\"}}";
WxCpChatModel modelCalendar = WxCpChatModel.fromJson(calendar);
log.info("数据为:" + modelCalendar.toJson());
/*
* 混合消息
*/
String mixed = "{\"msgid\":\"DAQQluDa4QUY0On4kYSABAMgzPrShAE=\",\"action\":\"send\",\"from\":\"HeMiao\"," +
"\"tolist\":[\"HeChangTian\",\"LiuZeYu\"],\"roomid\":\"wr_tZ2BwAAUwHpYMwy9cIWqnlU3Hzqfg\"," +
"\"msgtime\":1577414359072,\"msgtype\":\"mixed\",\"mixed\":{\"item\":[{\"type\":\"text\"," +
"\"content\":\"{\\\"content\\\":\\\"你好[微笑]\\\\n\\\"}\"},{\"type\":\"image\"," +
"\"content\":\"{\\\"md5sum\\\":\\\"368b6c18c82e6441bfd89b343e9d2429\\\",\\\"filesize\\\":13177," +
"\\\"sdkfileid" +
"\\\":\\\"CtYBMzA2OTAyMDEwMjA0NjIzMDYwMDIwMTAwMDWwNDVmYWY4Y2Q3MDIwMzBmNTliMTAyMDQwYzljNTQ3NzAyMDQ1ZTA1NmFlMjA0MjQ2NjM0NjIzNjY2MzYzNTMyMmQzNzYxMzQ2NDJkMzQ2MjYxNjQyZDM4MzMzMzM4MmQ3MTYyMzczMTM4NjM2NDYxMzczMjY2MzkwMjAxMDAwMjAzMDIwMDEwMDQxMDM2OGI2YzE4YzgyZTY0NDFiZmQ4OWIyNDNlOWQyNDI4MDIwMTAyMDIwMTAwMDQwMBI4TkRkZk2UWTRPRGcxTVRneE5URTFNRGc1TVY4eE1UTTFOak0yTURVeFh6RTFOemMwTVRNek5EYz0aIDQzMTY5NDFlM2MxZDRmZjhhMjEwY2M0NDQzZGUXOTEy\\\"}\"}]}}";
WxCpChatModel modelMixed = WxCpChatModel.fromJson(mixed);
log.info("获取混合消息,文件对象为:{}", modelMixed.getMixed().getItem().get(0).getContent());
// 返回文件对象
WxCpFileItem wxCpFileItem = WxCpFileItem.fromJson(modelMixed.getMixed().getItem().get(1).getContent());
log.info("获取混合消息,文件对象为:{}", wxCpFileItem.toJson());
log.info("数据为:" + modelMixed.toJson());
/*
* 音频存档消息
*/
String meetingVoiceCall = "{\"msgid\":\"17952229780246929345_1594197637\",\"action\":\"send\"," +
"\"from\":\"wo137MCgAAYW6pIiKKrDe5SlzEhSgwbA\",\"tolist\":[\"wo137MCgAAYW6pIiKKrDe5SlzEhSgwbA\"]," +
"\"msgtime\":1594197581203,\"msgtype\":\"meeting_voice_call\"," +
"\"voiceid\":\"grb8a4c48a3c094a70982c518d55e40557\",\"meeting_voice_call\":{\"endtime\":1594197635," +
"\"sdkfileid" +
"\":\"CpsBKjAqd0xhb2JWRUJldGtwcE5DVTB6UjRUalN6c09vTjVyRnF4YVJ5M24rZC9YcHF3cHRPVzRwUUlaMy9iTytFcnc0SlBkZDU1YjRNb0MzbTZtRnViOXV5WjUwZUIwKzhjbU9uRUlxZ3pyK2VXSVhUWVN2ejAyWFJaTldGSkRJVFl0aUhkcVdjbDJ1L2RPbjJsRlBOamJaVDNnPT0SOE5EZGZNVFk0T0RnMU16YzVNVGt5T1RJMk9GOHhNalk0TXpBeE9EZzJYekUxT1RReE9UYzJNemM9GiA3YTYyNzA3NTY4Nzc2MTY3NzQ2MTY0NzA2ZTc4NjQ2OQ==\",\"demofiledata\":[{\"filename\":\"65eb1cdd3e7a3c1740ecd74220b6c627.docx\",\"demooperator\":\"wo137MCgAAYW6pIiKKrDe5SlzEhSgwbA\",\"starttime\":1594197599,\"endtime\":1594197609}],\"sharescreendata\":[{\"share\":\"wo137MCgAAYW6pIiKKrDe5SlzEhSgwbA\",\"starttime\":1594197624,\"endtime\":1594197624}]}}";
WxCpChatModel modelMeetingVoiceCall = WxCpChatModel.fromJson(meetingVoiceCall);
log.info("数据为:" + modelMeetingVoiceCall.toJson());
/*
* 音频共享文档消息
*/
String voipDocShare = "{\"msgid\":\"16527954622422422847_1594199256\",\"action\":\"send\"," +
"\"from\":\"18002520162\",\"tolist\":[\"wo137MCgAAYW6pIiKKrDe5SlzEhSgwbA\"],\"msgtime\":1594199235014," +
"\"msgtype\":\"voip_doc_share\",\"voipid\":\"gr2751c98b19300571f8afb3b74514bd32\"," +
"\"voip_doc_share\":{\"filename\":\"欢迎使用微盘.pdf.pdf\",\"md5sum\":\"ff893900f24e55e216e617a40e5c4648\"," +
"\"filesize\":4400654," +
"\"sdkfileid" +
"\":\"CpsBKjAqZUlLdWJMd2gvQ1JxMzd0ZjlpdW5mZzJOOE9JZm5kbndvRmRqdnBETjY0QlcvdGtHSFFTYm95dHM2VlllQXhkUUN5KzRmSy9KT3pudnA2aHhYZFlPemc2aVZ6YktzaVh3YkFPZHlqNnl2L2MvcGlqcVRjRTlhZEZsOGlGdHJpQ2RWSVNVUngrVFpuUmo3TGlPQ1BJemlRPT0SOE5EZGZNVFk0T0RnMU16YzVNVGt5T1RJMk9GODFNelUyTlRBd01qQmZNVFU1TkRFNU9USTFOZz09GiA3YTcwNmQ2Zjc5NjY3MDZjNjY2Zjc4NzI3NTZmN2E2YQ==\"}}";
WxCpChatModel modelVoipDocShare = WxCpChatModel.fromJson(voipDocShare);
log.info("数据为:" + modelVoipDocShare.toJson());
/*
* 互通红包消息
*/
String externalRedpacket = "{\"msgid\":\"8632214264349267353_1603786184\",\"action\":\"send\"," +
"\"from\":\"woJ7ijBwAAmqwojT8r_DaNMbr_NAvaag\",\"tolist\":[\"woJ7ijBwAA6SjS_sIyPLZtyEPJlT7Cfw\"," +
"\"tiny-six768\"],\"roomid\":\"wrJ7ijBwAAG1vly_DzVI72Ghc-PtA5Dw\",\"msgtime\":1603786183955," +
"\"msgtype\":\"external_redpacket\",\"redpacket\":{\"type\":1,\"wish\":\"恭喜发财,大吉大利\",\"totalcnt\":2," +
"\"totalamount\":20}}";
WxCpChatModel modelExternalRedpacket = WxCpChatModel.fromJson(externalRedpacket);
log.info("数据为:" + modelExternalRedpacket.toJson());
/*
* 视频号消息
*/
String sphfeed = "{\"msgid\":\"5702551662099334532_1619511584_external\",\"action\":\"send\"," +
"\"from\":\"yangzhu1\",\"tolist\":[\"wmJSb5CgAA4aWXWndJspQGpJMDbsMwMA\"],\"roomid\":\"\"," +
"\"msgtime\":1619511584444,\"msgtype\":\"sphfeed\",\"sphfeed\":{\"feed_type\":4,\"sph_name\":\"云游天地旅行家\"," +
"\"feed_desc\":\"瑞士丨盖尔默缆车,名副其实的过山车~\\n\\n#旅行#风景#热门\"}}";
WxCpChatModel modelSphFeed = WxCpChatModel.fromJson(sphfeed);
log.info("数据为:" + modelSphFeed.toJson());
/*
* 获取会话内容存档开启成员列表
*/
List<String> permitUserList = cpService.getMsgAuditService().getPermitUserList(null);
log.info(permitUserList.toString());
ArrayList<WxCpCheckAgreeRequest.Info> userList = Lists.newArrayList();
WxCpCheckAgreeRequest checkAgreeRequest = new WxCpCheckAgreeRequest();
/*
* 获取会话同意情况
*/
WxCpCheckAgreeRequest.Info info = new WxCpCheckAgreeRequest.Info();
info.setUserid("wangkai");
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | true |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpOaAgentTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpOaAgentTest.java | package me.chanjar.weixin.cp.api;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.XmlUtils;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.oa.selfagent.WxCpOpenApprovalData;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.demo.WxCpDemoInMemoryConfigStorage;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import org.testng.annotations.Test;
import java.io.InputStream;
/**
* 企业微信自建应用接口测试类.
* https://developer.work.weixin.qq.com/document/path/90269
* https://developer.work.weixin.qq.com/document/path/90240#%E5%AE%A1%E6%89%B9%E7%8A%B6%E6%80%81%E9%80%9A%E7%9F%A5%E4
* %BA%8B%E4%BB%B6
*
* @author <a href="https://gitee.com/Wang_Wong/">Wang_Wong</a> created on 2022-04-06
*/
@Slf4j
public class WxCpOaAgentTest {
// extends WxCpBaseResp
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService cpService;
/**
* Test.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void test() throws WxErrorException {
InputStream inputStream = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(inputStream);
wxCpConfigStorage = config;
cpService = new WxCpServiceImpl();
cpService.setWxCpConfigStorage(config);
/**
* 测试 审批状态通知事件
*/
String testXml2 = "<xml>\n" +
" <ToUserName><![CDATA[wwddddccc7775555aaa]]></ToUserName>\n" +
" <FromUserName><![CDATA[sys]]></FromUserName>\n" +
" <CreateTime>1527838022</CreateTime>\n" +
" <MsgType><![CDATA[event]]></MsgType>\n" +
" <Event><![CDATA[open_approval_change]]></Event>\n" +
" <AgentID>1</AgentID>\n" +
" <ApprovalInfo>\n" +
" <ThirdNo><![CDATA[201806010001]]></ThirdNo>\n" +
" <OpenSpName><![CDATA[付款]]></OpenSpName>\n" +
" <OpenTemplateId><![CDATA[1234567890]]></OpenTemplateId>\n" +
" <OpenSpStatus>1</OpenSpStatus>\n" +
" <ApplyTime>1527837645</ApplyTime>\n" +
" <ApplyUserName><![CDATA[xiaoming]]></ApplyUserName>\n" +
" <ApplyUserId><![CDATA[1]]></ApplyUserId>\n" +
" <ApplyUserParty><![CDATA[产品部]]></ApplyUserParty>\n" +
" <ApplyUserImage><![CDATA[http://www.qq.com/xxx.png]]></ApplyUserImage>\n" +
" <ApprovalNodes>\n" +
" <ApprovalNode>\n" +
" <NodeStatus>1</NodeStatus>\n" +
" <NodeAttr>1</NodeAttr>\n" +
" <NodeType>1</NodeType>\n" +
" <Items>\n" +
" <Item>\n" +
" <ItemName><![CDATA[xiaohong]]></ItemName>\n" +
" <ItemUserId><![CDATA[2]]></ItemUserId>\n" +
" <ItemImage><![CDATA[http://www.qq.com/xxx.png]]></ItemImage>\n" +
" <ItemStatus>1</ItemStatus>\n" +
" <ItemSpeech><![CDATA[]]></ItemSpeech>\n" +
" <ItemOpTime>0</ItemOpTime>\n" +
" </Item>\n" +
" </Items>\n" +
" </ApprovalNode>\n" +
" </ApprovalNodes>\n" +
" <NotifyNodes>\n" +
" <NotifyNode>\n" +
" <ItemName><![CDATA[xiaogang]]></ItemName>\n" +
" <ItemUserId><![CDATA[3]]></ItemUserId>\n" +
" <ItemImage><![CDATA[http://www.qq.com/xxx.png]]></ItemImage>\n" +
" </NotifyNode>\n" +
" </NotifyNodes>\n" +
" <approverstep>0</approverstep>\n" +
" </ApprovalInfo>\n" +
"</xml>\n";
final WxCpXmlMessage mess2 = XStreamTransformer.fromXml(WxCpXmlMessage.class, testXml2);
mess2.setAllFieldsMap(XmlUtils.xml2Map(testXml2));
log.info("xmlJson: {}", WxCpGsonBuilder.create().toJson(mess2));
/**
* 测试 弹出微信相册发图器的事件推送
*
* https://developer.work.weixin.qq.com/document/path/90240
*/
String testXml = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[FromUser]]></FromUserName>\n" +
"\t<CreateTime>1408090816</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[pic_weixin]]></Event>\n" +
"\t<EventKey><![CDATA[6]]></EventKey>\n" +
"\t<SendPicsInfo><Count>1</Count>\n" +
"\t<PicList><item><PicMd5Sum><![CDATA[5a75aaca956d97be686719218f275c6b]]></PicMd5Sum>\n" +
"\t</item>\n" +
"\t</PicList>\n" +
"\t</SendPicsInfo>\n" +
"\t<AgentID>1</AgentID>\n" +
"</xml>\n";
final WxCpXmlMessage mess = XStreamTransformer.fromXml(WxCpXmlMessage.class, testXml);
mess.setAllFieldsMap(XmlUtils.xml2Map(testXml));
log.info("xmlJson: {}", WxCpGsonBuilder.create().toJson(mess));
/**
* 审批流程引擎
* 自建应用审批状态变化通知回调
*
* https://developer.work.weixin.qq.com/document/path/90269
*/
String approvalInfoXml = "<xml>\n" +
" <ToUserName>wwd08c8e7c775abaaa</ToUserName> \n" +
" <FromUserName>sys</FromUserName> \n" +
" <CreateTime>1527838022</CreateTime> \n" +
" <MsgType>event</MsgType> \n" +
" <Event>open_approval_change</Event>\n" +
" <AgentID>1</AgentID>\n" +
" <ApprovalInfo> \n" +
" <ThirdNo>thirdNoxxx</ThirdNo> \n" +
" <OpenSpName>付款</OpenSpName> \n" +
" <OpenTemplateId>1234567111</OpenTemplateId> \n" +
" <OpenSpStatus>1</OpenSpStatus> \n" +
" <ApplyTime>1527837645</ApplyTime> \n" +
" <ApplyUserName>jackiejjwu</ApplyUserName> \n" +
" <ApplyUserId>WuJunJie</ApplyUserId> \n" +
" <ApplyUserParty>产品部</ApplyUserParty> \n" +
" <ApplyUserImage>http://www.qq.com/xxx.png</ApplyUserImage> \n" +
" <ApprovalNodes> \n" +
" <ApprovalNode> \n" +
" <NodeStatus>1</NodeStatus> \n" +
" <NodeAttr>1</NodeAttr> \n" +
" <NodeType>1</NodeType> \n" +
" <Items> \n" +
" <Item> \n" +
" <ItemName>chauvetxiao</ItemName> \n" +
" <ItemUserid>XiaoWen</ItemUserid> \n" +
" <ItemParty>产品部</ItemParty> \n" +
" <ItemImage>http://www.qq.com/xxx.png</ItemImage> \n" +
" <ItemStatus>1</ItemStatus> \n" +
" <ItemSpeech></ItemSpeech> \n" +
" <ItemOpTime>0</ItemOpTime> \n" +
" </Item> \n" +
" </Items> \n" +
" </ApprovalNode> \n" +
" </ApprovalNodes> \n" +
" <NotifyNodes> \n" +
" <NotifyNode> \n" +
" <ItemName>jinhuiguo</ItemName> \n" +
" <ItemUserid>GuoJinHui</ItemUserid> \n" +
" <ItemParty>行政部</ItemParty> \n" +
" <ItemImage>http://www.qq.com/xxx.png</ItemImage> \n" +
" </NotifyNode> \n" +
" </NotifyNodes> \n" +
" <ApproverStep>0</ApproverStep> \n" +
" </ApprovalInfo> \n" +
"</xml>\n";
final WxCpXmlMessage msg = XStreamTransformer.fromXml(WxCpXmlMessage.class, approvalInfoXml);
msg.setAllFieldsMap(XmlUtils.xml2Map(approvalInfoXml));
log.info("xmlJson: {}", WxCpGsonBuilder.create().toJson(msg));
/**
* 增加
* 自建应用审批状态变化通知回调类型
*/
String openApprovalChange = WxCpConsts.EventType.OPEN_APPROVAL_CHANGE;
/**
* Test
*/
String test = "{\"errcode\":0,\"errmsg\":\"ok\",\"data\":{\"ThirdNo\":\"thirdNoxxx\"," +
"\"OpenTemplateId\":\"1234567111\",\"OpenSpName\":\"付款\",\"OpenSpstatus\":1,\"ApplyTime\":1527837645," +
"\"ApplyUsername\":\"jackiejjwu\",\"ApplyUserParty\":\"产品部\",\"ApplyUserImage\":\"http://www.qq.com/xxx.png\"," +
"\"ApplyUserId\":\"WuJunJie\",\"ApprovalNodes\":{\"ApprovalNode\":[{\"NodeStatus\":1,\"NodeAttr\":1," +
"\"NodeType\":1,\"Items\":{\"Item\":[{\"ItemName\":\"chauvetxiao\",\"ItemParty\":\"产品部\"," +
"\"ItemImage\":\"http://www.qq.com/xxx.png\",\"ItemUserId\":\"XiaoWen\",\"ItemStatus\":1,\"ItemSpeech\":\"\"," +
"\"ItemOpTime\":0}]}}]},\"NotifyNodes\":{\"NotifyNode\":[{\"ItemName\":\"jinhuiguo\",\"ItemParty\":\"行政部\"," +
"\"ItemImage\":\"http://www.qq.com/xxx.png\",\"ItemUserId\":\"GuoJinHui\"}]},\"ApproverStep\":0}}";
final WxCpOpenApprovalData data = WxCpGsonBuilder.create()
.fromJson(GsonParser.parse(test).get("data"),
new TypeToken<WxCpOpenApprovalData>() {
}.getType()
);
log.info(data.toJson());
WxCpOpenApprovalData openApprovalData = cpService.getOaAgentService().getOpenApprovalData("943225459735269376");
log.info(openApprovalData.toJson());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpSchoolTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpSchoolTest.java | package me.chanjar.weixin.cp.api;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.living.WxCpLivingResult;
import me.chanjar.weixin.cp.bean.school.*;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.demo.WxCpDemoInMemoryConfigStorage;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
/**
* 企业微信家校应用 复学码相关接口.
* https://developer.work.weixin.qq.com/document/path/93744
*
* @author <a href="https://github.com/0katekate0">Wang_Wong</a> created on : 2022/5/31 9:10
*/
@Slf4j
public class WxCpSchoolTest {
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService cpService;
/**
* Test.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void test() throws WxErrorException {
/**
* 注意:
* 权限说明:仅复学码应用可以调用
*/
InputStream inputStream = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(inputStream);
wxCpConfigStorage = config;
cpService = new WxCpServiceImpl();
cpService.setWxCpConfigStorage(config);
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
/**
* 上课直播
*/
String livingId = "lvOQpTDwAAh0hxHsSeSwTQcmH0nWUC_Q";
/**
* 获取老师直播ID列表
* https://developer.work.weixin.qq.com/document/path/93739
*/
WxCpLivingResult.LivingIdResult result = cpService.getSchoolService().getUserAllLivingId("WangKai", null, 20);
log.info("result:{}", result.toJson());
/**
* 删除直播回放
* https://developer.work.weixin.qq.com/document/path/93743
*/
WxCpLivingResult livingResult = cpService.getSchoolService().deleteReplayData(livingId);
log.info("livingResult:{}", livingResult.toJson());
/**
* 获取未观看直播统计
* https://developer.work.weixin.qq.com/document/path/93742
*/
String str3 = "{\"errcode\":0,\"errmsg\":\"ok\",\"ending\":1,\"next_key\":\"NEXT_KEY\"," +
"\"stat_info\":{\"students\":[{\"student_userid\":\"zhansan_child\",\"parent_userid\":\"zhangsan\"," +
"\"partyids\":[10,11]},{\"student_userid\":\"lisi_child\",\"parent_userid\":\"lisi\",\"partyids\":[5]}]}}";
WxCpSchoolUnwatchStat schoolUnwatchStat = WxCpSchoolUnwatchStat.fromJson(str3);
log.info("unwatchStat:{}", schoolUnwatchStat.toJson());
WxCpSchoolUnwatchStat unwatchStat = cpService.getSchoolService().getUnwatchStat(livingId, "0");
log.info("unwatchStat:{}", unwatchStat.toJson());
/**
* 获取观看直播统计
* https://developer.work.weixin.qq.com/document/path/93741
*/
String str2 = "{\"errcode\":0,\"errmsg\":\"ok\",\"ending\":1,\"next_key\":\"NEXT_KEY\"," +
"\"stat_infoes\":{\"students\":[{\"student_userid\":\"zhansan_child\",\"parent_userid\":\"zhangsan\"," +
"\"partyids\":[10,11],\"watch_time\":30,\"enter_time\":1586433904,\"leave_time\":1586434000,\"is_comment\":1}," +
"{\"student_userid\":\"lisi_child\",\"parent_userid\":\"lisi\",\"partyids\":[10,11],\"watch_time\":30," +
"\"enter_time\":1586433904,\"leave_time\":1586434000,\"is_comment\":0}]," +
"\"visitors\":[{\"nickname\":\"wx_nickname1\",\"watch_time\":30,\"enter_time\":1586433904," +
"\"leave_time\":1586434000,\"is_comment\":1},{\"nickname\":\"wx_nickname2\",\"watch_time\":30," +
"\"enter_time\":1586433904,\"leave_time\":1586434000,\"is_comment\":0}]}}";
WxCpSchoolWatchStat wxCpSchoolWatchStat = WxCpSchoolWatchStat.fromJson(str2);
log.info("wxCpSchoolWatchStat:{}", wxCpSchoolWatchStat.toJson());
WxCpSchoolWatchStat watchStat = cpService.getSchoolService().getWatchStat(livingId, "0");
log.info("watchStat:{}", watchStat.toJson());
String str1 = "{\"errcode\":0,\"errmsg\":\"ok\",\"living_info\":{\"theme\":\"直角三角形讲解\"," +
"\"living_start\":1586405229,\"living_duration\":1800,\"anchor_userid\":\"zhangsan\"," +
"\"living_range\":{\"partyids\":[1,4,9],\"group_names\":[\"group_name1\",\"group_name2\"]},\"viewer_num\":100," +
"\"comment_num\":110,\"open_replay\":1,\"push_stream_url\":\"https://www.qq.test.com\"}}";
WxCpSchoolLivingInfo wxCpSchoolLivingInfo = WxCpSchoolLivingInfo.fromJson(str1);
log.info("str1:{}", wxCpSchoolLivingInfo.toJson());
/**
* 获取直播详情
* https://developer.work.weixin.qq.com/document/path/93740
*/
WxCpSchoolLivingInfo schoolLivingInfo = cpService.getSchoolService().getLivingInfo(livingId);
log.info("schoolLivingInfo:{}", schoolLivingInfo.toJson());
/**
* 获取学生付款结果
* https://developer.work.weixin.qq.com/document/path/94553
*/
String paymentResultStr = "{\"errcode\":0,\"errmsg\":\"ok\",\"project_name\":\"学费\",\"amount\":998," +
"\"payment_result\":[{\"student_userid\":\"xxxx\",\"trade_state\":1,\"trade_no\":\"xxxxx\"," +
"\"payer_parent_userid\":\"zhangshan\"}]}";
WxCpPaymentResult cpPaymentResult = WxCpPaymentResult.fromJson(paymentResultStr);
log.info("cpPaymentResult:{}", cpPaymentResult.toJson());
WxCpPaymentResult paymentResult = cpService.getSchoolService().getPaymentResult("");
log.info("paymentResult:{}", paymentResult.toJson());
/**
* 获取订单详情
* https://developer.work.weixin.qq.com/document/path/94554
*/
String tradeStr = "{\n" +
"\t\"errcode\":0,\n" +
"\t\"errmsg\":\"ok\",\n" +
"\t\"transaction_id\":\"xxxxx\", \t \n" +
"\t\"pay_time\":12345\n" +
"}";
WxCpTrade wxCpTrade = WxCpTrade.fromJson(tradeStr);
log.info("wxCpTrade:{}", wxCpTrade.toJson());
WxCpTrade trade = cpService.getSchoolService().getTrade("", "");
log.info("trade:{}", trade.toJson());
/**
* 获取老师健康信息
* https://developer.work.weixin.qq.com/document/path/93744
*/
WxCpCustomizeHealthInfo teacherCustomizeHealthInfo =
cpService.getSchoolService().getTeacherCustomizeHealthInfo(date, null, null);
log.info("teacherCustomizeHealthInfo为:{}", teacherCustomizeHealthInfo.toJson());
/**
* 获取学生健康信息
* https://developer.work.weixin.qq.com/document/path/93745
*/
WxCpCustomizeHealthInfo studentCustomizeHealthInfo =
cpService.getSchoolService().getStudentCustomizeHealthInfo(date, null, null);
log.info("studentCustomizeHealthInfo为:{}", studentCustomizeHealthInfo.toJson());
/**
* 获取师生健康码
* https://developer.work.weixin.qq.com/document/path/93746
*/
ArrayList<String> userIds = Lists.newArrayList();
userIds.add("Wangkai");
WxCpResultList healthQrCode = cpService.getSchoolService().getHealthQrCode(userIds, 1);
log.info("healthQrCode为:{}", healthQrCode.toJson());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java | package me.chanjar.weixin.cp.api;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
/**
* 基础API测试
*
* @author Daniel Qian
*/
@Test(groups = "baseAPI")
@Guice(modules = ApiTestModule.class)
public class WxCpBaseAPITest {
/**
* The Wx service.
*/
@Inject
protected WxCpServiceImpl wxService;
/**
* Test refresh access token.
*
* @throws WxErrorException the wx error exception
*/
public void testRefreshAccessToken() throws WxErrorException {
WxCpConfigStorage configStorage = this.wxService.getWxCpConfigStorage();
String before = configStorage.getAccessToken();
this.wxService.getAccessToken(false);
String after = configStorage.getAccessToken();
Assert.assertNotEquals(before, after);
Assert.assertTrue(StringUtils.isNotBlank(after));
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpLivingTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpLivingTest.java | package me.chanjar.weixin.cp.api;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.XmlUtils;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.living.*;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.demo.WxCpDemoInMemoryConfigStorage;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
/**
* 企业微信直播测试类.
* 官方文档:https://open.work.weixin.qq.com/api/doc/90000/90135/93632
*
* @author <a href="https://github.com/0katekate0">Wang_Wong</a> created on 2021-12-23
*/
@Slf4j
public class WxCpLivingTest {
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService wxCpService;
/**
* Test.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void test() throws WxErrorException {
InputStream inputStream = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(inputStream);
wxCpConfigStorage = config;
wxCpService = new WxCpServiceImpl();
wxCpService.setWxCpConfigStorage(config);
/**
* 直播回调事件
* 一场完整的直播,会经历 预约直播/开始直播/结束直播 等一系列状态变更。
* 为了让企业实时获取直播的动态,当直播状态变更后,企业微信会将该变更推送到开发者配置的回调URL。
* 只有通过接口创建的预约/立即直播才会回调。
*
* 请注意,只有用企业微信api创建的直播才能收到回调,且调用创建直播接口的应用,要配置好回调url。
*/
String livingXml = "<xml>\n" +
" <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
" <FromUserName><![CDATA[fromUser]]></FromUserName> \n" +
" <CreateTime>1348831860</CreateTime>\n" +
" <MsgType><![CDATA[event]]></MsgType>\n" +
" <Event><![CDATA[living_status_change]]></Event>\n" +
" <LivingId><![CDATA[LivingId]]></LivingId>\n" +
" <Status>1</Status>\n" +
" <AgentID>1</AgentID>\n" +
"</xml>";
final WxCpXmlMessage livingXmlMsg = XStreamTransformer.fromXml(WxCpXmlMessage.class, livingXml);
livingXmlMsg.setAllFieldsMap(XmlUtils.xml2Map(livingXml));
log.info("livingXmlMsg:{}", WxCpGsonBuilder.create().toJson(livingXmlMsg));
/**
* 直播回调事件常量
* https://developer.work.weixin.qq.com/document/path/94145
*/
String livingStatusChange = WxCpConsts.EventType.LIVING_STATUS_CHANGE;
/**
* 测试创建直播
*/
WxCpLivingCreateRequest createRequest = new WxCpLivingCreateRequest();
createRequest.setAnchorUserid("WangKai");
createRequest.setTheme("直播1");
long currentTimeMillis = System.currentTimeMillis() + 3600000L;
createRequest.setLivingStart(currentTimeMillis);
createRequest.setLivingDuration(3600L);
createRequest.setType(4);
createRequest.setDescription("这是通用直播1");
val activityDetail = new WxCpLivingCreateRequest.ActivityDetail();
activityDetail.setDescription("活动描述,非活动类型的直播不用传");
// String[] strings = new String[]{"MEDIA_ID_2", "MEDIA_ID_1"};
ArrayList imageList = new ArrayList();
imageList.add("MEDIA_ID_1");
imageList.add("MEDIA_ID_2");
activityDetail.setImageList(imageList);
createRequest.setActivityDetail(activityDetail);
String livingCreate = wxCpService.getLivingService().livingCreate(createRequest);
log.info("返回的直播id为:{}", livingCreate);
WxCpLivingCreateRequest thisReq = WxCpLivingCreateRequest.fromJson(createRequest.toJson());
log.info("返回的数据:{}", thisReq.toJson());
// 创建预约直播
String createJson = "{\"anchor_userid\":\"ChenHu\",\"theme\":\"theme\",\"living_start\":164037820420," +
"\"living_duration\":3600,\"description\":\"test description\",\"type\":4,\"remind_time\":60," +
"\"activity_cover_mediaid\":\"MEDIA_ID\",\"activity_share_mediaid\":\"MEDIA_ID\"," +
"\"activity_detail\":{\"description\":\"活动描述,非活动类型的直播不用传\",\"image_list\":[\"xxxx1\",\"xxxx1\"]}}";
WxCpLivingCreateRequest requestData = WxCpLivingCreateRequest.fromJson(createJson);
String thisLivingId = wxCpService.getLivingService().livingCreate(requestData);
log.info("livingId为:{}", thisLivingId);
/**
* other api
*/
String livingCode = wxCpService.getLivingService().getLivingCode("o50by5NezHciWnoexJsrI49ILNqI",
"lvOQpTDwAAD2MYuOq9y_bmLNMJfbbdGw");
log.info(WxCpGsonBuilder.create().toJson(livingCode));
// 直播详情
WxCpLivingInfo livingInfo = wxCpService.getLivingService().getLivingInfo("lvOQpTDwAAcP9wNOSSxTwpbni-TMPNSg");
log.info(livingInfo.toJson());
// 直播观看明细
WxCpWatchStat watchStat = wxCpService.getLivingService().getWatchStat("lvOQpTDwAAcP9wNOSSxTwpbni-TMPNSg", "0");
log.info(watchStat.toJson());
final String watchStateJson = "{\"errcode\":0,\"errmsg\":\"ok\",\"ending\":1,\"next_key\":\"NEXT_KEY\"," +
"\"stat_info\":{\"users\":[{\"userid\":\"userid\",\"watch_time\":30,\"is_comment\":1,\"is_mic\":1}]," +
"\"external_users\":[{\"external_userid\":\"external_userid1\",\"type\":1,\"name\":\"user name\"," +
"\"watch_time\":30,\"is_comment\":1,\"is_mic\":1},{\"external_userid\":\"external_userid2\",\"type\":2," +
"\"name\":\"user_name\",\"watch_time\":30,\"is_comment\":1,\"is_mic\":1}]}}";
WxCpWatchStat wxCpWatchStat = WxCpWatchStat.fromJson(watchStateJson);
log.info(wxCpWatchStat.toJson());
// 直播观众信息
final String livingShareInfo = "{\"errcode\":0,\"errmsg\":\"ok\",\"livingid\":\"livingid\"," +
"\"viewer_userid\":\"viewer_userid\",\"viewer_external_userid\":\"viewer_external_userid\"," +
"\"invitor_userid\":\"invitor_userid\",\"invitor_external_userid\":\"invitor_external_userid\"}";
WxCpLivingShareInfo wxCpLivingShareInfo = WxCpLivingShareInfo.fromJson(livingShareInfo);
log.info(wxCpLivingShareInfo.toJson());
// 获取成员直播ID列表
WxCpLivingResult.LivingIdResult livingResult = wxCpService.getLivingService().getUserAllLivingId("ChenHu", null,
null);
log.info(livingResult.toJson());
String livinglist = "{\"errcode\":0,\"errmsg\":\"ok\",\"next_cursor\":\"next_cursor\"," +
"\"livingid_list\":[\"livingid1\",\"livingid2\"]}";
WxCpLivingResult.LivingIdResult livingIdResult = WxCpLivingResult.LivingIdResult.fromJson(livinglist);
log.info(livingIdResult.toJson());
log.info("{}", new Date().getTime());
// 创建预约直播
String create = "{\"anchor_userid\":\"ChenHu\",\"theme\":\"theme\",\"living_start\":164037820420," +
"\"living_duration\":3600,\"description\":\"test description\",\"type\":4,\"remind_time\":60," +
"\"activity_cover_mediaid\":\"MEDIA_ID\",\"activity_share_mediaid\":\"MEDIA_ID\"," +
"\"activity_detail\":{\"description\":\"活动描述,非活动类型的直播不用传\",\"image_list\":[\"xxxx1\",\"xxxx1\"]}}";
WxCpLivingCreateRequest request = WxCpLivingCreateRequest.fromJson(create);
String livingId = wxCpService.getLivingService().livingCreate(request);
log.info("livingId为:{}", livingId);
String modify = "{\"livingid\": \"" + livingId + "\",\"theme\":\"theme\",\"living_start\":164047820420," +
"\"living_duration\":3600,\"description\":\"描述:description\",\"type\":1,\"remind_time\":60}";
WxCpLivingModifyRequest modifyReq = WxCpLivingModifyRequest.fromJson(modify);
WxCpLivingResult result = wxCpService.getLivingService().livingModify(modifyReq);
log.info("result:{}", result.toJson());
// 取消预约直播
// WxCpLivingResult result2 = wxCpService.getLivingService().livingCancel("lvOQpTDwAA0KyLmWZhf_LIENzYIBVD2g");
WxCpLivingResult result2 = wxCpService.getLivingService().livingCancel(livingId);
log.info("取消预约直播为:{}", result2.toJson());
// 删除直播回放
// WxCpLivingResult response = wxCpService.getLivingService().deleteReplayData("lvOQpTDwAAVdCHyXMgSK63TKPfKDII7w");
// log.info(response.toJson());
}
/**
* Main.
*
* @param args the args
*/
public static void main(String[] args) {
log.info("{}", new Date().getTime());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpSchoolHealthTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpSchoolHealthTest.java | package me.chanjar.weixin.cp.api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.school.health.WxCpGetHealthReportStat;
import me.chanjar.weixin.cp.bean.school.health.WxCpGetReportAnswer;
import me.chanjar.weixin.cp.bean.school.health.WxCpGetReportJobIds;
import me.chanjar.weixin.cp.bean.school.health.WxCpGetReportJobInfo;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.demo.WxCpDemoInMemoryConfigStorage;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 企业微信家校应用 健康上报接口.
* https://developer.work.weixin.qq.com/document/path/93676
*
* @author <a href="https://github.com/0katekate0">Wang_Wong</a> created on : 2022/5/31 9:10
*/
@Slf4j
public class WxCpSchoolHealthTest {
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService cpService;
/**
* Test.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void test() throws WxErrorException {
InputStream inputStream = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(inputStream);
wxCpConfigStorage = config;
cpService = new WxCpServiceImpl();
cpService.setWxCpConfigStorage(config);
String currDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// Test Json
String reportAnswerStr = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"answers\":[\n" +
"\t\t{\n" +
"\t\t\t\"id_type\": 1,\n" +
"\t\t\t\"userid\": \"userid2\",\n" +
"\t\t\t\"report_time\": 123456789,\n" +
"\t\t\t\"report_values\": [\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"question_id\": 1,\n" +
"\t\t\t\t\t\"single_choice\": 2\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"question_id\": 2,\n" +
"\t\t\t\t\t\"text\": \"广东省广州市\"\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"question_id\": 3,\n" +
"\t\t\t\t\t\"multi_choice\": [\n" +
"\t\t\t\t\t\t1, 3\n" +
"\t\t\t\t\t]\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"question_id\": 4,\n" +
"\t\t\t\t\t\"fileid\": [\n" +
" \"XXXXXXX\"\n" +
" ]\n" +
"\t\t\t\t}\n" +
"\t\t\t]\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"id_type\": 2,\n" +
"\t\t\t\"student_userid\": \"student_userid1\",\n" +
"\t\t\t\"parent_userid\": \"parent_userid1\",\n" +
"\t\t\t\"report_time\": 123456789,\n" +
"\t\t\t\"report_values\":[\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"question_id\": 1,\n" +
"\t\t\t\t\t\"single_choice\": 1\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"question_id\": 2,\n" +
"\t\t\t\t\t\"text\": \"广东省深圳市\"\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"question_id\": 3,\n" +
"\t\t\t\t\t\"multi_choice\":[\n" +
"\t\t\t\t\t\t1,2,3\n" +
"\t\t\t\t\t]\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"question_id\": 4,\n" +
"\t\t\t\t\t\"fileid\": [\n" +
" \"XXXXXXX\"\n" +
" ]\n" +
"\t\t\t\t}\n" +
"\t\t\t]\n" +
"\t\t}\n" +
"\t]\n" +
"}";
WxCpGetReportAnswer getReportAnswer = WxCpGetReportAnswer.fromJson(reportAnswerStr);
log.info("获取对应的getReportAnswer:{}", getReportAnswer.toJson());
/**
* 获取用户填写答案
* https://developer.work.weixin.qq.com/document/path/93679
*/
WxCpGetReportAnswer reportAnswer = cpService.getSchoolHealthService().getReportAnswer("xxxx", currDate, null, null);
log.info("返回的reportAnswer为:{}", reportAnswer.toJson());
/**
* 获取健康上报任务ID列表
* https://developer.work.weixin.qq.com/document/path/93677
*/
WxCpGetReportJobIds reportJobids = cpService.getSchoolHealthService().getReportJobIds(null, null);
log.info("返回的reportJobids为:{}", reportJobids.toJson());
/**
* 获取健康上报任务详情
* https://developer.work.weixin.qq.com/document/path/93678
*/
WxCpGetReportJobInfo reportJobInfo = cpService.getSchoolHealthService().getReportJobInfo(null, currDate);
log.info("返回的reportJobInfo为:{}", reportJobInfo.toJson());
/**
* 获取健康上报使用统计
* https://developer.work.weixin.qq.com/document/path/93676
*/
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
WxCpGetHealthReportStat healthReportStat = cpService.getSchoolHealthService().getHealthReportStat(date);
log.info("返回的healthReportStat为:{}", healthReportStat.toJson());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpSchoolUserTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpSchoolUserTest.java | package me.chanjar.weixin.cp.api;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.XmlUtils;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.school.user.*;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.demo.WxCpDemoInMemoryConfigStorage;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 企业微信家校沟通相关接口.
* https://developer.work.weixin.qq.com/document/path/91638
*
* @author <a href="https://github.com/0katekate0">Wang_Wong</a> created on : 2022/6/18 9:10
*/
@Slf4j
public class WxCpSchoolUserTest {
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService cpService;
/**
* Test.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void test() throws WxErrorException {
InputStream inputStream = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(inputStream);
wxCpConfigStorage = config;
cpService = new WxCpServiceImpl();
cpService.setWxCpConfigStorage(config);
List<Integer> list = Lists.newArrayList();
list.add(1);
list.add(2);
list.add(3);
log.info("list:{}", list);
final String userId = "WangKai";
final String exUserId = "wmOQpTDwAAJFHrryZ8I8ALLEZuLHIUKA";
/**
* 获取部门家长详情
*
* https://developer.work.weixin.qq.com/document/path/92446
*/
WxCpListParentResult userListParent = cpService.getSchoolUserService().getUserListParent(1);
String jsonUserListParentResult = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"parents\": [\n" +
" {\n" +
" \"parent_userid\": \"zhangsan_parent\",\n" +
" \"mobile\": \"18900000000\",\n" +
" \"is_subscribe\": 1,\n" +
"\t\t\t\"external_userid\":\"xxx\",\n" +
" \"children\": [\n" +
" {\n" +
" \"student_userid\": \"zhangsan\",\n" +
" \"relation\": \"爸爸\",\n" +
" \"name\": \"张三\"\n" +
" }\n" +
" ]\n" +
" },\n" +
"\t\t{\n" +
" \"parent_userid\": \"lisi_parent\",\n" +
" \"mobile\": \"18900000001\",\n" +
" \"is_subscribe\": 0,\n" +
" \"children\": [\n" +
" {\n" +
" \"student_userid\": \"lisi\",\n" +
" \"relation\": \"妈妈\",\n" +
" \"name\": \"李四\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
WxCpListParentResult wxCpListParentResult = WxCpListParentResult.fromJson(jsonUserListParentResult);
assertThat(wxCpListParentResult.toJson()).isEqualTo(GsonParser.parse(jsonUserListParentResult).toString());
/**
* 获取部门成员详情
*
* https://developer.work.weixin.qq.com/document/path/92043
*/
WxCpUserListResult userList = cpService.getSchoolUserService().getUserList(1, 0);
String jsonUserListResult = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"students\":[\n" +
"\t\t{\n" +
"\t\t\t\"student_userid\": \"zhangsan\",\n" +
"\t\t\t\"name\": \"张三\",\n" +
"\t\t\t\"department\": [1, 2],\n" +
"\t\t\t\"parents\": [\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"parent_userid\": \"zhangsan_parent1\",\n" +
"\t\t\t\t\t\"relation\": \"爸爸\",\n" +
"\t\t\t\t\t\"mobile\": \"18000000001\",\n" +
"\t\t\t\t\t\"is_subscribe\": 1,\n" +
"\t\t\t\t\t\"external_userid\":\"xxx\"\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"parent_userid\": \"zhangsan_parent2\",\n" +
"\t\t\t\t\t\"relation\": \"妈妈\",\n" +
"\t\t\t\t\t\"mobile\": \"18000000002\",\n" +
"\t\t\t\t\t\"is_subscribe\": 0\n" +
"\t\t\t\t}\n" +
"\t\t\t]\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"student_userid\": \"lisi\",\n" +
"\t\t\t\"name\": \"李四\",\n" +
"\t\t\t\"department\": [4, 5],\n" +
"\t\t\t\"parents\": [\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"parent_userid\": \"lisi_parent1\",\n" +
"\t\t\t\t\t\"relation\": \"爷爷\",\n" +
"\t\t\t\t\t\"mobile\": \"18000000003\",\n" +
"\t\t\t\t\t\"is_subscribe\": 1,\n" +
"\t\t\t\t\t\"external_userid\":\"xxx\"\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"parent_userid\": \"lisi_parent2\",\n" +
"\t\t\t\t\t\"relation\": \"妈妈\",\n" +
"\t\t\t\t\t\"mobile\": \"18000000004\",\n" +
"\t\t\t\t\t\"is_subscribe\": 1,\n" +
"\t\t\t\t\t\"external_userid\":\"xxx\"\n" +
"\t\t\t\t}\n" +
"\t\t\t]\n" +
"\t\t}\n" +
"\t]\n" +
"}";
WxCpUserListResult wxCpUserListResult = WxCpUserListResult.fromJson(jsonUserListResult);
assertThat(wxCpUserListResult.toJson()).isEqualTo(GsonParser.parse(jsonUserListResult).toString());
/**
* 读取学生或家长
*
* https://developer.work.weixin.qq.com/document/path/92337
*/
WxCpUserResult userResult = cpService.getSchoolUserService().getUser(userId);
String jsonUserResult = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"user_type\": 1,\n" +
"\t\"student\":{\n" +
"\t\t\"student_userid\": \"zhangsan\",\n" +
"\t\t\"name\": \"张三\",\n" +
"\t\t\"department\": [1, 2],\n" +
"\t\t\"parents\":[\n" +
"\t\t\t{\n" +
"\t\t\t\t\"parent_userid\": \"zhangsan_parent1\",\n" +
"\t\t\t\t\"relation\": \"爸爸\",\n" +
"\t\t\t\t\"mobile\":\"18000000000\",\n" +
"\t\t\t\t\"is_subscribe\": 1,\n" +
"\t\t\t\t\"external_userid\":\"xxxxx\"\n" +
"\t\t\t},\n" +
"\t\t\t{\n" +
"\t\t\t\t\"parent_userid\": \"zhangsan_parent2\",\n" +
"\t\t\t\t\"relation\": \"妈妈\",\n" +
"\t\t\t\t\"mobile\": \"18000000001\",\n" +
"\t\t\t\t\"is_subscribe\": 0\n" +
"\t\t\t}\n" +
"\t\t]\n" +
" },\n" +
"\t\"parent\":{\n" +
"\t\t\"parent_userid\": \"zhangsan_parent2\",\n" +
"\t\t\"mobile\": \"18000000003\",\n" +
"\t\t\"is_subscribe\": 1,\n" +
"\t\t\"external_userid\":\"xxxxx\",\n" +
"\t\t\"children\":[\n" +
"\t\t\t{\n" +
"\t\t\t\t\"student_userid\": \"zhangsan\",\n" +
"\t\t\t\t\"relation\": \"妈妈\"\n" +
"\t\t\t},\n" +
"\t\t\t{\n" +
"\t\t\t\t\"student_userid\": \"lisi\",\n" +
"\t\t\t\t\"relation\": \"伯母\"\n" +
"\t\t\t}\n" +
"\t\t]\n" +
"\t}\n" +
"}";
WxCpUserResult wxCpUserResult = WxCpUserResult.fromJson(jsonUserResult);
assertThat(wxCpUserResult.toJson()).isEqualTo(GsonParser.parse(jsonUserResult).toString());
/**
* 批量更新家长
*
* https://developer.work.weixin.qq.com/document/path/92336
*/
String batchUpdateParentRequestParam = "{\n" +
" \"parents\":[\n" +
" { \n" +
" \"parent_userid\": \"zhangsan_baba\",\n" +
"\t\t\t\"new_parent_userid\":\"zhangsan_baba_new\",\n" +
" \"mobile\": \"10000000000\",\n" +
" \"children\":[\n" +
" { \n" +
" \"student_userid\": \"zhangsan\",\n" +
" \"relation\": \"爸爸\"\n" +
" } \n" +
" ] \n" +
" }, \n" +
" { \n" +
" \"parent_userid\": \"lisi_mama\",\n" +
" \"mobile\": \"10000000001\",\n" +
" \"children\":[\n" +
" {\n" +
" \"student_userid\": \"lisi\",\n" +
" \"relation\": \"妈妈\"\n" +
" } \n" +
" ] \n" +
" } \n" +
" ] \n" +
"}";
WxCpBatchUpdateParentRequest batchUpdateParentRequest =
WxCpBatchUpdateParentRequest.fromJson(batchUpdateParentRequestParam);
WxCpBatchResultList batchUpdateParentResult =
cpService.getSchoolUserService().batchUpdateParent(batchUpdateParentRequest);
/**
* 批量删除家长
*
* https://developer.work.weixin.qq.com/document/path/92335
*/
WxCpBatchResultList batchDeleteParentResult = cpService.getSchoolUserService().batchDeleteParent("abc", userId);
/**
* 批量创建家长 封装请求参数
*
* https://developer.work.weixin.qq.com/document/path/92334
*/
var child1 = WxCpBatchCreateParentRequest.Children.builder()
.relation("爸爸")
.studentUserId("zhangsan")
.build();
var child2 = WxCpBatchCreateParentRequest.Children.builder()
.relation("伯父")
.studentUserId("lisi")
.build();
var child3 = WxCpBatchCreateParentRequest.Children.builder()
.relation("爸爸")
.studentUserId("lisi")
.build();
var child4 = WxCpBatchCreateParentRequest.Children.builder()
.relation("伯父")
.studentUserId("zhangsan")
.build();
List<WxCpBatchCreateParentRequest.Children> childrenList1 = Lists.newArrayList();
childrenList1.add(child1);
childrenList1.add(child2);
List<WxCpBatchCreateParentRequest.Children> childrenList2 = Lists.newArrayList();
childrenList2.add(child3);
childrenList2.add(child4);
var zhangsanParent = WxCpBatchCreateParentRequest.Parent.builder()
.parentUserId("zhangsan_parent_userid")
.mobile("18000000000")
.toInvite(false)
.children(childrenList1)
.build();
var lisiParent = WxCpBatchCreateParentRequest.Parent.builder()
.parentUserId("lisi_parent_userid")
.mobile("18000000001")
.children(childrenList2)
.build();
List<WxCpBatchCreateParentRequest.Parent> batchCreateParent = Lists.newArrayList();
batchCreateParent.add(zhangsanParent);
batchCreateParent.add(lisiParent);
WxCpBatchCreateParentRequest wxCpBatchCreateParentRequest = WxCpBatchCreateParentRequest.builder()
.parents(batchCreateParent)
.build();
// 请求参数json
String batchCreateParentRequestParam = "{\n" +
"\t\"parents\":[\n" +
"\t\t{\n" +
"\t\t\t\"parent_userid\": \"zhangsan_parent_userid\",\n" +
" \t\t\"mobile\": \"18000000000\",\n" +
"\t\t\t\"to_invite\": false,\n" +
"\t\t\t\"children\":[\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"student_userid\": \"zhangsan\",\n" +
" \t\t \"relation\": \"爸爸\"\n" +
" \t\t },\n" +
" \t\t {\n" +
"\t\t\t\t\t\"student_userid\": \"lisi\",\n" +
" \t\t \"relation\": \"伯父\"\n" +
" \t\t }\n" +
" \t\t]\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"parent_userid\": \"lisi_parent_userid\",\n" +
" \t\t\"mobile\": \"18000000001\",\n" +
"\t\t\t\"children\":[\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"student_userid\": \"lisi\",\n" +
" \t\t \"relation\": \"爸爸\"\n" +
" \t\t },\n" +
" \t\t {\n" +
"\t\t\t\t\t\"student_userid\": \"zhangsan\",\n" +
" \t\t \"relation\": \"伯父\"\n" +
" \t\t }\n" +
" \t\t]\n" +
"\t\t}\n" +
"\t]\n" +
"}";
assertThat(wxCpBatchCreateParentRequest.toJson()).isEqualTo(GsonParser.parse(batchCreateParentRequestParam).toString());
WxCpBatchResultList batchCreateParentResult =
cpService.getSchoolUserService().batchCreateParent(wxCpBatchCreateParentRequest);
// 返回结果
String batchResultStr = "{\n" +
"\t\"errcode\": 1,\n" +
"\t\"errmsg\": \"invalid parent_userid: lisi_parent_userid\",\n" +
"\t\"result_list\": [\n" +
"\t\t{\n" +
"\t\t\t\"parent_userid\": \"lisi_parent_userid\",\n" +
"\t\t\t\"errcode\": 1,\n" +
"\t\t\t\"errmsg\": \"invalid parent_userid: lisi_parent_userid\",\n" +
"\t\t}\n" +
"\t]\n" +
"}";
assertThat(batchCreateParentResult.toJson()).isEqualTo(GsonParser.parse(batchResultStr).toString());
/**
* 获取家校访问用户身份
*
* https://developer.work.weixin.qq.com/document/path/95791
*/
WxCpOauth2UserInfo schoolUserInfo = cpService.getSchoolUserService().getSchoolUserInfo("abc");
assertThat(schoolUserInfo).isNotNull();
WxCpOauth2UserInfo oauth2UserInfo = cpService.getSchoolUserService().getUserInfo("abc");
assertThat(oauth2UserInfo).isNotNull();
WxCpOauth2UserInfo userInfo = cpService.getOauth2Service().getUserInfo("abc");
assertThat(userInfo).isNotNull();
// 返回值
String batchResult = "{\n" +
"\t\"errcode\": 1,\n" +
"\t\"errmsg\": \"invalid student_userid: zhangsan\",\n" +
"\t\"result_list\": [\n" +
"\t\t{\n" +
"\t\t\t\"student_userid\": \"zhangsan\",\n" +
"\t\t\t\"errcode\": 1,\n" +
"\t\t\t\"errmsg\": \"invalid student_userid: zhangsan\"\n" +
"\t\t}\n" +
"\t]\n" +
"}";
WxCpBatchResultList batchResultList = WxCpBatchResultList.fromJson(batchResult);
log.info("batchResultList: {}", batchResultList.toJson());
/**
* 批量更新学生
* https://developer.work.weixin.qq.com/document/path/92330
*
* 请求方式:POST(HTTPS)
* 请求地址:https://qyapi.weixin.qq.com/cgi-bin/school/user/batch_update_student?access_token=ACCESS_TOKEN
*/
String batchUpdateStudent = "{\n" +
"\t\"students\":[\n" +
" {\n" +
"\t\t\t\"student_userid\": \"zhangsan\",\n" +
"\t\t\t\"new_student_userid\":\"zhangsan_new\",\n" +
"\t\t\t\"name\": \"张三\",\n" +
"\t\t\t\"department\": [1, 2]\n" +
"\t\t},\n" +
" {\n" +
"\t\t\t\"student_userid\": \"lisi\",\n" +
"\t\t\t\"name\": \"李四\",\n" +
"\t\t\t\"department\": [3, 4]\n" +
"\t\t}\n" +
" ]\n" +
"}";
WxCpBatchUpdateStudentRequest batchUpdateStudentRequest =
WxCpBatchUpdateStudentRequest.fromJson(batchUpdateStudent);
WxCpBatchResultList list3 = cpService.getSchoolUserService().batchUpdateStudent(batchUpdateStudentRequest);
log.info("list3: {}", list3.toJson());
/**
* 批量删除学生
* https://developer.work.weixin.qq.com/document/path/92329
*
* 请求方式:POST(HTTPS)
* 请求地址:https://qyapi.weixin.qq.com/cgi-bin/school/user/batch_delete_student?access_token=ACCESS_TOKEN
*/
String batchDeleteStudent = "{\n" +
"\t\"useridlist\": [\"zhangsan\", \"lisi\"]\n" +
"}\n";
WxCpBatchDeleteStudentRequest batchDeleteStudentRequest =
WxCpBatchDeleteStudentRequest.fromJson(batchDeleteStudent);
WxCpBatchResultList list2 = cpService.getSchoolUserService().batchDeleteStudent(batchDeleteStudentRequest);
log.info("list2: {}", list2.toJson());
/**
* 批量创建学生
* https://developer.work.weixin.qq.com/document/path/92328
*/
String batchCreateStudent = "{\n" +
"\t\"students\":[\n" +
" {\n" +
"\t\t\t\"student_userid\": \"zhangsan\",\n" +
"\t\t\t\"name\": \"张三\",\n" +
"\t\t\t\"department\": [1, 2]\n" +
"\t\t},\n" +
" {\n" +
"\t\t\t\"student_userid\": \"lisi\",\n" +
"\t\t\t\"name\": \"李四\",\n" +
"\t\t\t\"department\": [3, 4]\n" +
"\t\t}\n" +
" ]\n" +
"}";
WxCpBatchCreateStudentRequest batchCreateStudentRequest =
WxCpBatchCreateStudentRequest.fromJson(batchCreateStudent);
WxCpBatchResultList list1 = cpService.getSchoolUserService().batchCreateStudent(batchCreateStudentRequest);
log.info("list1: {}", list1.toJson());
// String changeContact = WxCpConsts.EventType.CHANGE_CONTACT;
/**
* 增加变更事件类型:
*/
// WxCpConsts.EventType.CHANGE_SCHOOL_CONTACT;
// WxCpConsts.SchoolContactChangeType.DELETE_STUDENT;
// WxCpConsts.SchoolContactChangeType.CREATE_DEPARTMENT;
/**
* 测试家校通讯录变更回调
* https://developer.work.weixin.qq.com/document/path/92052
*
* 新增学生事件
* 当学校在家校通讯录中新增学生时,回调此事件。
*/
String createStudentXml = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[change_school_contact]]></Event>\n" +
"\t<ChangeType><![CDATA[create_student]]></ChangeType>\n" +
"\t<Id><![CDATA[xiaoming]]></Id>\n" +
"</xml>";
/**
* 家长取消关注事件
* 当家长取消关注家校通知时,回调此事件。
*/
String unSubscribeXml = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[change_school_contact]]></Event>\n" +
"\t<ChangeType><![CDATA[unsubscribe]]></ChangeType>\n" +
"\t<Id><![CDATA[xiaoming]]></Id>\n" +
"</xml>";
/**
* 创建部门事件
* 当学校在家校通讯录中创建部门时,回调此事件。
*/
String createDepartmentXml = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[change_school_contact]]></Event>\n" +
"\t<ChangeType><![CDATA[create_deparmtment]]></ChangeType>\n" +
"\t<Id><![CDATA[1]]></Id>\n" +
"</xml>";
/**
* 删除部门事件
* 当学校删除家校通讯录部门时,回调此事件。
*/
String deleteDepartmentXml = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[change_school_contact]]></Event>\n" +
"\t<ChangeType><![CDATA[delete_deparmtment]]></ChangeType>\n" +
"\t<Id><![CDATA[1]]></Id>\n" +
"</xml>";
// WxCpXmlMessage.fromXml(createStudentXml);
final WxCpXmlMessage createStudentMsg = XStreamTransformer.fromXml(WxCpXmlMessage.class, createStudentXml);
Map<String, Object> map1 = XmlUtils.xml2Map(createStudentXml);
createStudentMsg.setAllFieldsMap(map1);
log.info("createStudentMsg:{}", WxCpGsonBuilder.create().toJson(createStudentMsg));
final WxCpXmlMessage unSubscribeMsg = XStreamTransformer.fromXml(WxCpXmlMessage.class, unSubscribeXml);
Map<String, Object> map2 = XmlUtils.xml2Map(unSubscribeXml);
unSubscribeMsg.setAllFieldsMap(map2);
log.info("unSubscribeMsg:{}", WxCpGsonBuilder.create().toJson(unSubscribeMsg));
final WxCpXmlMessage createDepartmentMsg = XStreamTransformer.fromXml(WxCpXmlMessage.class, createDepartmentXml);
createDepartmentMsg.setAllFieldsMap(XmlUtils.xml2Map(createDepartmentXml));
log.info("createDepartmentMsg:{}", WxCpGsonBuilder.create().toJson(createDepartmentMsg));
final WxCpXmlMessage deleteDepartmentMsg = XStreamTransformer.fromXml(WxCpXmlMessage.class, deleteDepartmentXml);
deleteDepartmentMsg.setAllFieldsMap(XmlUtils.xml2Map(deleteDepartmentXml));
log.info("deleteDepartmentMsg:{}", WxCpGsonBuilder.create().toJson(deleteDepartmentMsg));
/**
* 获取可使用的家长范围
* https://developer.work.weixin.qq.com/document/path/94895
*/
String str8 = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"allow_scope\": {\n" +
" \"students\": [\n" +
" {\"userid\": \"student1\"},\n" +
" {\"userid\": \"student2\"}\n" +
" ],\n" +
"\t \"departments\": [1, 2]\n" +
" }\n" +
"}";
WxCpAllowScope cpAllowScope = WxCpAllowScope.fromJson(str8);
log.info("cpAllowScope:{}", cpAllowScope.toJson());
WxCpAllowScope allowScope = cpService.getSchoolUserService().getAllowScope(100000);
log.info("allowScope:{}", allowScope);
/**
* 外部联系人openid转换
* https://developer.work.weixin.qq.com/document/path/92323
*/
String openId = cpService.getSchoolUserService().convertToOpenId("wmOQpTDwAAh_sKvmJBJ4FQ0iYAcbppFA");
log.info("openId:{}", openId);
/**
* 家校沟通 获取外部联系人详情
* https://developer.work.weixin.qq.com/document/path/92322
*/
String str7 = "{\"errcode\":0,\"errmsg\":\"ok\",\"external_contact\":{\"external_userid\":\"woAAAA\"," +
"\"name\":\"李四\",\"position\":\"Mangaer\",\"avatar\":\"http://p.qlogo.cn/bizmail/IcsdgagqefergqerhewSdage/0\"," +
"\"corp_name\":\"腾讯\",\"corp_full_name\":\"腾讯科技有限公司\",\"type\":2,\"gender\":1,\"unionid\":\"unAAAAA\"," +
"\"is_subscribe\":1,\"subscriber_info\":{\"tag_id\":[\"TAG_ID1\",\"TAG_ID2\"]," +
"\"remark_mobiles\":[\"10000000000\",\"10000000001\"],\"remark\":\"李小明-爸爸\"}," +
"\"external_profile\":{\"external_attr\":[{\"type\":0,\"name\":\"文本名称\",\"text\":{\"value\":\"文本\"}}," +
"{\"type\":1,\"name\":\"网页名称\",\"web\":{\"url\":\"http://www.test.com\",\"title\":\"标题\"}},{\"type\":2," +
"\"name\":\"测试app\",\"miniprogram\":{\"appid\":\"wxAAAAA\",\"pagepath\":\"/index\",\"title\":\"my " +
"miniprogram\"}}]}},\"follow_user\":[{\"userid\":\"rocky\",\"remark\":\"李部长\",\"description\":\"对接采购事物\"," +
"\"createtime\":1525779812,\"tags\":[{\"group_name\":\"标签分组名称\",\"tag_name\":\"标签名称\",\"type\":1}]," +
"\"remark_corp_name\":\"腾讯科技\",\"remark_mobiles\":[10000000003,10000000004]},{\"userid\":\"tommy\"," +
"\"remark\":\"李总\",\"description\":\"采购问题咨询\",\"createtime\":1525881637,\"state\":\"外联二维码1\"}]}";
WxCpExternalContact wxCpExternalContact = WxCpExternalContact.fromJson(str7);
log.info("wxCpExternalContact:{}", wxCpExternalContact.toJson());
// cpService.getExternalContactService().getExternalContact();
WxCpExternalContact externalContact = cpService.getSchoolUserService().getExternalContact(exUserId);
log.info("externalContact:{}", externalContact.toJson());
/**
* 获取关注「学校通知」的模式
* 可通过此接口获取家长关注「学校通知」的模式:“可扫码填写资料加入”或“禁止扫码填写资料加入”
* https://developer.work.weixin.qq.com/document/path/92290
*/
Integer subscribeMode = cpService.getSchoolUserService().getSubscribeMode();
log.info("subscribeMode:{}", subscribeMode);
/**
* 管理「学校通知」的关注模式
* 设置关注「学校通知」的模式
* https://developer.work.weixin.qq.com/document/path/92290
*/
WxCpBaseResp setSubscribeMode = cpService.getSchoolUserService().setSubscribeMode(1);
log.info("setSubscribeMode:{}", setSubscribeMode.toJson());
/**
* 获取「学校通知」二维码
* https://developer.work.weixin.qq.com/document/path/92320
*/
String str6 = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"qrcode_big\":\"http://p.qpic.cn/wwhead/XXXX\",\n" +
" \"qrcode_middle\":\"http://p.qpic.cn/wwhead/XXXX\",\n" +
" \"qrcode_thumb\":\"http://p.qpic.cn/wwhead/XXXX\"\n" +
"}";
WxCpSubscribeQrCode cpSubscribeQrCode = WxCpSubscribeQrCode.fromJson(str6);
log.info("cpSubscribeQrCode:{}", cpSubscribeQrCode.toJson());
WxCpSubscribeQrCode subscribeQrCode = cpService.getSchoolUserService().getSubscribeQrCode();
log.info("subscribeQrCode:{}", subscribeQrCode.toJson());
/**
* 修改自动升年级的配置
* https://developer.work.weixin.qq.com/document/path/92949
*/
WxCpSetUpgradeInfo wxCpSetUpgradeInfo = cpService.getSchoolUserService().setUpgradeInfo(1594090969L, 2);
log.info("wxCpSetUpgradeInfo:{}", wxCpSetUpgradeInfo.toJson());
/**
* 获取部门列表
* https://developer.work.weixin.qq.com/document/path/92343
*/
String str5 = "{\"errcode\":0,\"errmsg\":\"ok\",\"departments\":[{\"name\":\"一年级\",\"parentid\":1,\"id\":2," +
"\"type\":2,\"register_year\":2018,\"standard_grade\":1,\"order\":1," +
"\"department_admins\":[{\"userid\":\"zhangsan\",\"type\":1},{\"userid\":\"lisi\",\"type\":2}]," +
"\"is_graduated\":0},{\"name\":\"一年级一班\",\"parentid\":1,\"id\":3,\"type\":1," +
"\"department_admins\":[{\"userid\":\"zhangsan\",\"type\":3,\"subject\":\"语文\"},{\"userid\":\"lisi\"," +
"\"type\":4,\"subject\":\"数学\"}],\"open_group_chat\":1,\"group_chat_id\":\"group_chat_id\"}]}";
WxCpDepartmentList wxCpDepartmentList = WxCpDepartmentList.fromJson(str5);
log.info("wxCpDepartmentList:{}", wxCpDepartmentList.toJson());
WxCpDepartmentList departmentList = cpService.getSchoolUserService().listDepartment(7);
log.info("departmentList:{}", departmentList.toJson());
/**
* 删除部门
* https://developer.work.weixin.qq.com/document/path/92342
*/
WxCpBaseResp deleteDepartment = cpService.getSchoolUserService().deleteDepartment(7);
log.info("deleteDepartment:{}", deleteDepartment.toJson());
/**
* 更新部门
* https://developer.work.weixin.qq.com/document/path/92341
*/
String str4 = "{\"name\":\"一年级\",\"parentid\":5,\"id\":2,\"register_year\":2018,\"standard_grade\":1,\"order\":1," +
"\"new_id\":100,\"department_admins\":[{\"op\":0,\"userid\":\"zhangsan\",\"type\":3,\"subject\":\"语文\"}," +
"{\"op\":1,\"userid\":\"lisi\",\"type\":4,\"subject\":\"数学\"}]}";
WxCpUpdateDepartmentRequest wxCpUpdateDepartmentRequest = WxCpUpdateDepartmentRequest.fromJson(str4);
log.info("wxCpUpdateParentRequest:{}", wxCpUpdateDepartmentRequest.toJson());
WxCpBaseResp updateDepartment = cpService.getSchoolUserService().updateDepartment(wxCpUpdateDepartmentRequest);
log.info("updateDepartment:{}", updateDepartment.toJson());
/**
* 创建部门
* https://developer.work.weixin.qq.com/document/path/92340
*/
String str3 = "{\"name\":\"一年级\",\"parentid\":5,\"id\":2,\"type\":1,\"register_year\":2018,\"standard_grade\":1," +
"\"order\":1,\"department_admins\":[{\"userid\":\"zhangsan\",\"type\":4,\"subject\":\"语文\"}," +
"{\"userid\":\"lisi\",\"type\":3,\"subject\":\"数学\"}]}";
WxCpCreateDepartmentRequest wxCpCreateDepartmentRequest = WxCpCreateDepartmentRequest.fromJson(str3);
log.info("wxCpCreateDepartmentRequest:{}", wxCpCreateDepartmentRequest.toJson());
WxCpCreateDepartmentRequest createDepartmentRequest = new WxCpCreateDepartmentRequest();
createDepartmentRequest.setParentId(5);
createDepartmentRequest.setName("一年级");
createDepartmentRequest.setId(2);
createDepartmentRequest.setType(1);
createDepartmentRequest.setRegisterYear(2018);
createDepartmentRequest.setStandardGrade(1);
createDepartmentRequest.setOrder(1);
var departmentAdmin = new WxCpCreateDepartmentRequest.DepartmentAdmin();
departmentAdmin.setUserId(userId);
departmentAdmin.setType(4);
departmentAdmin.setSubject("英语");
List<WxCpCreateDepartmentRequest.DepartmentAdmin> createDepartList = Lists.newArrayList();
createDepartList.add(departmentAdmin);
createDepartmentRequest.setDepartmentAdmins(createDepartList);
WxCpCreateDepartment createDepartment = cpService.getSchoolUserService().createDepartment(createDepartmentRequest);
log.info("createDepartment:{}", createDepartment.toJson());
/**
* 更新家长
* https://developer.work.weixin.qq.com/document/path/92333
*/
String str2 = "{\"parent_userid\":\"zhangsan_parent_userid\",\"new_parent_userid\":\"NEW_ID\"," +
"\"mobile\":\"18000000000\",\"children\":[{\"student_userid\":\"zhangsan\",\"relation\":\"爸爸\"}," +
"{\"student_userid\":\"lisi\",\"relation\":\"伯父\"}]}";
WxCpUpdateParentRequest updateParentRequest1 = WxCpUpdateParentRequest.fromJson(str2);
log.info("updateParentRequest1:{}", updateParentRequest1.toJson());
WxCpUpdateParentRequest updateParentRequest = new WxCpUpdateParentRequest();
updateParentRequest.setParentUserId("zhangsan");
updateParentRequest.setMobile("17324399999");
updateParentRequest.setNewParentUserId("wangkai");
var child = new WxCpUpdateParentRequest.Children();
child.setStudentUserId("zhangguiyuan");
child.setRelation("伯父");
List<WxCpUpdateParentRequest.Children> childList = Lists.newArrayList();
childList.add(child);
updateParentRequest.setChildren(childList);
WxCpBaseResp updateParent = cpService.getSchoolUserService().updateParent(updateParentRequest);
log.info("updateParent:{}", updateParent.toJson());
/**
* 删除家长
* https://developer.work.weixin.qq.com/document/path/92332
*/
WxCpBaseResp deleteParent = cpService.getSchoolUserService().deleteParent("zhangsan");
log.info("deleteParent:{}", deleteParent.toJson());
/**
* 创建家长
* https://developer.work.weixin.qq.com/document/path/92331
*/
String str1 = "{\"parent_userid\":\"zhangsan_parent_userid\",\"mobile\":\"10000000000\",\"to_invite\":false," +
"\"children\":[{\"student_userid\":\"zhangsan\",\"relation\":\"爸爸\"},{\"student_userid\":\"lisi\"," +
"\"relation\":\"伯父\"}]}";
WxCpCreateParentRequest createParentRequest1 = WxCpCreateParentRequest.fromJson(str1);
log.info("createParentRequest1:{}", createParentRequest1.toJson());
WxCpCreateParentRequest createParentRequest = new WxCpCreateParentRequest();
createParentRequest.setParentUserId("wangkai");
createParentRequest.setMobile("17324398888");
createParentRequest.setToInvite(false);
var children1 = new WxCpCreateParentRequest.Children();
children1.setStudentUserId("zhangguiyuan");
children1.setRelation("伯父");
List<WxCpCreateParentRequest.Children> children = Lists.newArrayList();
children.add(children1);
createParentRequest.setChildren(children);
WxCpBaseResp createParent = cpService.getSchoolUserService().createParent(createParentRequest);
log.info("createParent:{}", createParent.toJson());
/**
* 设置家校通讯录自动同步模式
* 企业和第三方可通过此接口修改家校通讯录与班级标签之间的自动同步模式,注意,一旦设置禁止自动同步,将无法再次开启。
*/
WxCpBaseResp setArchSyncMode = cpService.getSchoolUserService().setArchSyncMode(2);
log.info("setArchSyncMode:{}", setArchSyncMode.toJson());
/**
* 更新学生
*/
WxCpBaseResp updateStudent = cpService.getSchoolUserService().updateStudent("WangKai", "wangkai", "王", list);
log.info("updateStudent:{}", updateStudent.toJson());
/**
* 删除学生
*/
WxCpBaseResp deleteStudent = cpService.getSchoolUserService().deleteStudent("WangKai");
log.info("deleteStudent:{}", deleteStudent.toJson());
/**
* 创建学生
*/
WxCpBaseResp student = cpService.getSchoolUserService().createStudent("WangKai", "王", list);
log.info("student:{}", student.toJson());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTpMessageRouterTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTpMessageRouterTest.java | package me.chanjar.weixin.cp.api;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.bean.message.WxCpTpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.tp.message.WxCpTpMessageHandler;
import me.chanjar.weixin.cp.tp.message.WxCpTpMessageRouter;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import me.chanjar.weixin.cp.tp.service.impl.WxCpTpServiceApacheHttpClientImpl;
import org.testng.annotations.Test;
import java.util.Map;
import static org.testng.Assert.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
/**
* The type Wx cp tp message router test.
*/
public class WxCpTpMessageRouterTest {
/**
* Test message router.
*/
@Test
public void testMessageRouter() {
WxCpTpService service = new WxCpTpServiceApacheHttpClientImpl();
WxCpTpMessageRouter router = new WxCpTpMessageRouter(service);
String xml = "<xml>\n" +
" <SuiteId><![CDATA[ww4asffe99e54cxxxx]]></SuiteId>\n" +
" <AuthCorpId><![CDATA[wxf8b4f85f3a79xxxx]]></AuthCorpId>\n" +
" <InfoType><![CDATA[change_contact]]></InfoType>\n" +
" <TimeStamp>1403610513</TimeStamp>\n" +
" <ChangeType><![CDATA[update_tag]]></ChangeType>\n" +
" <TagId>1</TagId>\n" +
" <AddUserItems><![CDATA[zhangsan,lisi]]></AddUserItems>\n" +
" <DelUserItems><![CDATA[zhangsan1,lisi1]]></DelUserItems>\n" +
" <AddPartyItems><![CDATA[1,2]]></AddPartyItems>\n" +
" <DelPartyItems><![CDATA[3,4]]></DelPartyItems>\n" +
"</xml>";
WxCpTpXmlMessage wxXmlMessage = WxCpTpXmlMessage.fromXml(xml);
router.rule().infoType("change_contact").changeType("update_tag").handler(new WxCpTpMessageHandler() {
@Override
public WxCpXmlOutMessage handle(WxCpTpXmlMessage wxMessage, Map<String, Object> context,
WxCpTpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
System.out.println("handler enter");
assertNotNull(wxCpService);
return null;
}
}).end();
assertNull(router.route(wxXmlMessage));
System.out.println("over");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpExternalContactTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpExternalContactTest.java | package me.chanjar.weixin.cp.api;
import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalUnassignList;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
/**
* 离职继承测试类
* <p>
* 官方文档:
* https://developer.work.weixin.qq.com/document/path/92124
*/
@Slf4j
@Guice(modules = ApiTestModule.class)
public class WxCpExternalContactTest {
@Inject
private WxCpService wxCpService;
/**
* The Config storage.
*/
@Inject
protected ApiTestModule.WxXmlCpInMemoryConfigStorage configStorage;
/**
* Test get external contact.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetExternalContact() throws WxErrorException {
String externalUserId = this.configStorage.getExternalUserId();
WxCpUserExternalUnassignList unassignList = this.wxCpService.getExternalContactService().listUnassignedList(null,
null, 100);
log.info(unassignList.toJson());
// test str
String result = "{\"errcode\":0,\"errmsg\":\"ok\",\"info\":[{\"handover_userid\":\"zhangsan\"," +
"\"external_userid\":\"woAJ2GCAAAd4uL12hdfsdasassdDmAAAAA\",\"dimission_time\":1550838571}," +
"{\"handover_userid\":\"lisi\",\"external_userid\":\"wmAJ2GCAAAzLTI123ghsdfoGZNqqAAAA\"," +
"\"dimission_time\":1550661468}],\"is_last\":false,\"next_cursor\":\"aSfwejksvhToiMMfFeIGZZ\"}";
WxCpUserExternalUnassignList json = WxCpUserExternalUnassignList.fromJson(result);
log.info(json.toJson());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java | package me.chanjar.weixin.cp.api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* The type Wx cp busy retry test.
*/
@Test
@Slf4j
public class WxCpBusyRetryTest {
/**
* Get service object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider(name = "getService")
public Object[][] getService() {
WxCpService service = new WxCpServiceImpl() {
@Override
public synchronized <T, E> T executeInternal(
RequestExecutor<T, E> executor, String uri, E data, boolean doNotAutoRefresh)
throws WxErrorException {
log.info("Executed");
throw new WxErrorException("something");
}
};
service.setMaxRetryTimes(3);
service.setRetrySleepMillis(500);
return new Object[][]{
new Object[]{service}
};
}
/**
* Test retry.
*
* @param service the service
* @throws WxErrorException the wx error exception
*/
@Test(dataProvider = "getService", expectedExceptions = RuntimeException.class)
public void testRetry(WxCpService service) throws WxErrorException {
service.execute(null, null, null);
}
/**
* Test retry in thread pool.
*
* @param service the service
* @throws InterruptedException the interrupted exception
* @throws ExecutionException the execution exception
*/
@Test(dataProvider = "getService")
public void testRetryInThreadPool(final WxCpService service) throws InterruptedException, ExecutionException {
// 当线程池中的线程复用的时候,还是能保证相同的重试次数
ExecutorService executorService = Executors.newFixedThreadPool(1);
Runnable runnable = () -> {
try {
System.out.println("=====================");
System.out.println(Thread.currentThread().getName() + ": testRetry");
service.execute(null, null, null);
} catch (WxErrorException e) {
throw new WxRuntimeException(e);
} catch (RuntimeException e) {
// OK
}
};
Future<?> submit1 = executorService.submit(runnable);
Future<?> submit2 = executorService.submit(runnable);
submit1.get();
submit2.get();
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java | package me.chanjar.weixin.cp.api;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.StandardSessionManager;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.message.WxCpMessageHandler;
import me.chanjar.weixin.cp.message.WxCpMessageMatcher;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Map;
/**
* 测试消息路由器
*
* @author Daniel Qian
*/
@Test
public class WxCpMessageRouterTest {
/**
* Prepare.
*
* @param async the async
* @param sb the sb
* @param router the router
*/
@Test(enabled = false)
public void prepare(boolean async, StringBuffer sb, WxCpMessageRouter router) {
router
.rule()
.async(async)
.msgType(WxConsts.XmlMsgType.TEXT).event(WxConsts.EventType.CLICK).eventKey("KEY_1").content("CONTENT_1")
.handler(new WxEchoCpMessageHandler(sb, "COMBINE_4"))
.end()
.rule()
.async(async)
.msgType(WxConsts.XmlMsgType.TEXT).event(WxConsts.EventType.CLICK).eventKey("KEY_1")
.handler(new WxEchoCpMessageHandler(sb, "COMBINE_3"))
.end()
.rule()
.async(async)
.msgType(WxConsts.XmlMsgType.TEXT).event(WxConsts.EventType.CLICK)
.handler(new WxEchoCpMessageHandler(sb, "COMBINE_2"))
.end()
.rule().async(async).msgType(WxConsts.XmlMsgType.TEXT).handler(new WxEchoCpMessageHandler(sb,
WxConsts.XmlMsgType.TEXT)).end()
.rule().async(async).event(WxConsts.EventType.CLICK).handler(new WxEchoCpMessageHandler(sb,
WxConsts.EventType.CLICK)).end()
.rule().async(async).eventKey("KEY_1").handler(new WxEchoCpMessageHandler(sb, "KEY_1")).end()
.rule().async(async).content("CONTENT_1").handler(new WxEchoCpMessageHandler(sb, "CONTENT_1")).end()
.rule().async(async).rContent(".*bc.*").handler(new WxEchoCpMessageHandler(sb, "abcd")).end()
.rule().async(async).matcher(new WxCpMessageMatcher() {
@Override
public boolean match(WxCpXmlMessage message) {
return "strangeformat".equals(message.getFormat());
}
}).handler(new WxEchoCpMessageHandler(sb, "matcher")).end()
.rule().async(async).handler(new WxEchoCpMessageHandler(sb, "ALL")).end();
}
/**
* Test sync.
*
* @param message the message
* @param expected the expected
*/
@Test(dataProvider = "messages-1")
public void testSync(WxCpXmlMessage message, String expected) {
StringBuffer sb = new StringBuffer();
WxCpMessageRouter router = new WxCpMessageRouter(null);
prepare(false, sb, router);
router.route(message);
Assert.assertEquals(sb.toString(), expected);
}
/**
* Test async.
*
* @param message the message
* @param expected the expected
* @throws InterruptedException the interrupted exception
*/
@Test(dataProvider = "messages-1")
public void testAsync(WxCpXmlMessage message, String expected) throws InterruptedException {
StringBuffer sb = new StringBuffer();
WxCpMessageRouter router = new WxCpMessageRouter(null);
prepare(true, sb, router);
router.route(message);
Thread.sleep(500);
Assert.assertEquals(sb.toString(), expected);
}
/**
* Test concurrency.
*
* @throws InterruptedException the interrupted exception
*/
public void testConcurrency() throws InterruptedException {
final WxCpMessageRouter router = new WxCpMessageRouter(null);
router.rule().handler(new WxCpMessageHandler() {
@Override
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService wxCpService,
WxSessionManager sessionManager) {
return null;
}
}).end();
final WxCpXmlMessage m = new WxCpXmlMessage();
Runnable r = () -> {
router.route(m);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
};
for (int i = 0; i < 10; i++) {
new Thread(r).start();
}
Thread.sleep(2000);
}
/**
* Messages 2 object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider(name = "messages-1")
public Object[][] messages2() {
WxCpXmlMessage message1 = new WxCpXmlMessage();
message1.setMsgType(WxConsts.XmlMsgType.TEXT);
WxCpXmlMessage message2 = new WxCpXmlMessage();
message2.setEvent(WxConsts.EventType.CLICK);
WxCpXmlMessage message3 = new WxCpXmlMessage();
message3.setEventKey("KEY_1");
WxCpXmlMessage message4 = new WxCpXmlMessage();
message4.setContent("CONTENT_1");
WxCpXmlMessage message5 = new WxCpXmlMessage();
message5.setContent("BLA");
WxCpXmlMessage message6 = new WxCpXmlMessage();
message6.setContent("abcd");
WxCpXmlMessage message7 = new WxCpXmlMessage();
message7.setFormat("strangeformat");
WxCpXmlMessage c2 = new WxCpXmlMessage();
c2.setMsgType(WxConsts.XmlMsgType.TEXT);
c2.setEvent(WxConsts.EventType.CLICK);
WxCpXmlMessage c3 = new WxCpXmlMessage();
c3.setMsgType(WxConsts.XmlMsgType.TEXT);
c3.setEvent(WxConsts.EventType.CLICK);
c3.setEventKey("KEY_1");
WxCpXmlMessage c4 = new WxCpXmlMessage();
c4.setMsgType(WxConsts.XmlMsgType.TEXT);
c4.setEvent(WxConsts.EventType.CLICK);
c4.setEventKey("KEY_1");
c4.setContent("CONTENT_1");
return new Object[][]{
new Object[]{message1, WxConsts.XmlMsgType.TEXT + ","},
new Object[]{message2, WxConsts.EventType.CLICK + ","},
new Object[]{message3, "KEY_1,"},
new Object[]{message4, "CONTENT_1,"},
new Object[]{message5, "ALL,"},
new Object[]{message6, "abcd,"},
new Object[]{message7, "matcher,"},
new Object[]{c2, "COMBINE_2,"},
new Object[]{c3, "COMBINE_3,"},
new Object[]{c4, "COMBINE_4,"}
};
}
/**
* Standard session manager object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider
public Object[][] standardSessionManager() {
// 故意把session存活时间变短,清理更频繁
StandardSessionManager ism = new StandardSessionManager();
ism.setMaxInactiveInterval(1);
ism.setProcessExpiresFrequency(1);
ism.setBackgroundProcessorDelay(1);
return new Object[][]{
new Object[]{ism}
};
}
/**
* Test session clean 1.
*
* @param ism the ism
* @throws InterruptedException the interrupted exception
*/
@Test(dataProvider = "standardSessionManager")
public void testSessionClean1(StandardSessionManager ism) throws InterruptedException {
// 两个同步请求,看是否处理完毕后会被清理掉
final WxCpMessageRouter router = new WxCpMessageRouter(null);
router.setSessionManager(ism);
router
.rule().async(false).handler(new WxSessionMessageHandler()).next()
.rule().async(false).handler(new WxSessionMessageHandler()).end();
WxCpXmlMessage msg = new WxCpXmlMessage();
msg.setFromUserName("abc");
router.route(msg);
Thread.sleep(2000);
Assert.assertEquals(ism.getActiveSessions(), 0);
}
/**
* Test session clean 2.
*
* @param ism the ism
* @throws InterruptedException the interrupted exception
*/
@Test(dataProvider = "standardSessionManager")
public void testSessionClean2(StandardSessionManager ism) throws InterruptedException {
// 1个同步,1个异步请求,看是否处理完毕后会被清理掉
{
final WxCpMessageRouter router = new WxCpMessageRouter(null);
router.setSessionManager(ism);
router
.rule().async(false).handler(new WxSessionMessageHandler()).next()
.rule().async(true).handler(new WxSessionMessageHandler()).end();
WxCpXmlMessage msg = new WxCpXmlMessage();
msg.setFromUserName("abc");
router.route(msg);
Thread.sleep(2000);
Assert.assertEquals(ism.getActiveSessions(), 0);
}
{
final WxCpMessageRouter router = new WxCpMessageRouter(null);
router.setSessionManager(ism);
router
.rule().async(true).handler(new WxSessionMessageHandler()).next()
.rule().async(false).handler(new WxSessionMessageHandler()).end();
WxCpXmlMessage msg = new WxCpXmlMessage();
msg.setFromUserName("abc");
router.route(msg);
Thread.sleep(2000);
Assert.assertEquals(ism.getActiveSessions(), 0);
}
}
/**
* Test session clean 3.
*
* @param ism the ism
* @throws InterruptedException the interrupted exception
*/
@Test(dataProvider = "standardSessionManager")
public void testSessionClean3(StandardSessionManager ism) throws InterruptedException {
// 2个异步请求,看是否处理完毕后会被清理掉
final WxCpMessageRouter router = new WxCpMessageRouter(null);
router.setSessionManager(ism);
router
.rule().async(true).handler(new WxSessionMessageHandler()).next()
.rule().async(true).handler(new WxSessionMessageHandler()).end();
WxCpXmlMessage msg = new WxCpXmlMessage();
msg.setFromUserName("abc");
router.route(msg);
Thread.sleep(2000);
Assert.assertEquals(ism.getActiveSessions(), 0);
}
/**
* Test session clean 4.
*
* @param ism the ism
* @throws InterruptedException the interrupted exception
*/
@Test(dataProvider = "standardSessionManager")
public void testSessionClean4(StandardSessionManager ism) throws InterruptedException {
// 一个同步请求,看是否处理完毕后会被清理掉
{
final WxCpMessageRouter router = new WxCpMessageRouter(null);
router.setSessionManager(ism);
router
.rule().async(false).handler(new WxSessionMessageHandler()).end();
WxCpXmlMessage msg = new WxCpXmlMessage();
msg.setFromUserName("abc");
router.route(msg);
Thread.sleep(2000);
Assert.assertEquals(ism.getActiveSessions(), 0);
}
{
final WxCpMessageRouter router = new WxCpMessageRouter(null);
router.setSessionManager(ism);
router
.rule().async(true).handler(new WxSessionMessageHandler()).end();
WxCpXmlMessage msg = new WxCpXmlMessage();
msg.setFromUserName("abc");
router.route(msg);
Thread.sleep(2000);
Assert.assertEquals(ism.getActiveSessions(), 0);
}
}
/**
* The type Wx echo cp message handler.
*/
public static class WxEchoCpMessageHandler implements WxCpMessageHandler {
private final StringBuffer sb;
private final String echoStr;
/**
* Instantiates a new Wx echo cp message handler.
*
* @param sb the sb
* @param echoStr the echo str
*/
public WxEchoCpMessageHandler(StringBuffer sb, String echoStr) {
this.sb = sb;
this.echoStr = echoStr;
}
@Override
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService wxCpService,
WxSessionManager sessionManager) {
this.sb.append(this.echoStr).append(',');
return null;
}
}
/**
* The type Wx session message handler.
*/
public static class WxSessionMessageHandler implements WxCpMessageHandler {
@Override
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService wxCpService,
WxSessionManager sessionManager) {
sessionManager.getSession(wxMessage.getFromUserName());
return null;
}
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpGroupRobotServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpGroupRobotServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.fs.FileUtils;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpGroupRobotService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 微信群机器人消息发送api 单元测试
*
* @author yr created on 2020-08-20
*/
@Slf4j
@Guice(modules = ApiTestModule.class)
public class WxCpGroupRobotServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
private WxCpGroupRobotService robotService;
/**
* Sets .
*/
@BeforeTest
public void setup() {
robotService = wxService.getGroupRobotService();
}
/**
* Test send text.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendText() throws WxErrorException {
robotService.sendText("Hello World", null, null);
}
/**
* Test send mark down.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendMarkDown() throws WxErrorException {
String content = "实时新增用户反馈<font color=\"warning\">132例</font>,请相关同事注意。\n" +
">类型:<font color=\"comment\">用户反馈</font> \n" +
">普通用户反馈:<font color=\"comment\">117例</font> \n" +
">VIP用户反馈:<font color=\"comment\">15例</font>";
robotService.sendMarkdown(content);
}
/**
* Test send mark down v2.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendMarkDownV2() throws WxErrorException {
String content = "# 一、标题\n" +
"## 二级标题\n" +
"### 三级标题\n" +
"# 二、字体\n" +
"*斜体*\n" +
"\n" +
"**加粗**\n" +
"# 三、列表 \n" +
"- 无序列表 1 \n" +
"- 无序列表 2\n" +
" - 无序列表 2.1\n" +
" - 无序列表 2.2\n" +
"1. 有序列表 1\n" +
"2. 有序列表 2\n" +
"# 四、引用\n" +
"> 一级引用\n" +
">>二级引用\n" +
">>>三级引用\n" +
"# 五、链接\n" +
"[这是一个链接](https://work.weixin.qq.com/api/doc)\n" +
"\n" +
"# 六、分割线\n" +
"\n" +
"---\n" +
"# 七、代码\n" +
"`这是行内代码`\n" +
"```\n" +
"这是独立代码块\n" +
"```\n" +
"\n" +
"# 八、表格\n" +
"| 姓名 | 文化衫尺寸 | 收货地址 |\n" +
"| :----- | :----: | -------: |\n" +
"| 张三 | S | 广州 |\n" +
"| 李四 | L | 深圳 |";
robotService.sendMarkdownV2(content);
}
/**
* Test send image.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendImage() throws WxErrorException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("mm.jpeg");
assert inputStream != null;
String base64 = FileUtils.imageToBase64ByStream(inputStream);
String md5 = "1cb2e787063d66e24f5f89e7fc267a4d";
robotService.sendImage(base64, md5);
}
/**
* Test send news.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendNews() throws WxErrorException {
NewArticle article = new NewArticle("图文消息测试", "hello world", "http://www.baidu.com",
"http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png", null, null, null);
robotService.sendNews(Stream.of(article).collect(Collectors.toList()));
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOaCalendarServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOaCalendarServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.calendar.WxCpOaCalendar;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 单元测试.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-09-20
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxCpOaCalendarServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
private final String calId = "wcbBJNCQAARipW967iE8DKPAp5Kb96qQ";
/**
* Test add.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testAdd() throws WxErrorException {
this.wxService.getOaCalendarService().add(WxCpOaCalendar.builder()
.organizer("binary")
.readonly(1)
.setAsDefault(1)
.summary("test_summary")
.color("#FF3030")
.description("test_describe")
.shares(Arrays.asList(new WxCpOaCalendar.ShareInfo("binary", null),
new WxCpOaCalendar.ShareInfo("binary", 1)))
.build());
}
/**
* Test update.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUpdate() throws WxErrorException {
this.wxService.getOaCalendarService().update(WxCpOaCalendar.builder()
.calId(calId)
.organizer("binary")
.readonly(1)
.setAsDefault(1)
.summary("test_summary")
.color("#FF3030")
.description("test_describe")
.shares(Arrays.asList(new WxCpOaCalendar.ShareInfo("binary", null),
new WxCpOaCalendar.ShareInfo("binary", 1)))
.build());
}
/**
* Test get.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGet() throws WxErrorException {
final List<WxCpOaCalendar> calendars = this.wxService.getOaCalendarService().get(Collections.singletonList(calId));
assertThat(calendars).isNotEmpty();
}
/**
* Test delete.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testDelete() throws WxErrorException {
this.wxService.getOaCalendarService().delete(calId);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpCorpGroupServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpCorpGroupServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.gson.JsonObject;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.corpgroup.WxCpCorpGroupCorp;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.List;
import static org.testng.Assert.assertNotNull;
/**
* @author libo
*/
@Guice(modules = ApiTestModule.class)
public class WxCpCorpGroupServiceImplTest {
@Inject
private WxCpService wxService;
@Test
public void testListAppShareInfo() throws WxErrorException {
Integer agentId = wxService.getWxCpConfigStorage().getAgentId();
Integer businessType = 1;
String corpId = null;
Integer limit = null;
String cursor = null;
List<WxCpCorpGroupCorp> resp = wxService.getCorpGroupService().listAppShareInfo(agentId, businessType, corpId, limit, cursor);
assertNotNull(resp);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOaServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOaServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.gson.Gson;
import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.oa.*;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
import java.text.ParseException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 企业微信 OA数据接口 测试用例
*
* @author Element & Wang_Wong
*/
@Slf4j
@Guice(modules = ApiTestModule.class)
public class WxCpOaServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
/**
* The Gson.
*/
@Inject
protected Gson gson;
/**
* Test get checkin data.
*
* @throws ParseException the parse exception
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCheckinData() throws ParseException, WxErrorException {
Date startTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2019-04-11");
Date endTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2019-05-10");
List<WxCpCheckinData> results = wxService.getOaService()
.getCheckinData(1, startTime, endTime, Lists.newArrayList("binary"));
assertThat(results).isNotNull();
System.out.println("results ");
System.out.println(gson.toJson(results));
}
/**
* Test get checkin day data.
*
* @throws ParseException the parse exception
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCheckinDayData() throws ParseException, WxErrorException {
Date startTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2021-06-30");
Date endTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2021-07-31");
List<WxCpCheckinDayData> results = wxService.getOaService()
.getCheckinDayData(startTime, endTime, Lists.newArrayList("12003648"));
assertThat(results).isNotNull();
System.out.println("results ");
System.out.println(gson.toJson(results));
}
/**
* Test get checkin month data.
*
* @throws ParseException the parse exception
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCheckinMonthData() throws ParseException, WxErrorException {
Date startTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2021-07-01");
Date endTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2021-07-31");
List<WxCpCheckinMonthData> results = wxService.getOaService()
.getCheckinMonthData(startTime, endTime, Lists.newArrayList("12003648"));
assertThat(results).isNotNull();
System.out.println("results ");
System.out.println(gson.toJson(results));
}
/**
* Test get checkin schedule data.
*
* @throws ParseException the parse exception
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCheckinScheduleData() throws ParseException, WxErrorException {
Date startTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2021-07-01");
Date endTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2021-07-31");
List<WxCpCheckinSchedule> results = wxService.getOaService()
.getCheckinScheduleList(startTime, endTime, Lists.newArrayList("12003648"));
assertThat(results).isNotNull();
System.out.println("results ");
System.out.println(gson.toJson(results));
}
/**
* Test set checkin schedule list.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSetCheckinScheduleList() throws WxErrorException {
WxCpSetCheckinSchedule wxCpSetCheckinSchedule = new WxCpSetCheckinSchedule();
wxCpSetCheckinSchedule.setGroupId(3);
wxCpSetCheckinSchedule.setYearmonth(202108);
WxCpSetCheckinSchedule.Item item = new WxCpSetCheckinSchedule.Item();
item.setScheduleId(0);
item.setDay(20);
item.setUserid("12003648");
wxCpSetCheckinSchedule.setItems(Collections.singletonList(item));
wxService.getOaService().setCheckinScheduleList(wxCpSetCheckinSchedule);
}
/**
* Test get checkin option.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCheckinOption() throws WxErrorException {
Date now = new Date();
List<WxCpCheckinOption> results = wxService.getOaService().getCheckinOption(now, Lists.newArrayList("binary"));
assertThat(results).isNotNull();
System.out.println("results ");
System.out.println(gson.toJson(results));
}
/**
* Test get crop checkin option.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCropCheckinOption() throws WxErrorException {
List<WxCpCropCheckinOption> results = wxService.getOaService().getCropCheckinOption();
assertThat(results).isNotNull();
System.out.println("results ");
System.out.println(gson.toJson(results));
}
/**
* Test new ot_info_v2 structure deserialization.
*/
@Test
public void testOtInfoV2Deserialization() {
// Test JSON with ot_info_v2 structure based on the new API response format
String jsonWithOtInfoV2 = "{\n" +
" \"groupid\": 1,\n" +
" \"groupname\": \"test group\",\n" +
" \"grouptype\": 0,\n" +
" \"ot_info_v2\": {\n" +
" \"workdayconf\": {\n" +
" \"allow_ot\": true,\n" +
" \"type\": 1\n" +
" },\n" +
" \"restdayconf\": {\n" +
" \"allow_ot\": false,\n" +
" \"type\": 0\n" +
" },\n" +
" \"holidayconf\": {\n" +
" \"allow_ot\": true,\n" +
" \"type\": 2\n" +
" }\n" +
" }\n" +
"}";
WxCpCropCheckinOption option = WxCpGsonBuilder.create().fromJson(jsonWithOtInfoV2, WxCpCropCheckinOption.class);
assertThat(option).isNotNull();
assertThat(option.getOtInfoV2()).isNotNull();
assertThat(option.getOtInfoV2().getWorkdayConf()).isNotNull();
assertThat(option.getOtInfoV2().getWorkdayConf().getAllowOt()).isTrue();
assertThat(option.getOtInfoV2().getWorkdayConf().getType()).isEqualTo(1);
assertThat(option.getOtInfoV2().getRestdayConf()).isNotNull();
assertThat(option.getOtInfoV2().getRestdayConf().getAllowOt()).isFalse();
assertThat(option.getOtInfoV2().getHolidayConf().getAllowOt()).isTrue();
System.out.println("Parsed ot_info_v2 structure:");
System.out.println(gson.toJson(option.getOtInfoV2()));
}
/**
* Test late_rule field deserialization in getCropCheckinOption response.
*/
@Test
public void testLateRuleDeserialization() {
// Test JSON with late_rule structure based on the issue #3323
String jsonWithLateRule = "{\n" +
" \"grouptype\": 1,\n" +
" \"groupid\": 1,\n" +
" \"checkindate\": [\n" +
" {\n" +
" \"workdays\": [1, 2, 3, 4, 5],\n" +
" \"checkintime\": [\n" +
" {\n" +
" \"time_id\": 1,\n" +
" \"work_sec\": 32400,\n" +
" \"off_work_sec\": 64800,\n" +
" \"remind_work_sec\": 31800,\n" +
" \"remind_off_work_sec\": 64800,\n" +
" \"rest_begin_time\": 43200,\n" +
" \"rest_end_time\": 48600,\n" +
" \"allow_rest\": true,\n" +
" \"earliest_work_sec\": 21600,\n" +
" \"latest_work_sec\": 64740,\n" +
" \"earliest_off_work_sec\": 32460,\n" +
" \"latest_off_work_sec\": 107940,\n" +
" \"no_need_checkon\": false,\n" +
" \"no_need_checkoff\": false\n" +
" }\n" +
" ],\n" +
" \"noneed_offwork\": false,\n" +
" \"limit_aheadtime\": 0,\n" +
" \"flex_on_duty_time\": 0,\n" +
" \"flex_off_duty_time\": 0,\n" +
" \"allow_flex\": false,\n" +
" \"late_rule\": {\n" +
" \"offwork_after_time\": 3600,\n" +
" \"onwork_flex_time\": 3600,\n" +
" \"allow_offwork_after_time\": true,\n" +
" \"timerules\": [\n" +
" {\n" +
" \"offwork_after_time\": 18000,\n" +
" \"onwork_flex_time\": 3600\n" +
" },\n" +
" {\n" +
" \"offwork_after_time\": 21600,\n" +
" \"onwork_flex_time\": 7200\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"max_allow_arrive_early\": 0,\n" +
" \"max_allow_arrive_late\": 0\n" +
" }\n" +
" ],\n" +
" \"groupname\": \"打卡\",\n" +
" \"need_photo\": false\n" +
"}";
WxCpCropCheckinOption option = WxCpGsonBuilder.create().fromJson(jsonWithLateRule, WxCpCropCheckinOption.class);
assertThat(option).isNotNull();
assertThat(option.getCheckinDate()).isNotNull();
assertThat(option.getCheckinDate().size()).isEqualTo(1);
WxCpCheckinGroupBase.CheckinDate checkinDate = option.getCheckinDate().get(0);
assertThat(checkinDate).isNotNull();
assertThat(checkinDate.getAllowFlex()).isFalse();
assertThat(checkinDate.getMaxAllowArriveEarly()).isEqualTo(0);
assertThat(checkinDate.getMaxAllowArriveLate()).isEqualTo(0);
// Test late_rule field
assertThat(checkinDate.getLateRule()).isNotNull();
assertThat(checkinDate.getLateRule().getOffWorkAfterTime()).isEqualTo(3600);
assertThat(checkinDate.getLateRule().getOnWorkFlexTime()).isEqualTo(3600);
assertThat(checkinDate.getLateRule().getAllowOffWorkAfterTime()).isTrue();
assertThat(checkinDate.getLateRule().getTimerules()).isNotNull();
assertThat(checkinDate.getLateRule().getTimerules().size()).isEqualTo(2);
// Test timerules
WxCpCheckinGroupBase.TimeRule firstRule = checkinDate.getLateRule().getTimerules().get(0);
assertThat(firstRule.getOffWorkAfterTime()).isEqualTo(18000);
assertThat(firstRule.getOnWorkFlexTime()).isEqualTo(3600);
// Test CheckinTime fields
assertThat(checkinDate.getCheckinTime()).isNotNull();
assertThat(checkinDate.getCheckinTime().size()).isEqualTo(1);
WxCpCheckinGroupBase.CheckinTime checkinTime = checkinDate.getCheckinTime().get(0);
assertThat(checkinTime.getTimeId()).isEqualTo(1);
assertThat(checkinTime.getRestBeginTime()).isEqualTo(43200);
assertThat(checkinTime.getRestEndTime()).isEqualTo(48600);
assertThat(checkinTime.getAllowRest()).isTrue();
assertThat(checkinTime.getEarliestWorkSec()).isEqualTo(21600);
assertThat(checkinTime.getLatestWorkSec()).isEqualTo(64740);
assertThat(checkinTime.getEarliestOffWorkSec()).isEqualTo(32460);
assertThat(checkinTime.getLatestOffWorkSec()).isEqualTo(107940);
assertThat(checkinTime.getNoNeedCheckon()).isFalse();
assertThat(checkinTime.getNoNeedCheckoff()).isFalse();
System.out.println("Successfully parsed late_rule and new checkintime fields:");
System.out.println(gson.toJson(option));
}
/**
* Test issue #3323 - full JSON from the issue report.
*/
@Test
public void testIssue3323FullJson() {
// Full JSON from issue #3323
String issueJson = "{\n" +
" \"grouptype\": 1,\n" +
" \"groupid\": 1,\n" +
" \"checkindate\": [\n" +
" {\n" +
" \"workdays\": [\n" +
" 1,\n" +
" 2,\n" +
" 3,\n" +
" 4,\n" +
" 5\n" +
" ],\n" +
" \"checkintime\": [\n" +
" {\n" +
" \"time_id\": 1,\n" +
" \"work_sec\": 32400,\n" +
" \"off_work_sec\": 64800,\n" +
" \"remind_work_sec\": 31800,\n" +
" \"remind_off_work_sec\": 64800,\n" +
" \"rest_begin_time\": 43200,\n" +
" \"rest_end_time\": 48600,\n" +
" \"allow_rest\": true,\n" +
" \"earliest_work_sec\": 21600,\n" +
" \"latest_work_sec\": 64740,\n" +
" \"earliest_off_work_sec\": 32460,\n" +
" \"latest_off_work_sec\": 107940,\n" +
" \"no_need_checkon\": false,\n" +
" \"no_need_checkoff\": false\n" +
" }\n" +
" ],\n" +
" \"noneed_offwork\": false,\n" +
" \"limit_aheadtime\": 0,\n" +
" \"flex_on_duty_time\": 0,\n" +
" \"flex_off_duty_time\": 0,\n" +
" \"allow_flex\": false,\n" +
" \"late_rule\": {\n" +
" \"offwork_after_time\": 3600,\n" +
" \"onwork_flex_time\": 3600,\n" +
" \"allow_offwork_after_time\": true,\n" +
" \"timerules\": [\n" +
" {\n" +
" \"offwork_after_time\": 18000,\n" +
" \"onwork_flex_time\": 3600\n" +
" },\n" +
" {\n" +
" \"offwork_after_time\": 21600,\n" +
" \"onwork_flex_time\": 7200\n" +
" },\n" +
" {\n" +
" \"offwork_after_time\": 28800,\n" +
" \"onwork_flex_time\": 10800\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"max_allow_arrive_early\": 0,\n" +
" \"max_allow_arrive_late\": 0\n" +
" }\n" +
" ],\n" +
" \"spe_workdays\": [],\n" +
" \"spe_offdays\": [],\n" +
" \"sync_holidays\": true,\n" +
" \"groupname\": \"打卡\",\n" +
" \"need_photo\": false,\n" +
" \"wifimac_infos\": [],\n" +
" \"note_can_use_local_pic\": true,\n" +
" \"allow_checkin_offworkday\": false,\n" +
" \"allow_apply_offworkday\": false,\n" +
" \"loc_infos\": []\n" +
" }";
WxCpCropCheckinOption option = WxCpGsonBuilder.create().fromJson(issueJson, WxCpCropCheckinOption.class);
assertThat(option).isNotNull();
assertThat(option.getGroupId()).isEqualTo(1);
assertThat(option.getGroupName()).isEqualTo("打卡");
assertThat(option.getCheckinDate()).isNotNull();
assertThat(option.getCheckinDate().size()).isEqualTo(1);
WxCpCheckinGroupBase.CheckinDate checkinDate = option.getCheckinDate().get(0);
assertThat(checkinDate.getLateRule()).isNotNull();
assertThat(checkinDate.getLateRule().getOffWorkAfterTime()).isEqualTo(3600);
assertThat(checkinDate.getLateRule().getOnWorkFlexTime()).isEqualTo(3600);
assertThat(checkinDate.getLateRule().getAllowOffWorkAfterTime()).isTrue();
assertThat(checkinDate.getLateRule().getTimerules()).isNotNull();
assertThat(checkinDate.getLateRule().getTimerules().size()).isEqualTo(3);
System.out.println("✓ Successfully parsed full JSON from issue #3323");
System.out.println("✓ Late Rule offwork_after_time: " + checkinDate.getLateRule().getOffWorkAfterTime());
System.out.println("✓ Late Rule onwork_flex_time: " + checkinDate.getLateRule().getOnWorkFlexTime());
System.out.println("✓ Late Rule allow_offwork_after_time: " + checkinDate.getLateRule().getAllowOffWorkAfterTime());
System.out.println("✓ Late Rule timerules count: " + checkinDate.getLateRule().getTimerules().size());
}
/**
* Test get approval info.
*
* @throws WxErrorException the wx error exception
* @throws ParseException the parse exception
*/
@Test
public void testGetApprovalInfo() throws WxErrorException, ParseException {
Date startTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2019-12-01");
Date endTime = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse("2019-12-31");
WxCpApprovalInfo result = wxService.getOaService().getApprovalInfo(startTime, endTime);
assertThat(result).isNotNull();
System.out.println("result ");
System.out.println(gson.toJson(result));
}
/**
* Test get approval detail.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetApprovalDetail() throws WxErrorException {
String spNo = "201912020001";
WxCpApprovalDetailResult result = wxService.getOaService().getApprovalDetail(spNo);
assertThat(result).isNotNull();
System.out.println("result ");
System.out.println(gson.toJson(result));
}
/**
* Test get template detail.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetTemplateDetail() throws WxErrorException {
String json = "{\"errcode\":0,\"errmsg\":\"ok\",\"template_names\":[{\"text\":\"销售用章申请-CIC测试\",\"lang\":\"zh_CN\"}],\"template_content\":{\"controls\":[{\"property\":{\"control\":\"Text\",\"id\":\"Text-1642064119106\",\"title\":[{\"text\":\"甲方全称\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请输入\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1}},{\"property\":{\"control\":\"Selector\",\"id\":\"Selector-1641521155746\",\"title\":[{\"text\":\"用章公司\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请选择\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"selector\":{\"type\":\"single\",\"options\":[{\"key\":\"option-1641521155746\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1703845381898\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1643277806277\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1641521181119\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1641521191559\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1641521216515\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1650417735718\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1652756795298\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1664422448363\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1673487035814\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1675128722320\",\"value\":[{\"text\":\"事务所\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1678071926146\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1678071927225\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1703845339862\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1703845330660\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1684459670059\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1698111016115\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1705559650950\",\"value\":[{\"text\":\"有限公司\",\"lang\":\"zh_CN\"}]}],\"op_relations\":[]}}},{\"property\":{\"control\":\"Text\",\"id\":\"Text-1641521297125\",\"title\":[{\"text\":\"渠道来源\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请输入\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1}},{\"property\":{\"control\":\"Selector\",\"id\":\"Selector-1641521316173\",\"title\":[{\"text\":\"印章类型\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请选择\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"selector\":{\"type\":\"single\",\"options\":[{\"key\":\"option-1641521316173\",\"value\":[{\"text\":\"公章\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1641521316174\",\"value\":[{\"text\":\"业务章\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1641521339762\",\"value\":[{\"text\":\"法人章\",\"lang\":\"zh_CN\"}]}],\"op_relations\":[]}}},{\"property\":{\"control\":\"Selector\",\"id\":\"Selector-1641521355432\",\"title\":[{\"text\":\"是否外带\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请选择\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"selector\":{\"type\":\"single\",\"options\":[{\"key\":\"option-1641521355432\",\"value\":[{\"text\":\"否\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1641521355433\",\"value\":[{\"text\":\"是\",\"lang\":\"zh_CN\"}]}],\"op_relations\":[]}}},{\"property\":{\"control\":\"Selector\",\"id\":\"Selector-1648619603087\",\"title\":[{\"text\":\"盖章形式\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请选择\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"selector\":{\"type\":\"single\",\"options\":[{\"key\":\"option-1648619603087\",\"value\":[{\"text\":\"电子合同章\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1648619603088\",\"value\":[{\"text\":\"纸质合同章\",\"lang\":\"zh_CN\"}]}],\"op_relations\":[]}}},{\"property\":{\"control\":\"Textarea\",\"id\":\"Textarea-1641521378351\",\"title\":[{\"text\":\"用印事由\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请输入\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1}},{\"property\":{\"control\":\"Date\",\"id\":\"Date-1641521411373\",\"title\":[{\"text\":\"借用时间\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请选择\",\"lang\":\"zh_CN\"}],\"require\":0,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"date\":{\"type\":\"hour\"}}},{\"property\":{\"control\":\"Date\",\"id\":\"Date-1641521421730\",\"title\":[{\"text\":\"归还时间\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请选择\",\"lang\":\"zh_CN\"}],\"require\":0,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"date\":{\"type\":\"hour\"}}},{\"property\":{\"control\":\"Selector\",\"id\":\"Selector-1641521441251\",\"title\":[{\"text\":\"文件类型\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请选择\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"selector\":{\"type\":\"single\",\"options\":[{\"key\":\"option-1641521441251\",\"value\":[{\"text\":\"业务合同\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1643278221491\",\"value\":[{\"text\":\"人事行政类文件\",\"lang\":\"zh_CN\"}]},{\"key\":\"option-1641521534238\",\"value\":[{\"text\":\"经纪人、商事服务合作合同\",\"lang\":\"zh_CN\"}]}],\"op_relations\":[]}}},{\"property\":{\"control\":\"Text\",\"id\":\"Text-1641521571559\",\"title\":[{\"text\":\"文件名称\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请输入\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1}},{\"property\":{\"control\":\"Text\",\"id\":\"Text-1641521587698\",\"title\":[{\"text\":\"文件份数\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请输入整数\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1}},{\"property\":{\"control\":\"Date\",\"id\":\"Date-1641521607834\",\"title\":[{\"text\":\"用印日期\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"请选择\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"date\":{\"type\":\"day\"}}},{\"property\":{\"control\":\"File\",\"id\":\"File-1641521617014\",\"title\":[{\"text\":\"附件\",\"lang\":\"zh_CN\"}],\"placeholder\":[{\"text\":\"一定要上传所盖章原件,以附件内容为主\",\"lang\":\"zh_CN\"}],\"require\":1,\"un_print\":0,\"inner_id\":\"\",\"un_replace\":0,\"display\":1},\"config\":{\"file\":{\"is_only_photo\":0}}}]}}";
WxCpOaApprovalTemplateResult oaApprovalTemplateResult = WxCpOaApprovalTemplateResult.fromJson(json);
System.out.println("模板信息:" + oaApprovalTemplateResult.toJson());
String templateId = "3TkZjxugodbqpEMk9j7X6h6zKqYkc7MxQrrFmT7H";
WxCpOaApprovalTemplateResult result = wxService.getOaService().getTemplateDetail(templateId);
assertThat(result).isNotNull();
System.out.println("result ");
System.out.println(gson.toJson(result));
}
/**
* Test apply.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testApply() throws WxErrorException {
this.wxService.getOaService().apply(new WxCpOaApplyEventRequest().setCreatorUserId("123"));
}
/**
* 获取审批数据(旧)
* https://developer.work.weixin.qq.com/document/path/91530
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetApprovalData() throws WxErrorException {
// 提示:推荐使用新接口“批量获取审批单号”及“获取审批申请详情”,此接口后续将不再维护、逐步下线。
// WxCpGetApprovalData approvalData = this.wxService.getOaService().getApprovalData(System.currentTimeMillis(),
// System.currentTimeMillis() + 3600L, null);
// log.info("返回数据:{}", approvalData.toJson());
String text = "{\"errcode\":0,\"errmsg\":\"ok\",\"count\":3,\"total\":5,\"next_spnum\":201704240001," +
"\"data\":[{\"spname\":\"报销\",\"apply_name\":\"报销测试\",\"apply_org\":\"报销测试企业\",\"approval_name\":[\"审批人测试\"]," +
"\"notify_name\":[\"抄送人测试\"],\"sp_status\":1,\"sp_num\":201704200001," +
"\"mediaids\":[\"WWCISP_G8PYgRaOVHjXWUWFqchpBqqqUpGj0OyR9z6WTwhnMZGCPHxyviVstiv_2fTG8YOJq8L8zJT2T2OvTebANV-2MQ" +
"\"],\"apply_time\":1499153693,\"apply_user_id\":\"testuser\",\"expense\":{\"expense_type\":1,\"reason\":\"\"," +
"\"item\":[{\"expenseitem_type\":6,\"time\":1492617600,\"sums\":9900,\"reason\":\"\"}]}," +
"\"comm\":{\"apply_data\":\"{\\\"item-1492610773696\\\":{\\\"title\\\":\\\"abc\\\",\\\"type\\\":\\\"text\\\"," +
"\\\"value\\\":\\\"\\\"}}\"}},{\"spname\":\"请假\",\"apply_name\":\"请假测试\",\"apply_org\":\"请假测试企业\"," +
"\"approval_name\":[\"审批人测试\"],\"notify_name\":[\"抄送人测试\"],\"sp_status\":1,\"sp_num\":201704200004," +
"\"apply_time\":1499153693,\"apply_user_id\":\"testuser\",\"leave\":{\"timeunit\":0,\"leave_type\":4," +
"\"start_time\":1492099200,\"end_time\":1492790400,\"duration\":144,\"reason\":\"\"}," +
"\"comm\":{\"apply_data\":\"{\\\"item-1492610773696\\\":{\\\"title\\\":\\\"abc\\\",\\\"type\\\":\\\"text\\\"," +
"\\\"value\\\":\\\"\\\"}}\"}},{\"spname\":\"自定义审批\",\"apply_name\":\"自定义\",\"apply_org\":\"自定义测试企业\"," +
"\"approval_name\":[\"自定义审批人\"],\"notify_name\":[\"自定义抄送人\"],\"sp_status\":1,\"sp_num\":201704240001," +
"\"apply_time\":1499153693,\"apply_user_id\":\"testuser\"," +
"\"comm\":{\"apply_data\":\"{\\\"item-1492610773696\\\":{\\\"title\\\":\\\"abc\\\",\\\"type\\\":\\\"text\\\"," +
"\\\"value\\\":\\\"\\\"}}\"}}]}";
WxCpGetApprovalData wxCpGetApprovalData = WxCpGetApprovalData.fromJson(text);
log.info("返回数据2:{}", wxCpGetApprovalData.toJson());
}
/**
* Test get dial record.
*/
@Test
public void testGetDialRecord() {
}
/**
* 获取企业假期管理配置
* https://developer.work.weixin.qq.com/document/path/93375
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCorpConf() throws WxErrorException {
WxCpCorpConfInfo corpConf = this.wxService.getOaService().getCorpConf();
log.info(corpConf.toJson());
}
/**
* 获取成员假期余额
* https://developer.work.weixin.qq.com/document/path/93376
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetUserVacationQuota() throws WxErrorException {
WxCpUserVacationQuota vacationQuota = this.wxService.getOaService().getUserVacationQuota("WangKai");
log.info(vacationQuota.toJson());
String text =
"{\"errcode\":0,\"errmsg\":\"ok\",\"lists\":[{\"id\":1,\"assignduration\":0,\"usedduration\":0," +
"\"leftduration\":604800,\"vacationname\":\"年假\"},{\"id\":2,\"assignduration\":0,\"usedduration\":0," +
"\"leftduration\":1296000,\"vacationname\":\"事假\"},{\"id\":3,\"assignduration\":0,\"usedduration\":0," +
"\"leftduration\":0,\"vacationname\":\"病假\"}]}";
WxCpUserVacationQuota json = WxCpUserVacationQuota.fromJson(text);
log.info("数据为:{}", json.toJson());
}
/**
* 修改成员假期余额
* https://developer.work.weixin.qq.com/document/path/93377
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSetOneUserQuota() throws WxErrorException {
String text = "{\"errcode\":0,\"errmsg\":\"ok\"}";
WxCpBaseResp resp = WxCpBaseResp.fromJson(text);
log.info("返回结果为:{}", resp.toJson());
// WxCpBaseResp wxCpBaseResp = this.wxService.getOaService().setOneUserQuota(, , , , );
}
/**
* 创建审批模板
* https://developer.work.weixin.qq.com/document/path/97437
*/
@Test
public void testCreateOaApprovalTemplate() {
//TODO
String json = "{\n" +
" \"template_name\": [{\n" +
" \"text\": \"我的api测试模版\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }],\n" +
" \"template_content\": {\n" +
" \"controls\": [{\n" +
" \"property\": {\n" +
" \"control\": \"Selector\",\n" +
" \"id\": \"Selector-01\",\n" +
" \"title\": [{\n" +
" \"text\": \"控件名称\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }],\n" +
" \"placeholder\": [{\n" +
" \"text\": \"控件说明\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }],\n" +
" \"require\": 0,\n" +
" \"un_print\": 1\n" +
" },\n" +
" \"config\":{\n" +
" \"selector\": {\n" +
" \"type\": \"multi\",\n" +
" \"options\": [\n" +
" {\n" +
" \"key\": \"option-1\", \n" +
" \"value\":{\n" +
" \"text\":\"选项1\",\n" +
" \"lang\":\"zh_CN\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"key\": \"option-2\",\n" +
" \"value\":{\n" +
" \"text\":\"选项2\",\n" +
" \"lang\":\"zh_CN\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }]\n" +
" }\n" +
"}";
WxCpOaApprovalTemplate createTemplate = WxCpOaApprovalTemplate.fromJson(json);
System.out.println("create_template数据为:" + createTemplate.toJson());
}
@Test
public void testUpdateOaApprovalTemplate() {
//TODO
}
@Test
public void testGetCheckinScheduleList() {
//TODO
}
@Test
public void testAddCheckInUserFace() {
//TODO
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpMessageServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpMessageServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.github.dreamhead.moco.HttpServer;
import com.github.dreamhead.moco.Runner;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpLinkedCorpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendStatistics;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import static com.github.dreamhead.moco.Moco.file;
import static com.github.dreamhead.moco.MocoJsonRunner.jsonHttpServer;
import static me.chanjar.weixin.cp.api.ApiTestModuleWithMockServer.mockServerPort;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertNotNull;
/**
* 测试类.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-08-30
*/
@Test
//@Guice(modules = ApiTestModuleWithMockServer.class)
@Guice(modules = ApiTestModule.class)
public class WxCpMessageServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
private Runner mockRunner;
private ApiTestModule.WxXmlCpInMemoryConfigStorage configStorage;
private WxCpMessageSendResult wxCpMessageSendResult;
/**
* Sets .
*/
@BeforeTest
public void setup() {
HttpServer mockServer = jsonHttpServer(mockServerPort, file("src/test/resources/moco/message.json"));
this.mockRunner = Runner.runner(mockServer);
this.mockRunner.start();
this.configStorage = (ApiTestModule.WxXmlCpInMemoryConfigStorage) this.wxService.getWxCpConfigStorage();
}
/**
* Stop mock server.
*/
@AfterTest
public void stopMockServer() {
this.mockRunner.stop();
}
/**
* Test send message.
*
* @throws WxErrorException the wx error exception
*/
public void testSendMessage() throws WxErrorException {
WxCpMessage message = new WxCpMessage();
// message.setAgentId(configStorage.getAgentId());
message.setMsgType(WxConsts.KefuMsgType.TEXT);
message.setToUser(configStorage.getUserId());
message.setContent("欢迎欢迎,热烈欢迎\n换行测试\n超链接:<a href=\"http://www.baidu.com\">Hello World</a>");
WxCpMessageSendResult messageSendResult = this.wxService.getMessageService().send(message);
assertNotNull(messageSendResult);
System.out.println(messageSendResult);
System.out.println(messageSendResult.getInvalidPartyList());
System.out.println(messageSendResult.getInvalidUserList());
System.out.println(messageSendResult.getInvalidTagList());
System.out.println(messageSendResult.getUnlicensedUserList());
}
/**
* Test send message 1.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendMessage1() throws WxErrorException {
WxCpMessage message = WxCpMessage
.TEXT()
// .agentId(configStorage.getAgentId())
.toUser(configStorage.getUserId())
.content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:<a href=\"http://www.baidu.com\">Hello World</a>")
.build();
WxCpMessageSendResult messageSendResult = this.wxService.getMessageService().send(message);
assertNotNull(messageSendResult);
wxCpMessageSendResult = messageSendResult;
System.out.println(messageSendResult);
System.out.println(messageSendResult.getInvalidPartyList());
System.out.println(messageSendResult.getInvalidUserList());
System.out.println(messageSendResult.getInvalidTagList());
}
/**
* Test send message markdown.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendMessage_markdown() throws WxErrorException {
WxCpMessage message = WxCpMessage
.MARKDOWN()
.toUser(configStorage.getUserId())
.content("您的会议室已经预定,稍后会同步到`邮箱` \n" +
" >**事项详情** \n" +
" >事 项:<font color=\\\"info\\\">开会</font> \n" +
" >组织者:@miglioguan \n" +
" >参与者:@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang \n" +
" > \n" +
" >会议室:<font color=\\\"info\\\">广州TIT 1楼 301</font> \n" +
" >日 期:<font color=\\\"warning\\\">2018年5月18日</font> \n" +
" >时 间:<font color=\\\"comment\\\">上午9:00-11:00</font> \n" +
" > \n" +
" >请准时参加会议。 \n" +
" > \n" +
" >如需修改会议信息,请点击:[修改会议信息](https://work.weixin.qq.com)")
.build();
WxCpMessageSendResult messageSendResult = this.wxService.getMessageService().send(message);
assertNotNull(messageSendResult);
System.out.println(messageSendResult);
System.out.println(messageSendResult.getInvalidPartyList());
System.out.println(messageSendResult.getInvalidUserList());
System.out.println(messageSendResult.getInvalidTagList());
}
/**
* Test send message text card.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendMessage_textCard() throws WxErrorException {
WxCpMessage message = WxCpMessage
.TEXTCARD()
.toUser(configStorage.getUserId())
.btnTxt("更多")
.description("<div class=\"gray\">2016年9月26日</div> <div class=\"normal\">恭喜你抽中iPhone 7一台,领奖码:xxxx</div><div " +
"class=\"highlight\">请于2016年10月10日前联系行政同事领取</div>")
.url("URL")
.title("领奖通知")
.build();
WxCpMessageSendResult messageSendResult = this.wxService.getMessageService().send(message);
assertNotNull(messageSendResult);
System.out.println(messageSendResult);
System.out.println(messageSendResult.getInvalidPartyList());
System.out.println(messageSendResult.getInvalidUserList());
System.out.println(messageSendResult.getInvalidTagList());
}
/**
* Test send message mini program notice.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendMessage_miniProgram_notice() throws WxErrorException {
WxCpMessage message = WxCpMessage
.newMiniProgramNoticeBuilder()
.toUser(configStorage.getUserId())
.appId("wx123123123123123")
.page("pages/index?userid=zhangsan&orderid=123123123")
.title("会议室预订成功通知")
.description("4月27日 16:16")
.emphasisFirstItem(true)
.contentItems(ImmutableMap.of("会议室", "402",
"会议地点", "广州TIT-402会议室",
"会议时间", "2018年8月1日 09:00-09:30"))
.build();
WxCpMessageSendResult messageSendResult = this.wxService.getMessageService().send(message);
assertNotNull(messageSendResult);
System.out.println(messageSendResult);
System.out.println(messageSendResult.getInvalidPartyList());
System.out.println(messageSendResult.getInvalidUserList());
System.out.println(messageSendResult.getInvalidTagList());
}
/**
* Test send linked corp message.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendLinkedCorpMessage() throws WxErrorException {
this.wxService.getMessageService().sendLinkedCorpMessage(WxCpLinkedCorpMessage.builder()
.msgType(WxConsts.KefuMsgType.TEXT)
.toUsers(new String[]{configStorage.getUserId()})
.content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:<a href=\"http://www.baidu.com\">Hello World</a>")
.build());
}
/**
* Test send.
*/
@Test
public void testSend() {
// see other test methods
}
/**
* Test get statistics.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetStatistics() throws WxErrorException {
final WxCpMessageSendStatistics statistics = this.wxService.getMessageService().getStatistics(1);
assertNotNull(statistics);
assertThat(statistics.getStatistics()).isNotNull();
}
/**
* Test message recall
* @throws WxErrorException
*/
@Test(dependsOnMethods = "testSendMessage1")
public void testRecall() throws WxErrorException {
this.wxService.getMessageService().recall(wxCpMessageSendResult.getMsgId());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOAuth2ServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOAuth2ServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.WxCpUserDetail;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <pre>
* Created by BinaryWang on 2018/4/22.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Guice(modules = ApiTestModule.class)
public class WxCpOAuth2ServiceImplTest {
@Inject
private WxCpService wxService;
/**
* Test get user detail.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetUserDetail() throws WxErrorException {
WxCpUserDetail userDetail = this.wxService.getOauth2Service().getUserDetail("b");
System.out.println(userDetail);
}
/**
* Test get user info.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetUserInfo() throws WxErrorException {
final WxCpOauth2UserInfo result = this.wxService.getOauth2Service().getUserInfo("abc");
assertThat(result).isNotNull();
System.out.println(result);
}
/**
* Test build authorization url.
*/
@Test
public void testBuildAuthorizationUrl() {
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpUserServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpUserServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.Gender;
import me.chanjar.weixin.cp.bean.WxCpInviteResult;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.user.WxCpDeptUserResult;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
/**
* <pre>
* Created by BinaryWang on 2017/6/24.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Slf4j
@Guice(modules = ApiTestModule.class)
public class WxCpUserServiceImplTest {
@Inject
private WxCpService wxCpService;
private final String userId = "someone" + System.currentTimeMillis();
/**
* Test authenticate.
*
* @throws Exception the exception
*/
@Test
public void testAuthenticate() throws Exception {
this.wxCpService.getUserService().authenticate("abc");
}
/**
* Test create.
*
* @throws Exception the exception
*/
@Test
public void testCreate() throws Exception {
WxCpUser user = new WxCpUser();
user.setUserId(userId);
user.setName("Some Woman");
user.setDepartIds(new Long[]{2L});
user.setEmail("none@none.com");
user.setGender(Gender.FEMALE);
user.setMobile("13560084979");
user.setPosition("woman");
user.setTelephone("3300393");
user.addExtAttr("爱好", "table");
this.wxCpService.getUserService().create(user);
}
/**
* Test update.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = "testCreate")
public void testUpdate() throws Exception {
WxCpUser user = new WxCpUser();
user.setUserId(userId);
user.setName("Some Woman");
user.addExtAttr("爱好", "table2");
this.wxCpService.getUserService().update(user);
}
/**
* Test delete.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = {"testCreate", "testUpdate"})
public void testDelete() throws Exception {
this.wxCpService.getUserService().delete(userId);
}
/**
* Test get by id.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = "testUpdate")
public void testGetById() throws Exception {
WxCpUser user = this.wxCpService.getUserService().getById(userId);
assertNotNull(user);
}
/**
* Test list by department.
*
* @throws Exception the exception
*/
@Test
public void testListByDepartment() throws Exception {
List<WxCpUser> users = this.wxCpService.getUserService().listByDepartment(2L, true, 0);
assertNotEquals(users.size(), 0);
for (WxCpUser user : users) {
System.out.println(ToStringBuilder.reflectionToString(user, ToStringStyle.MULTI_LINE_STYLE));
}
}
/**
* Test list simple by department.
*
* @throws Exception the exception
*/
@Test
public void testListSimpleByDepartment() throws Exception {
List<WxCpUser> users = this.wxCpService.getUserService().listSimpleByDepartment(1L, true, 0);
assertNotEquals(users.size(), 0);
for (WxCpUser user : users) {
System.out.println(ToStringBuilder.reflectionToString(user, ToStringStyle.MULTI_LINE_STYLE));
}
}
/**
* Test invite.
*
* @throws Exception the exception
*/
@Test
public void testInvite() throws Exception {
WxCpInviteResult result = this.wxCpService.getUserService().invite(
Lists.newArrayList(userId), null, null);
System.out.println(result);
}
/**
* Test user id 2 openid.
*
* @throws Exception the exception
*/
@Test
public void testUserId2Openid() throws Exception {
Map<String, String> result = this.wxCpService.getUserService().userId2Openid(userId, null);
System.out.println(result);
assertNotNull(result);
}
/**
* Test openid 2 user id.
*
* @throws Exception the exception
*/
@Test
public void testOpenid2UserId() throws Exception {
String result = this.wxCpService.getUserService().openid2UserId(userId);
System.out.println(result);
assertNotNull(result);
}
/**
* Test get user id.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetUserId() throws WxErrorException {
String result = this.wxCpService.getUserService().getUserId("xxx");
System.out.println(result);
assertNotNull(result);
}
/**
* Test get user id by email.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetUserIdByEmail() throws WxErrorException {
String result = this.wxCpService.getUserService().getUserIdByEmail("xxx",1);
System.out.println(result);
assertNotNull(result);
}
/**
* Test get external contact.
*/
@Test
public void testGetExternalContact() {
}
/**
* Test get active stat.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetActiveStat() throws WxErrorException {
Integer activeStat = this.wxCpService.getUserService().getActiveStat(new Date());
System.out.printf("active stat: %d", activeStat);
assertNotNull(activeStat);
}
/**
* 获取成员ID列表
* 获取企业成员的userid与对应的部门ID列表,预计于2022年8月8号发布。若需要获取其他字段,参见「适配建议」。
* <p>
* https://developer.work.weixin.qq.com/document/40856
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetUserListId() throws WxErrorException {
WxCpDeptUserResult result = this.wxCpService.getUserService().getUserListId(null, 10);
log.info("返回结果为:{}", result.toJson());
assertNotNull(result);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpTagServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpTagServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.common.base.Splitter;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpTagService;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.WxCpTagAddOrRemoveUsersResult;
import me.chanjar.weixin.cp.bean.WxCpTagGetResult;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.constant.WxCpApiPathConsts;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
/**
* <pre>
* Created by Binary Wang on 2017-6-25.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Guice(modules = ApiTestModule.class)
public class WxCpTagServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
/**
* The Config storage.
*/
@Inject
protected ApiTestModule.WxXmlCpInMemoryConfigStorage configStorage;
private String tagId;
/**
* Test create.
*
* @throws Exception the exception
*/
@Test
public void testCreate() throws Exception {
this.tagId = this.wxService.getTagService().create("测试标签" + System.currentTimeMillis(), null);
System.out.println(this.tagId);
}
/**
* Test update.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = "testCreate")
public void testUpdate() throws Exception {
this.wxService.getTagService().update(this.tagId, "测试标签-改名" + System.currentTimeMillis());
}
/**
* Test list all.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = {"testUpdate", "testCreate"})
public void testListAll() throws Exception {
List<WxCpTag> tags = this.wxService.getTagService().listAll();
assertNotEquals(tags.size(), 0);
}
/**
* Test add users 2 tag.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = {"testListAll", "testUpdate", "testCreate"})
public void testAddUsers2Tag() throws Exception {
List<String> userIds = Splitter.on("|").splitToList(this.configStorage.getUserId());
WxCpTagAddOrRemoveUsersResult result = this.wxService.getTagService().addUsers2Tag(this.tagId, userIds, null);
assertEquals(result.getErrCode(), Integer.valueOf(0));
}
/**
* Test list users by tag id.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = {"testAddUsers2Tag", "testListAll", "testUpdate", "testCreate"})
public void testListUsersByTagId() throws Exception {
List<WxCpUser> users = this.wxService.getTagService().listUsersByTagId(this.tagId);
assertNotEquals(users.size(), 0);
}
/**
* Test remove users from tag.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = {"testListUsersByTagId", "testAddUsers2Tag", "testListAll", "testUpdate", "testCreate"})
public void testRemoveUsersFromTag() throws Exception {
List<String> userIds = Splitter.on("|").splitToList(this.configStorage.getUserId());
WxCpTagAddOrRemoveUsersResult result = this.wxService.getTagService().removeUsersFromTag(this.tagId, userIds, null);
assertEquals(result.getErrCode(), Integer.valueOf(0));
}
/**
* Test delete.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = {"testRemoveUsersFromTag", "testListUsersByTagId", "testAddUsers2Tag", "testListAll",
"testUpdate", "testCreate"})
public void testDelete() throws Exception {
this.wxService.getTagService().delete(this.tagId);
}
/**
* Test get.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGet() throws WxErrorException {
String apiResultJson = "{\"errcode\": 0,\"errmsg\": \"ok\",\"userlist\": [{\"userid\": \"0124035\",\"name\": " +
"\"王五\"},{\"userid\": \"0114035\",\"name\": \"梦雪\"}],\"partylist\": [9576,9567,9566],\"tagname\": \"测试标签-001\"}";
WxCpService wxService = mock(WxCpService.class);
when(wxService.get(String.format(wxService.getWxCpConfigStorage().getApiUrl(WxCpApiPathConsts.Tag.TAG_GET), 150),
null)).thenReturn(apiResultJson);
when(wxService.getTagService()).thenReturn(new WxCpTagServiceImpl(wxService));
WxCpTagService wxCpTagService = wxService.getTagService();
WxCpTagGetResult wxCpTagGetResult = wxCpTagService.get(String.valueOf(150));
assertEquals(0, wxCpTagGetResult.getErrcode().intValue());
assertEquals(2, wxCpTagGetResult.getUserlist().size());
assertEquals(3, wxCpTagGetResult.getPartylist().size());
assertEquals("测试标签-001", wxCpTagGetResult.getTagname());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpSchoolUserServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpSchoolUserServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.gson.Gson;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.school.user.WxCpDepartmentList;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.mockito.Mockito;
import org.testng.annotations.Test;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.School.DEPARTMENT_LIST;
import static org.testng.Assert.assertEquals;
public class WxCpSchoolUserServiceImplTest {
String allDeptListJson = "{\n" +
"\t\"errcode\": 0,\n" +
"\t\"errmsg\": \"ok\",\n" +
"\t\"departments\": [\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"一年级\",\n" +
"\t\t\t\"parentid\": 1,\n" +
"\t\t\t\"id\": 2,\n" +
"\t\t\t\"type\":2,\n" +
"\t\t\t\"register_year\":2018,\n" +
"\t\t\t\"standard_grade\":1,\n" +
"\t\t\t\"order\":1,\n" +
"\t\t\t\"department_admins\": [\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"userid\": \"zhangsan\",\n" +
"\t\t\t\t\t\"type\": 1\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"userid\": \"lisi\",\n" +
"\t\t\t\t\t\"type\": 2\n" +
"\t\t\t\t}\n" +
"\t\t\t],\n" +
" \"is_graduated\": 0\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"一年级一班\",\n" +
"\t\t\t\"parentid\": 1,\n" +
"\t\t\t\"id\": 3,\n" +
"\t\t\t\"type\": 1,\n" +
"\t\t\t\"department_admins\": [\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"userid\": \"zhangsan\",\n" +
"\t\t\t\t\t\"type\": 3,\n" +
"\t\t\t\t\t\"subject\":\"语文\"\n" +
"\t\t\t\t},\n" +
"\t\t\t\t{\n" +
"\t\t\t\t\t\"userid\": \"lisi\",\n" +
"\t\t\t\t\t\"type\": 4,\n" +
"\t\t\t\t\t\"subject\":\"数学\"\n" +
"\t\t\t\t}\n" +
"\t\t\t],\n" +
"\t\t\t\"open_group_chat\": 1,\n" +
" \"group_chat_id\": \"group_chat_id\"\n" +
"\t\t}\n" +
"\t]\n" +
"}\n";
String deptId3Json = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"departments\": [\n" +
" {\n" +
" \"name\": \"一年级一班\",\n" +
" \"parentid\": 1,\n" +
" \"id\": 3,\n" +
" \"type\": 1,\n" +
" \"department_admins\": [\n" +
" {\n" +
" \"userid\": \"zhangsan\",\n" +
" \"type\": 3,\n" +
" \"subject\":\"语文\"\n" +
" },\n" +
" {\n" +
" \"userid\": \"lisi\",\n" +
" \"type\": 4,\n" +
" \"subject\":\"数学\"\n" +
" }\n" +
" ],\n" +
" \"open_group_chat\": 1,\n" +
" \"group_chat_id\": \"group_chat_id\"\n" +
" }\n" +
" ]\n" +
"}";
String deptId2Json = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"departments\": []\n" +
"}\n";
@Test
public void testListDepartmentWhenIdIsNull() throws WxErrorException {
WxCpService mockCpService = Mockito.mock(WxCpService.class);
WxCpSchoolUserServiceImpl wxCpSchoolUserService = new WxCpSchoolUserServiceImpl(mockCpService);
Mockito.when(mockCpService.getWxCpConfigStorage()).thenReturn(new WxCpDefaultConfigImpl());
Mockito.when(mockCpService.get(mockCpService.getWxCpConfigStorage().getApiUrl(DEPARTMENT_LIST), null)).thenReturn(allDeptListJson);
WxCpDepartmentList wxCpDepartmentList = wxCpSchoolUserService.listDepartment(null);
//WxCpDepartmentList没有重写Equals和Hashcode,不能直接比较
Gson gson = new Gson();
assertEquals(gson.toJson(wxCpDepartmentList), gson.toJson(gson.fromJson(allDeptListJson, WxCpDepartmentList.class)), "should be equal");
}
@Test
public void testListDepartmentWhenIdIs2() throws WxErrorException {
WxCpService mockCpService = Mockito.mock(WxCpService.class);
WxCpSchoolUserServiceImpl wxCpSchoolUserService = new WxCpSchoolUserServiceImpl(mockCpService);
Mockito.when(mockCpService.getWxCpConfigStorage()).thenReturn(new WxCpDefaultConfigImpl());
Gson gson = new Gson();
int deptId = 2;
Mockito.when(mockCpService.get(String.format("%s?id=%s", mockCpService.getWxCpConfigStorage().getApiUrl(DEPARTMENT_LIST), deptId), null)).thenReturn(deptId2Json);
//WxCpDepartmentList没有重写Equals和Hashcode,不能直接比较
assertEquals(gson.toJson(wxCpSchoolUserService.listDepartment(deptId)), gson.toJson(gson.fromJson(deptId2Json, WxCpDepartmentList.class)), "should be equal");
}
@Test
public void testListDepartmentWhenIdIs3() throws WxErrorException {
WxCpService mockCpService = Mockito.mock(WxCpService.class);
WxCpSchoolUserServiceImpl wxCpSchoolUserService = new WxCpSchoolUserServiceImpl(mockCpService);
Mockito.when(mockCpService.getWxCpConfigStorage()).thenReturn(new WxCpDefaultConfigImpl());
Gson gson = new Gson();
int deptId = 3;
Mockito.when(mockCpService.get(String.format("%s?id=%s", mockCpService.getWxCpConfigStorage().getApiUrl(DEPARTMENT_LIST), deptId), null)).thenReturn(deptId3Json);
//WxCpDepartmentList没有重写Equals和Hashcode,不能直接比较
assertEquals(gson.toJson(wxCpSchoolUserService.listDepartment(deptId)), gson.toJson(gson.fromJson(deptId3Json, WxCpDepartmentList.class)), "should be equal");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpExternalContactServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpExternalContactServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import static org.testng.Assert.assertNotNull;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.XmlUtils;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.external.*;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactBatchInfo;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactListInfo;
import me.chanjar.weixin.cp.bean.external.msg.Attachment;
import me.chanjar.weixin.cp.bean.external.msg.AttachmentBuilder;
import me.chanjar.weixin.cp.bean.external.msg.Image;
import me.chanjar.weixin.cp.bean.external.msg.Video;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import org.testng.collections.CollectionUtils;
/**
* The type Wx cp external contact service impl test.
*/
@Guice(modules = ApiTestModule.class)
public class WxCpExternalContactServiceImplTest {
@Inject
private WxCpService wxCpService;
/**
* The Config storage.
*/
@Inject
protected ApiTestModule.WxXmlCpInMemoryConfigStorage configStorage;
private final String userId = "someone" + System.currentTimeMillis();
/**
* Test get external contact.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetExternalContact() throws WxErrorException {
String externalUserId = this.configStorage.getExternalUserId();
WxCpExternalContactInfo result = this.wxCpService.getExternalContactService().getExternalContact(externalUserId);
System.out.println(result);
assertNotNull(result);
}
/**
* Test add contact way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testAddContactWay() throws WxErrorException {
final String concatUserId = "HuangXiaoMing";
WxCpContactWayInfo.ContactWay wayInfo = new WxCpContactWayInfo.ContactWay();
wayInfo.setType(WxCpContactWayInfo.TYPE.SINGLE);
wayInfo.setScene(WxCpContactWayInfo.SCENE.QRCODE);
wayInfo.setUsers(Lists.newArrayList(concatUserId));
wayInfo.setRemark("CreateDate:" + DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format(new Date()));
WxCpContactWayInfo info = new WxCpContactWayInfo();
info.setContactWay(wayInfo);
this.wxCpService.getExternalContactService().addContactWay(info);
}
/**
* Test get contact way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetContactWay() throws WxErrorException {
final String configId = "39fea3d93e30faaa8c7a9edd4cfe4d08";
WxCpContactWayInfo contactWayInfo = this.wxCpService.getExternalContactService().getContactWay(configId);
System.out.println(contactWayInfo.toJson());
assertNotNull(contactWayInfo);
}
/**
* Test list contact way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testListContactWay() throws WxErrorException {
long startTime = LocalDateTime.now().minusDays(1).toEpochSecond(ZoneOffset.of("+8"));
long endTime = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
WxCpContactWayList wxCpContactWayList = this.wxCpService.getExternalContactService().listContactWay(startTime, endTime, null, 100L);
System.out.println(wxCpContactWayList.toJson());
assertNotNull(wxCpContactWayList);
}
/**
* Test update contact way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUpdateContactWay() throws WxErrorException {
final String configId = "2d7a68c657663afbd1d90db19a4b5ee9";
final String concatUserId = "符合要求的userId";
WxCpContactWayInfo.ContactWay wayInfo = new WxCpContactWayInfo.ContactWay();
wayInfo.setConfigId(configId);
wayInfo.setUsers(Lists.newArrayList(concatUserId));
wayInfo.setRemark("CreateDate:" + DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format(new Date()));
WxCpContactWayInfo info = new WxCpContactWayInfo();
info.setContactWay(wayInfo);
WxCpBaseResp resp = this.wxCpService.getExternalContactService().updateContactWay(info);
System.out.println(resp);
assertNotNull(resp);
}
/**
* Test del contact way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testDelContactWay() throws WxErrorException {
final String configId = "2d7a68c657663afbd1d90db19a4b5ee9";
WxCpBaseResp resp = this.wxCpService.getExternalContactService().deleteContactWay(configId);
System.out.println(resp);
assertNotNull(resp);
}
/**
* Test close temp chat.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testCloseTempChat() throws WxErrorException {
final String externalUserId = "externalUserId";
WxCpBaseResp resp = this.wxCpService.getExternalContactService().closeTempChat(userId, externalUserId);
System.out.println(resp);
}
/**
* Test list external contacts.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testListExternalContacts() throws WxErrorException {
String userId = this.configStorage.getUserId();
List<String> ret = this.wxCpService.getExternalContactService().listExternalContacts(userId);
System.out.println(ret);
assertNotNull(ret);
}
/**
* Test list external with permission.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testListExternalWithPermission() throws WxErrorException {
List<String> ret = this.wxCpService.getExternalContactService().listFollowers();
System.out.println(ret);
assertNotNull(ret);
}
/**
* Test get contact detail.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetContactDetail() throws WxErrorException {
String externalUserId = this.configStorage.getExternalUserId();
WxCpExternalContactInfo result = this.wxCpService.getExternalContactService().getContactDetail(externalUserId,
null);
System.out.println(result);
assertNotNull(result);
}
/**
* Test get contact detail batch.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetContactDetailBatch() throws WxErrorException {
String userId = this.configStorage.getUserId();
WxCpExternalContactBatchInfo result =
this.wxCpService.getExternalContactService().getContactDetailBatch(new String[]{userId}, "", 100);
System.out.println(result);
assertNotNull(result);
}
/**
* Test get contact list.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetContactList() throws WxErrorException {
WxCpExternalContactListInfo result =
this.wxCpService.getExternalContactService().getContactList("", 100);
System.out.println(result);
assertNotNull(result);
}
/**
* Test get corp tag list.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetCorpTagList() throws WxErrorException {
String[] tag = {};
WxCpUserExternalTagGroupList result = this.wxCpService.getExternalContactService().getCorpTagList(null);
System.out.println(result);
assertNotNull(result);
}
/**
* Test add corp tag.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testAddCorpTag() throws WxErrorException {
List<WxCpUserExternalTagGroupInfo.Tag> list = new ArrayList<>();
WxCpUserExternalTagGroupInfo.Tag tag = new WxCpUserExternalTagGroupInfo.Tag();
tag.setName("测试标签20");
tag.setOrder(1L);
list.add(tag);
WxCpUserExternalTagGroupInfo tagGroupInfo = new WxCpUserExternalTagGroupInfo();
WxCpUserExternalTagGroupInfo.TagGroup tagGroup = new WxCpUserExternalTagGroupInfo.TagGroup();
tagGroup.setGroupName("其他");
tagGroup.setOrder(1L);
tagGroup.setTag(list);
tagGroupInfo.setTagGroup(tagGroup);
WxCpUserExternalTagGroupInfo result = this.wxCpService.getExternalContactService().addCorpTag(tagGroupInfo);
System.out.println(result.toJson());
assertNotNull(result);
}
/**
* Test edit corp tag.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testEditCorpTag() throws WxErrorException {
WxCpBaseResp result = this.wxCpService.getExternalContactService().editCorpTag("et2omCCwAA6PtGsfeEOQMENl3Ub1FA6A"
, "未知6", 2);
System.out.println(result);
assertNotNull(result);
}
/**
* Test del corp tag.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testDelCorpTag() throws WxErrorException {
String[] tagId = {};
String[] groupId = {"et2omCCwAAM3WzL00QpK9xARab3HGkAg"};
WxCpBaseResp result = this.wxCpService.getExternalContactService().delCorpTag(tagId, groupId);
System.out.println(result);
assertNotNull(result);
}
/**
* Test mark tag.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testMarkTag() throws WxErrorException {
String userid = "HuangXiaoMing";
String externalUserid = "wo2omCCwAAzR0Rt1omz-90o_XJkPGXIQ";
String[] addTag = {"et2omCCwAAzdcSK-RV80YS9sbpCXlNlQ"};
String[] removeTag = {};
WxCpBaseResp result = this.wxCpService.getExternalContactService().markTag(userid, externalUserid, addTag,
removeTag);
System.out.println(result);
assertNotNull(result);
}
/**
* Test delete contact way.
*/
@Test
public void testDeleteContactWay() {
}
/**
* Test list followers.
*/
@Test
public void testListFollowers() {
}
/**
* Test list unassigned list.
*/
@Test
public void testListUnassignedList() {
}
/**
* Test transfer external contact.
*/
@Test
public void testTransferExternalContact() {
}
/**
* Test transfer customer.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testTransferCustomer() throws WxErrorException {
WxCpUserTransferCustomerReq req = new WxCpUserTransferCustomerReq();
req.setExternalUserid(Collections.emptyList());
req.setHandOverUserid("123");
req.setTakeOverUserid("234");
WxCpBaseResp result = this.wxCpService.getExternalContactService().transferCustomer(req);
System.out.println(result);
assertNotNull(result);
}
/**
* Test trnsfer result.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testTrnsferResult() throws WxErrorException {
WxCpUserTransferResultResp result = this.wxCpService.getExternalContactService().transferResult("123", "234", "");
System.out.println(result);
assertNotNull(result);
}
/**
* Testresigned transfer customer.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testresignedTransferCustomer() throws WxErrorException {
WxCpUserTransferCustomerReq req = new WxCpUserTransferCustomerReq();
req.setExternalUserid(Collections.emptyList());
req.setHandOverUserid("123");
req.setTakeOverUserid("234");
WxCpBaseResp result = this.wxCpService.getExternalContactService().resignedTransferCustomer(req);
System.out.println(result);
assertNotNull(result);
}
/**
* Testresigned trnsfer result.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testresignedTrnsferResult() throws WxErrorException {
WxCpUserTransferResultResp result = this.wxCpService.getExternalContactService().resignedTransferResult("123",
"234", "");
System.out.println(result);
assertNotNull(result);
}
/**
* Test list group chat.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testListGroupChat() throws WxErrorException {
WxCpUserExternalGroupChatList result = this.wxCpService.getExternalContactService().listGroupChat(0, 100, 0,
new String[1], new String[1]);
System.out.println(result);
assertNotNull(result);
}
/**
* Test list group chat v 3.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testListGroupChatV3() throws WxErrorException {
WxCpUserExternalGroupChatList result = this.wxCpService.getExternalContactService().listGroupChat(100, "", 0,
new String[1]);
System.out.println(result);
assertNotNull(result);
}
/**
* Test get group chat.
*/
@Test
public void testGetGroupChat() throws WxErrorException {
final WxCpUserExternalGroupChatInfo result = this.wxCpService.getExternalContactService().getGroupChat("wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA", 1);
System.out.println(result);
assertNotNull(result);
}
/**
* Test transfer group chat.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testTransferGroupChat() throws WxErrorException {
String[] str = {"wri1_QEAAATfnZl_VJ4hlQda0e4Mgf1A"};
WxCpUserExternalGroupChatTransferResp result = this.wxCpService.getExternalContactService().transferGroupChat(str
, "123");
System.out.println(result);
assertNotNull(result);
}
/**
* Test onjob transfer group chat.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testOnjobTransferGroupChat() throws WxErrorException {
String[] str = {"wrHlLKQAAAFbfB99-BO97YZlcywznGZg", "error_group_id"};
WxCpUserExternalGroupChatTransferResp result = this.wxCpService.getExternalContactService().onjobTransferGroupChat(str
, "x");
System.out.println(result);
assertNotNull(result);
}
/**
* Test get user behavior statistic.
*/
@Test
public void testGetUserBehaviorStatistic() {
}
/**
* Test get group chat statistic.
*/
@Test
public void testGetGroupChatStatistic() {
}
/**
* Test add msg template.
*/
@Test
public void testAddMsgTemplate() {
}
/**
* Test send welcome msg.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendWelcomeMsg() throws WxErrorException {
Image image = new Image();
image.setMediaId("123123");
Attachment attachment = new Attachment();
attachment.setImage(image);
Video video = new Video();
video.setMediaId("video_media_id");
Attachment attachment2 = new Attachment();
attachment2.setVideo(video);
List<Attachment> attachments = new ArrayList<>();
attachments.add(attachment);
attachments.add(attachment2);
this.wxCpService.getExternalContactService().sendWelcomeMsg(WxCpWelcomeMsg.builder()
.welcomeCode("abc")
.attachments(attachments)
.build());
}
/**
* Test send welcome msg. use AttachmentBuilder
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendWelcomeMsg2() throws WxErrorException {
Attachment imageAttachment = AttachmentBuilder.imageBuilder().mediaId("123123").build();
Attachment videoAttachment = AttachmentBuilder.videoBuilder().mediaId("video_media_id").build();
Attachment miniProgramAttachment = AttachmentBuilder.miniProgramBuilder()
.title("title")
.picMediaId("123123123")
.appId("wxcxxxxxxxxxxx")
.page("https://")
.build();
List<Attachment> attachments = new ArrayList<>();
attachments.add(imageAttachment);
attachments.add(videoAttachment);
attachments.add(miniProgramAttachment);
this.wxCpService.getExternalContactService().sendWelcomeMsg(WxCpWelcomeMsg.builder()
.welcomeCode("abc")
.attachments(attachments)
.build());
}
/**
* Test update remark.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUpdateRemark() throws WxErrorException {
this.wxCpService.getExternalContactService().updateRemark(WxCpUpdateRemarkRequest.builder()
.description("abc")
.userId("aaa")
.externalUserId("aaa")
.remark("aa")
.remarkCompany("aaa")
.remarkMobiles(new String[]{"111", "222"})
.remarkPicMediaId("aaa")
.build());
}
/**
* Test get product list album.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetProductListAlbum() throws WxErrorException {
WxCpProductAlbumListResult result = this.wxCpService.getExternalContactService()
.getProductAlbumList(100, null);
System.out.println(result);
assertNotNull(result);
if (CollectionUtils.hasElements(result.getProductList())) {
WxCpProductAlbumResult result1 =
this.wxCpService.getExternalContactService().getProductAlbum(result.getProductList().get(0).getProductId());
System.out.println(result1);
assertNotNull(result1);
}
}
/**
* Test get moment list.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetMomentList() throws WxErrorException {
WxCpGetMomentList result = this.wxCpService.getExternalContactService()
.getMomentList(1636732800L, 1636991999L, null, null, null, null);
System.out.println(result);
assertNotNull(result);
}
/**
* Test add join way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testAddJoinWay() throws WxErrorException {
WxCpGroupJoinWayInfo.JoinWay joinWay = new WxCpGroupJoinWayInfo.JoinWay();
joinWay.setChatIdList(Collections.singletonList("wrfpBaCwAAxR-iIqIUa5vvbpZQcAexJA"));
joinWay.setScene(2);
joinWay.setAutoCreateRoom(1);
joinWay.setRemark("CreateDate:" + DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format(new Date()));
WxCpGroupJoinWayInfo info = new WxCpGroupJoinWayInfo();
info.setJoinWay(joinWay);
this.wxCpService.getExternalContactService().addJoinWay(info);
}
/**
* Test update join way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUpdateJoinWay() throws WxErrorException {
final String configId = "";
WxCpGroupJoinWayInfo.JoinWay joinWay = new WxCpGroupJoinWayInfo.JoinWay();
joinWay.setConfigId(configId);
joinWay.setChatIdList(Collections.singletonList("wrfpBaCwAAxR-iIqIUa5vvbpZQcAexJA"));
joinWay.setScene(2);
joinWay.setAutoCreateRoom(1);
joinWay.setRemark("CreateDate:" + DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format(new Date()));
WxCpGroupJoinWayInfo info = new WxCpGroupJoinWayInfo();
info.setJoinWay(joinWay);
this.wxCpService.getExternalContactService().updateJoinWay(info);
}
/**
* Test del join way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testDelJoinWay() throws WxErrorException {
final String configId = "";
this.wxCpService.getExternalContactService().delJoinWay(configId);
}
/**
* Test get join way.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetJoinWay() throws WxErrorException {
final String configId = "";
this.wxCpService.getExternalContactService().getJoinWay(configId);
}
/**
* 提醒成员群发
*
* @throws WxErrorException
*/
@Test
public void testRemindGroupMsgSend() throws WxErrorException {
this.wxCpService.getExternalContactService()
.remindGroupMsgSend("msgGCAAAXtWyujaWJHDDGi0mACAAAA");
}
/**
* 测试取消提醒成员群发
*
* @throws WxErrorException
*/
@Test
public void testCancelGroupMsgSend() throws WxErrorException {
this.wxCpService.getExternalContactService()
.cancelGroupMsgSend("msgGCAAAXtWyujaWJHDDGi0mACAAAA");
}
/**
* 获客助手事件通知
* https://developer.work.weixin.qq.com/document/path/97299
*
* @throws WxErrorException
*/
@Test
public void testEvent() throws WxErrorException {
/**
* 获客额度即将耗尽事件
*/
String xml1 = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[customer_acquisition]]></Event>\n" +
"\t<ChangeType><![CDATA[balance_low]]></ChangeType>\n" +
"</xml>";
WxCpXmlMessage msg1 = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml1);
msg1.setAllFieldsMap(XmlUtils.xml2Map(xml1));
System.out.println("获客额度即将耗尽事件:" + WxCpGsonBuilder.create().toJson(msg1));
/**
* 使用量已经耗尽事件
*/
String xml2 = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[customer_acquisition]]></Event>\n" +
"\t<ChangeType><![CDATA[balance_exhausted]]></ChangeType>\n" +
"</xml>";
WxCpXmlMessage msg2 = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml2);
msg2.setAllFieldsMap(XmlUtils.xml2Map(xml2));
System.out.println("使用量已经耗尽事件:" + WxCpGsonBuilder.create().toJson(msg2));
/**
* 获客链接不可用事件
*/
String xml3 = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[customer_acquisition]]></Event>\n" +
"\t<ChangeType><![CDATA[link_unavailable]]></ChangeType>\n" +
"\t<LinkId><![CDATA[cawcdea7783d7330b4]]></LinkId>\n" +
"</xml>";
WxCpXmlMessage msg3 = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml3);
msg3.setAllFieldsMap(XmlUtils.xml2Map(xml3));
System.out.println("获客链接不可用事件:" + WxCpGsonBuilder.create().toJson(msg3));
/**
* 微信客户发起会话事件
*/
String xml4 = "<xml>\n" +
"<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"<CreateTime>1403610513</CreateTime>\n" +
"<MsgType><![CDATA[event]]></MsgType>\n" +
"<Event><![CDATA[customer_acquisition]]></Event>\n" +
"<ChangeType><![CDATA[customer_start_chat]]></ChangeType>\n" +
"<UserID><![CDATA[zhangsan]]></UserID>\n" +
"<ExternalUserID><![CDATA[woAJ2GCAAAXtWyujaWJHDDGi0mAAAA]]></ExternalUserID>\n" +
"</xml>";
WxCpXmlMessage msg4 = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml4);
msg4.setAllFieldsMap(XmlUtils.xml2Map(xml4));
System.out.println("微信客户发起会话事件:" + WxCpGsonBuilder.create().toJson(msg4));
/**
* 删除获客链接事件
*/
String xml5 = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1403610513</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[customer_acquisition]]></Event>\n" +
"\t<ChangeType><![CDATA[delete_link]]></ChangeType>\n" +
"\t<LinkId><![CDATA[cawcdea7783d7330b4]]></LinkId>\n" +
"</xml>";
WxCpXmlMessage msg5 = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml5);
msg5.setAllFieldsMap(XmlUtils.xml2Map(xml5));
System.out.println("删除获客链接事件:" + WxCpGsonBuilder.create().toJson(msg5));
/**
* 通过获客链接申请好友事件
*/
String xml6 = "<xml>\n" +
"\t<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName> \n" +
"\t<CreateTime>1689171577</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[customer_acquisition]]></Event>\n" +
"\t<ChangeType><![CDATA[friend_request]]></ChangeType>\n" +
"\t<LinkId><![CDATA[cawcdea7783d7330b4]]></LinkId>\n" +
"\t<State><![CDATA[STATE]]></State>\n" +
"</xml>";
WxCpXmlMessage msg6 = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml6);
msg6.setAllFieldsMap(XmlUtils.xml2Map(xml6));
System.out.println("通过获客链接申请好友事件:" + WxCpGsonBuilder.create().toJson(msg6));
/**
* 获客助手事件通知ChangeType
* @see me.chanjar.weixin.cp.constant.WxCpConsts.CustomerAcquisitionChangeType.CUSTOMER_START_CHAT
*/
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpKfServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpKfServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
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.util.XmlUtils;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.kf.*;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.io.InputStream;
/**
* WxCpKfServiceImpl-测试类
* 需要用到专门的secret
* <a href="https://developer.work.weixin.qq.com/document/path/94638">官方文档1</a>
* <a href="https://kf.weixin.qq.com/api/doc/path/93304#secret">官方文档2</a>
*
* @author Fu created on 2022/1/19 20:12
*/
@Guice(modules = ApiTestModule.class)
public class WxCpKfServiceImplTest {
@Inject
private WxCpService wxService;
private static String kfid = "wkPzhXVAAAJD9oR75LrO1DmURSOUFBIg";
/**
* Test account add.
*
* @throws Exception the exception
*/
@Test(priority = 1)
public void testAccountAdd() throws Exception {
try (InputStream in = ClassLoader.getSystemResourceAsStream("mm.jpeg")) {
WxMediaUploadResult result = this.wxService.getMediaService().upload(WxConsts.MediaFileType.IMAGE, "jpeg", in);
String mediaId = result.getMediaId();
WxCpKfAccountAdd add = new WxCpKfAccountAdd();
add.setMediaId(mediaId);
add.setName("kefu01");
WxCpKfAccountAddResp resp = this.wxService.getKfService().addAccount(add);
System.out.println(resp);
kfid = resp.getOpenKfid();
}
}
/**
* Test account upd.
*
* @throws Exception the exception
*/
@Test(priority = 2)
public void testAccountUpd() throws Exception {
WxCpKfAccountUpd upd = new WxCpKfAccountUpd();
upd.setOpenKfid(kfid);
upd.setName("kefu01-upd");
WxCpBaseResp resp = this.wxService.getKfService().updAccount(upd);
System.out.println(resp);
}
/**
* Test account list.
*
* @throws Exception the exception
*/
@Test(priority = 3)
public void testAccountList() throws Exception {
WxCpKfAccountListResp resp = this.wxService.getKfService().listAccount(0, 10);
System.out.println(resp);
}
/**
* Test account link.
*
* @throws Exception the exception
*/
@Test(priority = 4)
public void testAccountLink() throws Exception {
WxCpKfAccountLink link = new WxCpKfAccountLink();
link.setOpenKfid(kfid);
link.setScene("scene");
WxCpKfAccountLinkResp resp = this.wxService.getKfService().getAccountLink(link);
System.out.println(resp);
}
/**
* Test account del.
*
* @throws Exception the exception
*/
@Test(priority = 5)
public void testAccountDel() throws Exception {
WxCpKfAccountDel del = new WxCpKfAccountDel();
del.setOpenKfid(kfid);
WxCpBaseResp resp = this.wxService.getKfService().delAccount(del);
System.out.println(resp);
}
/**
* 测试回调事件
* https://developer.work.weixin.qq.com/document/path/94670
* https://developer.work.weixin.qq.com/document/path/97712
*
* @throws Exception
*/
@Test(priority = 6)
public void testEvent() throws Exception {
// 客服账号授权变更事件
String xml1 = "<xml>\n" +
" <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
" <FromUserName><![CDATA[sys]]></FromUserName> \n" +
" <CreateTime>1348831860</CreateTime>\n" +
" <MsgType><![CDATA[event]]></MsgType>\n" +
" <Event><![CDATA[kf_account_auth_change]]></Event>\n" +
" <AuthAddOpenKfId><![CDATA[wkxxxx1]]></AuthAddOpenKfId>\n" +
" <AuthDelOpenKfId><![CDATA[wkxxxx2]]></AuthDelOpenKfId>\n" +
"</xml>";
WxCpXmlMessage xmlMsg1 = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml1);
xmlMsg1.setAllFieldsMap(XmlUtils.xml2Map(xml1));
System.out.println(WxCpGsonBuilder.create().toJson(xmlMsg1));
String xml = "<xml>\n" +
" <ToUserName><![CDATA[ww12345678910]]></ToUserName>\n" +
" <CreateTime>1348831860</CreateTime>\n" +
" <MsgType><![CDATA[event]]></MsgType>\n" +
" <Event><![CDATA[kf_msg_or_event]]></Event>\n" +
" <Token><![CDATA[ENCApHxnGDNAVNY4AaSJKj4Tb5mwsEMzxhFmHVGcra996NR]]></Token>\n" +
" <OpenKfId><![CDATA[wkxxxxxxx]]></OpenKfId>\n" +
"</xml>";
WxCpXmlMessage xmlMsg = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml);
xmlMsg.setAllFieldsMap(XmlUtils.xml2Map(xml));
System.out.println(WxCpGsonBuilder.create().toJson(xmlMsg));
System.out.println("token:" + xmlMsg.getToken());
System.out.println("openKfId:" + xmlMsg.getOpenKfId());
/**
* 微信客服事件推送
* @see me.chanjar.weixin.cp.constant.WxCpConsts.EventType.KF_MSG_OR_EVENT
* @see me.chanjar.weixin.cp.constant.WxCpConsts.EventType.KF_ACCOUNT_AUTH_CHANGE
*/
System.out.println("微信客服事件:" + me.chanjar.weixin.cp.constant.WxCpConsts.EventType.KF_MSG_OR_EVENT);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpMenuServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpMenuServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import static org.testng.Assert.assertNotNull;
/**
* <pre>
*
* Created by Binary Wang on 2017-6-25.
* @author <a href="https://github.com/binarywang">Binary Wang</a> </pre>
*/
@Guice(modules = ApiTestModule.class)
public class WxCpMenuServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
/**
* Menu data object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider
public Object[][] menuData() {
WxMenu menu = new WxMenu();
WxMenuButton button1 = new WxMenuButton();
button1.setType(WxConsts.MenuButtonType.CLICK);
button1.setName("今日歌曲");
button1.setKey("V1001_TODAY_MUSIC");
WxMenuButton button2 = new WxMenuButton();
button2.setType(WxConsts.MenuButtonType.CLICK);
button2.setName("歌手简介");
button2.setKey("V1001_TODAY_SINGER");
WxMenuButton button3 = new WxMenuButton();
button3.setName("菜单");
menu.getButtons().add(button1);
menu.getButtons().add(button2);
menu.getButtons().add(button3);
WxMenuButton button31 = new WxMenuButton();
button31.setType(WxConsts.MenuButtonType.VIEW);
button31.setName("搜索");
button31.setUrl("http://www.soso.com/");
WxMenuButton button32 = new WxMenuButton();
button32.setType(WxConsts.MenuButtonType.VIEW);
button32.setName("视频");
button32.setUrl("http://v.qq.com/");
WxMenuButton button33 = new WxMenuButton();
button33.setType(WxConsts.MenuButtonType.CLICK);
button33.setName("赞一下我们");
button33.setKey("V1001_GOOD");
button3.getSubButtons().add(button31);
button3.getSubButtons().add(button32);
button3.getSubButtons().add(button33);
return new Object[][]{
new Object[]{
menu
}
};
}
/**
* Test create.
*
* @param wxMenu the wx menu
* @throws Exception the exception
*/
@Test(dataProvider = "menuData")
public void testCreate(WxMenu wxMenu) throws Exception {
this.wxService.getMenuService().create(wxMenu);
}
/**
* Test get.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = "testCreate")
public void testGet() throws Exception {
WxMenu menu = this.wxService.getMenuService().get();
assertNotNull(menu);
System.out.println(menu.toJson());
}
/**
* Test delete.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = {"testGet", "testCreate"})
public void testDelete() throws Exception {
this.wxService.getMenuService().delete();
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/BaseWxCpServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/BaseWxCpServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxMpErrorMsgEnum;
import me.chanjar.weixin.common.util.http.HttpClientType;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* <pre>
* Created by BinaryWang on 2019/3/31.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Test
@Guice(modules = ApiTestModule.class)
public class BaseWxCpServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
/**
* Test get agent jsapi ticket.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetAgentJsapiTicket() throws WxErrorException {
assertThat(this.wxService.getAgentJsapiTicket()).isNotEmpty();
assertThat(this.wxService.getAgentJsapiTicket(true)).isNotEmpty();
}
/**
* Test js code 2 session.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testJsCode2Session() throws WxErrorException {
assertThat(this.wxService.jsCode2Session("111")).isNotNull();
}
/**
* Test get provider token.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetProviderToken() throws WxErrorException {
assertThat(this.wxService.getProviderToken("111", "123")).isNotNull();
}
/**
* Test execute auto refresh token.
*
* @throws WxErrorException the wx error exception
* @throws IOException the io exception
*/
@Test
public void testExecuteAutoRefreshToken() throws WxErrorException, IOException {
//测试access token获取时的重试机制
WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
BaseWxCpServiceImpl service = new BaseWxCpServiceImpl() {
@Override
public Object getRequestHttpClient() {
return null;
}
@Override
public Object getRequestHttpProxy() {
return null;
}
@Override
public HttpClientType getRequestType() {
return null;
}
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
return "模拟一个过期的access token:" + System.currentTimeMillis();
}
@Override
public void initHttp() {
}
@Override
public WxCpConfigStorage getWxCpConfigStorage() {
return config;
}
};
config.setAgentId(1);
service.setWxCpConfigStorage(config);
RequestExecutor<Object, Object> re = mock(RequestExecutor.class);
AtomicInteger counter = new AtomicInteger();
Mockito.when(re.execute(Mockito.anyString(), Mockito.any(), Mockito.any())).thenAnswer(invocation -> {
counter.incrementAndGet();
WxError error =
WxError.builder().errorCode(WxMpErrorMsgEnum.CODE_40001.getCode()).errorMsg(WxMpErrorMsgEnum.CODE_40001.getMsg()).build();
throw new WxErrorException(error);
});
try {
Object execute = service.execute(re, "http://baidu.com", new HashMap<>());
Assert.fail("代码应该不会执行到这里");
} catch (WxErrorException e) {
Assert.assertEquals(WxMpErrorMsgEnum.CODE_40001.getCode(), e.getError().getErrorCode());
Assert.assertEquals(2, counter.get());
}
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpMediaServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpMediaServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
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.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.TestConstants;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.media.MediaUploadByUrlReq;
import me.chanjar.weixin.cp.bean.media.MediaUploadByUrlResult;
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.net.URL;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertTrue;
/**
* Created by Binary Wang on 2017-6-25.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Guice(modules = ApiTestModule.class)
public class WxCpMediaServiceImplTest {
@Inject
private WxCpService wxService;
private final List<String> mediaIds = new ArrayList<>();
/**
* Media data object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider
public Object[][] mediaData() {
return new Object[][]{
new Object[]{WxConsts.MediaFileType.IMAGE, TestConstants.FILE_JPG, "mm.jpeg"},
//new Object[]{WxConsts.MediaFileType.VOICE, TestConstants.FILE_MP3, "mm.mp3"},
// {"errcode":301017,"errmsg":"voice file only support amr like myvoice.amr"}
new Object[]{WxConsts.MediaFileType.VOICE, TestConstants.FILE_AMR, "mm.amr"},
new Object[]{WxConsts.MediaFileType.VIDEO, TestConstants.FILE_MP4, "mm.mp4"},
new Object[]{WxConsts.MediaFileType.FILE, TestConstants.FILE_JPG, "mm.jpeg"}
};
}
/**
* Test upload media.
*
* @param mediaType the media type
* @param fileType the file type
* @param fileName the file name
* @throws WxErrorException the wx error exception
* @throws IOException the io exception
*/
@Test(dataProvider = "mediaData")
public void testUploadMedia(String mediaType, String fileType, String fileName) throws WxErrorException, IOException {
try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName)) {
WxMediaUploadResult res = this.wxService.getMediaService().upload(mediaType, fileType, inputStream);
assertThat(res).isNotNull();
assertThat(res.getType()).isNotEmpty();
assertThat(res.getCreatedAt()).isGreaterThan(0);
assertTrue(res.getMediaId() != null || res.getThumbMediaId() != null);
if (res.getMediaId() != null) {
this.mediaIds.add(res.getMediaId());
}
if (res.getThumbMediaId() != null) {
this.mediaIds.add(res.getThumbMediaId());
}
}
}
/**
* Download media object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@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)};
}
return params;
}
/**
* Test download.
*
* @param mediaId the media id
* @throws WxErrorException the wx error exception
*/
@Test(dependsOnMethods = {"testUploadMedia"}, dataProvider = "downloadMedia")
public void testDownload(String mediaId) throws WxErrorException {
File file = this.wxService.getMediaService().download(mediaId);
assertThat(file).isNotNull();
System.out.println(file);
}
/**
* Test upload img.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUploadImg() throws WxErrorException {
URL url = ClassLoader.getSystemResource("mm.jpeg");
String res = this.wxService.getMediaService().uploadImg(new File(url.getFile()));
assertThat(res).isNotEmpty();
}
/**
* Test get jssdk file.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetJssdkFile() throws WxErrorException {
File file = this.wxService.getMediaService().getJssdkFile("....");
assertThat(file).isNotNull();
System.out.println(file);
}
/**
* Test upload media by url.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUploadMediaByUrl() throws WxErrorException {
MediaUploadByUrlReq req = new MediaUploadByUrlReq();
req.setScene(1);
req.setType("video");
req.setFilename("mov_bbb");
req.setUrl("https://www.w3school.com.cn/example/html5/mov_bbb.mp4");
req.setMd5("198918f40ecc7cab0fc4231adaf67c96");
String jobId = this.wxService.getMediaService().uploadByUrl(req);
System.out.println(jobId);
}
/**
* Test upload media by url.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUploadMediaByUrlResult() throws WxErrorException, InterruptedException {
String jobId = "job1745801375_5GIKWuFF3M7hcIkeSNMqs_W26xy5VeSWjLaLFTEdSfQ";
MediaUploadByUrlResult result = this.wxService.getMediaService().uploadByUrl(jobId);
System.out.println(result);
}
@Test
public void testUploadMediaJobFinishEvent() throws WxErrorException {
File file = this.wxService.getMediaService().getJssdkFile("....");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpAgentServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpAgentServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpAgentService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpAgent;
import me.chanjar.weixin.cp.bean.WxCpTpAdmin;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import me.chanjar.weixin.cp.constant.WxCpApiPathConsts;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
/**
* <pre>
* 管理企业号应用-测试
* Created by huansinho on 2018/4/13.
* </pre>
*
* @author <a href="https://github.com/huansinho">huansinho</a>
*/
@Guice(modules = ApiTestModule.class)
public class WxCpAgentServiceImplTest {
@Inject
private WxCpService wxCpService;
/**
* Test get.
*
* @throws Exception the exception
*/
@Test
public void testGet() throws Exception {
final Integer agentId = this.wxCpService.getWxCpConfigStorage().getAgentId();
WxCpAgent wxCpAgent = this.wxCpService.getAgentService().get(agentId);
assertThat(wxCpAgent.getAgentId()).isEqualTo(agentId);
assertThat(wxCpAgent.getAllowUserInfos().getUsers().toArray()).isNotEmpty();
assertThat(wxCpAgent.getAllowParties().getPartyIds().toArray()).isNotEmpty();
assertThat(wxCpAgent.getAllowTags().getTagIds().toArray()).isNotEmpty();
}
/**
* Test set.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSet() throws WxErrorException {
final Integer agentId = this.wxCpService.getWxCpConfigStorage().getAgentId();
this.wxCpService.getAgentService().set(WxCpAgent.builder()
.description("abcddd")
.logoMediaId("aaaaaaaaaaaaaa")
.agentId(agentId)
.build());
}
/**
* Test list.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testList() throws WxErrorException {
List<WxCpAgent> list = this.wxCpService.getAgentService().list();
assertThat(list).isNotEmpty();
assertThat(list.get(0).getAgentId()).isNotNull();
assertThat(list.get(0).getName()).isNotEmpty();
assertThat(list.get(0).getSquareLogoUrl()).isNotEmpty();
}
/**
* Test get admin list.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetAdminList() throws WxErrorException {
final Integer agentId = this.wxCpService.getWxCpConfigStorage().getAgentId();
WxCpTpAdmin adminList = this.wxCpService.getAgentService().getAdminList(agentId);
assertThat(adminList).isNotNull();
assertThat(adminList.getErrcode()).isEqualTo(0L);
}
/**
* The type Mock test.
*/
public static class MockTest {
private final WxCpService wxService = mock(WxCpService.class);
/**
* Test get.
*
* @throws Exception the exception
*/
@Test
public void testGet() throws Exception {
String returnJson = "{\"errcode\": 0,\"errmsg\": \"ok\",\"agentid\": 9,\"name\": \"测试应用\",\"square_logo_url\": " +
"\"http://wx.qlogo.cn/mmhead/alksjf;lasdjf;lasjfuodiuj3rj2o34j/0\",\"description\": \"这是一个企业号应用\"," +
"\"allow_userinfos\": {\"user\": [{\"userid\": \"0009854\"}, {\"userid\": \"1723\"}, {\"userid\": " +
"\"5625\"}]},\"allow_partys\": {\"partyid\": [42762742]},\"allow_tags\": {\"tagid\": [23, 22, 35, 19, 32, " +
"125, 133, 46, 150, 38, 183, 9, 7]},\"close\": 0,\"redirect_domain\": \"weixin.com.cn\"," +
"\"report_location_flag\": 0,\"isreportenter\": 0,\"home_url\": \"\"}";
final WxCpConfigStorage configStorage = new WxCpDefaultConfigImpl();
when(wxService.getWxCpConfigStorage()).thenReturn(configStorage);
when(wxService.get(String.format(configStorage.getApiUrl(WxCpApiPathConsts.Agent.AGENT_GET), 9), null)).thenReturn(returnJson);
when(wxService.getAgentService()).thenReturn(new WxCpAgentServiceImpl(wxService));
WxCpAgentService wxAgentService = this.wxService.getAgentService();
WxCpAgent wxCpAgent = wxAgentService.get(9);
assertEquals(9, wxCpAgent.getAgentId().intValue());
assertEquals(new Integer[]{42762742}, wxCpAgent.getAllowParties().getPartyIds().toArray());
assertEquals(new Integer[]{23, 22, 35, 19, 32, 125, 133, 46, 150, 38, 183, 9, 7},
wxCpAgent.getAllowTags().getTagIds().toArray());
}
/**
* Test get admin list.
*
* @throws Exception the exception
*/
@Test
public void testGetAdminList() throws Exception {
// 构建响应JSON
JsonObject admin1 = new JsonObject();
admin1.addProperty("userid", "zhangsan");
admin1.addProperty("open_userid", "woAJ2GCAAAXtWyujaWJHDDGi0mACH71w");
admin1.addProperty("auth_type", 1);
JsonObject admin2 = new JsonObject();
admin2.addProperty("userid", "lisi");
admin2.addProperty("open_userid", "woAJ2GCAAAXtWyujaWJHDDGi0mACH72w");
admin2.addProperty("auth_type", 2);
JsonArray adminArray = new JsonArray();
adminArray.add(admin1);
adminArray.add(admin2);
JsonObject returnJsonObj = new JsonObject();
returnJsonObj.addProperty("errcode", 0);
returnJsonObj.addProperty("errmsg", "ok");
returnJsonObj.add("admin", adminArray);
String returnJson = returnJsonObj.toString();
JsonObject requestJson = new JsonObject();
requestJson.addProperty("agentid", 9);
final WxCpConfigStorage configStorage = new WxCpDefaultConfigImpl();
when(wxService.getWxCpConfigStorage()).thenReturn(configStorage);
when(wxService.post(configStorage.getApiUrl(WxCpApiPathConsts.Agent.AGENT_GET_ADMIN_LIST), requestJson.toString())).thenReturn(returnJson);
when(wxService.getAgentService()).thenReturn(new WxCpAgentServiceImpl(wxService));
WxCpAgentService wxAgentService = this.wxService.getAgentService();
WxCpTpAdmin adminList = wxAgentService.getAdminList(9);
assertEquals(0, adminList.getErrcode().intValue());
assertEquals(2, adminList.getAdmin().size());
assertEquals("zhangsan", adminList.getAdmin().get(0).getUserId());
assertEquals("woAJ2GCAAAXtWyujaWJHDDGi0mACH71w", adminList.getAdmin().get(0).getOpenUserId());
assertEquals(1, adminList.getAdmin().get(0).getAuthType().intValue());
}
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpAgentWorkBenchImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpAgentWorkBenchImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpAgentWorkBench;
import me.chanjar.weixin.cp.bean.workbench.WorkBenchKeyData;
import me.chanjar.weixin.cp.bean.workbench.WorkBenchList;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
/**
* 测试工作台服务
*
* @author songshiyu
* created at 10:31 2020/9/29
*/
@Guice(modules = ApiTestModule.class)
public class WxCpAgentWorkBenchImplTest {
@Inject
private WxCpService wxCpService;
/**
* Test template set.
*
* @param template the template
* @throws WxErrorException the wx error exception
*/
@Test(dataProvider = "template")
public void testTemplateSet(WxCpAgentWorkBench template) throws WxErrorException {
this.wxCpService.getWorkBenchService().setWorkBenchTemplate(template);
}
/**
* Test template get.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testTemplateGet() throws WxErrorException {
String result = this.wxCpService.getWorkBenchService().getWorkBenchTemplate(1000011L);
System.out.println("获取工作台模板设置:" + result);
}
/**
* Test user data set.
*
* @param userDatas the user datas
* @throws WxErrorException the wx error exception
*/
@Test(dataProvider = "userDatas")
public void testUserDataSet(WxCpAgentWorkBench userDatas) throws WxErrorException {
this.wxCpService.getWorkBenchService().setWorkBenchData(userDatas);
}
/**
* Template object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider
public Object[][] template() {
return new Object[][]{
{WxCpAgentWorkBench.builder()
.agentId(1000011L)
.replaceUserData(true)
.type(WxCpConsts.WorkBenchType.IMAGE)
.url("http://www.qq.com")
.jumpUrl("http://www.qq.com")
.pagePath("pages/index")
.build()
},
};
}
/**
* User datas object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider
public Object[][] userDatas() {
return new Object[][]{
{WxCpAgentWorkBench.builder()
.agentId(1000011L)
.userId("HaHa")
.type(WxCpConsts.WorkBenchType.IMAGE)
.url("http://www.qq.com")
.jumpUrl("http://www.qq.com")
.pagePath("pages/index")
.build()
},
};
}
/**
* Test key data template set.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testKeyDataTemplateSet() throws WxErrorException {
WxCpAgentWorkBench template = new WxCpAgentWorkBench();
template.setAgentId(1000011L);
template.setType(WxCpConsts.WorkBenchType.KEYDATA);
List<WorkBenchKeyData> workBenchKeyDataList = new ArrayList<>();
for (int i = 1; i < 4; i++) {
WorkBenchKeyData workBenchKeyData = new WorkBenchKeyData();
workBenchKeyData.setKey("审批" + i);
workBenchKeyData.setData(String.valueOf(i));
workBenchKeyData.setJumpUrl("http://www.qq.com");
workBenchKeyData.setPagePath("pages/index");
workBenchKeyDataList.add(workBenchKeyData);
}
template.setKeyDataList(workBenchKeyDataList);
template.setReplaceUserData(true);
this.wxCpService.getWorkBenchService().setWorkBenchTemplate(template);
}
/**
* Test key data user data set.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testKeyDataUserDataSet() throws WxErrorException {
WxCpAgentWorkBench template = new WxCpAgentWorkBench();
template.setAgentId(1000011L);
template.setUserId("HaHa");
template.setType(WxCpConsts.WorkBenchType.KEYDATA);
List<WorkBenchKeyData> workBenchKeyDataList = new ArrayList<>();
WorkBenchKeyData workBenchKeyData = new WorkBenchKeyData();
workBenchKeyData.setKey("待审批");
workBenchKeyData.setData("2");
workBenchKeyData.setJumpUrl("http://www.qq.com");
workBenchKeyData.setPagePath("pages/index");
workBenchKeyDataList.add(workBenchKeyData);
template.setKeyDataList(workBenchKeyDataList);
this.wxCpService.getWorkBenchService().setWorkBenchTemplate(template);
}
/**
* Test list template set.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testListTemplateSet() throws WxErrorException {
WxCpAgentWorkBench template = new WxCpAgentWorkBench();
template.setAgentId(1000011L);
template.setType(WxCpConsts.WorkBenchType.LIST);
List<WorkBenchList> workBenchListArray = new ArrayList<>();
for (int i = 0; i < 2; i++) {
WorkBenchList workBenchlist = new WorkBenchList();
workBenchlist.setTitle("测试" + i);
workBenchlist.setJumpUrl("http://www.qq.com");
workBenchlist.setPagePath("pages/index");
workBenchListArray.add(workBenchlist);
}
template.setLists(workBenchListArray);
template.setReplaceUserData(true);
this.wxCpService.getWorkBenchService().setWorkBenchTemplate(template);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpChatServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpChatServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpChat;
import me.chanjar.weixin.cp.bean.article.MpnewsArticle;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import me.chanjar.weixin.cp.bean.message.WxCpAppChatMessage;
import me.chanjar.weixin.cp.constant.WxCpConsts.AppChatMsgType;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 测试群聊服务
*
* @author gaigeshen
*/
@Guice(modules = ApiTestModule.class)
public class WxCpChatServiceImplTest {
private String chatId;
private String userId;
@Inject
private WxCpService cpService;
/**
* Init.
*/
@BeforeTest
public void init() {
this.chatId = "mychatid";
this.userId = ((ApiTestModule.WxXmlCpInMemoryConfigStorage) this.cpService.getWxCpConfigStorage()).getUserId();
}
/**
* Test create.
*
* @throws Exception the exception
*/
@Test
public void testCreate() throws Exception {
final String result = cpService.getChatService().create("测试群聊", userId,
Arrays.asList(userId, userId), chatId);
assertThat(result).isNotEmpty();
assertThat(result).isEqualTo(chatId);
}
/**
* Test get.
*
* @throws Exception the exception
*/
@Test
public void testGet() throws Exception {
WxCpChat chat = this.cpService.getChatService().get(chatId);
System.out.println(chat);
Assert.assertEquals(chat.getName(), "测试群聊");
}
/**
* Test update.
*
* @throws Exception the exception
*/
@Test
public void testUpdate() throws Exception {
this.cpService.getChatService().update(chatId, "", "", Collections.singletonList("ZhengWuYao"), null);
WxCpChat chat = this.cpService.getChatService().get(chatId);
System.out.println(chat);
Assert.assertEquals(chat.getUsers().size(), 3);
}
/**
* Messages object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider
public Object[][] messages() {
return new Object[][]{
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.TEXT)
.chatId(chatId)
.content("你的快递已到\n请携带工卡前往邮件中心领取")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.IMAGE)
.chatId(chatId)
.mediaId("3_xWGPXZhpOKZrlRISWrjhPrDUZqZ-jIEVzxd56jLuqM")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.VOICE)
.chatId(chatId)
.mediaId("3X5t6HkdN1hUgB7OzrdRnc8v0yI0CqlAxFxnCkS3msTnTLanpYrV4esLv4foZVnlf")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.VIDEO)
.chatId(chatId)
.mediaId("3otWyy_acbID8fyltmCOW5hGVD8oa0_p0za5jhukxKTUDoGT71lqTvtQAWoycXpQf")
.title("aaaa")
.description("ddddd")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.FILE)
.chatId(chatId)
.mediaId("34AyVyDdndVhB4Z2tT-_FYKZ7Xqrr47LPC11GHH4oy7o")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.TEXTCARD)
.chatId(chatId)
.btnTxt("更多")
.title("领奖通知")
.url("https://zhidao.baidu.com/question/2073647112026042748.html")
.description("<div class=\"gray\">2016年9月26日</div> <div class=\"normal\"> 恭喜你抽中iPhone " +
"7一台,领奖码:520258</div><div class=\"highlight\">请于2016年10月10日前联系行 政同事领取</div>")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.NEWS)
.chatId(chatId)
.articles(Lists.newArrayList(NewArticle.builder()
.title("领奖通知")
.url("https://zhidao.baidu.com/question/2073647112026042748.html")
.description("今年中秋节公司有豪礼相送")
.picUrl("http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png")
.build()
))
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.MPNEWS)
.chatId(chatId)
.mpnewsArticles(Lists.newArrayList(MpnewsArticle.newBuilder()
.title("地球一小时")
.thumbMediaId("3_xWGPXZhpOKZrlRISWrjhPrDUZqZ-jIEVzxd56jLuqM")
.author("Author")
.contentSourceUrl("https://work.weixin.qq.com")
.content("3月24日20:30-21:30 \n办公区将关闭照明一小时,请各部门同事相互转告")
.digest("3月24日20:30-21:30 \n办公区将关闭照明一小时")
.build()
))
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.MARKDOWN)
.chatId(chatId)
.content("您的会议室已经预定,稍后会同步到`邮箱` \n" +
" >**事项详情** \n" +
" >事 项:<font color=\\\"info\\\">开会</font> \n" +
" >组织者:@miglioguan \n" +
" >参与者:@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang \n" +
" > \n" +
" >会议室:<font color=\\\"info\\\">广州TIT 1楼 301</font> \n" +
" >日 期:<font color=\\\"warning\\\">2018年5月18日</font> \n" +
" >时 间:<font color=\\\"comment\\\">上午9:00-11:00</font> \n" +
" > \n" +
" >请准时参加会议。 \n" +
" > \n" +
" >如需修改会议信息,请点击:[修改会议信息](https://work.weixin.qq.com)")
.build()
},
};
}
/**
* Test send msg.
*
* @param message the message
* @throws WxErrorException the wx error exception
*/
@Test(dataProvider = "messages")
public void testSendMsg(WxCpAppChatMessage message) throws WxErrorException {
this.cpService.getChatService().sendMsg(message);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpTaskCardServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpTaskCardServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import me.chanjar.weixin.cp.bean.taskcard.TaskCardButton;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.Arrays;
import static org.testng.Assert.assertNotNull;
/**
* 测试任务卡片服务
*
* @author <a href="https://github.com/domainname">Jeff</a> created on 2019-05-16
*/
@Guice(modules = ApiTestModule.class)
public class WxCpTaskCardServiceImplTest {
@Inject
private WxCpService wxCpService;
/**
* Test send task card.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendTaskCard() throws WxErrorException {
TaskCardButton btn1 = TaskCardButton.builder()
.key("key1")
.name("同意")
.replaceName("已同意")
.bold(true)
.build();
TaskCardButton btn2 = TaskCardButton.builder()
.key("key2")
.name("拒绝")
.replaceName("已拒绝")
.color("red")
.build();
WxCpMessage message = WxCpMessage.TASKCARD()
.toUser("jeff|mr.t")
.title("有一个待审批的请求")
.description("申请:购买图书\n金额:100 元")
.taskId("task_1")
.url("http://www.qq.com")
.buttons(Arrays.asList(btn1, btn2))
.build();
WxCpMessageSendResult messageSendResult = this.wxCpService.getMessageService().send(message);
assertNotNull(messageSendResult);
System.out.println(messageSendResult);
System.out.println(messageSendResult.getInvalidPartyList());
System.out.println(messageSendResult.getInvalidUserList());
System.out.println(messageSendResult.getInvalidTagList());
}
/**
* Test update.
*
* @throws Exception the exception
*/
@Test
public void testUpdate() throws Exception {
wxCpService.getTaskCardService().update(Arrays.asList("jeff", "mr.t"), "task_1", "key1");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOaMeetingRoomServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOaMeetingRoomServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.meetingroom.*;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 单元测试.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-09-20
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxCpOaMeetingRoomServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
/**
* Test add.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testAdd() throws WxErrorException {
this.wxService.getOaMeetingRoomService().addMeetingRoom(WxCpOaMeetingRoom.builder()
.building("腾讯大厦")
.capacity(10)
.city("深圳")
.name("18F-会议室")
.floor("18F")
.equipment(Arrays.asList(1, 2))
// .coordinate()
.build());
}
/**
* Test update.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUpdate() throws WxErrorException {
this.wxService.getOaMeetingRoomService().editMeetingRoom(WxCpOaMeetingRoom.builder()
.building("腾讯大厦")
.capacity(10)
.city("深圳")
.name("16F-会议室")
.floor("16F")
.equipment(Arrays.asList(1, 2, 3))
.meetingroomId(1)
.build());
}
/**
* Test get.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGet() throws WxErrorException {
final List<WxCpOaMeetingRoom> meetingRooms =
this.wxService.getOaMeetingRoomService().listMeetingRoom(WxCpOaMeetingRoom.builder()
.building("腾讯大厦")
.city("深圳")
.equipment(Arrays.asList(1, 2))
.build());
assertThat(meetingRooms).isNotEmpty();
}
/**
* Test delete.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testDelete() throws WxErrorException {
Integer calId = 1;
this.wxService.getOaMeetingRoomService().deleteMeetingRoom(calId);
}
@Test
public void testGetMeetingRoomBookingInfo() throws WxErrorException {
final WxCpOaMeetingRoomBookingInfoResult meetingRoomBookingInfo = this.wxService.getOaMeetingRoomService().getMeetingRoomBookingInfo(WxCpOaMeetingRoomBookingInfoRequest.builder()
.meetingroomId(19)
.build());
System.out.println(meetingRoomBookingInfo);
assertThat(meetingRoomBookingInfo).isNotNull();
}
@Test
public void testBookingMeetingRoom() throws WxErrorException {
WxCpOaMeetingRoomBookResult wxCpOaMeetingRoomBookResult = this.wxService.getOaMeetingRoomService().bookingMeetingRoom(WxCpOaMeetingRoomBookRequest.builder().subject("测试会议").meetingroomId(19).startTime(1730118646).endTime(1730120446).booker("LiangLinWei").attendees(Arrays.asList("LiangLinWei", "ZhaoYuCheng")).build());
System.out.println(wxCpOaMeetingRoomBookResult);
assertThat(wxCpOaMeetingRoomBookResult).isNotNull();
}
@Test
public void testBookingMeetingRoomBySchedule() throws WxErrorException {
WxCpOaMeetingRoomBookResult wxCpOaMeetingRoomBookResult = this.wxService.getOaMeetingRoomService().bookingMeetingRoomBySchedule(WxCpOaMeetingRoomBookByScheduleRequest.builder()
.booker("LiangLinWei")
.meetingroomId(19)
.schedule_id("bkWChLPrv9YpPRLeeYU-uFwl9BQX3G2_rQYQRg1W1uR3A")
.build());
System.out.println(wxCpOaMeetingRoomBookResult);
assertThat(wxCpOaMeetingRoomBookResult).isNotNull();
}
@Test
public void testBookingMeetingRoomByMeeting() throws WxErrorException {
WxCpOaMeetingRoomBookResult wxCpOaMeetingRoomBookResult = this.wxService.getOaMeetingRoomService().bookingMeetingRoomByMeeting(WxCpOaMeetingRoomBookByMeetingRequest.builder()
.booker("LiangLinWei")
.meetingroomId(19)
.meetingid("bkWChLPrv9YpPRLeeYU-uFwl9BQX3G2_rQYQRg1W1uR3A")
.build());
System.out.println(wxCpOaMeetingRoomBookResult);
assertThat(wxCpOaMeetingRoomBookResult).isNotNull();
}
@Test
public void testCancelBookMeetingRoom() throws WxErrorException {
this.wxService.getOaMeetingRoomService().cancelBookMeetingRoom(WxCpOaMeetingRoomCancelBookRequest.builder().booking_id("bkWChLPrv9YpPRLeeYU-uFwl9BQX3G2_rQYQRg1W1uR3A").build());
}
@Test
public void testGetBookingInfoByBookingId() throws WxErrorException {
WxCpOaMeetingRoomBookingInfoByBookingIdResult bookingInfoByBookingId = this.wxService.getOaMeetingRoomService().getBookingInfoByBookingId(WxCpOaMeetingRoomBookingInfoByBookingIdRequest.builder().meetingroom_id(19).booking_id("bkWChLPrv9YpPRLeeYU-uFwl9BQX3G2_rQYQRg1W1uR3A").build());
System.out.println(bookingInfoByBookingId);
assertThat(bookingInfoByBookingId).isNotNull();
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpMeetingServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpMeetingServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpMeetingService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.meeting.WxCpMeeting;
import me.chanjar.weixin.cp.bean.oa.meeting.WxCpMeetingUpdateResult;
import me.chanjar.weixin.cp.bean.oa.meeting.WxCpUserMeetingIdResult;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertEquals;
/**
* 单元测试类.
*
* @author <a href="https://github.com/wangmeng3486">wangmeng3486</a> created on 2023-02-03
*/
@Test
@Slf4j
@Guice(modules = ApiTestModule.class)
public class WxCpMeetingServiceImplTest {
/**
* The Wx service.
*/
@Inject
private WxCpService wxCpService;
/**
* The Config storage.
*/
@Inject
protected ApiTestModule.WxXmlCpInMemoryConfigStorage configStorage;
/**
* Test
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testAdd() throws WxErrorException {
WxCpMeetingService wxCpMeetingService = this.wxCpService.getMeetingService();
/*
测试 创建会议
*/
long startTime = System.currentTimeMillis() / 1000 + 30 * 60L;
List<String> userIds = Lists.newArrayList(this.configStorage.getUserId(), "lisi");
WxCpMeeting wxCpMeeting = new WxCpMeeting().setAdminUserId(this.configStorage.getUserId()).setTitle("新建会议")
.setMeetingStart(startTime).setMeetingDuration(3600).setDescription("新建会议描述").setLocation("广州媒体港")
.setAttendees(new WxCpMeeting.Attendees().setUserId(userIds))
.setSettings(new WxCpMeeting.Setting().setRemindScope(1).setPassword("1234").setEnableWaitingRoom(false)
.setAllowEnterBeforeHost(true).setEnableEnterMute(1).setAllowExternalUser(false).setEnableScreenWatermark(false)
.setHosts(new WxCpMeeting.Attendees().setUserId(userIds)).setRingUsers(new WxCpMeeting.Attendees().setUserId(userIds)))
.setReminders(new WxCpMeeting.Reminder().setIsRepeat(1).setRepeatType(0).setRepeatUntil(startTime + 24 * 60 * 60L)
.setRepeatInterval(1).setRemindBefore(Lists.newArrayList(0, 900)));
String meetingId = "hyXG0RCQAAogMgFb9Tx_b-1-lhJRWvvg";// wxCpMeetingService.create(wxCpMeeting);
assertThat(meetingId).isNotNull();
/*
测试 获取用户会议列表
*/
wxCpMeeting.setMeetingId(meetingId);
WxCpUserMeetingIdResult wxCpUserMeetingIdResult = wxCpMeetingService.getUserMeetingIds(this.configStorage.getUserId(), null, null, startTime, null);
assertThat(wxCpUserMeetingIdResult.getMeetingIdList()).isNotNull();
log.info("获取用户会议列表: {}", wxCpUserMeetingIdResult.toJson());
/*
测试 修改会议
*/
wxCpMeeting.setTitle("修改会议");
wxCpMeeting.setDescription("修改会议描述");
WxCpMeetingUpdateResult wxCpMeetingUpdateResult = wxCpMeetingService.update(wxCpMeeting);
assertEquals(wxCpMeetingUpdateResult.getErrcode().longValue(), 0L);
/*
测试 获取会议详情
*/
WxCpMeeting wxCpMeetingResult = wxCpMeetingService.getDetail(meetingId);
log.info("获取会议详情: {}", wxCpMeetingResult.toJson());
/*
测试 取消会议
*/
wxCpMeetingService.cancel(meetingId);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpDepartmentServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpDepartmentServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <pre>
* Created by BinaryWang on 2017/6/24.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Guice(modules = ApiTestModule.class)
public class WxCpDepartmentServiceImplTest {
@Inject
private WxCpService wxCpService;
private WxCpDepart depart;
/**
* Test create.
*
* @throws Exception the exception
*/
@Test
public void testCreate() throws Exception {
WxCpDepart cpDepart = new WxCpDepart();
cpDepart.setName("子部门" + System.currentTimeMillis());
cpDepart.setParentId(1L);
cpDepart.setOrder(1L);
Long departId = this.wxCpService.getDepartmentService().create(cpDepart);
System.out.println(departId);
}
/**
* Depart ids object [ ] [ ].
*
* @return the object [ ] [ ]
*/
@DataProvider
public Object[][] departIds() {
return new Object[][]{
{null},
{12L},
{5L}
};
}
/**
* Test list.
*
* @param id the id
* @throws Exception the exception
*/
@Test(dataProvider = "departIds")
public void testList(Long id) throws Exception {
System.out.println("=================获取部门");
List<WxCpDepart> departList = this.wxCpService.getDepartmentService().list(id);
assertThat(departList).isNotEmpty();
for (WxCpDepart g : departList) {
this.depart = g;
System.out.println(this.depart.getId() + ":" + this.depart.getName());
assertThat(g.getName()).isNotBlank();
}
}
/**
* Test update.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = {"testList", "testCreate"})
public void testUpdate() throws Exception {
System.out.println("=================更新部门");
this.depart.setName("子部门改名" + System.currentTimeMillis());
this.wxCpService.getDepartmentService().update(this.depart);
}
/**
* Test delete.
*
* @throws Exception the exception
*/
@Test(dependsOnMethods = "testUpdate")
public void testDelete() throws Exception {
System.out.println("=================删除部门");
System.out.println(this.depart.getId() + ":" + this.depart.getName());
this.wxCpService.getDepartmentService().delete(this.depart.getId());
}
/**
* 获取子部门ID列表
* https://developer.work.weixin.qq.com/document/path/95350
*
* @param id the id
* @throws WxErrorException the wx error exception
*/
@Test(dataProvider = "departIds")
public void testSimpleList(Long id) throws WxErrorException {
System.out.println("=================获取子部门ID列表");
List<WxCpDepart> departList = this.wxCpService.getDepartmentService().simpleList(id);
assertThat(departList).isNotEmpty();
departList.forEach(System.out::println);
}
/**
* Test get.
*
* @param id the id
* @throws WxErrorException the wx error exception
*/
@Test(dataProvider = "departIds")
public void testGet(Long id) throws WxErrorException {
if (id == null) {
return;
}
WxCpDepart depart = this.wxCpService.getDepartmentService().get(id);
assertThat(depart).isNotNull();
System.out.println(depart);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOaScheduleServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpOaScheduleServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.WxCpOaSchedule;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
/**
* 单元测试类.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-12-25
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxCpOaScheduleServiceImplTest {
/**
* The Wx service.
*/
@Inject
protected WxCpService wxService;
/**
* Test add.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testAdd() throws WxErrorException {
this.wxService.getOaScheduleService().add(new WxCpOaSchedule().setOrganizer("userid1")
.setDescription("description").setStartTime(111111111111L).setEndTime(222222222222L)
.setSummary("summary"), null);
}
/**
* Test update.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testUpdate() throws WxErrorException {
this.wxService.getOaScheduleService().update(new WxCpOaSchedule().setScheduleId("2222").setOrganizer("userid1")
.setDescription("description").setStartTime(111111111111L).setEndTime(222222222222L)
.setSummary("summary"));
}
/**
* Test get details.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testGetDetails() throws WxErrorException {
this.wxService.getOaScheduleService().getDetails(Collections.singletonList("11111"));
}
/**
* Test delete.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testDelete() throws WxErrorException {
this.wxService.getOaScheduleService().delete("111");
}
/**
* Test list by calendar.
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testListByCalendar() throws WxErrorException {
this.wxService.getOaScheduleService().listByCalendar("111", null, null);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpIntelligentRobotServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpIntelligentRobotServiceImplTest.java | package me.chanjar.weixin.cp.api.impl;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.bean.intelligentrobot.*;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import javax.inject.Inject;
/**
* 智能机器人接口测试
*
* @author Binary Wang
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxCpIntelligentRobotServiceImplTest {
@Inject
private WxCpService wxCpService;
@Test
public void testCreateRobot() {
// 测试创建智能机器人请求对象创建
WxCpIntelligentRobotCreateRequest request = new WxCpIntelligentRobotCreateRequest();
request.setName("测试机器人");
request.setDescription("这是一个测试的智能机器人");
request.setAvatar("avatar_url");
// 验证JSON序列化
String json = request.toJson();
assert json.contains("测试机器人");
assert json.contains("这是一个测试的智能机器人");
// 验证反序列化
WxCpIntelligentRobotCreateRequest fromJson = WxCpIntelligentRobotCreateRequest.fromJson(json);
assert fromJson.getName().equals("测试机器人");
}
@Test
public void testChatRequest() {
// 测试聊天请求对象创建
WxCpIntelligentRobotChatRequest request = new WxCpIntelligentRobotChatRequest();
request.setRobotId("robot123");
request.setUserid("user123");
request.setMessage("你好,机器人");
request.setSessionId("session123");
// 验证JSON序列化
String json = request.toJson();
assert json.contains("robot123");
assert json.contains("你好,机器人");
// 验证反序列化
WxCpIntelligentRobotChatRequest fromJson = WxCpIntelligentRobotChatRequest.fromJson(json);
assert fromJson.getRobotId().equals("robot123");
assert fromJson.getMessage().equals("你好,机器人");
}
@Test
public void testUpdateRequest() {
// 测试更新请求对象创建
WxCpIntelligentRobotUpdateRequest request = new WxCpIntelligentRobotUpdateRequest();
request.setRobotId("robot123");
request.setName("更新后的机器人");
request.setDescription("更新后的描述");
request.setStatus(1);
// 验证JSON序列化
String json = request.toJson();
assert json.contains("robot123");
assert json.contains("更新后的机器人");
// 验证反序列化
WxCpIntelligentRobotUpdateRequest fromJson = WxCpIntelligentRobotUpdateRequest.fromJson(json);
assert fromJson.getRobotId().equals("robot123");
assert fromJson.getName().equals("更新后的机器人");
assert fromJson.getStatus().equals(1);
}
@Test
public void testServiceIntegration() {
// 验证服务可以正确获取
assert this.wxCpService.getIntelligentRobotService() != null;
assert this.wxCpService.getIntelligentRobotService() instanceof WxCpIntelligentRobotServiceImpl;
}
@Test
public void testSendMessageRequest() {
// 测试主动发送消息请求对象创建
WxCpIntelligentRobotSendMessageRequest request = new WxCpIntelligentRobotSendMessageRequest();
request.setRobotId("robot123");
request.setUserid("user123");
request.setMessage("您好,这是来自智能机器人的主动消息");
request.setSessionId("session123");
request.setMsgId("msg123");
// 验证JSON序列化
String json = request.toJson();
assert json.contains("robot123");
assert json.contains("您好,这是来自智能机器人的主动消息");
assert json.contains("session123");
// 验证反序列化
WxCpIntelligentRobotSendMessageRequest fromJson = WxCpIntelligentRobotSendMessageRequest.fromJson(json);
assert fromJson.getRobotId().equals("robot123");
assert fromJson.getMessage().equals("您好,这是来自智能机器人的主动消息");
assert fromJson.getSessionId().equals("session123");
}
@Test
public void testSendMessageResponse() {
// 测试主动发送消息响应对象
String responseJson = "{\"errcode\":0,\"errmsg\":\"ok\",\"msg_id\":\"msg123\",\"session_id\":\"session123\"}";
WxCpIntelligentRobotSendMessageResponse response = WxCpIntelligentRobotSendMessageResponse.fromJson(responseJson);
assert response.getMsgId().equals("msg123");
assert response.getSessionId().equals("session123");
assert response.getErrcode() == 0;
}
} | java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpTpXmlPackageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpTpXmlPackageTest.java | package me.chanjar.weixin.cp.bean;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* .
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2019-08-18
*/
public class WxCpTpXmlPackageTest {
/**
* Test from xml.
*/
@Test
public void testFromXml() {
WxCpTpXmlPackage result = WxCpTpXmlPackage.fromXml("<xml> \n" +
" <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
" <AgentID><![CDATA[toAgentID]]></AgentID>\n" +
" <Encrypt><![CDATA[msg_encrypt]]></Encrypt>\n" +
"</xml>\n");
assertThat(result).isNotNull();
assertThat(result.getToUserName()).isEqualTo("toUser");
assertThat(result.getAgentId()).isEqualTo("toAgentID");
assertThat(result.getMsgEncrypt()).isEqualTo("msg_encrypt");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpAgentTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpAgentTest.java | package me.chanjar.weixin.cp.bean;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Created by huansinho on 2018/4/13.
*/
@Test
public class WxCpAgentTest {
/**
* Test deserialize.
*/
public void testDeserialize() {
String json = "{\"errcode\": 0,\"errmsg\": \"ok\",\"agentid\": 9,\"name\": \"测试应用\"," +
"\"square_logo_url\": \"http://wx.qlogo.cn/mmhead/alksjf;lasdjf;lasjfuodiuj3rj2o34j/0\"," +
"\"description\": \"这是一个企业号应用\",\"allow_userinfos\": {\"user\": [{\"userid\": \"0009854\"}," +
" {\"userid\": \"1723\"}, {\"userid\": \"5625\"}]},\"allow_partys\": {\"partyid\": [42762742]}," +
"\"allow_tags\": {\"tagid\": [23, 22, 35, 19, 32, 125, 133, 46, 150, 38, 183, 9, 7]}," +
"\"close\": 0,\"redirect_domain\": \"weixin.com.cn\",\"report_location_flag\": 0," +
"\"isreportenter\": 0,\"home_url\": \"\"}";
WxCpAgent wxCpAgent = WxCpAgent.fromJson(json);
Assert.assertEquals(9, wxCpAgent.getAgentId().intValue());
Assert.assertEquals(new Integer[]{42762742}, wxCpAgent.getAllowParties().getPartyIds().toArray());
Assert.assertEquals(new Integer[]{23, 22, 35, 19, 32, 125, 133, 46, 150, 38, 183, 9, 7},
wxCpAgent.getAllowTags().getTagIds().toArray());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/oa/WxCpOaApprovalTemplateResultTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/oa/WxCpOaApprovalTemplateResultTest.java | package me.chanjar.weixin.cp.bean.oa;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class WxCpOaApprovalTemplateResultTest {
@Test
public void testFromJson() {
String json = "{\n"
+ " \"errcode\": 0,\n"
+ " \"errmsg\": \"ok\",\n"
+ " \"template_names\": [\n"
+ " {\n"
+ " \"text\": \"智能印章\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Company Seal\",\n"
+ " \"lang\": \"en\"\n"
+ " }\n"
+ " ],\n"
+ " \"template_content\": {\n"
+ " \"controls\": [\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Text\",\n"
+ " \"id\": \"Text-1747127819114\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"用印事由\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 1,\n"
+ " \"un_print\": 0,\n"
+ " \"inner_id\": \"\",\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Selector\",\n"
+ " \"id\": \"Selector-1747123508806\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"用印类型\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 1,\n"
+ " \"un_print\": 0,\n"
+ " \"inner_id\": \"\",\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " },\n"
+ " \"config\": {\n"
+ " \"selector\": {\n"
+ " \"type\": \"single\",\n"
+ " \"options\": [\n"
+ " {\n"
+ " \"key\": \"option-1747123508806\",\n"
+ " \"value\": [\n"
+ " {\n"
+ " \"text\": \"一般事务性用印\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ]\n"
+ " },\n"
+ " {\n"
+ " \"key\": \"option-1747123508807\",\n"
+ " \"value\": [\n"
+ " {\n"
+ " \"text\": \"对外事务性用印\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ]\n"
+ " },\n"
+ " {\n"
+ " \"key\": \"option-1747123530814\",\n"
+ " \"value\": [\n"
+ " {\n"
+ " \"text\": \"重大事务性用印\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ],\n"
+ " \"op_relations\": [],\n"
+ " \"external_option\": {\n"
+ " \"use_external_option\": false,\n"
+ " \"external_url\": \"\"\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Tips\",\n"
+ " \"id\": \"Tips-1747123397470\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"说明\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [],\n"
+ " \"require\": 0,\n"
+ " \"un_print\": 0,\n"
+ " \"inner_id\": \"\",\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " },\n"
+ " \"config\": {\n"
+ " \"tips\": {\n"
+ " \"tips_content\": [\n"
+ " {\n"
+ " \"text\": {\n"
+ " \"sub_text\": [\n"
+ " {\n"
+ " \"type\": 1,\n"
+ " \"content\": {\n"
+ " \"plain_text\": {\n"
+ " \"content\": \"用印类型说明:1. 一般事务性用印:内部日常材料流转、常规业务报表报送、非对外承诺性质的证明文件,用印文件内容不得涉及经济、法律责任条款 \"\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " ]\n"
+ " },\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Table\",\n"
+ " \"id\": \"Table-1746005041962\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"印章明细\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 0,\n"
+ " \"un_print\": 0,\n"
+ " \"inner_id\": \"\",\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " },\n"
+ " \"config\": {\n"
+ " \"table\": {\n"
+ " \"children\": [\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Text\",\n"
+ " \"id\": \"Text-1747127691499\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"印章名称\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"请输入“公章”\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 1,\n"
+ " \"un_print\": 0,\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Number\",\n"
+ " \"id\": \"Number-1746006598992\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"普通用印\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"请填写正文用印次数\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 1,\n"
+ " \"un_print\": 0,\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Number\",\n"
+ " \"id\": \"Number-1746006601002\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"骑缝用印\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"请填写骑缝用印次数\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 1,\n"
+ " \"un_print\": 0,\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Selector\",\n"
+ " \"id\": \"Selector-1746005136537\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"是否外借\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 0,\n"
+ " \"un_print\": 0,\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " },\n"
+ " \"config\": {\n"
+ " \"selector\": {\n"
+ " \"type\": \"single\",\n"
+ " \"exp_type\": 0,\n"
+ " \"options\": [\n"
+ " {\n"
+ " \"key\": \"option-1746005136537\",\n"
+ " \"value\": [\n"
+ " {\n"
+ " \"text\": \"是\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ]\n"
+ " },\n"
+ " {\n"
+ " \"key\": \"option-1746005136538\",\n"
+ " \"value\": [\n"
+ " {\n"
+ " \"text\": \"否\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ],\n"
+ " \"op_relations\": [],\n"
+ " \"external_option\": {\n"
+ " \"use_external_option\": false,\n"
+ " \"external_url\": \"\"\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Date\",\n"
+ " \"id\": \"Date-1746005165574\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"外借开始时间\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 0,\n"
+ " \"un_print\": 0,\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " },\n"
+ " \"config\": {\n"
+ " \"date\": {\n"
+ " \"type\": \"day\"\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"Date\",\n"
+ " \"id\": \"Date-1746005173386\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"外借结束时间\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 0,\n"
+ " \"un_print\": 0,\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " },\n"
+ " \"config\": {\n"
+ " \"date\": {\n"
+ " \"type\": \"day\"\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " ],\n"
+ " \"stat_field\": [],\n"
+ " \"sum_field\": [],\n"
+ " \"print_format\": 0\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"property\": {\n"
+ " \"control\": \"File\",\n"
+ " \"id\": \"item-1494250388062\",\n"
+ " \"title\": [\n"
+ " {\n"
+ " \"text\": \"用印文件\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Attachment\",\n"
+ " \"lang\": \"en\"\n"
+ " }\n"
+ " ],\n"
+ " \"placeholder\": [\n"
+ " {\n"
+ " \"text\": \"\",\n"
+ " \"lang\": \"zh_CN\"\n"
+ " }\n"
+ " ],\n"
+ " \"require\": 1,\n"
+ " \"un_print\": 0,\n"
+ " \"inner_id\": \"\",\n"
+ " \"un_replace\": 0,\n"
+ " \"display\": 1\n"
+ " }\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ "}";
WxCpOaApprovalTemplateResult templateDetail = WxCpGsonBuilder.create().fromJson(json, WxCpOaApprovalTemplateResult.class);
System.out.println(templateDetail);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/oa/WxCpOaApplyEventRequestTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/oa/WxCpOaApplyEventRequestTest.java | package me.chanjar.weixin.cp.bean.oa;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.bean.oa.applydata.ApplyDataContent;
import me.chanjar.weixin.cp.bean.oa.applydata.ContentValue;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 测试.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-07-18
*/
public class WxCpOaApplyEventRequestTest {
/**
* Test to json.
*/
@Test
public void testToJson() {
String json = "{\n" +
" \"creator_userid\": \"WangXiaoMing\",\n" +
" \"template_id\": \"3Tka1eD6v6JfzhDMqPd3aMkFdxqtJMc2ZRioeFXkaaa\",\n" +
" \"use_template_approver\":0,\n" +
" \"approver\": [\n" +
" {\n" +
" \"attr\": 2,\n" +
" \"userid\": [\"WuJunJie\",\"WangXiaoMing\"]\n" +
" },\n" +
" {\n" +
" \"attr\": 1,\n" +
" \"userid\": [\"LiuXiaoGang\"]\n" +
" }\n" +
" ],\n" +
" \"notifyer\":[ \"WuJunJie\",\"WangXiaoMing\" ],\n" +
" \"notify_type\" : 1,\n" +
" \"apply_data\": {\n" +
" \"contents\": [\n" +
" {\n" +
" \"control\": \"Text\",\n" +
" \"id\": \"Text-15111111111\",\n" +
" \"value\": {\n" +
" \"text\": \"文本填写的内容\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"summary_list\": [\n" +
" {\n" +
" \"summary_info\": [{\n" +
" \"text\": \"摘要第1行\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }]\n" +
" },\n" +
" {\n" +
" \"summary_info\": [{\n" +
" \"text\": \"摘要第2行\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }]\n" +
" },\n" +
" {\n" +
" \"summary_info\": [{\n" +
" \"text\": \"摘要第3行\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }]\n" +
" }\n" +
" ]\n" +
"}";
WxCpOaApplyEventRequest request = new WxCpOaApplyEventRequest();
request.setCreatorUserId("WangXiaoMing")
.setTemplateId("3Tka1eD6v6JfzhDMqPd3aMkFdxqtJMc2ZRioeFXkaaa")
.setUseTemplateApprover(0)
.setApprovers(Arrays.asList(new WxCpOaApplyEventRequest.Approver().setAttr(2).setUserIds(new String[]{"WuJunJie"
, "WangXiaoMing"}),
new WxCpOaApplyEventRequest.Approver().setAttr(1).setUserIds(new String[]{"LiuXiaoGang"})))
.setNotifiers(new String[]{"WuJunJie", "WangXiaoMing"})
.setNotifyType(1)
.setApplyData(new WxCpOaApplyEventRequest.ApplyData()
.setContents(Collections.singletonList(new ApplyDataContent()
.setControl("Text").setId("Text-15111111111").setValue(new ContentValue().setText("文本填写的内容")))))
.setSummaryList(Arrays.asList(new SummaryInfo()
.setSummaryInfoData(Collections.singletonList(new SummaryInfo.SummaryInfoData().setLang("zh_CN").setText(
"摘要第1行"))),
new SummaryInfo()
.setSummaryInfoData(Collections.singletonList(new SummaryInfo.SummaryInfoData().setLang("zh_CN").setText(
"摘要第2行"))),
new SummaryInfo()
.setSummaryInfoData(Collections.singletonList(new SummaryInfo.SummaryInfoData().setLang("zh_CN").setText(
"摘要第3行")))))
;
assertThat(request.toJson()).isEqualTo(GsonParser.parse(json).toString());
}
/**
* Test to json with process.
*/
@Test
public void testToJsonWithProcess() {
String json = "{\n" +
" \"creator_userid\": \"WangXiaoMing\",\n" +
" \"template_id\": \"3Tka1eD6v6JfzhDMqPd3aMkFdxqtJMc2ZRioeFXkaaa\",\n" +
" \"use_template_approver\":0,\n" +
" \"process\": {\n" +
" \"node_list\": [\n" +
" {\n" +
" \"type\": 1,\n" +
" \"apv_rel\": 2,\n" +
" \"userid\": [\"WuJunJie\",\"WangXiaoMing\"]\n" +
" },\n" +
" {\n" +
" \"type\": 1,\n" +
" \"apv_rel\": 1,\n" +
" \"userid\": [\"LiuXiaoGang\"]\n" +
" },\n" +
" {\n" +
" \"type\": 2,\n" +
" \"userid\": [\"ZhangSan\",\"LiSi\"]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"apply_data\": {\n" +
" \"contents\": [\n" +
" {\n" +
" \"control\": \"Text\",\n" +
" \"id\": \"Text-15111111111\",\n" +
" \"value\": {\n" +
" \"text\": \"文本填写的内容\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"summary_list\": [\n" +
" {\n" +
" \"summary_info\": [{\n" +
" \"text\": \"摘要第1行\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }]\n" +
" },\n" +
" {\n" +
" \"summary_info\": [{\n" +
" \"text\": \"摘要第2行\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }]\n" +
" },\n" +
" {\n" +
" \"summary_info\": [{\n" +
" \"text\": \"摘要第3行\",\n" +
" \"lang\": \"zh_CN\"\n" +
" }]\n" +
" }\n" +
" ]\n" +
"}";
WxCpOaApplyEventRequest request = new WxCpOaApplyEventRequest();
request.setCreatorUserId("WangXiaoMing")
.setTemplateId("3Tka1eD6v6JfzhDMqPd3aMkFdxqtJMc2ZRioeFXkaaa")
.setUseTemplateApprover(0)
.setProcess(new WxCpOaApplyEventRequest.Process()
.setNodeList(Arrays.asList(
new WxCpOaApplyEventRequest.ProcessNode()
.setType(1)
.setApvRel(2)
.setUserIds(new String[]{"WuJunJie", "WangXiaoMing"}),
new WxCpOaApplyEventRequest.ProcessNode()
.setType(1)
.setApvRel(1)
.setUserIds(new String[]{"LiuXiaoGang"}),
new WxCpOaApplyEventRequest.ProcessNode()
.setType(2)
.setUserIds(new String[]{"ZhangSan", "LiSi"})
)))
.setApplyData(new WxCpOaApplyEventRequest.ApplyData()
.setContents(Collections.singletonList(new ApplyDataContent()
.setControl("Text").setId("Text-15111111111").setValue(new ContentValue().setText("文本填写的内容")))))
.setSummaryList(Arrays.asList(new SummaryInfo()
.setSummaryInfoData(Collections.singletonList(new SummaryInfo.SummaryInfoData().setLang("zh_CN").setText(
"摘要第1行"))),
new SummaryInfo()
.setSummaryInfoData(Collections.singletonList(new SummaryInfo.SummaryInfoData().setLang("zh_CN").setText(
"摘要第2行"))),
new SummaryInfo()
.setSummaryInfoData(Collections.singletonList(new SummaryInfo.SummaryInfoData().setLang("zh_CN").setText(
"摘要第3行")))))
;
assertThat(request.toJson()).isEqualTo(GsonParser.parse(json).toString());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/oa/calendar/WxCpOaCalendarTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/oa/calendar/WxCpOaCalendarTest.java | package me.chanjar.weixin.cp.bean.oa.calendar;
import me.chanjar.weixin.common.util.json.GsonParser;
import org.testng.annotations.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 单元测试.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-09-20
*/
public class WxCpOaCalendarTest {
/**
* Test to json.
*/
@Test
public void testToJson() {
String json = "{\n" +
" \"calendar\" : {\n" +
" \"organizer\" : \"userid1\",\n" +
" \"readonly\" : 1,\n" +
" \"set_as_default\" : 1,\n" +
" \"summary\" : \"test_summary\",\n" +
" \"color\" : \"#FF3030\",\n" +
" \"description\" : \"test_describe\",\n" +
" \"shares\" : [\n" +
" {\n" +
" \"userid\" : \"userid2\"\n" +
" },\n" +
" {\n" +
" \"userid\" : \"userid3\",\n" +
" \"readonly\" : 1\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n";
assertThat(WxCpOaCalendar.builder()
.organizer("userid1")
.readonly(1)
.setAsDefault(1)
.summary("test_summary")
.color("#FF3030")
.description("test_describe")
.shares(Arrays.asList(new WxCpOaCalendar.ShareInfo("userid2", null),
new WxCpOaCalendar.ShareInfo("userid3", 1)))
.build().toJson())
.isEqualTo(GsonParser.parse(json).toString());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/external/WxCpUpdateRemarkRequestTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/external/WxCpUpdateRemarkRequestTest.java | package me.chanjar.weixin.cp.bean.external;
import me.chanjar.weixin.common.util.json.GsonParser;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 单元测试.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-09-20
*/
public class WxCpUpdateRemarkRequestTest {
/**
* Test to json.
*/
@Test
public void testToJson() {
String json = "{\n" +
" \"userid\":\"zhangsan\",\n" +
" \"external_userid\":\"woAJ2GCAAAd1asdasdjO4wKmE8Aabj9AAA\",\n" +
" \"remark\":\"备注信息\",\n" +
" \"description\":\"描述信息\",\n" +
" \"remark_company\":\"腾讯科技\",\n" +
" \"remark_mobiles\":[\n" +
" \"13800000001\",\n" +
" \"13800000002\"\n" +
" ],\n" +
" \"remark_pic_mediaid\":\"MEDIAID\"\n" +
"}\n";
WxCpUpdateRemarkRequest request = WxCpUpdateRemarkRequest.builder()
.description("描述信息")
.userId("zhangsan")
.externalUserId("woAJ2GCAAAd1asdasdjO4wKmE8Aabj9AAA")
.remark("备注信息")
.remarkCompany("腾讯科技")
.remarkMobiles(new String[]{"13800000001", "13800000002"})
.remarkPicMediaId("MEDIAID")
.build();
assertThat(request.toJson()).isEqualTo(GsonParser.parse(json).toString());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/external/WxCpUserExternalContactInfoTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/external/WxCpUserExternalContactInfoTest.java | package me.chanjar.weixin.cp.bean.external;
import com.google.gson.reflect.TypeToken;
import lombok.val;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.external.contact.ExternalContact;
import me.chanjar.weixin.cp.bean.external.contact.FollowedUser;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import org.testng.annotations.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <pre>
*
* Created by Binary Wang on 2018/9/16.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
public class WxCpUserExternalContactInfoTest {
/**
* Test from json.
*/
@Test
public void testFromJson() {
final String json = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"external_contact\": {\n" +
" \"external_userid\": \"woAJ2GCAAAXtWyujaWJHDDGi0mACH71w\",\n" +
" \"name\": \"李四\",\n" +
" \"position\": \"Mangaer\",\n" +
" \"avatar\": \"http://p.qlogo.cn/bizmail/IcsdgagqefergqerhewSdage/0\",\n" +
" \"corp_name\": \"腾讯\",\n" +
" \"corp_full_name\": \"腾讯科技有限公司\",\n" +
" \"type\": 2,\n" +
" \"gender\": 1,\n" +
" \"unionid\": \"ozynqsulJFCZ2z1aYeS8h-nuasdfR1\",\n" +
" \"external_profile\": {\n" +
" \"external_attr\": [\n" +
" {\n" +
" \"type\": 0,\n" +
" \"name\": \"文本名称\",\n" +
" \"text\": {\n" +
" \"value\": \"文本\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\": 1,\n" +
" \"name\": \"网页名称\",\n" +
" \"web\": {\n" +
" \"url\": \"http://www.test.com\",\n" +
" \"title\": \"标题\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\": 2,\n" +
" \"name\": \"测试app\",\n" +
" \"miniprogram\": {\n" +
" \"appid\": \"wx8bd80126147df384\",\n" +
" \"pagepath\": \"/index\",\n" +
" \"title\": \"my miniprogram\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" \"follow_user\": [\n" +
" {\n" +
" \"userid\": \"rocky\",\n" +
" \"remark\": \"李部长\",\n" +
" \"description\": \"对接采购事物\",\n" +
" \"createtime\": 1525779812,\n" +
" \"wechat_channels\": {\n" +
" \"nickname\": \"视频号名称\",\n" +
" \"source\": 1\n" +
" }" +
" },\n" +
" {\n" +
" \"userid\": \"tommy\",\n" +
" \"remark\": \"李总\",\n" +
" \"description\": \"采购问题咨询\",\n" +
" \"createtime\": 1525881637\n" +
" }\n" +
" ]\n" +
"}";
final String testJson = "{\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"department\": [\n" +
" {\n" +
" \"id\": 2,\n" +
" \"name\": \"广州研发中心\",\n" +
" \"name_en\": \"RDGZ\",\n" +
" \"department_leader\":[\"zhangsan\",\"lisi\"],\n" +
" \"parentid\": 1,\n" +
" \"order\": 10\n" +
" },\n" +
" {\n" +
" \"id\": 3,\n" +
" \"name\": \"邮箱产品部\",\n" +
" \"name_en\": \"mail\",\n" +
" \"department_leader\":[\"lisi\",\"wangwu\"],\n" +
" \"parentid\": 2,\n" +
" \"order\": 40\n" +
" }\n" +
" ]\n" +
"}\n";
// 测试序列化
val depart = new WxCpDepart();
depart.setId(8L);
depart.setName("name");
depart.setEnName("enName");
depart.setDepartmentLeader(new String[]{"zhangsan", "lisi"});
depart.setParentId(88L);
depart.setOrder(99L);
String toJson = depart.toJson();
// 测试企业微信字段返回
List<WxCpDepart> department = WxCpGsonBuilder.create().fromJson(GsonParser.parse(testJson).get("department"),
new TypeToken<List<WxCpDepart>>() {
}.getType());
final WxCpExternalContactInfo contactInfo = WxCpExternalContactInfo.fromJson(json);
assertThat(contactInfo).isNotNull();
assertThat(contactInfo.getExternalContact()).isNotNull();
assertThat(contactInfo.getExternalContact().getExternalUserId()).isEqualTo("woAJ2GCAAAXtWyujaWJHDDGi0mACH71w");
assertThat(contactInfo.getExternalContact().getPosition()).isEqualTo("Mangaer");
assertThat(contactInfo.getExternalContact().getAvatar()).isEqualTo("http://p.qlogo" +
".cn/bizmail/IcsdgagqefergqerhewSdage/0");
assertThat(contactInfo.getExternalContact().getCorpName()).isEqualTo("腾讯");
assertThat(contactInfo.getExternalContact().getCorpFullName()).isEqualTo("腾讯科技有限公司");
assertThat(contactInfo.getExternalContact().getType()).isEqualTo(2);
assertThat(contactInfo.getExternalContact().getGender()).isEqualTo(1);
assertThat(contactInfo.getExternalContact().getUnionId()).isEqualTo("ozynqsulJFCZ2z1aYeS8h-nuasdfR1");
assertThat(contactInfo.getExternalContact().getName()).isEqualTo("李四");
assertThat(contactInfo.getExternalContact().getExternalProfile()).isNotNull();
final List<ExternalContact.ExternalAttribute> externalAttrs =
contactInfo.getExternalContact().getExternalProfile().getExternalAttrs();
assertThat(externalAttrs).isNotEmpty();
final ExternalContact.ExternalAttribute externalAttr1 = externalAttrs.get(0);
assertThat(externalAttr1.getType()).isEqualTo(0);
assertThat(externalAttr1.getName()).isEqualTo("文本名称");
assertThat(externalAttr1.getText().getValue()).isEqualTo("文本");
final ExternalContact.ExternalAttribute externalAttr2 = externalAttrs.get(1);
assertThat(externalAttr2.getType()).isEqualTo(1);
assertThat(externalAttr2.getName()).isEqualTo("网页名称");
assertThat(externalAttr2.getWeb().getUrl()).isEqualTo("http://www.test.com");
assertThat(externalAttr2.getWeb().getTitle()).isEqualTo("标题");
final ExternalContact.ExternalAttribute externalAttr3 = externalAttrs.get(2);
assertThat(externalAttr3.getType()).isEqualTo(2);
assertThat(externalAttr3.getName()).isEqualTo("测试app");
assertThat(externalAttr3.getMiniProgram().getAppid()).isEqualTo("wx8bd80126147df384");
assertThat(externalAttr3.getMiniProgram().getPagePath()).isEqualTo("/index");
assertThat(externalAttr3.getMiniProgram().getTitle()).isEqualTo("my miniprogram");
List<FollowedUser> followedUsers = contactInfo.getFollowedUsers();
assertThat(followedUsers).isNotEmpty();
assertThat(followedUsers.get(0).getUserId()).isEqualTo("rocky");
assertThat(followedUsers.get(0).getRemark()).isEqualTo("李部长");
assertThat(followedUsers.get(0).getDescription()).isEqualTo("对接采购事物");
assertThat(followedUsers.get(0).getCreateTime()).isEqualTo(1525779812);
assertThat(followedUsers.get(0).getWechatChannels().getNickname()).isEqualTo("视频号名称");
assertThat(followedUsers.get(0).getWechatChannels().getSource()).isEqualTo(1);
assertThat(followedUsers.get(1).getUserId()).isEqualTo("tommy");
assertThat(followedUsers.get(1).getRemark()).isEqualTo("李总");
assertThat(followedUsers.get(1).getDescription()).isEqualTo("采购问题咨询");
assertThat(followedUsers.get(1).getCreateTime()).isEqualTo(1525881637);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/external/contact/WxCpGroupMsgResultTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/external/contact/WxCpGroupMsgResultTest.java | package me.chanjar.weixin.cp.bean.external.contact;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* The type Wx cp group msg result test.
*/
public class WxCpGroupMsgResultTest {
/**
* Test to json.
*/
@Test
public void testToJson() {
/*
@see https://work.weixin.qq.com/api/doc/16251
*/
String json = "{ " +
"\"errcode\": 0, " +
"\"errmsg\": \"ok\", " +
"\"detail_list\": [ " +
" { " +
" \"external_userid\": \"wmqfasd1e19278asdasAAAA\", " +
" \"chat_id\":\"wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA\", " +
" \"userid\": \"zhangsan\", " +
" \"status\": 1, " +
" \"send_time\": 1552536375 " +
" } " +
" ] " +
"}";
WxCpGroupMsgResult result = WxCpGroupMsgResult.fromJson(json);
assertThat(result.getDetailList().size()).isEqualTo(1);
WxCpGroupMsgResult.ExternalContactGroupMsgDetailInfo detail = result.getDetailList().get(0);
assertThat(detail.getChatId()).isEqualTo("wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA");
assertThat(detail.getExternalUserId()).isEqualTo("wmqfasd1e19278asdasAAAA");
assertThat(detail.getUserId()).isEqualTo("zhangsan");
assertThat(detail.getStatus()).isEqualTo(1);
assertThat(detail.getSendTime()).isEqualTo(1552536375L);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/TemplateCardMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/TemplateCardMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import com.google.common.collect.Lists;
import me.chanjar.weixin.common.util.json.GsonParser;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 测试用例中的json参考 <a href="https://developer.work.weixin.qq.com/document/path/94888">https://developer.work.weixin.qq.com/document/path/94888</a>
* <br>
* created on 2024-10-22
*/
public class TemplateCardMessageTest {
/**
* Test to json video.
*/
@Test
public void testToJson() {
TemplateCardMessage templateCardMessage = new TemplateCardMessage();
templateCardMessage.setAgentid(0);
templateCardMessage.setUserids(Lists.newArrayList("userid1", "userid2"));
templateCardMessage.setResponseCode("xihrjiohewirfhwripsiqwjerdio_dhweu");
TemplateCardMessage.TemplateCardDTO templateCardDTO = new TemplateCardMessage.TemplateCardDTO();
templateCardMessage.setTemplateCard(templateCardDTO);
TemplateCardMessage.TemplateCardDTO.SelectListDTO selectListDTO = new TemplateCardMessage.TemplateCardDTO.SelectListDTO();
selectListDTO.setSelectedId("id");
selectListDTO.setQuestionKey("question");
templateCardDTO.setSelectList(Lists.newArrayList(selectListDTO));
final String json = templateCardMessage.toJson();
System.out.println(json);
String expectedJson = "{\"userids\":[\"userid1\",\"userid2\"],\"agentid\":0,\"response_code\":\"xihrjiohewirfhwripsiqwjerdio_dhweu\",\"template_card\":{\"select_list\":[{\"question_key\":\"question\",\"selected_id\":\"id\"}]}}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpTpXmlMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpTpXmlMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* The type Wx cp tp xml message test.
*/
public class WxCpTpXmlMessageTest {
/**
* Test user notify xml.
*/
@Test
public void testUserNotifyXML() {
String xml = "<xml>\n" +
" <SuiteId><![CDATA[ww4asffe99e54c0f4c]]></SuiteId>\n" +
" <AuthCorpId><![CDATA[wxf8b4f85f3axxxxxx]]></AuthCorpId>\n" +
" <InfoType><![CDATA[change_contact]]></InfoType>\n" +
" <TimeStamp>1403610513</TimeStamp>\n" +
" <ChangeType><![CDATA[create_user]]></ChangeType>\n" +
" <UserID><![CDATA[zhangsan]]></UserID>\n" +
" <Name><![CDATA[张三]]></Name>\n" +
" <Department><![CDATA[1,2,3]]></Department>\n" +
" <MainDepartment>1</MainDepartment>\n" +
" <IsLeaderInDept><![CDATA[1,0,0]]></IsLeaderInDept>\n" +
" <Mobile><![CDATA[11111111111]]></Mobile>\n" +
" <Position><![CDATA[产品经理]]></Position>\n" +
" <Gender>1</Gender>\n" +
" <Email><![CDATA[zhangsan@xxx.com]]></Email>\n" +
" <Avatar><![CDATA[http://wx.qlogo" +
".cn/mmopen/ajNVdqHZLLA3WJ6DSZUfiakYe37PKnQhBIeOQBO4czqrnZDS79FH5Wm5m4X69TBicnHFlhiafvDwklOpZeXYQQ2icg/0" +
"]]></Avatar>\n" +
" <Alias><![CDATA[zhangsan]]></Alias>\n" +
" <Telephone><![CDATA[020-111111]]></Telephone>\n" +
" <ExtAttr>\n" +
" <Item>\n" +
" <Name><![CDATA[爱好]]></Name>\n" +
" <Type>0</Type>\n" +
" <Text>\n" +
" <Value><![CDATA[旅游]]></Value>\n" +
" </Text>\n" +
" </Item>\n" +
" <Item>\n" +
" <Name><![CDATA[卡号]]></Name>\n" +
" <Type>1</Type>\n" +
" <Web>\n" +
" <Title><![CDATA[企业微信]]></Title>\n" +
" <Url><![CDATA[https://work.weixin.qq.com]]></Url>\n" +
" </Web>\n" +
" </Item>\n" +
" </ExtAttr>\n" +
"</xml>";
WxCpTpXmlMessage wxXmlMessage = WxCpTpXmlMessage.fromXml(xml);
assertEquals(wxXmlMessage.getSuiteId(), "ww4asffe99e54c0f4c");
assertEquals(wxXmlMessage.getPosition(), "产品经理");
assertEquals(wxXmlMessage.getGender(), Integer.valueOf(1));
assertEquals(wxXmlMessage.getTelephone(), "020-111111");
}
/**
* Test register corp.
*/
@Test
public void testRegisterCorp() {
String xml = "<xml>\n" +
" <ServiceCorpId><![CDATA[wwddddccc7775555aab]]></ServiceCorpId>\n" +
" <InfoType><![CDATA[register_corp]]></InfoType>\n" +
" <TimeStamp>1502682173</TimeStamp>\n" +
" <RegisterCode><![CDATA[pIKi3wRPNWCGF-pyP-YU5KWjDDD]]></RegisterCode>\n" +
" <AuthCorpId><![CDATA[wwddddccc7775555aaa]]></AuthCorpId>\n" +
" <ContactSync>\n" +
" <AccessToken><![CDATA[accesstoken000001]]></AccessToken>\n" +
" <ExpiresIn>1800</ExpiresIn>\n" +
" </ContactSync>\n" +
" <AuthUserInfo>\n" +
" <UserId><![CDATA[zhangshan]]></UserId>\n" +
" </AuthUserInfo>\n" +
" <State><![CDATA[state1]]></State>\n" +
" <TemplateId><![CDATA[tpl1test]]></TemplateId>\n" +
"</xml>";
WxCpTpXmlMessage wxXmlMessage = WxCpTpXmlMessage.fromXml(xml);
assertEquals(wxXmlMessage.getServiceCorpId(), "wwddddccc7775555aab");
assertEquals(wxXmlMessage.getInfoType(), "register_corp");
assertEquals(wxXmlMessage.getRegisterCode(), "pIKi3wRPNWCGF-pyP-YU5KWjDDD");
assertNotNull(wxXmlMessage.getContactSync());
assertEquals(wxXmlMessage.getContactSync().getAccessToken(), "accesstoken000001");
assertEquals(wxXmlMessage.getContactSync().getExpiresIn(), Integer.valueOf(1800));
assertNotNull(wxXmlMessage.getAuthUserInfo());
assertEquals(wxXmlMessage.getAuthUserInfo().getUserId(), "zhangshan");
assertEquals(wxXmlMessage.getTemplateId(), "tpl1test");
}
/**
* Tag notify test.
*/
@Test
public void tagNotifyTest() {
String xml = "<xml>\n" +
" <SuiteId><![CDATA[ww4asffe99e54cxxxx]]></SuiteId>\n" +
" <AuthCorpId><![CDATA[wxf8b4f85f3a79xxxx]]></AuthCorpId>\n" +
" <InfoType><![CDATA[change_contact]]></InfoType>\n" +
" <TimeStamp>1403610513</TimeStamp>\n" +
" <ChangeType><![CDATA[update_tag]]></ChangeType>\n" +
" <TagId>1</TagId>\n" +
" <AddUserItems><![CDATA[zhangsan,lisi]]></AddUserItems>\n" +
" <DelUserItems><![CDATA[zhangsan1,lisi1]]></DelUserItems>\n" +
" <AddPartyItems><![CDATA[1,2]]></AddPartyItems>\n" +
" <DelPartyItems><![CDATA[3,4]]></DelPartyItems>\n" +
"</xml>";
WxCpTpXmlMessage wxXmlMessage = WxCpTpXmlMessage.fromXml(xml);
assertEquals(wxXmlMessage.getTagId(), Integer.valueOf(1));
assertNotNull(wxXmlMessage.getAddUserItems());
assertEquals(wxXmlMessage.getAddUserItems()[0], "zhangsan");
assertEquals(wxXmlMessage.getAddUserItems()[1], "lisi");
assertNotNull(wxXmlMessage.getDelUserItems());
assertNotNull(wxXmlMessage.getDelUserItems()[0], "zhangsan1");
assertNotNull(wxXmlMessage.getDelUserItems()[0], "lisi1");
assertNotNull(wxXmlMessage.getAddPartyItems());
assertEquals(wxXmlMessage.getAddPartyItems()[0], Integer.valueOf(1));
assertEquals(wxXmlMessage.getAddPartyItems()[1], Integer.valueOf(2));
}
/**
* Enter app test.
*/
@Test
public void enterAppTest() {
String xml = "<xml><ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"<FromUserName><![CDATA[FromUser]]></FromUserName>\n" +
"<CreateTime>1408091189</CreateTime>\n" +
"<MsgType><![CDATA[event]]></MsgType>\n" +
"<Event><![CDATA[enter_agent]]></Event>\n" +
"<EventKey><![CDATA[]]></EventKey>\n" +
"<AgentID>1</AgentID>\n" +
"</xml>";
WxCpTpXmlMessage wxXmlMessage = WxCpTpXmlMessage.fromXml(xml);
assertEquals(wxXmlMessage.getToUserName(), "toUser");
assertEquals(wxXmlMessage.getFromUserName(), "FromUser");
assertEquals(wxXmlMessage.getCreateTime(), Long.valueOf(1408091189));
assertEquals(wxXmlMessage.getEvent(), "enter_agent");
assertEquals(wxXmlMessage.getEventKey(), "");
assertEquals(wxXmlMessage.getAgentID(), 1);
}
/**
* Text message test.
*/
@Test
public void textMessageTest() {
String xml = "<xml>\n" +
" <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
" <FromUserName><![CDATA[fromUser]]></FromUserName> \n" +
" <CreateTime>1348831860</CreateTime>\n" +
" <MsgType><![CDATA[text]]></MsgType>\n" +
" <Content><![CDATA[this is a test]]></Content>\n" +
" <MsgId>1234567890123456</MsgId>\n" +
" <Id><![CDATA[etEsNADQAAaiB0cWCSDFiJ2qCap-ww9A]]></Id>" +
" <AgentID>1</AgentID>\n" +
"</xml>";
WxCpTpXmlMessage wxXmlMessage = WxCpTpXmlMessage.fromXml(xml);
assertEquals(wxXmlMessage.getToUserName(), "toUser");
assertEquals(wxXmlMessage.getFromUserName(), "fromUser");
assertEquals(wxXmlMessage.getCreateTime(), Long.valueOf(1348831860));
assertEquals(wxXmlMessage.getMsgType(), "text");
assertEquals(wxXmlMessage.getMsgId(), "1234567890123456");
assertEquals(wxXmlMessage.getId(), "etEsNADQAAaiB0cWCSDFiJ2qCap-ww9A");
}
/**
* Approval info test.
*/
@Test
public void ApprovalInfoTest() {
String xml = "<xml>\n" +
" <ToUserName>wwddddccc7775555aaa</ToUserName> \n" +
" <FromUserName>sys</FromUserName> \n" +
" <CreateTime>1527838022</CreateTime> \n" +
" <MsgType>event</MsgType> \n" +
" <Event>open_approval_change</Event>\n" +
" <AgentID>1</AgentID>\n" +
" <ApprovalInfo> \n" +
" <ThirdNo>201806010001</ThirdNo> \n" +
" <OpenSpName>付款</OpenSpName> \n" +
" <OpenTemplateId>1234567890</OpenTemplateId> \n" +
" <OpenSpStatus>1</OpenSpStatus> \n" +
" <ApplyTime>1527837645</ApplyTime> \n" +
" <ApplyUserName>xiaoming</ApplyUserName> \n" +
" <ApplyUserId>1</ApplyUserId> \n" +
" <ApplyUserParty>产品部</ApplyUserParty> \n" +
" <ApplyUserImage>http://www.qq.com/xxx.png</ApplyUserImage> \n" +
" <ApprovalNodes> \n" +
" <ApprovalNode> \n" +
" <NodeStatus>1</NodeStatus> \n" +
" <NodeAttr>1</NodeAttr> \n" +
" <NodeType>1</NodeType> \n" +
" <Items> \n" +
" <Item> \n" +
" <ItemName>xiaohong</ItemName> \n" +
" <ItemUserId>2</ItemUserId> \n" +
" <ItemImage>http://www.qq.com/xxx.png</ItemImage> \n" +
" <ItemStatus>1</ItemStatus> \n" +
" <ItemSpeech></ItemSpeech> \n" +
" <ItemOpTime>0</ItemOpTime> \n" +
" </Item> \n" +
" </Items> \n" +
" </ApprovalNode> \n" +
" </ApprovalNodes> \n" +
" <NotifyNodes> \n" +
" <NotifyNode> \n" +
" <ItemName>xiaogang</ItemName> \n" +
" <ItemUserId>3</ItemUserId> \n" +
" <ItemImage>http://www.qq.com/xxx.png</ItemImage> \n" +
" </NotifyNode> \n" +
" </NotifyNodes> \n" +
" <approverstep>0</approverstep> \n" +
" </ApprovalInfo> \n" +
"</xml>";
WxCpTpXmlMessage wxXmlMessage = WxCpTpXmlMessage.fromXml(xml);
assertEquals(wxXmlMessage.getToUserName(), "wwddddccc7775555aaa");
assertEquals(wxXmlMessage.getFromUserName(), "sys");
assertEquals(wxXmlMessage.getCreateTime(), Long.valueOf(1527838022));
assertEquals(wxXmlMessage.getEvent(), "open_approval_change");
assertNotNull(wxXmlMessage.getApprovalInfo());
assertEquals(wxXmlMessage.getApprovalInfo().getThirdNo(), Long.valueOf(201806010001L));
assertEquals(wxXmlMessage.getApprovalInfo().getOpenSpName(), "付款");
assertEquals(wxXmlMessage.getApprovalInfo().getThirdNo(), Long.valueOf(201806010001L));
assertEquals(wxXmlMessage.getApprovalInfo().getApplyTime(), Long.valueOf(1527837645));
assertEquals(wxXmlMessage.getApprovalInfo().getApplyUserName(), "xiaoming");
assertNotNull(wxXmlMessage.getApprovalInfo().getApprovalNodes());
assertNotNull(wxXmlMessage.getApprovalInfo().getApprovalNodes().get(0));
assertEquals(wxXmlMessage.getApprovalInfo().getApprovalNodes().get(0).getNodeAttr(), Integer.valueOf(1));
assertEquals(wxXmlMessage.getApprovalInfo().getApprovalNodes().get(0).getNodeType(), Integer.valueOf(1));
assertNotNull(wxXmlMessage.getApprovalInfo().getApprovalNodes().get(0).getItems());
assertEquals(wxXmlMessage.getApprovalInfo().getApprovalNodes().get(0).getItems().get(0).getItemName(), "xiaohong");
assertEquals(wxXmlMessage.getApprovalInfo().getApprovalNodes().get(0).getItems().get(0).getItemOpTime(),
Long.valueOf(0));
assertNotNull(wxXmlMessage.getApprovalInfo().getNotifyNodes().get(0));
assertEquals(wxXmlMessage.getApprovalInfo().getNotifyNodes().get(0).getItemImage(), "http://www.qq.com/xxx.png");
assertEquals(wxXmlMessage.getApprovalInfo().getNotifyNodes().get(0).getItemUserId(), Integer.valueOf(3));
}
/**
* Test from xml.
*/
@Test
public void testFromXml() {
String xml = "<xml>\n" +
" <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
" <FromUserName><![CDATA[fromUser]]></FromUserName> \n" +
" <CreateTime>1348831860</CreateTime>\n" +
" <MsgType><![CDATA[text]]></MsgType>\n" +
" <Content><![CDATA[this is a test]]></Content>\n" +
" <MsgId>1234567890123456</MsgId>\n" +
" <Id>2</Id>\n" +
" <AgentID>1</AgentID>\n" +
"</xml>";
WxCpTpXmlMessage wxXmlMessage = WxCpTpXmlMessage.fromXml(xml);
assertEquals(wxXmlMessage.getToUserName(), "toUser");
assertEquals(wxXmlMessage.getFromUserName(), "fromUser");
assertEquals(wxXmlMessage.getCreateTime(), Long.valueOf(1348831860));
assertEquals(wxXmlMessage.getMsgType(), "text");
assertEquals(wxXmlMessage.getMsgId(), "1234567890123456");
assertEquals(wxXmlMessage.getId(), "2");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpSchoolContactMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpSchoolContactMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.article.MpnewsArticle;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import me.chanjar.weixin.cp.bean.school.user.WxCpAllowScope;
import me.chanjar.weixin.cp.bean.school.user.WxCpListParentResult;
import me.chanjar.weixin.cp.bean.school.user.WxCpUserListResult;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.demo.WxCpDemoInMemoryConfigStorage;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 发送「学校通知」消息测试类
* https://developer.work.weixin.qq.com/document/path/92321
*
* @author <a href="https://github.com/0katekate0">Wang_Wong</a> created on 2022-06-29
*/
@Slf4j
public class WxCpSchoolContactMessageTest {
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService cpService;
/**
* 发送「学校通知」
* 学校可以通过此接口来给家长发送不同类型的学校通知,来满足多种场景下的学校通知需求。目前支持的消息类型为文本、图片、语音、视频、文件、图文。
* <p>
* https://developer.work.weixin.qq.com/document/path/92321
* <p>
* 消息体类型请参考测试类
* WxCpSchoolContactMessageTest
* {@link WxCpSchoolContactMessageTest}
*
* @throws WxErrorException the wx error exception
*/
@Test
public void testSendSchoolContactMessage() throws WxErrorException {
InputStream inputStream = ClassLoader.getSystemResourceAsStream("test-config.xml");
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(inputStream);
wxCpConfigStorage = config;
cpService = new WxCpServiceImpl();
cpService.setWxCpConfigStorage(config);
// 获取可使用的家长范围 返回的数据
WxCpAllowScope allowScope = cpService.getSchoolUserService().getAllowScope(1000002);
WxCpUserListResult userList = cpService.getSchoolUserService().getUserList(1, 1);
// 测试发送给家长 [学校通知]
WxCpListParentResult userListParent = cpService.getSchoolUserService().getUserListParent(1);
List<WxCpListParentResult.Parent> collect = userListParent.getParents()
.stream()
.filter(parent -> parent.getMobile().equals("13079226621"))
.collect(Collectors.toList());
String[] parentsId = {"ab0b1691d0204d4900f6b7a7e5a6aa8f", collect.get(0).getParentUserId()};
WxCpSchoolContactMessageSendResult sendResult = cpService.getMessageService().sendSchoolContactMessage(
WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.NEWS)
.toParentUserId(parentsId)
// .toStudentUserId(new String[]{"student_userid1", "student_userid2"})
// .toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(cpService.getWxCpConfigStorage().getAgentId())
.articles(Lists.newArrayList(NewArticle.builder()
.title("这是接口测试标题")
.description("今年中秋节公司有豪礼相送哦")
.url("https://www.baidu.com/")
.picUrl("http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png")
.build()))
.build()
);
log.info("sendResult: {}", sendResult.toJson());
}
/**
* Test to json text.
*/
// WxCpConsts.SchoolContactChangeType
@Test
public void testToJson_text() {
WxCpSchoolContactMessage message = WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.TEXT)
.toParentUserId(new String[]{"parent_userid1", "parent_userid2"})
.toStudentUserId(new String[]{"student_userid1", "student_userid2"})
.toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(1)
.content("你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。")
.enableIdTrans(false)
.enableDuplicateCheck(false)
.duplicateCheckInterval(1800)
.build();
WxCpSchoolContactMessage schoolContactMessage1 = new WxCpSchoolContactMessage();
schoolContactMessage1.setMsgType(WxConsts.SchoolContactMsgType.TEXT);
schoolContactMessage1.setRecvScope(0);
schoolContactMessage1.setToParentUserId(new String[]{"parent_userid1", "parent_userid2"});
schoolContactMessage1.setToStudentUserId(new String[]{"student_userid1", "student_userid2"});
schoolContactMessage1.setToParty(new String[]{"partyid1", "partyid2"});
schoolContactMessage1.setToAll(false);
schoolContactMessage1.setAgentId(1);
schoolContactMessage1.setContent("你的快递已到,请携带工卡前往邮件中心领取");
schoolContactMessage1.setEnableIdTrans(false);
schoolContactMessage1.setEnableDuplicateCheck(false);
schoolContactMessage1.setDuplicateCheckInterval(1800);
final String jsonMsg = schoolContactMessage1.toJson();
final String json = message.toJson();
String expectedJson = "{\n" +
"\t\"recv_scope\" : 0,\n" +
"\t\"to_parent_userid\": [\"parent_userid1\", \"parent_userid2\"],\n" +
"\t\"to_student_userid\": [\"student_userid1\", \"student_userid2\"],\n" +
"\t\"to_party\": [\"partyid1\", \"partyid2\"],\n" +
"\t\"toall\" : 0,\n" +
"\t\"msgtype\" : \"text\",\n" +
"\t\"agentid\" : 1,\n" +
"\t\"text\" : {\n" +
"\t\t\"content\" : \"你的快递已到,请携带工卡前往邮件中心领取。\\n出发前可查看<a href=\\\"http://work.weixin.qq" +
".com\\\">邮件中心视频实况</a>,聪明避开排队。\"\n" +
"\t},\n" +
"\t\"enable_id_trans\": 0,\n" +
"\t\"enable_duplicate_check\": 0,\n" +
"\t\"duplicate_check_interval\": 1800\n" +
"}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json image.
*/
@Test
public void testToJson_image() {
WxCpSchoolContactMessage message = WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.IMAGE)
.toParentUserId(new String[]{"parent_userid1", "parent_userid2"})
.toStudentUserId(new String[]{"student_userid1", "student_userid2"})
.toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(1)
.mediaId("MEDIA_ID")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
"\t\"recv_scope\" : 0,\n" +
"\t\"to_parent_userid\": [\"parent_userid1\", \"parent_userid2\"],\n" +
"\t\"to_student_userid\": [\"student_userid1\", \"student_userid2\"],\n" +
"\t\"to_party\": [\"partyid1\", \"partyid2\"],\n" +
"\t\"toall\" : 0,\n" +
"\t\"msgtype\" : \"image\",\n" +
"\t\"agentid\" : 1,\n" +
"\t\"image\" : {\n" +
"\t\t\"media_id\" : \"MEDIA_ID\"\n" +
"\t},\n" +
"\t\"enable_duplicate_check\": 0,\n" +
"\t\"duplicate_check_interval\": 1800\n" +
"}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json voice.
*/
@Test
public void testToJson_voice() {
WxCpSchoolContactMessage message = WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.VOICE)
.toParentUserId(new String[]{"parent_userid1", "parent_userid2"})
.toStudentUserId(new String[]{"student_userid1", "student_userid2"})
.toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(1)
.mediaId("MEDIA_ID")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
"\t\"recv_scope\" : 0,\n" +
"\t\"to_parent_userid\": [\"parent_userid1\", \"parent_userid2\"],\n" +
"\t\"to_student_userid\": [\"student_userid1\", \"student_userid2\"],\n" +
"\t\"to_party\": [\"partyid1\", \"partyid2\"],\n" +
"\t\"toall\" : 0,\n" +
"\t\"msgtype\" : \"voice\",\n" +
"\t\"agentid\" : 1,\n" +
"\t\"voice\" : {\n" +
"\t\t\"media_id\" : \"MEDIA_ID\"\n" +
"\t},\n" +
"\t\"enable_duplicate_check\": 0,\n" +
"\t\"duplicate_check_interval\": 1800\n" +
"}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json video.
*/
@Test
public void testToJson_video() {
WxCpSchoolContactMessage message = WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.VIDEO)
.toParentUserId(new String[]{"parent_userid1", "parent_userid2"})
.toStudentUserId(new String[]{"student_userid1", "student_userid2"})
.toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(1)
.mediaId("MEDIA_ID")
.title("Title")
.description("Description")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
"\t\"recv_scope\" : 0,\n" +
"\t\"to_parent_userid\": [\"parent_userid1\", \"parent_userid2\"],\n" +
"\t\"to_student_userid\": [\"student_userid1\", \"student_userid2\"],\n" +
"\t\"to_party\": [\"partyid1\", \"partyid2\"],\n" +
"\t\"toall\" : 0,\n" +
"\t\"msgtype\" : \"video\",\n" +
"\t\"agentid\" : 1,\n" +
"\t\"video\" : {\n" +
" \"media_id\" : \"MEDIA_ID\",\n" +
" \"title\" : \"Title\",\n" +
" \"description\" : \"Description\"\n" +
"\t},\n" +
"\t\"enable_duplicate_check\": 0,\n" +
"\t\"duplicate_check_interval\": 1800\n" +
"}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json file.
*/
@Test
public void testToJson_file() {
WxCpSchoolContactMessage message = WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.FILE)
.toParentUserId(new String[]{"parent_userid1", "parent_userid2"})
.toStudentUserId(new String[]{"student_userid1", "student_userid2"})
.toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(1)
.mediaId("1Yv-zXfHjSjU-7LH-GwtYqDGS-zz6w22KmWAT5COgP7o")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
"\t\"recv_scope\" : 0,\n" +
"\t\"to_parent_userid\": [\"parent_userid1\", \"parent_userid2\"],\n" +
"\t\"to_student_userid\": [\"student_userid1\", \"student_userid2\"],\n" +
"\t\"to_party\": [\"partyid1\", \"partyid2\"],\n" +
"\t\"toall\" : 0,\n" +
"\t\"msgtype\" : \"file\",\n" +
"\t\"agentid\" : 1,\n" +
"\t\"file\" : {\n" +
" \"media_id\" : \"1Yv-zXfHjSjU-7LH-GwtYqDGS-zz6w22KmWAT5COgP7o\"\n" +
"\t},\n" +
"\t\"enable_duplicate_check\": 0,\n" +
"\t\"duplicate_check_interval\": 1800\n" +
"}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json news.
*/
@Test
public void testToJson_news() {
WxCpSchoolContactMessage message = WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.NEWS)
.toParentUserId(new String[]{"parent_userid1", "parent_userid2"})
.toStudentUserId(new String[]{"student_userid1", "student_userid2"})
.toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(1)
.articles(Lists.newArrayList(NewArticle.builder()
.title("中秋节礼品领取")
.description("今年中秋节公司有豪礼相送")
.url("URL")
.picUrl("http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png")
.build()))
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"recv_scope\" : 0,\n" +
" \"to_parent_userid\": [\"parent_userid1\", \"parent_userid2\"],\n" +
" \"to_student_userid\": [\"student_userid1\", \"student_userid2\"],\n" +
" \"to_party\": [\"partyid1\", \"partyid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"news\",\n" +
" \"agentid\" : 1,\n" +
" \"news\" : {\n" +
" \"articles\" : [\n" +
" {\n" +
" \"title\" : \"中秋节礼品领取\",\n" +
" \"description\" : \"今年中秋节公司有豪礼相送\",\n" +
" \"url\" : \"URL\",\n" +
" \"picurl\" : \"http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1" +
".png\"\n" +
" }\n" +
"\t\t]\n" +
" },\n" +
" \"enable_id_trans\": 0,\n" +
" \"enable_duplicate_check\": 0,\n" +
" \"duplicate_check_interval\": 1800\n" +
"}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json mpnews.
*/
@Test
public void testToJson_mpnews() {
WxCpSchoolContactMessage message = WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.MPNEWS)
.toParentUserId(new String[]{"parent_userid1", "parent_userid2"})
.toStudentUserId(new String[]{"student_userid1", "student_userid2"})
.toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(1)
.mpNewsArticles(Lists.newArrayList(MpnewsArticle.newBuilder()
.title("Title")
.thumbMediaId("MEDIA_ID")
.author("Author")
.contentSourceUrl("URL")
.content("Content")
.digest("Digest description")
.build()))
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"recv_scope\" : 0,\n" +
" \"to_parent_userid\": [\"parent_userid1\", \"parent_userid2\"],\n" +
" \"to_student_userid\": [\"student_userid1\", \"student_userid2\"],\n" +
" \"to_party\": [\"partyid1\", \"partyid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"mpnews\",\n" +
" \"agentid\" : 1,\n" +
" \"mpnews\" : {\n" +
" \"articles\":[\n" +
" {\n" +
" \"title\": \"Title\", \n" +
" \"thumb_media_id\": \"MEDIA_ID\",\n" +
" \"author\": \"Author\",\n" +
" \"content_source_url\": \"URL\",\n" +
" \"content\": \"Content\",\n" +
" \"digest\": \"Digest description\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"enable_id_trans\": 0,\n" +
" \"enable_duplicate_check\": 0,\n" +
" \"duplicate_check_interval\": 1800\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json mini program.
*/
@Test
public void testToJson_miniProgram() {
WxCpSchoolContactMessage message = WxCpSchoolContactMessage.builder()
.recvScope(0)
.msgType(WxConsts.SchoolContactMsgType.MINIPROGRAM)
.toParentUserId(new String[]{"parent_userid1", "parent_userid2"})
.toStudentUserId(new String[]{"student_userid1", "student_userid2"})
.toParty(new String[]{"partyid1", "partyid2"})
.toAll(false)
.agentId(1)
.appId("APPID")
.title("欢迎报名夏令营")
.thumbMediaId("MEDIA_ID")
.pagePath("PAGE_PATH")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"recv_scope\" : 0,\n" +
" \"to_parent_userid\": [\"parent_userid1\", \"parent_userid2\"],\n" +
" \"to_student_userid\": [\"student_userid1\", \"student_userid2\"],\n" +
" \"to_party\": [\"partyid1\", \"partyid2\"],\n" +
" \"toall\" : 0,\n" +
" \"agentid\" : 1,\n" +
" \"msgtype\" : \"miniprogram\",\n" +
" \"miniprogram\" : {\n" +
" \"appid\": \"APPID\",\n" +
" \"title\": \"欢迎报名夏令营\",\n" +
" \"thumb_media_id\": \"MEDIA_ID\",\n" +
" \"pagepath\": \"PAGE_PATH\"\n" +
" },\n" +
" \"enable_id_trans\": 0,\n" +
" \"enable_duplicate_check\": 0,\n" +
" \"duplicate_check_interval\": 1800\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutTaskCardMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutTaskCardMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* The type Wx cp xml out task card message test.
*/
@Test
public class WxCpXmlOutTaskCardMessageTest {
/**
* Test.
*/
public void test() {
WxCpXmlOutTaskCardMessage m = new WxCpXmlOutTaskCardMessage();
m.setReplaceName("已驳回");
m.setCreateTime(1122L);
m.setFromUserName("from");
m.setToUserName("to");
String expected = "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[update_taskcard]]></MsgType>"
+ "<TaskCard><ReplaceName><![CDATA[已驳回]]></ReplaceName></TaskCard>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
/**
* Test build.
*/
public void testBuild() {
WxCpXmlOutTaskCardMessage m =
WxCpXmlOutMessage.TASK_CARD().replaceName("已驳回").fromUser("from").toUser("to").build();
String expected = "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[update_taskcard]]></MsgType>"
+ "<TaskCard><ReplaceName><![CDATA[已驳回]]></ReplaceName></TaskCard>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutImageMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutImageMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* The type Wx cp xml out image message test.
*/
@Test
public class WxCpXmlOutImageMessageTest {
/**
* Test.
*/
public void test() {
WxCpXmlOutImageMessage m = new WxCpXmlOutImageMessage();
m.setMediaId("ddfefesfsdfef");
m.setCreateTime(1122L);
m.setFromUserName("from");
m.setToUserName("to");
String expected = "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[image]]></MsgType>"
+ "<Image><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Image>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
/**
* Test build.
*/
public void testBuild() {
WxCpXmlOutImageMessage m = WxCpXmlOutMessage.IMAGE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build();
String expected = "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[image]]></MsgType>"
+ "<Image><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Image>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutVideoMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutVideoMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* The type Wx cp xml out video message test.
*/
@Test
public class WxCpXmlOutVideoMessageTest {
/**
* Test.
*/
public void test() {
WxCpXmlOutVideoMessage m = new WxCpXmlOutVideoMessage();
m.setMediaId("media_id");
m.setTitle("title");
m.setDescription("ddfff");
m.setCreateTime(1122L);
m.setFromUserName("fromUser");
m.setToUserName("toUser");
String expected = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[video]]></MsgType>"
+ "<Video>"
+ "<MediaId><![CDATA[media_id]]></MediaId>"
+ "<Title><![CDATA[title]]></Title>"
+ "<Description><![CDATA[ddfff]]></Description>"
+ "</Video> "
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
/**
* Test build.
*/
public void testBuild() {
WxCpXmlOutVideoMessage m = WxCpXmlOutMessage.VIDEO()
.mediaId("media_id")
.fromUser("fromUser")
.toUser("toUser")
.title("title")
.description("ddfff")
.build();
String expected = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[video]]></MsgType>"
+ "<Video>"
+ "<MediaId><![CDATA[media_id]]></MediaId>"
+ "<Title><![CDATA[title]]></Title>"
+ "<Description><![CDATA[ddfff]]></Description>"
+ "</Video> "
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.cp.bean.article.MpnewsArticle;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import me.chanjar.weixin.cp.bean.taskcard.TaskCardButton;
import me.chanjar.weixin.cp.bean.templatecard.*;
import org.testng.annotations.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
/**
* The type Wx cp message test.
*/
@Test
public class WxCpMessageTest {
/**
* Test text build.
*/
public void testTextBuild() {
WxCpMessage reply = WxCpMessage.TEXT().toUser("OPENID").content("sfsfdsdf").build();
assertThat(reply.toJson())
.isEqualTo("{\"touser\":\"OPENID\",\"msgtype\":\"text\",\"text\":{\"content\":\"sfsfdsdf\"},\"safe\":\"0\"}");
}
/**
* Test text card build.
*/
public void testTextCardBuild() {
WxCpMessage reply = WxCpMessage.TEXTCARD().toUser("OPENID")
.title("领奖通知")
.description("<div class=\"gray\">2016年9月26日</div> <div class=\"normal\">恭喜你抽中iPhone 7一台," +
"领奖码:xxxx</div><div class=\"highlight\">请于2016年10月10日前联系行政同事领取</div>")
.url("http://www.qq.com")
.btnTxt("更多")
.build();
assertThat(reply.toJson())
.isEqualTo("{\"touser\":\"OPENID\",\"msgtype\":\"textcard\",\"textcard\":{\"title\":\"领奖通知\"," +
"\"description\":\"<div class=\\\"gray\\\">2016年9月26日</div> <div class=\\\"normal\\\">" +
"恭喜你抽中iPhone 7一台,领奖码:xxxx</div><div class=\\\"highlight\\\">请于2016年10月10日前联系行政同事领取</div>\"," +
"\"url\":\"http://www.qq.com\",\"btntxt\":\"更多\"},\"safe\":\"0\"}");
}
/**
* Test image build.
*/
public void testImageBuild() {
WxCpMessage reply = WxCpMessage.IMAGE().toUser("OPENID").mediaId("MEDIA_ID").build();
assertThat(reply.toJson())
.isEqualTo("{\"touser\":\"OPENID\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"MEDIA_ID\"},\"safe\":\"0\"}");
}
/**
* Test voice build.
*/
public void testVoiceBuild() {
WxCpMessage reply = WxCpMessage.VOICE().toUser("OPENID").mediaId("MEDIA_ID").build();
assertThat(reply.toJson())
.isEqualTo("{\"touser\":\"OPENID\",\"msgtype\":\"voice\",\"voice\":{\"media_id\":\"MEDIA_ID\"},\"safe\":\"0\"}");
}
/**
* Test video build.
*/
public void testVideoBuild() {
WxCpMessage reply = WxCpMessage.VIDEO().toUser("OPENID").title("TITLE").mediaId("MEDIA_ID").thumbMediaId("MEDIA_ID")
.description("DESCRIPTION").build();
assertThat(reply.toJson())
.isEqualTo("{\"touser\":\"OPENID\",\"msgtype\":\"video\",\"video\":{\"media_id\":\"MEDIA_ID\"," +
"\"thumb_media_id\":\"MEDIA_ID\",\"title\":\"TITLE\",\"description\":\"DESCRIPTION\"},\"safe\":\"0\"}");
}
/**
* Test news build.
*/
public void testNewsBuild() {
NewArticle article1 = new NewArticle();
article1.setUrl("URL");
article1.setPicUrl("PIC_URL");
article1.setDescription("Is Really A Happy Day");
article1.setTitle("Happy Day");
NewArticle article2 = new NewArticle();
article2.setUrl("URL");
article2.setPicUrl("PIC_URL");
article2.setDescription("Is Really A Happy Day");
article2.setTitle("Happy Day");
WxCpMessage reply = WxCpMessage.NEWS().toUser("OPENID").addArticle(article1).addArticle(article2).build();
assertThat(reply.toJson())
.isEqualTo("{\"touser\":\"OPENID\",\"msgtype\":\"news\",\"news\":{\"articles\":" +
"[{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"}," +
"{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\"," +
"\"picurl\":\"PIC_URL\"}]}," +
"\"safe\":\"0\"}");
}
/**
* Test mpnews build with articles.
*/
public void testMpnewsBuild_with_articles() {
MpnewsArticle article1 = MpnewsArticle.newBuilder()
.title("Happy Day")
.author("aaaaaa")
.content("hahaha")
.contentSourceUrl("nice url")
.digest("digest")
.showCoverPic("heihei")
.thumbMediaId("thumb")
.build();
MpnewsArticle article2 = MpnewsArticle.newBuilder()
.title("Happy Day")
.author("aaaaaa")
.content("hahaha")
.contentSourceUrl("nice url")
.digest("digest")
.showCoverPic("heihei")
.thumbMediaId("thumb")
.build();
WxCpMessage reply = WxCpMessage.MPNEWS().toUser("OPENID").addArticle(article1, article2).build();
assertThat(reply.toJson())
.isEqualTo("{\"touser\":\"OPENID\",\"msgtype\":\"mpnews\",\"mpnews\":{\"articles\":" +
"[{\"title\":\"Happy Day\",\"thumb_media_id\":\"thumb\",\"author\":\"aaaaaa\"," +
"\"content_source_url\":\"nice url\",\"content\":\"hahaha\",\"digest\":\"digest\"," +
"\"show_cover_pic\":\"heihei\"}" +
",{\"title\":\"Happy Day\",\"thumb_media_id\":\"thumb\",\"author\":\"aaaaaa\"," +
"\"content_source_url\":\"nice url\",\"content\":\"hahaha\",\"digest\":\"digest\"," +
"\"show_cover_pic\":\"heihei\"}]}," +
"\"safe\":\"0\"}");
}
/**
* Test mpnews build with media id.
*/
public void testMpnewsBuild_with_media_id() {
WxCpMessage reply = WxCpMessage.MPNEWS().toUser("OPENID").mediaId("mmm").build();
assertThat(reply.toJson())
.isEqualTo("{\"touser\":\"OPENID\",\"msgtype\":\"mpnews\",\"mpnews\":{\"media_id\":\"mmm\"},\"safe\":\"0\"}");
}
/**
* Test task card builder.
*/
public void testTaskCardBuilder() {
TaskCardButton button1 = TaskCardButton.builder()
.key("yes")
.name("批准")
.replaceName("已批准")
.color("blue")
.bold(true)
.build();
TaskCardButton button2 = TaskCardButton.builder()
.key("yes")
.name("拒绝")
.replaceName("已拒绝")
.color("red")
.bold(false)
.build();
WxCpMessage reply = WxCpMessage.TASKCARD().toUser("OPENID")
.title("任务卡片")
.description("有一条待处理任务")
.url("http://www.qq.com")
.taskId("task_123")
.buttons(Arrays.asList(button1, button2))
.build();
assertThat(reply.toJson())
.isEqualTo(
"{\"touser\":\"OPENID\",\"msgtype\":\"taskcard\",\"taskcard\":{\"title\":\"任务卡片\"," +
"\"description\":\"有一条待处理任务\",\"url\":\"http://www.qq.com\",\"task_id\":\"task_123\"," +
"\"btn\":[{\"key\":\"yes\",\"name\":\"批准\",\"replace_name\":\"已批准\",\"color\":\"blue\",\"is_bold\":true}," +
"{\"key\":\"yes\",\"name\":\"拒绝\",\"replace_name\":\"已拒绝\",\"color\":\"red\",\"is_bold\":false}]}}");
}
/**
* 测试模板卡片消息
* 文本通知型
*/
public void TestTemplateCardBuilder_text_notice() {
HorizontalContent hContent1 = HorizontalContent.builder()
.keyname("邀请人")
.value("张三")
.build();
HorizontalContent hContent2 = HorizontalContent.builder()
.type(1)
.keyname("企业微信官网")
.value("点击访问")
.url("https://work.weixin.qq.com")
.build();
HorizontalContent hContent3 = HorizontalContent.builder()
.type(2)
.keyname("企业微信下载")
.value("企业微信.apk")
.media_id("文件的media_id")
.build();
HorizontalContent hContent4 = HorizontalContent.builder()
.type(3)
.keyname("员工信息")
.value("点击查看")
.userid("zhangsan")
.build();
TemplateCardJump jump1 = TemplateCardJump.builder()
.type(1)
.title("企业微信官网")
.url("https://work.weixin.qq.com")
.build();
TemplateCardJump jump2 = TemplateCardJump.builder()
.type(2)
.title("跳转小程序")
.appid("小程序的appid")
.pagepath("/index.html")
.build();
QuoteArea quoteArea = QuoteArea.builder()
.type(1)
.title("引用文献标题")
.appid("小程序的appid")
.pagepath("/index.html")
.url("https://work.weixin.qq.com")
.quoteText("引用文献样式的引用文案")
.build();
ActionMenuItem action1 = ActionMenuItem.builder()
.text("接受推送")
.key("A")
.build();
ActionMenuItem action2 = ActionMenuItem.builder()
.text("不再推送")
.key("B")
.build();
WxCpMessage reply = WxCpMessage.TEMPLATECARD().toUser("OPENID")
.toParty("PartyID1 | PartyID2")
.toTag("TagID1 | TagID2")
.agentId(1000002)
.cardType(WxConsts.TemplateCardType.TEXT_NOTICE)
.taskId("task_id")
.sourceIconUrl("图片的url")
.sourceDesc("企业微信")
.sourceDescColor(1)
.actionMenuDesc("卡片副交互辅助文本说明")
.actionMenuActionList(Arrays.asList(action1, action2))
.mainTitleTitle("欢迎使用企业微信")
.mainTitleDesc("您的好友正在邀请您加入企业微信")
.emphasisContentTitle("100")
.emphasisContentDesc("核心数据")
.subTitleText("下载企业微信还能抢红包!")
.horizontalContents(Arrays.asList(hContent1, hContent2, hContent3, hContent4))
.jumps(Arrays.asList(jump1, jump2))
.cardActionType(2)
.cardActionAppid("小程序的appid")
.cardActionUrl("https://work.weixin.qq.com")
.cardActionPagepath("/index.html")
.quoteArea(quoteArea)
.build();
reply.setEnableIdTrans(false);
reply.setEnableDuplicateCheck(false);
reply.setDuplicateCheckInterval(1800);
// System.out.println(reply.toJson());
assertThat(reply.toJson())
.isEqualTo(
"{\"agentid\":1000002,\"touser\":\"OPENID\",\"msgtype\":\"template_card\",\"toparty\":\"PartyID1 | " +
"PartyID2\",\"totag\":\"TagID1 | TagID2\",\"duplicate_check_interval\":1800," +
"\"template_card\":{\"card_type\":\"text_notice\",\"source\":{\"icon_url\":\"图片的url\",\"desc\":\"企业微信\"," +
"\"desc_color\":1},\"action_menu\":{\"desc\":\"卡片副交互辅助文本说明\",\"action_list\":[{\"text\":\"接受推送\"," +
"\"key\":\"A\"},{\"text\":\"不再推送\",\"key\":\"B\"}]},\"main_title\":{\"title\":\"欢迎使用企业微信\"," +
"\"desc\":\"您的好友正在邀请您加入企业微信\"},\"emphasis_content\":{\"title\":\"100\",\"desc\":\"核心数据\"}," +
"\"sub_title_text\":\"下载企业微信还能抢红包!\",\"task_id\":\"task_id\"," +
"\"horizontal_content_list\":[{\"keyname\":\"邀请人\",\"value\":\"张三\"},{\"type\":1,\"keyname\":\"企业微信官网\"," +
"\"value\":\"点击访问\",\"url\":\"https://work.weixin.qq.com\"},{\"type\":2,\"keyname\":\"企业微信下载\"," +
"\"value\":\"企业微信.apk\",\"media_id\":\"文件的media_id\"},{\"type\":3,\"keyname\":\"员工信息\",\"value\":\"点击查看\"," +
"\"userid\":\"zhangsan\"}],\"jump_list\":[{\"type\":1,\"title\":\"企业微信官网\",\"url\":\"https://work.weixin.qq" +
".com\"},{\"type\":2,\"title\":\"跳转小程序\",\"appid\":\"小程序的appid\",\"pagepath\":\"/index.html\"}]," +
"\"card_action\":{\"type\":2,\"url\":\"https://work.weixin.qq.com\",\"appid\":\"小程序的appid\"," +
"\"pagepath\":\"/index.html\"},\"quote_area\":{\"type\":1,\"url\":\"https://work.weixin.qq.com\"," +
"\"appid\":\"小程序的appid\",\"pagepath\":\"/index.html\",\"title\":\"引用文献标题\"," +
"\"quote_text\":\"引用文献样式的引用文案\"}}}");
}
/**
* 测试模板卡片消息
* 图文展示型
*/
public void TestTemplateCardBuilder_news_notice() {
VerticalContent vContent1 = VerticalContent.builder()
.title("惊喜红包等你来拿")
.desc("下载企业微信还能抢红包!")
.build();
VerticalContent vContent2 = VerticalContent.builder()
.title("二级垂直内容")
.desc("二级垂直内容!")
.build();
HorizontalContent hContent1 = HorizontalContent.builder()
.keyname("邀请人")
.value("张三")
.build();
HorizontalContent hContent2 = HorizontalContent.builder()
.type(1)
.keyname("企业微信官网")
.value("点击访问")
.url("https://work.weixin.qq.com")
.build();
HorizontalContent hContent3 = HorizontalContent.builder()
.type(2)
.keyname("企业微信下载")
.value("企业微信.apk")
.media_id("文件的media_id")
.build();
TemplateCardJump jump1 = TemplateCardJump.builder()
.type(1)
.title("企业微信官网")
.url("https://work.weixin.qq.com")
.build();
TemplateCardJump jump2 = TemplateCardJump.builder()
.type(2)
.title("跳转小程序")
.appid("小程序的appid")
.pagepath("/index.html")
.build();
WxCpMessage reply = WxCpMessage.TEMPLATECARD().toUser("OPENID")
.agentId(1000002)
.cardType(WxConsts.TemplateCardType.NEWS_NOTICE)
.sourceIconUrl("图片的url")
.sourceDesc("企业微信")
.mainTitleTitle("欢迎使用企业微信")
.mainTitleDesc("您的好友正在邀请您加入企业微信")
.verticalContents(Arrays.asList(vContent1, vContent2))
.horizontalContents(Arrays.asList(hContent1, hContent2, hContent3))
.jumps(Arrays.asList(jump1, jump2))
.cardActionType(2)
.cardActionAppid("小程序的appid")
.cardActionUrl("https://work.weixin.qq.com")
.cardActionPagepath("/index.html")
.build();
reply.setEnableIdTrans(false);
reply.setEnableDuplicateCheck(false);
reply.setDuplicateCheckInterval(1800);
System.out.println(reply.toJson());
assertThat(reply.toJson())
.isEqualTo(
"{\"agentid\":1000002,\"touser\":\"OPENID\",\"msgtype\":\"template_card\",\"duplicate_check_interval\":1800," +
"\"template_card\":{\"card_type\":\"news_notice\",\"source\":{\"icon_url\":\"图片的url\",\"desc\":\"企业微信\"}," +
"\"main_title\":{\"title\":\"欢迎使用企业微信\",\"desc\":\"您的好友正在邀请您加入企业微信\"}," +
"\"vertical_content_list\":[{\"title\":\"惊喜红包等你来拿\",\"desc\":\"下载企业微信还能抢红包!\"},{\"title\":\"二级垂直内容\"," +
"\"desc\":\"二级垂直内容!\"}],\"horizontal_content_list\":[{\"keyname\":\"邀请人\",\"value\":\"张三\"},{\"type\":1," +
"\"keyname\":\"企业微信官网\",\"value\":\"点击访问\",\"url\":\"https://work.weixin.qq.com\"},{\"type\":2," +
"\"keyname\":\"企业微信下载\",\"value\":\"企业微信.apk\",\"media_id\":\"文件的media_id\"}],\"jump_list\":[{\"type\":1," +
"\"title\":\"企业微信官网\",\"url\":\"https://work.weixin.qq.com\"},{\"type\":2,\"title\":\"跳转小程序\"," +
"\"appid\":\"小程序的appid\",\"pagepath\":\"/index.html\"}],\"card_action\":{\"type\":2,\"url\":\"https://work" +
".weixin.qq.com\",\"appid\":\"小程序的appid\",\"pagepath\":\"/index.html\"}}}");
}
/**
* 测试模板卡片消息
* 按钮交互型
*/
public void TestTemplateCardBuilder_button_interaction() {
TemplateCardButton tButton1 = TemplateCardButton.builder()
.text("按钮1")
.style(1)
.key("button_key_1")
.build();
TemplateCardButton tButton2 = TemplateCardButton.builder()
.text("按钮2")
.style(2)
.key("button_key_2")
.build();
HorizontalContent hContent1 = HorizontalContent.builder()
.keyname("邀请人")
.value("张三")
.build();
HorizontalContent hContent2 = HorizontalContent.builder()
.type(1)
.keyname("企业微信官网")
.value("点击访问")
.url("https://work.weixin.qq.com")
.build();
HorizontalContent hContent3 = HorizontalContent.builder()
.type(2)
.keyname("企业微信下载")
.value("企业微信.apk")
.media_id("文件的media_id")
.build();
WxCpMessage reply = WxCpMessage.TEMPLATECARD().toUser("OPENID")
.agentId(1000002)
.cardType(WxConsts.TemplateCardType.BUTTON_INTERACTION)
.sourceIconUrl("图片的url")
.sourceDesc("企业微信")
.mainTitleTitle("欢迎使用企业微信")
.mainTitleDesc("您的好友正在邀请您加入企业微信")
.subTitleText("下载企业微信还能抢红包!")
.horizontalContents(Arrays.asList(hContent1, hContent2, hContent3))
.cardActionType(2)
.cardActionAppid("小程序的appid")
.cardActionUrl("https://work.weixin.qq.com")
.cardActionPagepath("/index.html")
.taskId("task_id")
.buttons(Arrays.asList(tButton1, tButton2))
.build();
reply.setEnableIdTrans(false);
reply.setEnableDuplicateCheck(false);
reply.setDuplicateCheckInterval(1800);
System.out.println(reply.toJson());
assertThat(reply.toJson())
.isEqualTo(
"{\"agentid\":1000002,\"touser\":\"OPENID\",\"msgtype\":\"template_card\",\"duplicate_check_interval\":1800," +
"\"template_card\":{\"card_type\":\"button_interaction\",\"source\":{\"icon_url\":\"图片的url\"," +
"\"desc\":\"企业微信\"},\"main_title\":{\"title\":\"欢迎使用企业微信\",\"desc\":\"您的好友正在邀请您加入企业微信\"}," +
"\"sub_title_text\":\"下载企业微信还能抢红包!\",\"task_id\":\"task_id\"," +
"\"horizontal_content_list\":[{\"keyname\":\"邀请人\",\"value\":\"张三\"},{\"type\":1,\"keyname\":\"企业微信官网\"," +
"\"value\":\"点击访问\",\"url\":\"https://work.weixin.qq.com\"},{\"type\":2,\"keyname\":\"企业微信下载\"," +
"\"value\":\"企业微信.apk\",\"media_id\":\"文件的media_id\"}],\"card_action\":{\"type\":2,\"url\":\"https://work" +
".weixin.qq.com\",\"appid\":\"小程序的appid\",\"pagepath\":\"/index.html\"},\"button_list\":[{\"text\":\"按钮1\"," +
"\"style\":1,\"key\":\"button_key_1\"},{\"text\":\"按钮2\",\"style\":2,\"key\":\"button_key_2\"}]}}");
}
/**
* 测试模板卡片消息
* 投票选择型
*/
public void TestTemplateCardBuilder_vote_interaction() {
CheckboxOption option1 = CheckboxOption.builder()
.id("option_id1")
.text("选择题选项1")
.is_checked(true)
.build();
CheckboxOption option2 = CheckboxOption.builder()
.id("option_id2")
.text("选择题选项2")
.is_checked(false)
.build();
WxCpMessage reply = WxCpMessage.TEMPLATECARD().toUser("OPENID")
.agentId(1000002)
.cardType(WxConsts.TemplateCardType.VOTE_INTERACTION)
.sourceIconUrl("图片的url")
.sourceDesc("企业微信")
.mainTitleTitle("欢迎使用企业微信")
.mainTitleDesc("您的好友正在邀请您加入企业微信")
.taskId("task_id")
.checkboxQuestionKey("question_key1")
.checkboxMode(1)
.options(Arrays.asList(option1, option2))
.submitButtonKey("key")
.submitButtonText("提交")
.build();
reply.setEnableIdTrans(false);
reply.setEnableDuplicateCheck(false);
reply.setDuplicateCheckInterval(1800);
System.out.println(reply.toJson());
assertThat(reply.toJson())
.isEqualTo(
"{\"agentid\":1000002,\"touser\":\"OPENID\",\"msgtype\":\"template_card\",\"duplicate_check_interval\":1800," +
"\"template_card\":{\"card_type\":\"vote_interaction\",\"source\":{\"icon_url\":\"图片的url\"," +
"\"desc\":\"企业微信\"},\"main_title\":{\"title\":\"欢迎使用企业微信\",\"desc\":\"您的好友正在邀请您加入企业微信\"}," +
"\"task_id\":\"task_id\",\"checkbox\":{\"question_key\":\"question_key1\",\"mode\":1," +
"\"option_list\":[{\"id\":\"option_id1\",\"text\":\"选择题选项1\",\"is_checked\":true},{\"id\":\"option_id2\"," +
"\"text\":\"选择题选项2\",\"is_checked\":false}]},\"submit_button\":{\"text\":\"提交\",\"key\":\"key\"}}}");
}
/**
* 测试模板卡片消息
* 投票选择型
*/
public void TestTemplateCardBuilder_multiple_interaction() {
CheckboxOption option1 = CheckboxOption.builder()
.id("selection_id1")
.text("选择器选项1")
.build();
CheckboxOption option2 = CheckboxOption.builder()
.id("selection_id2")
.text("选择题选项2")
.build();
CheckboxOption option3 = CheckboxOption.builder()
.id("selection_id3")
.text("选择器选项3")
.build();
CheckboxOption option4 = CheckboxOption.builder()
.id("selection_id4")
.text("选择题选项4")
.build();
MultipleSelect mSelect1 = MultipleSelect.builder()
.question_key("question_key1")
.title("选择器标签1")
.selected_id("selection_id1")
.options(Arrays.asList(option1, option2))
.build();
MultipleSelect mSelect2 = MultipleSelect.builder()
.question_key("question_key2")
.title("选择器标签2")
.selected_id("selection_id3")
.options(Arrays.asList(option3, option4))
.build();
WxCpMessage reply = WxCpMessage.TEMPLATECARD().toUser("OPENID")
.agentId(1000002)
.cardType(WxConsts.TemplateCardType.MULTIPLE_INTERACTION)
.sourceIconUrl("图片的url")
.sourceDesc("企业微信")
.mainTitleTitle("欢迎使用企业微信")
.mainTitleDesc("您的好友正在邀请您加入企业微信")
.taskId("task_id")
.selects(Arrays.asList(mSelect1, mSelect2))
.submitButtonKey("key")
.submitButtonText("提交")
.build();
reply.setEnableIdTrans(false);
reply.setEnableDuplicateCheck(false);
reply.setDuplicateCheckInterval(1800);
System.out.println(reply.toJson());
assertThat(reply.toJson())
.isEqualTo("{\"agentid\":1000002,\"touser\":\"OPENID\",\"msgtype\":\"template_card\"," +
"\"duplicate_check_interval\":1800,\"template_card\":{\"card_type\":\"multiple_interaction\"," +
"\"source\":{\"icon_url\":\"图片的url\",\"desc\":\"企业微信\"},\"main_title\":{\"title\":\"欢迎使用企业微信\"," +
"\"desc\":\"您的好友正在邀请您加入企业微信\"},\"task_id\":\"task_id\",\"submit_button\":{\"text\":\"提交\",\"key\":\"key\"}," +
"\"select_list\":[{\"question_key\":\"question_key1\",\"title\":\"选择器标签1\",\"selected_id\":\"selection_id1\"," +
"\"option_list\":[{\"id\":\"selection_id1\",\"text\":\"选择器选项1\"},{\"id\":\"selection_id2\"," +
"\"text\":\"选择题选项2\"}]},{\"question_key\":\"question_key2\",\"title\":\"选择器标签2\"," +
"\"selected_id\":\"selection_id3\",\"option_list\":[{\"id\":\"selection_id3\",\"text\":\"选择器选项3\"}," +
"{\"id\":\"selection_id4\",\"text\":\"选择题选项4\"}]}]}}");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutNewsMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutNewsMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* The type Wx cp xml out news message test.
*/
@Test
public class WxCpXmlOutNewsMessageTest {
/**
* Test.
*/
public void test() {
WxCpXmlOutNewsMessage m = new WxCpXmlOutNewsMessage();
m.setCreateTime(1122L);
m.setFromUserName("fromUser");
m.setToUserName("toUser");
WxCpXmlOutNewsMessage.Item item = new WxCpXmlOutNewsMessage.Item();
item.setDescription("description");
item.setPicUrl("picUrl");
item.setTitle("title");
item.setUrl("url");
m.addArticle(item);
m.addArticle(item);
String expected = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[news]]></MsgType>"
+ " <Articles>"
+ " <item>"
+ " <Title><![CDATA[title]]></Title>"
+ " <Description><![CDATA[description]]></Description>"
+ " <PicUrl><![CDATA[picUrl]]></PicUrl>"
+ " <Url><![CDATA[url]]></Url>"
+ " </item>"
+ " <item>"
+ " <Title><![CDATA[title]]></Title>"
+ " <Description><![CDATA[description]]></Description>"
+ " <PicUrl><![CDATA[picUrl]]></PicUrl>"
+ " <Url><![CDATA[url]]></Url>"
+ " </item>"
+ " </Articles>"
+ " <ArticleCount>2</ArticleCount>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
/**
* Test build.
*/
public void testBuild() {
WxCpXmlOutNewsMessage.Item item = new WxCpXmlOutNewsMessage.Item();
item.setDescription("description");
item.setPicUrl("picUrl");
item.setTitle("title");
item.setUrl("url");
WxCpXmlOutNewsMessage m = WxCpXmlOutMessage.NEWS()
.fromUser("fromUser")
.toUser("toUser")
.addArticle(item)
.addArticle(item)
.build();
String expected = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[news]]></MsgType>"
+ " <Articles>"
+ " <item>"
+ " <Title><![CDATA[title]]></Title>"
+ " <Description><![CDATA[description]]></Description>"
+ " <PicUrl><![CDATA[picUrl]]></PicUrl>"
+ " <Url><![CDATA[url]]></Url>"
+ " </item>"
+ " <item>"
+ " <Title><![CDATA[title]]></Title>"
+ " <Description><![CDATA[description]]></Description>"
+ " <PicUrl><![CDATA[picUrl]]></PicUrl>"
+ " <Url><![CDATA[url]]></Url>"
+ " </item>"
+ " </Articles>"
+ " <ArticleCount>2</ArticleCount>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
import org.testng.annotations.Test;
import static me.chanjar.weixin.cp.constant.WxCpConsts.EventType.TASKCARD_CLICK;
import static me.chanjar.weixin.cp.constant.WxCpConsts.EventType.UPLOAD_MEDIA_JOB_FINISH;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* The type Wx cp xml message test.
*/
@Test
public class WxCpXmlMessageTest {
/**
* Test from xml.
*/
public void testFromXml() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName> "
+ "<CreateTime>1348831860</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[this is a test]]></Content>"
+ "<MsgId>1234567890123456</MsgId>"
+ "<PicUrl><![CDATA[this is a url]]></PicUrl>"
+ "<MediaId><![CDATA[media_id]]></MediaId>"
+ "<Format><![CDATA[Format]]></Format>"
+ "<ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId>"
+ "<Location_X>23.134521</Location_X>"
+ "<Location_Y>113.358803</Location_Y>"
+ "<Scale>20</Scale>"
+ "<Label><![CDATA[位置信息]]></Label>"
+ "<Description><![CDATA[公众平台官网链接]]></Description>"
+ "<Url><![CDATA[url]]></Url>"
+ "<Title><![CDATA[公众平台官网链接]]></Title>"
+ "<Event><![CDATA[subscribe]]></Event>"
+ "<EventKey><![CDATA[qrscene_123123]]></EventKey>"
+ "<Ticket><![CDATA[TICKET]]></Ticket>"
+ "<Latitude>23.137466</Latitude>"
+ "<Longitude>113.352425</Longitude>"
+ "<Precision>119.385040</Precision>"
+ "<ScanCodeInfo>"
+ " <ScanType><![CDATA[qrcode]]></ScanType>"
+ " <ScanResult><![CDATA[1]]></ScanResult>"
+ "</ScanCodeInfo>"
+ "<SendPicsInfo>"
+ " <Count>1</Count>\n"
+ " <PicList>"
+ " <item>"
+ " <PicMd5Sum><![CDATA[1b5f7c23b5bf75682a53e7b6d163e185]]></PicMd5Sum>"
+ " </item>"
+ " </PicList>"
+ "</SendPicsInfo>"
+ "<SendLocationInfo>"
+ " <Location_X><![CDATA[23]]></Location_X>\n"
+ " <Location_Y><![CDATA[113]]></Location_Y>\n"
+ " <Scale><![CDATA[15]]></Scale>\n"
+ " <Label><![CDATA[ 广州市海珠区客村艺苑路 106号]]></Label>\n"
+ " <Poiname><![CDATA[wo de poi]]></Poiname>\n"
+ "</SendLocationInfo>"
+ "</xml>";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUserName(), "toUser");
assertEquals(wxMessage.getFromUserName(), "fromUser");
assertEquals(wxMessage.getCreateTime(), Long.valueOf(1348831860));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.TEXT);
assertEquals(wxMessage.getContent(), "this is a test");
assertEquals(wxMessage.getMsgId(), "1234567890123456");
assertEquals(wxMessage.getPicUrl(), "this is a url");
assertEquals(wxMessage.getMediaId(), "media_id");
assertEquals(wxMessage.getFormat(), "Format");
assertEquals(wxMessage.getThumbMediaId(), "thumb_media_id");
assertEquals(wxMessage.getLocationX().doubleValue(), 23.134521d);
assertEquals(wxMessage.getLocationY().doubleValue(), 113.358803d);
assertEquals(wxMessage.getScale().doubleValue(), 20d);
assertEquals(wxMessage.getLabel(), "位置信息");
assertEquals(wxMessage.getDescription(), "公众平台官网链接");
assertEquals(wxMessage.getUrl(), "url");
assertEquals(wxMessage.getTitle(), "公众平台官网链接");
assertEquals(wxMessage.getEvent(), "subscribe");
assertEquals(wxMessage.getEventKey(), "qrscene_123123");
assertEquals(wxMessage.getTicket(), "TICKET");
assertEquals(wxMessage.getLatitude().doubleValue(), 23.137466);
assertEquals(wxMessage.getLongitude().doubleValue(), 113.352425);
assertEquals(wxMessage.getPrecision().doubleValue(), 119.385040);
assertEquals(wxMessage.getScanCodeInfo().getScanType(), "qrcode");
assertEquals(wxMessage.getScanCodeInfo().getScanResult(), "1");
assertEquals(wxMessage.getSendPicsInfo().getCount(), Long.valueOf(1));
assertEquals(wxMessage.getSendPicsInfo().getPicList().get(0).getPicMd5Sum(), "1b5f7c23b5bf75682a53e7b6d163e185");
assertEquals(wxMessage.getSendLocationInfo().getLocationX(), "23");
assertEquals(wxMessage.getSendLocationInfo().getLocationY(), "113");
assertEquals(wxMessage.getSendLocationInfo().getScale(), "15");
assertEquals(wxMessage.getSendLocationInfo().getLabel(), " 广州市海珠区客村艺苑路 106号");
assertEquals(wxMessage.getSendLocationInfo().getPoiName(), "wo de poi");
}
/**
* Test send pics info.
*/
public void testSendPicsInfo() {
String xml = "<xml>" +
"<ToUserName><![CDATA[wx45a0972125658be9]]></ToUserName>" +
"<FromUserName><![CDATA[xiaohe]]></FromUserName>" +
"<CreateTime>1502012364</CreateTime>" +
"<MsgType><![CDATA[event]]></MsgType>" +
"<AgentID>1000004</AgentID>" +
"<Event><![CDATA[pic_weixin]]></Event>" +
"<EventKey><![CDATA[faceSimilarity]]></EventKey>" +
"<SendPicsInfo>" +
"<PicList><item><PicMd5Sum><![CDATA[aef52ae501537e552725c5d7f99c1741]]></PicMd5Sum></item></PicList>" +
"<PicList><item><PicMd5Sum><![CDATA[c4564632a4fab91378c39bea6aad6f9e]]></PicMd5Sum></item></PicList>" +
"<Count>2</Count>" +
"</SendPicsInfo>" +
"</xml>";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml.replace("</PicList><PicList>", ""));
assertEquals(wxMessage.getToUserName(), "wx45a0972125658be9");
assertEquals(wxMessage.getFromUserName(), "xiaohe");
assertEquals(wxMessage.getCreateTime(), Long.valueOf(1502012364L));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.EVENT);
assertEquals(wxMessage.getAgentId(), Integer.valueOf(1000004));
assertEquals(wxMessage.getEvent(), "pic_weixin");
assertEquals(wxMessage.getEventKey(), "faceSimilarity");
assertNotNull(wxMessage.getSendPicsInfo());
assertEquals(wxMessage.getSendPicsInfo().getCount(), Long.valueOf(2L));
assertEquals(wxMessage.getSendPicsInfo().getPicList().get(0).getPicMd5Sum(), "aef52ae501537e552725c5d7f99c1741");
assertEquals(wxMessage.getSendPicsInfo().getPicList().get(1).getPicMd5Sum(), "c4564632a4fab91378c39bea6aad6f9e");
}
/**
* Test ext attr.
*/
public void testExtAttr() {
String xml = "<xml>" +
" <ToUserName><![CDATA[w56c9fe3d50ad1ea2]]></ToUserName>" +
" <FromUserName><![CDATA[sys]]></FromUserName>" +
" <CreateTime>1557241961</CreateTime>" +
" <MsgType><![CDATA[event]]></MsgType>" +
" <Event><![CDATA[change_contact]]></Event>" +
" <ChangeType><![CDATA[update_user]]></ChangeType>" +
" <UserID><![CDATA[zhangsan]]></UserID>" +
" <ExtAttr>" +
" <Item><Name><![CDATA[爱好]]></Name><Value><![CDATA[111]]></Value><Text><Value><![CDATA[111]]></Value" +
"></Text></Item>" +
" <Item><Name><![CDATA[入职时间]]></Name><Value><![CDATA[11111]]></Value><Text><Value><![CDATA[11111" +
"]]></Value></Text></Item>" +
" <Item><Name><![CDATA[城市]]></Name><Value><![CDATA[11111]]></Value><Text><Value><![CDATA[11111]]></Value" +
"></Text></Item>" +
" </ExtAttr>" +
" <Address><![CDATA[11111]]></Address>" +
"</xml>";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUserName(), "w56c9fe3d50ad1ea2");
assertEquals(wxMessage.getFromUserName(), "sys");
assertEquals(wxMessage.getCreateTime(), Long.valueOf(1557241961));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.EVENT);
assertEquals(wxMessage.getEvent(), "change_contact");
assertEquals(wxMessage.getChangeType(), "update_user");
assertEquals(wxMessage.getUserId(), "zhangsan");
assertNotNull(wxMessage.getExtAttrs());
assertNotNull(wxMessage.getExtAttrs().getItems());
assertEquals(wxMessage.getExtAttrs().getItems().size(), 3);
assertEquals(wxMessage.getExtAttrs().getItems().get(0).getName(), "爱好");
}
/**
* Test task card event.
*/
public void testTaskCardEvent() {
String xml = "<xml>" +
"<ToUserName><![CDATA[toUser]]></ToUserName>" +
"<FromUserName><![CDATA[FromUser]]></FromUserName>" +
"<CreateTime>123456789</CreateTime>" +
"<MsgType><![CDATA[event]]></MsgType>" +
"<Event><![CDATA[taskcard_click]]></Event>" +
"<EventKey><![CDATA[key111]]></EventKey>" +
"<TaskId><![CDATA[taskid111]]></TaskId >" +
"<AgentID>1</AgentID>" +
"</xml>";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUserName(), "toUser");
assertEquals(wxMessage.getFromUserName(), "FromUser");
assertEquals(wxMessage.getCreateTime(), Long.valueOf(123456789L));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.EVENT);
assertEquals(wxMessage.getAgentId(), Integer.valueOf(1));
assertEquals(wxMessage.getEvent(), TASKCARD_CLICK);
assertEquals(wxMessage.getEventKey(), "key111");
assertEquals(wxMessage.getTaskId(), "taskid111");
}
/**
* Test add external user event.
*/
public void testAddExternalUserEvent() {
String xml = "<xml>" +
"<ToUserName><![CDATA[toUser]]></ToUserName>" +
"<FromUserName><![CDATA[sys]]></FromUserName>" +
"<CreateTime>1403610513</CreateTime>" +
"<MsgType><![CDATA[event]]></MsgType>" +
"<Event><![CDATA[change_external_contact]]></Event>" +
"<ChangeType><![CDATA[add_external_contact]]></ChangeType>" +
"<UserID><![CDATA[zhangsan]]></UserID>" +
"<ExternalUserID><![CDATA[woAJ2GCAAAXtWyujaWJHDDGi0mACH71w]]></ExternalUserID>" +
"<State><![CDATA[teststate]]></State>" +
"<WelcomeCode><![CDATA[WELCOMECODE]]></WelcomeCode>" +
"</xml >";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUserName(), "toUser");
assertEquals(wxMessage.getFromUserName(), "sys");
assertEquals(wxMessage.getCreateTime(), Long.valueOf(1403610513L));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.EVENT);
assertEquals(wxMessage.getEvent(), WxCpConsts.EventType.CHANGE_EXTERNAL_CONTACT);
assertEquals(wxMessage.getChangeType(), WxCpConsts.ExternalContactChangeType.ADD_EXTERNAL_CONTACT);
assertEquals(wxMessage.getExternalUserId(), "woAJ2GCAAAXtWyujaWJHDDGi0mACH71w");
assertEquals(wxMessage.getState(), "teststate");
assertEquals(wxMessage.getWelcomeCode(), "WELCOMECODE");
}
/**
* Test del external user event.
*/
public void testDelExternalUserEvent() {
String xml = "<xml>" +
"<ToUserName><![CDATA[toUser]]></ToUserName>" +
"<FromUserName><![CDATA[sys]]></FromUserName>" +
"<CreateTime>1403610513</CreateTime>" +
"<MsgType><![CDATA[event]]></MsgType>" +
"<Event><![CDATA[change_external_contact]]></Event>" +
"<ChangeType><![CDATA[del_external_contact]]></ChangeType>" +
"<UserID><![CDATA[zhangsan]]></UserID>" +
"<ExternalUserID><![CDATA[woAJ2GCAAAXtWyujaWJHDDGi0mACH71w]]></ExternalUserID>" +
"</xml>";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUserName(), "toUser");
assertEquals(wxMessage.getFromUserName(), "sys");
assertEquals(wxMessage.getCreateTime(), Long.valueOf(1403610513L));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.EVENT);
assertEquals(wxMessage.getEvent(), WxCpConsts.EventType.CHANGE_EXTERNAL_CONTACT);
assertEquals(wxMessage.getChangeType(), WxCpConsts.ExternalContactChangeType.DEL_EXTERNAL_CONTACT);
assertEquals(wxMessage.getUserId(), "zhangsan");
assertEquals(wxMessage.getExternalUserId(), "woAJ2GCAAAXtWyujaWJHDDGi0mACH71w");
}
/**
* Test change contact.
*/
public void testChangeContact() {
String xml = "<xml>\n" +
" <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
" <FromUserName><![CDATA[sys]]></FromUserName> \n" +
" <CreateTime>1403610513</CreateTime>\n" +
" <MsgType><![CDATA[event]]></MsgType>\n" +
" <Event><![CDATA[change_contact]]></Event>\n" +
" <ChangeType>update_user</ChangeType>\n" +
" <UserID><![CDATA[zhangsan]]></UserID>\n" +
" <NewUserID><![CDATA[zhangsan001]]></NewUserID>\n" +
" <Name><![CDATA[张三]]></Name>\n" +
" <Department><![CDATA[1,2,3]]></Department>\n" +
" <IsLeaderInDept><![CDATA[1,0,0]]></IsLeaderInDept>\n" +
" <Position><![CDATA[产品经理]]></Position>\n" +
" <Mobile>15913215421</Mobile>\n" +
" <Gender>1</Gender>\n" +
" <Email><![CDATA[zhangsan@gzdev.com]]></Email>\n" +
" <Status>1</Status>\n" +
" <Avatar><![CDATA[http://wx.qlogo" +
".cn/mmopen/ajNVdqHZLLA3WJ6DSZUfiakYe37PKnQhBIeOQBO4czqrnZDS79FH5Wm5m4X69TBicnHFlhiafvDwklOpZeXYQQ2icg/0" +
"]]></Avatar>\n" +
" <Alias><![CDATA[zhangsan]]></Alias>\n" +
" <Telephone><![CDATA[020-3456788]]></Telephone>\n" +
" <Address><![CDATA[广州市]]></Address>\n" +
" <ExtAttr>\n" +
" <Item>\n" +
" <Name><![CDATA[爱好]]></Name>\n" +
" <Type>0</Type>\n" +
" <Text>\n" +
" <Value><![CDATA[旅游]]></Value>\n" +
" </Text>\n" +
" </Item>\n" +
" <Item>\n" +
" <Name><![CDATA[卡号]]></Name>\n" +
" <Type>1</Type>\n" +
" <Web>\n" +
" <Title><![CDATA[企业微信]]></Title>\n" +
" <Url><![CDATA[https://work.weixin.qq.com]]></Url>\n" +
" </Web>\n" +
" </Item>\n" +
" </ExtAttr>\n" +
"</xml>";
WxCpXmlMessage wxCpXmlMessage = WxCpXmlMessage.fromXml(xml);
assertThat(wxCpXmlMessage).isNotNull();
assertThat(wxCpXmlMessage.getDepartments()).isNotEmpty();
System.out.println(XStreamTransformer.toXml(WxCpXmlMessage.class, wxCpXmlMessage));
}
/**
* Test template card event.
*/
public void testTemplateCardEvent() {
String xml = "<xml>\n" +
"<ToUserName><![CDATA[toUser]]></ToUserName>\n" +
"<FromUserName><![CDATA[FromUser]]></FromUserName>\n" +
"<CreateTime>123456789</CreateTime>\n" +
"<MsgType><![CDATA[event]]></MsgType>\n" +
"<Event><![CDATA[template_card_event]]></Event>\n" +
"<EventKey><![CDATA[key111]]></EventKey>\n" +
"<TaskId><![CDATA[taskid111]]></TaskId>\n" +
"<CardType><![CDATA[text_notice]]></CardType>\n" +
"<ResponseCode><![CDATA[ResponseCode]]></ResponseCode>\n" +
"<AgentID>1</AgentID>\n" +
"<SelectedItems>\n" +
" <SelectedItem>\n" +
" <QuestionKey><![CDATA[QuestionKey1]]></QuestionKey>\n" +
" <OptionIds>\n" +
" <OptionId><![CDATA[OptionId1]]></OptionId>\n" +
" <OptionId><![CDATA[OptionId2]]></OptionId>\n" +
" </OptionIds>\n" +
" </SelectedItem>\n" +
" <SelectedItem>\n" +
" <QuestionKey><![CDATA[QuestionKey2]]></QuestionKey>\n" +
" <OptionIds>\n" +
" <OptionId><![CDATA[OptionId3]]></OptionId>\n" +
" <OptionId><![CDATA[OptionId4]]></OptionId>\n" +
" </OptionIds>\n" +
" </SelectedItem>\n" +
"</SelectedItems>\n" +
"</xml>";
WxCpXmlMessage wxCpXmlMessage = WxCpXmlMessage.fromXml(xml);
assertThat(wxCpXmlMessage).isNotNull();
assertThat(wxCpXmlMessage.getSelectedItems()).isNotEmpty();
assertThat(wxCpXmlMessage.getSelectedItems().get(0).getQuestionKey()).isNotEmpty();
assertThat(wxCpXmlMessage.getSelectedItems().get(0).getOptionIds().get(0)).isNotEmpty();
}
/**
* Test open approval change.
*/
public void testOpenApprovalChange() {
String xml = "<xml>\n" +
" <ToUserName><![CDATA[wwddddccc7775555aaa]]></ToUserName>\n" +
" <FromUserName><![CDATA[sys]]></FromUserName>\n" +
" <CreateTime>1527838022</CreateTime>\n" +
" <MsgType><![CDATA[event]]></MsgType>\n" +
" <Event><![CDATA[open_approval_change]]></Event>\n" +
" <AgentID>1</AgentID>\n" +
" <ApprovalInfo>\n" +
" <ThirdNo><![CDATA[201806010001]]></ThirdNo>\n" +
" <OpenSpName><![CDATA[付款]]></OpenSpName>\n" +
" <OpenTemplateId><![CDATA[1234567890]]></OpenTemplateId>\n" +
" <OpenSpStatus>1</OpenSpStatus>\n" +
" <ApplyTime>1527837645</ApplyTime>\n" +
" <ApplyUserName><![CDATA[xiaoming]]></ApplyUserName>\n" +
" <ApplyUserId><![CDATA[1]]></ApplyUserId>\n" +
" <ApplyUserParty><![CDATA[产品部]]></ApplyUserParty>\n" +
" <ApplyUserImage><![CDATA[http://www.qq.com/xxx.png]]></ApplyUserImage>\n" +
" <ApprovalNodes>\n" +
" <ApprovalNode>\n" +
" <NodeStatus>1</NodeStatus>\n" +
" <NodeAttr>1</NodeAttr>\n" +
" <NodeType>1</NodeType>\n" +
" <Items>\n" +
" <Item>\n" +
" <ItemName><![CDATA[xiaohong]]></ItemName>\n" +
" <ItemUserId><![CDATA[2]]></ItemUserId>\n" +
" <ItemImage><![CDATA[http://www.qq.com/xxx.png]]></ItemImage>\n" +
" <ItemStatus>1</ItemStatus>\n" +
" <ItemSpeech><![CDATA[]]></ItemSpeech>\n" +
" <ItemOpTime>0</ItemOpTime>\n" +
" </Item>\n" +
" </Items>\n" +
" </ApprovalNode>\n" +
" <ApprovalNode>\n" +
" <NodeStatus>1</NodeStatus>\n" +
" <NodeAttr>1</NodeAttr>\n" +
" <NodeType>1</NodeType>\n" +
" <Items>\n" +
" <Item>\n" +
" <ItemName><![CDATA[xiaohong]]></ItemName>\n" +
" <ItemUserId><![CDATA[2]]></ItemUserId>\n" +
" <ItemImage><![CDATA[http://www.qq.com/xxx.png]]></ItemImage>\n" +
" <ItemStatus>1</ItemStatus>\n" +
" <ItemSpeech><![CDATA[]]></ItemSpeech>\n" +
" <ItemOpTime>0</ItemOpTime>\n" +
" </Item>\n" +
" <Item>\n" +
" <ItemName><![CDATA[xiaohong]]></ItemName>\n" +
" <ItemUserId><![CDATA[2]]></ItemUserId>\n" +
" <ItemImage><![CDATA[http://www.qq.com/xxx.png]]></ItemImage>\n" +
" <ItemStatus>1</ItemStatus>\n" +
" <ItemSpeech><![CDATA[]]></ItemSpeech>\n" +
" <ItemOpTime>0</ItemOpTime>\n" +
" </Item>\n" +
" </Items>\n" +
" </ApprovalNode>\n" +
" </ApprovalNodes>\n" +
" <NotifyNodes>\n" +
" <NotifyNode>\n" +
" <ItemName><![CDATA[xiaogang]]></ItemName>\n" +
" <ItemUserId><![CDATA[3]]></ItemUserId>\n" +
" <ItemImage><![CDATA[http://www.qq.com/xxx.png]]></ItemImage>\n" +
" </NotifyNode>\n" +
" </NotifyNodes>\n" +
" <approverstep>0</approverstep>\n" +
" </ApprovalInfo>\n" +
"</xml>\n";
WxCpXmlMessage wxCpXmlMessage = WxCpXmlMessage.fromXml(xml);
assertThat(wxCpXmlMessage).isNotNull();
assertThat(wxCpXmlMessage.getApprovalInfo().getApprovalNodes()).isNotEmpty();
assertThat(wxCpXmlMessage.getApprovalInfo().getApprovalNodes().get(0).getItems()).isNotEmpty();
assertThat(wxCpXmlMessage.getApprovalInfo().getApprovalNodes().get(0).getItems().get(0).getItemName()).isNotEmpty();
assertThat(wxCpXmlMessage.getApprovalInfo().getNotifyNodes().get(0).getItemName()).isNotEmpty();
}
/**
* Test open approval change.
*/
public void testUploadMediaJobFinishEvent() {
String xml = "<xml>\n" +
"\t<ToUserName><![CDATA[wx28dbb14e3720FAKE]]></ToUserName>\n" +
"\t<FromUserName><![CDATA[sys]]></FromUserName>\n" +
"\t<CreateTime>1425284517</CreateTime>\n" +
"\t<MsgType><![CDATA[event]]></MsgType>\n" +
"\t<Event><![CDATA[upload_media_job_finish]]></Event>\n" +
"\t<JobId><![CDATA[jobid_S0MrnndvRG5fadSlLwiBqiDDbM143UqTmKP3152FZk4]]></JobId>\n" +
"</xml>";
WxCpXmlMessage wxCpXmlMessage = WxCpXmlMessage.fromXml(xml);
assertThat(wxCpXmlMessage).isNotNull();
assertThat(wxCpXmlMessage.getJobId()).isNotEmpty();
assertThat(wxCpXmlMessage.getJobId()).isEqualTo("jobid_S0MrnndvRG5fadSlLwiBqiDDbM143UqTmKP3152FZk4");
assertThat(wxCpXmlMessage.getEvent()).isEqualTo(UPLOAD_MEDIA_JOB_FINISH);
}
/**
* Test both numeric and string msgId formats to ensure backward compatibility
*/
public void testMsgIdStringAndNumericFormats() {
// Test with numeric msgId (old format)
String xmlWithNumeric = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1348831860</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[this is a test]]></Content>"
+ "<MsgId>1234567890123456</MsgId>"
+ "</xml>";
WxCpXmlMessage wxMessageNumeric = WxCpXmlMessage.fromXml(xmlWithNumeric);
assertEquals(wxMessageNumeric.getMsgId(), "1234567890123456");
// Test with string msgId (new format - the actual issue case)
String xmlWithString = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1348831860</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[this is a test]]></Content>"
+ "<MsgId>CAIQg/PKxgYY2sC9tpuAgAMg9/zKaw==</MsgId>"
+ "</xml>";
WxCpXmlMessage wxMessageString = WxCpXmlMessage.fromXml(xmlWithString);
assertEquals(wxMessageString.getMsgId(), "CAIQg/PKxgYY2sC9tpuAgAMg9/zKaw==");
}
/**
* Test intelligent robot message parsing
* 测试智能机器人消息解析
*/
public void testIntelligentRobotMessage() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName>"
+ "<CreateTime>1348831860</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[你好,智能机器人]]></Content>"
+ "<MsgId>msg123456</MsgId>"
+ "<RobotId><![CDATA[robot_id_123]]></RobotId>"
+ "<SessionId><![CDATA[session_id_456]]></SessionId>"
+ "</xml>";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUserName(), "toUser");
assertEquals(wxMessage.getFromUserName(), "fromUser");
assertEquals(wxMessage.getCreateTime(), Long.valueOf(1348831860));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.TEXT);
assertEquals(wxMessage.getContent(), "你好,智能机器人");
assertEquals(wxMessage.getMsgId(), "msg123456");
assertEquals(wxMessage.getRobotId(), "robot_id_123");
assertEquals(wxMessage.getSessionId(), "session_id_456");
}
/**
* Test external chat change event
* 测试企业微信群聊变更事件解析 - 群成员变更场景
*/
public void testExternalChatChangeEvent() {
// 测试群成员加入事件
String xmlAddMember = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[sys]]></FromUserName>"
+ "<CreateTime>1403610513</CreateTime>"
+ "<MsgType><![CDATA[event]]></MsgType>"
+ "<Event><![CDATA[change_external_chat]]></Event>"
+ "<ChangeType><![CDATA[update]]></ChangeType>"
+ "<ChatId><![CDATA[wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA]]></ChatId>"
+ "<UpdateDetail><![CDATA[add_member]]></UpdateDetail>"
+ "<JoinScene>1</JoinScene>"
+ "<MemChangeCnt>2</MemChangeCnt>"
+ "<MemChangeList><![CDATA[wmEJiCwAAA9KG2qlSq6rKwASSgAAAA,wmEJiCwAAA9KG2qlSq6rKwBBBBBBB]]></MemChangeList>"
+ "</xml>";
WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xmlAddMember);
assertEquals(wxMessage.getToUserName(), "toUser");
assertEquals(wxMessage.getFromUserName(), "sys");
assertEquals(wxMessage.getCreateTime(), Long.valueOf(1403610513L));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.EVENT);
assertEquals(wxMessage.getEvent(), WxCpConsts.EventType.CHANGE_EXTERNAL_CHAT);
assertEquals(wxMessage.getChangeType(), "update");
assertEquals(wxMessage.getChatId(), "wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA");
assertEquals(wxMessage.getUpdateDetail(), "add_member");
assertEquals(wxMessage.getJoinScene(), "1");
assertEquals(wxMessage.getMemChangeCnt(), "2");
assertEquals(wxMessage.getMemChangeList(), "wmEJiCwAAA9KG2qlSq6rKwASSgAAAA,wmEJiCwAAA9KG2qlSq6rKwBBBBBBB");
// 测试群成员退出事件
String xmlDelMember = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[sys]]></FromUserName>"
+ "<CreateTime>1403610513</CreateTime>"
+ "<MsgType><![CDATA[event]]></MsgType>"
+ "<Event><![CDATA[change_external_chat]]></Event>"
+ "<ChangeType><![CDATA[update]]></ChangeType>"
+ "<ChatId><![CDATA[wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA]]></ChatId>"
+ "<UpdateDetail><![CDATA[del_member]]></UpdateDetail>"
+ "<QuitScene>1</QuitScene>"
+ "<MemChangeCnt>1</MemChangeCnt>"
+ "<MemChangeList><![CDATA[wmEJiCwAAA9KG2qlSq6rKwASSgAAAA]]></MemChangeList>"
+ "</xml>";
WxCpXmlMessage wxMessage2 = WxCpXmlMessage.fromXml(xmlDelMember);
assertEquals(wxMessage2.getEvent(), WxCpConsts.EventType.CHANGE_EXTERNAL_CHAT);
assertEquals(wxMessage2.getChangeType(), "update");
assertEquals(wxMessage2.getChatId(), "wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA");
assertEquals(wxMessage2.getUpdateDetail(), "del_member");
assertEquals(wxMessage2.getQuitScene(), "1");
assertEquals(wxMessage2.getMemChangeCnt(), "1");
assertEquals(wxMessage2.getMemChangeList(), "wmEJiCwAAA9KG2qlSq6rKwASSgAAAA");
// 测试空MemChangeList场景(某些情况下可能没有成员变更列表)
String xmlNoMemChangeList = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[sys]]></FromUserName>"
+ "<CreateTime>1403610513</CreateTime>"
+ "<MsgType><![CDATA[event]]></MsgType>"
+ "<Event><![CDATA[change_external_chat]]></Event>"
+ "<ChangeType><![CDATA[update]]></ChangeType>"
+ "<ChatId><![CDATA[wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA]]></ChatId>"
+ "<UpdateDetail><![CDATA[change_name]]></UpdateDetail>"
+ "</xml>";
WxCpXmlMessage wxMessage3 = WxCpXmlMessage.fromXml(xmlNoMemChangeList);
assertEquals(wxMessage3.getEvent(), WxCpConsts.EventType.CHANGE_EXTERNAL_CHAT);
assertEquals(wxMessage3.getChangeType(), "update");
assertEquals(wxMessage3.getUpdateDetail(), "change_name");
// 当XML中没有MemChangeList元素时,字段应该为null而不是空字符串
assertThat(wxMessage3.getMemChangeList()).isNull();
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutVoiceMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutVoiceMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* The type Wx cp xml out voice message test.
*/
@Test
public class WxCpXmlOutVoiceMessageTest {
/**
* Test.
*/
public void test() {
WxCpXmlOutVoiceMessage m = new WxCpXmlOutVoiceMessage();
m.setMediaId("ddfefesfsdfef");
m.setCreateTime(1122L);
m.setFromUserName("from");
m.setToUserName("to");
String expected = "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[voice]]></MsgType>"
+ "<Voice><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Voice>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
/**
* Test build.
*/
public void testBuild() {
WxCpXmlOutVoiceMessage m = WxCpXmlOutMessage.VOICE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build();
String expected = "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[voice]]></MsgType>"
+ "<Voice><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Voice>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpLinkedCorpMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpLinkedCorpMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.bean.article.MpnewsArticle;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import org.testng.annotations.Test;
import static me.chanjar.weixin.common.api.WxConsts.KefuMsgType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 测试用例中的json参考 https://work.weixin.qq.com/api/doc/90000/90135/90250
*
* @author <a href="https://github.com/binarywang">Binary Wang</a> created on 2020-08-30
*/
public class WxCpLinkedCorpMessageTest {
/**
* Test to json text.
*/
@Test
public void testToJson_text() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.TEXT)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.agentId(1)
.isToAll(false)
.isSafe(false)
.content("你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"text\",\n" +
" \"agentid\" : 1,\n" +
" \"text\" : {\n" +
" \"content\" : \"你的快递已到,请携带工卡前往邮件中心领取。\\n出发前可查看<a href=\\\"http://work.weixin.qq" +
".com\\\">邮件中心视频实况</a>,聪明避开排队。\"\n" +
" },\n" +
" \"safe\":0\n" +
"}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json image.
*/
@Test
public void testToJson_image() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.IMAGE)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.agentId(1)
.isToAll(false)
.isSafe(false)
.mediaId("MEDIA_ID")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"image\",\n" +
" \"agentid\" : 1,\n" +
" \"image\" : {\n" +
" \"media_id\" : \"MEDIA_ID\"\n" +
" },\n" +
" \"safe\":0\n" +
"}";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json video.
*/
@Test
public void testToJson_video() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.VIDEO)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.agentId(1)
.isToAll(false)
.isSafe(false)
.mediaId("MEDIA_ID")
.title("Title")
.description("Description")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"video\",\n" +
" \"agentid\" : 1,\n" +
" \"video\" : {\n" +
" \"media_id\" : \"MEDIA_ID\",\n" +
" \"title\" : \"Title\",\n" +
" \"description\" : \"Description\"\n" +
" },\n" +
" \"safe\":0\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json file.
*/
@Test
public void testToJson_file() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.FILE)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.agentId(1)
.isToAll(false)
.isSafe(false)
.mediaId("1Yv-zXfHjSjU-7LH-GwtYqDGS-zz6w22KmWAT5COgP7o")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"file\",\n" +
" \"agentid\" : 1,\n" +
" \"file\" : {\n" +
" \"media_id\" : \"1Yv-zXfHjSjU-7LH-GwtYqDGS-zz6w22KmWAT5COgP7o\"\n" +
" },\n" +
" \"safe\":0\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json text card.
*/
@Test
public void testToJson_textCard() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.TEXTCARD)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.agentId(1)
.isToAll(false)
.title("领奖通知")
.description("<div class=\"gray\">2016年9月26日</div> <div class=\"normal\">恭喜你抽中iPhone 7一台,领奖码:xxxx</div><div " +
"class=\"highlight\">请于2016年10月10日前联系行政同事领取</div>")
.url("URL")
.btnTxt("更多")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"textcard\",\n" +
" \"agentid\" : 1,\n" +
" \"textcard\" : {\n" +
" \"title\" : \"领奖通知\",\n" +
" \"description\" : \"<div class=\\\"gray\\\">2016年9月26日</div> <div class=\\\"normal\\\">恭喜你抽中iPhone" +
" 7一台,领奖码:xxxx</div><div class=\\\"highlight\\\">请于2016年10月10日前联系行政同事领取</div>\",\n" +
" \"url\" : \"URL\",\n" +
" \"btntxt\":\"更多\"\n" +
" }\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json news.
*/
@Test
public void testToJson_news() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.NEWS)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.agentId(1)
.isToAll(false)
.articles(Lists.newArrayList(NewArticle.builder()
.title("中秋节礼品领取")
.description("今年中秋节公司有豪礼相送")
.url("URL")
.picUrl("http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png")
.btnText("更多")
.build()))
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"news\",\n" +
" \"agentid\" : 1,\n" +
" \"news\" : {\n" +
" \"articles\" : [\n" +
" {\n" +
" \"title\" : \"中秋节礼品领取\",\n" +
" \"description\" : \"今年中秋节公司有豪礼相送\",\n" +
" \"url\" : \"URL\",\n" +
" \"picurl\" : \"http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1" +
".png\",\n" +
" \"btntxt\":\"更多\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json mpnews.
*/
@Test
public void testToJson_mpnews() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.MPNEWS)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.agentId(1)
.isToAll(false)
.isSafe(false)
.mpNewsArticles(Lists.newArrayList(MpnewsArticle.newBuilder()
.title("Title")
.thumbMediaId("MEDIA_ID")
.author("Author")
.contentSourceUrl("URL")
.content("Content")
.digest("Digest description")
.build()))
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"mpnews\",\n" +
" \"agentid\" : 1,\n" +
" \"mpnews\" : {\n" +
" \"articles\":[\n" +
" {\n" +
" \"title\": \"Title\", \n" +
" \"thumb_media_id\": \"MEDIA_ID\",\n" +
" \"author\": \"Author\",\n" +
" \"content_source_url\": \"URL\",\n" +
" \"content\": \"Content\",\n" +
" \"digest\": \"Digest description\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"safe\":0\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json markdown.
*/
@Test
public void testToJson_markdown() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.MARKDOWN)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.agentId(1)
.isToAll(false)
.content("您的会议室已经预定,稍后会同步到`邮箱`\n" +
" >**事项详情**\n" +
" >事 项:<font color=\"info\">开会</font>\n" +
" >组织者:@miglioguan\n" +
" >参与者:@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang\n" +
" >\n" +
" >会议室:<font color=\"info\">广州TIT 1楼 301</font>\n" +
" >日 期:<font color=\"warning\">2018年5月18日</font>\n" +
" >时 间:<font color=\"comment\">上午9:00-11:00</font>\n" +
" >\n" +
" >请准时参加会议。\n" +
" >\n" +
" >如需修改会议信息,请点击:[修改会议信息](https://work.weixin.qq.com)")
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"toall\" : 0,\n" +
" \"msgtype\" : \"markdown\",\n" +
" \"agentid\" : 1,\n" +
" \"markdown\": {\n" +
" \"content\": \"您的会议室已经预定,稍后会同步到`邮箱`\n" +
" >**事项详情**\n" +
" >事 项:<font color=\\\"info\\\">开会</font>\n" +
" >组织者:@miglioguan\n" +
" >参与者:@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang\n" +
" >\n" +
" >会议室:<font color=\\\"info\\\">广州TIT 1楼 301</font>\n" +
" >日 期:<font color=\\\"warning\\\">2018年5月18日</font>\n" +
" >时 间:<font color=\\\"comment\\\">上午9:00-11:00</font>\n" +
" >\n" +
" >请准时参加会议。\n" +
" >\n" +
" >如需修改会议信息,请点击:[修改会议信息](https://work.weixin.qq.com)\"\n" +
" }\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
/**
* Test to json mini program notice.
*/
@Test
public void testToJson_miniProgramNotice() {
WxCpLinkedCorpMessage message = WxCpLinkedCorpMessage.builder()
.msgType(KefuMsgType.MINIPROGRAM_NOTICE)
.toUsers(new String[]{"userid1", "userid2", "CorpId1/userid1", "CorpId2/userid2"})
.toParties(new String[]{"partyid1", "partyid2", "LinkedId1/partyid1", "LinkedId2/partyid2"})
.toTags(new String[]{"tagid1", "tagid2"})
.emphasisFirstItem(true)
.description("4月27日 16:16")
.title("会议室预订成功通知")
.appId("wx123123123123123")
.page("pages/index?userid=zhangsan&orderid=123123123")
.contentItems(ImmutableMap.of("会议室", "402",
"会议地点", "广州TIT-402会议室",
"会议时间", "2018年8月1日 09:00-09:30",
"参与人员", "周剑轩"))
.build();
final String json = message.toJson();
String expectedJson = "{\n" +
" \"touser\" : [\"userid1\",\"userid2\",\"CorpId1/userid1\",\"CorpId2/userid2\"],\n" +
" \"toparty\" : [\"partyid1\",\"partyid2\",\"LinkedId1/partyid1\",\"LinkedId2/partyid2\"],\n" +
" \"totag\" : [\"tagid1\",\"tagid2\"],\n" +
" \"msgtype\" : \"miniprogram_notice\",\n" +
" \"miniprogram_notice\" : {\n" +
" \"appid\": \"wx123123123123123\",\n" +
" \"page\": \"pages/index?userid=zhangsan&orderid=123123123\",\n" +
" \"title\": \"会议室预订成功通知\",\n" +
" \"description\": \"4月27日 16:16\",\n" +
" \"emphasis_first_item\": true,\n" +
" \"content_item\": [\n" +
" {\n" +
" \"key\": \"会议室\",\n" +
" \"value\": \"402\"\n" +
" },\n" +
" {\n" +
" \"key\": \"会议地点\",\n" +
" \"value\": \"广州TIT-402会议室\"\n" +
" },\n" +
" {\n" +
" \"key\": \"会议时间\",\n" +
" \"value\": \"2018年8月1日 09:00-09:30\"\n" +
" },\n" +
" {\n" +
" \"key\": \"参与人员\",\n" +
" \"value\": \"周剑轩\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n";
assertThat(json).isEqualTo(GsonParser.parse(expectedJson).toString());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutTextMessageTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/message/WxCpXmlOutTextMessageTest.java | package me.chanjar.weixin.cp.bean.message;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* The type Wx cp xml out text message test.
*/
@Test
public class WxCpXmlOutTextMessageTest {
/**
* Test.
*/
public void test() {
WxCpXmlOutTextMessage m = new WxCpXmlOutTextMessage();
m.setContent("content");
m.setCreateTime(1122L);
m.setFromUserName("from");
m.setToUserName("to");
String expected = "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[content]]></Content>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", ""));
}
/**
* Test build.
*/
public void testBuild() {
WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("content").fromUser("from").toUser("to").build();
String expected = "<xml>"
+ "<ToUserName><![CDATA[to]]></ToUserName>"
+ "<FromUserName><![CDATA[from]]></FromUserName>"
+ "<CreateTime>1122</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[content]]></Content>"
+ "</xml>";
System.out.println(m.toXml());
Assert.assertEquals(
m
.toXml()
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", ""),
expected
.replaceAll("\\s", "")
.replaceAll("<CreateTime>.*?</CreateTime>", "")
);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/config/impl/WxCpTpDefaultConfigImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/config/impl/WxCpTpDefaultConfigImplTest.java | package me.chanjar.weixin.cp.config.impl;
import me.chanjar.weixin.common.bean.WxAccessToken;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
/**
* The type Wx cp tp default config impl test.
*/
public class WxCpTpDefaultConfigImplTest {
/**
* Test get suite access token entity.
*
* @throws InterruptedException the interrupted exception
*/
@Test
public void testGetSuiteAccessTokenEntity() throws InterruptedException {
final String testAccessToken = "5O_32IEDOib99RliaF301vzGiZaAJw3CsaNb4QXyQ" +
"-07KJ0UDQ8nxq9vs66jNLIZ4TvYs3QFlYZag1WfG8i4gNu_dYQj2Ff89xznZPquv7EFMAZha_faYZrE0uCFRqkV";
final long testExpireTime = 7200L;
final long restTime = 10L;
WxCpTpDefaultConfigImpl storage = new WxCpTpDefaultConfigImpl();
storage.setSuiteAccessToken(testAccessToken);
storage.setSuiteAccessTokenExpiresTime(System.currentTimeMillis() + (testExpireTime - 200) * 1000L);
TimeUnit.SECONDS.sleep(restTime);
WxAccessToken accessToken = storage.getSuiteAccessTokenEntity();
Assert.assertEquals(accessToken.getAccessToken(), testAccessToken, "accessToken不一致");
Assert.assertTrue(accessToken.getExpiresIn() <= testExpireTime - restTime, "过期时间计算有误");
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/config/impl/DemoToStringFix.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/config/impl/DemoToStringFix.java | package me.chanjar.weixin.cp.config.impl;
import me.chanjar.weixin.common.redis.WxRedisOps;
/**
* Demonstration of the fix for toString() StackOverflowError issue
*/
public class DemoToStringFix {
public static void main(String[] args) {
System.out.println("=== Demonstrating toString() Fix for WxCp Redis Config ===");
// Create a simple stub WxRedisOps implementation for testing
WxRedisOps stubRedisOps = new WxRedisOps() {
@Override
public String getValue(String key) { return null; }
@Override
public void setValue(String key, String value, int expire, java.util.concurrent.TimeUnit timeUnit) {}
@Override
public Long getExpire(String key) { return null; }
@Override
public void expire(String key, int expire, java.util.concurrent.TimeUnit timeUnit) {}
@Override
public java.util.concurrent.locks.Lock getLock(String key) { return null; }
};
// Test AbstractWxCpInRedisConfigImpl directly with our stub
AbstractWxCpInRedisConfigImpl config = new AbstractWxCpInRedisConfigImpl(stubRedisOps, "demo:") {
// Anonymous class to test the abstract parent
};
config.setCorpId("demoCorpId");
config.setAgentId(1001);
System.out.println("Testing toString() method:");
try {
String result = config.toString();
System.out.println("✓ Success! toString() returned: " + result);
System.out.println("✓ No StackOverflowError occurred");
// Verify the result contains expected information and excludes redisOps
boolean containsCorpId = result.contains("demoCorpId");
boolean containsAgentId = result.contains("1001");
boolean containsKeyPrefix = result.contains("demo:");
boolean excludesRedisOps = !result.contains("redisOps") && !result.contains("WxRedisOps");
System.out.println("✓ Contains corpId: " + containsCorpId);
System.out.println("✓ Contains agentId: " + containsAgentId);
System.out.println("✓ Contains keyPrefix: " + containsKeyPrefix);
System.out.println("✓ Excludes redisOps: " + excludesRedisOps);
if (containsCorpId && containsAgentId && containsKeyPrefix && excludesRedisOps) {
System.out.println("✓ All validations passed!");
} else {
System.out.println("✗ Some validations failed");
}
} catch (StackOverflowError e) {
System.out.println("✗ StackOverflowError still occurred - fix failed");
} catch (Exception e) {
System.out.println("✗ Unexpected error: " + e.getMessage());
}
System.out.println("\n=== Demo completed ===");
}
} | java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/config/impl/WxCpRedisConfigImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/config/impl/WxCpRedisConfigImplTest.java | package me.chanjar.weixin.cp.config.impl;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
import redis.clients.jedis.JedisPool;
/**
* WxCpRedisConfigImpl 测试类
*/
public class WxCpRedisConfigImplTest {
/**
* 测试 getWebhookKey 方法不会导致无限递归
* 这个测试验证了 #issue 中提到的无限递归问题已被修复
*/
@Test
public void testGetWebhookKeyNoInfiniteRecursion() {
// 使用 Mockito 创建 mock JedisPool,避免真实连接
JedisPool jedisPool = Mockito.mock(JedisPool.class);
WxCpRedisConfigImpl config = new WxCpRedisConfigImpl(jedisPool);
// 测试1: webhookKey 为 null 时应该返回 null,而不是抛出 StackOverflowError
String webhookKey = config.getWebhookKey();
Assert.assertNull(webhookKey, "未设置 webhookKey 时应返回 null");
// 测试2: 通过反射设置 webhookKey,然后验证能够正确获取
// 注意:由于 WxCpRedisConfigImpl 没有提供 setWebhookKey 方法,
// 我们通过反射来设置这个字段以测试 getter 的正确性
try {
java.lang.reflect.Field field = WxCpRedisConfigImpl.class.getDeclaredField("webhookKey");
boolean originalAccessible = field.isAccessible();
field.setAccessible(true);
try {
String testWebhookKey = "test-webhook-key-123";
field.set(config, testWebhookKey);
String retrievedKey = config.getWebhookKey();
Assert.assertEquals(retrievedKey, testWebhookKey, "应该返回设置的 webhookKey 值");
} finally {
field.setAccessible(originalAccessible);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.fail("反射设置 webhookKey 失败: " + e.getMessage());
}
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/corpgroup/service/impl/WxCpCgServiceApacheHttpClientImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/corpgroup/service/impl/WxCpCgServiceApacheHttpClientImplTest.java | package me.chanjar.weixin.cp.corpgroup.service.impl;
import com.google.gson.JsonObject;
import com.google.inject.Inject;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceApacheHttpClientImpl;
import me.chanjar.weixin.cp.bean.WxCpAgent;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.corpgroup.WxCpCorpGroupCorpGetTokenReq;
import me.chanjar.weixin.cp.bean.corpgroup.WxCpMaTransferSession;
import me.chanjar.weixin.cp.config.WxCpCorpGroupConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpCorpGroupDefaultConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpCorpGroupRedissonConfigImpl;
import me.chanjar.weixin.cp.constant.WxCpApiPathConsts;
import me.chanjar.weixin.cp.corpgroup.service.WxCpCgService;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.CorpGroup.MA_TRANSFER_SESSION;
import static org.testng.Assert.assertNotNull;
/**
* @author libo
*/
@Guice(modules = ApiTestModule.class)
public class WxCpCgServiceApacheHttpClientImplTest {
private final WxCpCgService cgService = Mockito.spy(new WxCpCgServiceApacheHttpClientImpl());
WxCpCorpGroupConfigStorage wxCpCorpGroupConfigStorage;
@Inject
WxCpService wxCpService;
//下游企业的corpId
String corpId = "";
//下游企业的agentId
int agentId = 0;
int businessType = 0;
String userId = "";
WxCpCorpGroupCorpGetTokenReq wxCpCorpGroupCorpGetTokenReq;
@BeforeMethod
public void setUp() {
cgService.setWxCpCorpGroupConfigStorage(wxCpCorpGroupConfigStorage());
cgService.setWxCpService(wxCpService);
wxCpCorpGroupCorpGetTokenReq = new WxCpCorpGroupCorpGetTokenReq();
wxCpCorpGroupCorpGetTokenReq.setCorpId(corpId);
wxCpCorpGroupCorpGetTokenReq.setAgentId(agentId);
wxCpCorpGroupCorpGetTokenReq.setBusinessType(businessType);
}
public WxCpCorpGroupConfigStorage wxCpCorpGroupConfigStorage() {
wxCpCorpGroupConfigStorage = new WxCpCorpGroupDefaultConfigImpl();
wxCpCorpGroupConfigStorage.setCorpId(wxCpService.getWxCpConfigStorage().getCorpId());
wxCpCorpGroupConfigStorage.setAgentId(wxCpService.getWxCpConfigStorage().getAgentId());
return wxCpCorpGroupConfigStorage;
}
@Test
public void testGetCorpAccessToken() throws Exception {
String corpAccessToken = cgService.getCorpAccessToken(corpId, agentId, businessType);
assertNotNull(corpAccessToken);
}
/**
* 通讯录-读取成员
*
* @throws Exception
*/
@Test
public void testGetCorpUser() throws Exception {
String result = cgService.get(wxCpService.getWxCpConfigStorage().getApiUrl(WxCpApiPathConsts.User.USER_GET + userId), null, wxCpCorpGroupCorpGetTokenReq);
assertNotNull(result);
WxCpUser wxCpUser = WxCpUser.fromJson(result);
assertNotNull(wxCpUser.getUserId());
}
/**
* 应用管理-获取指定的应用详情
*
* @throws Exception
*/
@Test
public void testGetAgent() throws Exception {
String result = cgService.get(wxCpService.getWxCpConfigStorage().getApiUrl(String.format(WxCpApiPathConsts.Agent.AGENT_GET, agentId)), null, wxCpCorpGroupCorpGetTokenReq);
assertNotNull(result);
WxCpAgent wxCpAgent = WxCpAgent.fromJson(result);
assertNotNull(wxCpAgent.getAgentId());
}
/**
* 获取下级/下游企业小程序session
*
* @throws Exception
*/
@Test
public void testGetTransferSession() throws Exception {
String sessionKey = "";
WxCpMaTransferSession wxCpMaTransferSession = cgService.getCorpTransferSession(userId, sessionKey, wxCpCorpGroupCorpGetTokenReq);
assertNotNull(wxCpMaTransferSession);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/corpgroup/service/impl/WxCpLinkedCorpServiceImplTest.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/corpgroup/service/impl/WxCpLinkedCorpServiceImplTest.java | package me.chanjar.weixin.cp.corpgroup.service.impl;
import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.corpgroup.WxCpCorpGroupCorpGetTokenReq;
import me.chanjar.weixin.cp.bean.linkedcorp.WxCpLinkedCorpAgentPerm;
import me.chanjar.weixin.cp.bean.linkedcorp.WxCpLinkedCorpDepartment;
import me.chanjar.weixin.cp.bean.linkedcorp.WxCpLinkedCorpUser;
import me.chanjar.weixin.cp.config.WxCpCorpGroupConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpCorpGroupDefaultConfigImpl;
import me.chanjar.weixin.cp.corpgroup.service.WxCpCgService;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import java.util.List;
import static org.testng.Assert.assertNotNull;
/**
* @author libo
*/
@Guice(modules = ApiTestModule.class)
public class WxCpLinkedCorpServiceImplTest {
WxCpCorpGroupConfigStorage wxCpCorpGroupConfigStorage;
@Inject
WxCpService wxCpService;
WxCpCgService cgService;
//下游企业的corpId
String corpId = "";
//下游企业的agentId
int agentId = 0;
int businessType = 0;
//CorpID/UserID
String corpUserId = "";
String departmentId = "";
WxCpCorpGroupCorpGetTokenReq wxCpCorpGroupCorpGetTokenReq;
@BeforeMethod
public void setUp() {
cgService = new WxCpCgServiceApacheHttpClientImpl();
cgService.setWxCpCorpGroupConfigStorage(wxCpCorpGroupConfigStorage());
cgService.setWxCpService(wxCpService);
wxCpCorpGroupCorpGetTokenReq = new WxCpCorpGroupCorpGetTokenReq();
wxCpCorpGroupCorpGetTokenReq.setCorpId(corpId);
wxCpCorpGroupCorpGetTokenReq.setAgentId(agentId);
wxCpCorpGroupCorpGetTokenReq.setBusinessType(businessType);
}
public WxCpCorpGroupConfigStorage wxCpCorpGroupConfigStorage() {
wxCpCorpGroupConfigStorage = new WxCpCorpGroupDefaultConfigImpl();
wxCpCorpGroupConfigStorage.setCorpId(wxCpService.getWxCpConfigStorage().getCorpId());
wxCpCorpGroupConfigStorage.setAgentId(wxCpService.getWxCpConfigStorage().getAgentId());
return wxCpCorpGroupConfigStorage;
}
@Test
public void testGetLinkedCorpAgentPerm() throws WxErrorException {
WxCpLinkedCorpAgentPerm resp = cgService.getLinkedCorpService().getLinkedCorpAgentPerm(wxCpCorpGroupCorpGetTokenReq);
assertNotNull(resp);
}
@Test
public void testGetLinkedCorpUser() throws WxErrorException {
WxCpLinkedCorpUser resp = cgService.getLinkedCorpService().getLinkedCorpUser(corpUserId, wxCpCorpGroupCorpGetTokenReq);
assertNotNull(resp);
}
@Test
public void testGetLinkedCorpSimpleUserList() throws WxErrorException {
List<WxCpLinkedCorpUser> resp = cgService.getLinkedCorpService().getLinkedCorpSimpleUserList(departmentId, wxCpCorpGroupCorpGetTokenReq);
assertNotNull(resp);
}
@Test
public void testGetLinkedCorpUserList() throws WxErrorException {
List<WxCpLinkedCorpUser> resp = cgService.getLinkedCorpService().getLinkedCorpUserList(departmentId, wxCpCorpGroupCorpGetTokenReq);
assertNotNull(resp);
}
@Test
public void testGetLinkedCorpDepartmentList() throws WxErrorException {
List<WxCpLinkedCorpDepartment> resp = cgService.getLinkedCorpService().getLinkedCorpDepartmentList(departmentId, wxCpCorpGroupCorpGetTokenReq);
assertNotNull(resp);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java | package me.chanjar.weixin.cp.demo;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* The type Wx cp endpoint servlet.
*
* @author Daniel Qian
*/
public class WxCpEndpointServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* The Wx cp config storage.
*/
protected WxCpConfigStorage wxCpConfigStorage;
/**
* The Wx cp service.
*/
protected WxCpService wxCpService;
/**
* The Wx cp message router.
*/
protected WxCpMessageRouter wxCpMessageRouter;
/**
* Instantiates a new Wx cp endpoint servlet.
*
* @param wxCpConfigStorage the wx cp config storage
* @param wxCpService the wx cp service
* @param wxCpMessageRouter the wx cp message router
*/
public WxCpEndpointServlet(WxCpConfigStorage wxCpConfigStorage, WxCpService wxCpService,
WxCpMessageRouter wxCpMessageRouter) {
this.wxCpConfigStorage = wxCpConfigStorage;
this.wxCpService = wxCpService;
this.wxCpMessageRouter = wxCpMessageRouter;
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
String msgSignature = request.getParameter("msg_signature");
String nonce = request.getParameter("nonce");
String timestamp = request.getParameter("timestamp");
String echostr = request.getParameter("echostr");
if (StringUtils.isNotBlank(echostr)) {
if (!this.wxCpService.checkSignature(msgSignature, timestamp, nonce, echostr)) {
// 消息签名不正确,说明不是公众平台发过来的消息
response.getWriter().println("非法请求");
return;
}
WxCpCryptUtil cryptUtil = new WxCpCryptUtil(this.wxCpConfigStorage);
String plainText = cryptUtil.decrypt(echostr);
// 说明是一个仅仅用来验证的请求,回显echostr
response.getWriter().println(plainText);
return;
}
WxCpXmlMessage inMessage = WxCpXmlMessage
.fromEncryptedXml(request.getInputStream(), this.wxCpConfigStorage, timestamp, nonce, msgSignature);
WxCpXmlOutMessage outMessage = this.wxCpMessageRouter.route(inMessage);
if (outMessage != null) {
response.getWriter().write(outMessage.toEncryptedXml(this.wxCpConfigStorage));
}
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpApprovalWorkflowDemo.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpApprovalWorkflowDemo.java | package me.chanjar.weixin.cp.demo;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.WxCpApprovalDetailResult;
import me.chanjar.weixin.cp.bean.oa.WxCpApprovalInfo;
import me.chanjar.weixin.cp.bean.oa.WxCpOaApplyEventRequest;
import me.chanjar.weixin.cp.bean.oa.WxCpOaApprovalTemplateResult;
import me.chanjar.weixin.cp.bean.oa.applydata.ApplyDataContent;
import me.chanjar.weixin.cp.bean.oa.applydata.ContentValue;
import java.util.Arrays;
import java.util.Date;
/**
* 企业微信流程审批功能演示代码
* WeChat Enterprise Workflow Approval Demo
*
* 演示如何使用WxJava SDK中已实现的完整审批流程功能
* Demonstrates how to use the comprehensive approval workflow features already implemented in WxJava SDK
*
* 文档参考 Documentation Reference: https://work.weixin.qq.com/api/doc/90000/90135/91853
*/
public class WxCpApprovalWorkflowDemo {
private WxCpService wxCpService;
public WxCpApprovalWorkflowDemo(WxCpService wxCpService) {
this.wxCpService = wxCpService;
}
/**
* 示例1: 提交审批申请
* Example 1: Submit Approval Application
* API: /cgi-bin/oa/applyevent (Document 91853)
*/
public String submitApprovalApplication() throws Exception {
// 构建审批申请请求
WxCpOaApplyEventRequest request = new WxCpOaApplyEventRequest()
.setCreatorUserId("creator_user_id") // 申请人userid
.setTemplateId("3Tka1eD6v6JfzhDMqPd3aMkFdxqtJMc2ZRioUBGCNS") // 模板id
.setUseTemplateApprover(0) // 不使用模板中的审批流
.setApprovers(Arrays.asList(
new WxCpOaApplyEventRequest.Approver()
.setAttr(2) // 审批类型: 或签
.setUserIds(new String[]{"approver1", "approver2"})
))
.setNotifiers(new String[]{"notifier1", "notifier2"}) // 抄送人
.setNotifyType(1) // 抄送方式: 提单时抄送
.setApplyData(new WxCpOaApplyEventRequest.ApplyData()
.setContents(Arrays.asList(
// 文本控件
new ApplyDataContent()
.setControl("Text")
.setId("Text-1234567890")
.setValue(new ContentValue().setText("这是一个审批申请的文本内容")),
// 数字控件
new ApplyDataContent()
.setControl("Number")
.setId("Number-1234567890")
.setValue(new ContentValue().setNewNumber("1000")),
// 金额控件
new ApplyDataContent()
.setControl("Money")
.setId("Money-1234567890")
.setValue(new ContentValue().setNewMoney("10000"))
))
);
// 提交审批申请
String spNo = wxCpService.getOaService().apply(request);
System.out.println("审批申请提交成功,审批单号: " + spNo);
return spNo;
}
/**
* 示例2: 获取审批申请详情
* Example 2: Get Approval Application Details
* API: /cgi-bin/oa/getapprovaldetail
*/
public void getApprovalDetails(String spNo) throws Exception {
WxCpApprovalDetailResult result = wxCpService.getOaService().getApprovalDetail(spNo);
WxCpApprovalDetailResult.WxCpApprovalDetail detail = result.getInfo();
System.out.println("审批单号: " + detail.getSpNo());
System.out.println("审批名称: " + detail.getSpName());
System.out.println("审批状态: " + detail.getSpStatus());
System.out.println("申请人: " + detail.getApplier().getUserId());
System.out.println("申请时间: " + detail.getApplyTime());
// 打印审批记录
if (detail.getSpRecords() != null) {
Arrays.stream(detail.getSpRecords()).forEach(record -> {
System.out.println("审批节点状态: " + record.getStatus());
System.out.println("审批人: " + record.getDetails());
});
}
}
/**
* 示例3: 批量获取审批单号
* Example 3: Batch Get Approval Numbers
* API: /cgi-bin/oa/getapprovalinfo
*/
public void batchGetApprovalInfo() throws Exception {
// 获取最近7天的审批单
Date startTime = new Date(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000L);
Date endTime = new Date();
WxCpApprovalInfo approvalInfo = wxCpService.getOaService()
.getApprovalInfo(startTime, endTime, "0", 100, null);
System.out.println("获取到的审批单数量: " + (approvalInfo.getSpNoList() != null ? approvalInfo.getSpNoList().size() : 0));
// 遍历审批单号
if (approvalInfo.getSpNoList() != null) {
approvalInfo.getSpNoList().forEach(spNo -> {
System.out.println("审批单号: " + spNo);
// 可以进一步调用 getApprovalDetails 获取详情
});
}
}
/**
* 示例4: 模板管理
* Example 4: Template Management
*/
public void templateManagement() throws Exception {
// 获取模板详情
String templateId = "3Tka1eD6v6JfzhDMqPd3aMkFdxqtJMc2ZRioUBGCNS";
WxCpOaApprovalTemplateResult templateResult = wxCpService.getOaService().getTemplateDetail(templateId);
System.out.println("模板名称: " + templateResult.getTemplateNames());
System.out.println("模板内容: " + templateResult.getTemplateContent());
}
/**
* 完整的审批流程演示
* Complete Approval Workflow Demo
*/
public void completeWorkflowDemo() {
try {
System.out.println("=== 企业微信流程审批完整演示 ===");
// 1. 提交审批申请
System.out.println("\n1. 提交审批申请...");
String spNo = submitApprovalApplication();
// 2. 获取审批详情
System.out.println("\n2. 获取审批详情...");
getApprovalDetails(spNo);
// 3. 批量获取审批信息
System.out.println("\n3. 批量获取审批信息...");
batchGetApprovalInfo();
// 4. 模板管理
System.out.println("\n4. 模板管理...");
templateManagement();
System.out.println("\n=== 演示完成 ===");
System.out.println("WxJava SDK 已经完整支持企业微信流程审批功能!");
} catch (Exception e) {
System.err.println("演示过程中发生错误: " + e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
// 注意: 这里需要配置真实的企业微信服务
// Note: You need to configure real WeChat Enterprise service here
System.out.println("企业微信流程审批功能演示");
System.out.println("该演示代码展示了WxJava SDK中已经完整实现的审批流程功能");
System.out.println("包括文档91853中描述的所有核心功能");
System.out.println("");
System.out.println("主要功能:");
System.out.println("- 提交审批申请 (/cgi-bin/oa/applyevent)");
System.out.println("- 获取审批详情 (/cgi-bin/oa/getapprovaldetail)");
System.out.println("- 批量获取审批单号 (/cgi-bin/oa/getapprovalinfo)");
System.out.println("- 模板管理功能");
System.out.println("- 审批流程引擎支持");
System.out.println("");
System.out.println("如需运行演示,请配置正确的企业微信服务参数。");
}
} | java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java | package me.chanjar.weixin.cp.demo;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutTextMessage;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.message.WxCpMessageHandler;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import java.io.IOException;
import java.io.InputStream;
/**
* The type Wx cp demo server.
*/
public class WxCpDemoServer {
private static WxCpConfigStorage wxCpConfigStorage;
private static WxCpService wxCpService;
private static WxCpMessageRouter wxCpMessageRouter;
/**
* The entry point of application.
*
* @param args the input arguments
* @throws Exception the exception
*/
public static void main(String[] args) throws Exception {
initWeixin();
Server server = new Server(8080);
ServletHandler servletHandler = new ServletHandler();
server.setHandler(servletHandler);
ServletHolder endpointServletHolder = new ServletHolder(new WxCpEndpointServlet(wxCpConfigStorage, wxCpService,
wxCpMessageRouter));
servletHandler.addServletWithMapping(endpointServletHolder, "/*");
ServletHolder oauthServletHolder = new ServletHolder(new WxCpOAuth2Servlet(wxCpService));
servletHandler.addServletWithMapping(oauthServletHolder, "/oauth2/*");
server.start();
server.join();
}
private static void initWeixin() throws IOException {
try (InputStream is1 = ClassLoader
.getSystemResourceAsStream("test-config.xml")) {
WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage
.fromXml(is1);
wxCpConfigStorage = config;
wxCpService = new WxCpServiceImpl();
wxCpService.setWxCpConfigStorage(config);
WxCpMessageHandler handler = (wxMessage, context, wxService, sessionManager) -> {
WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("测试加密消息")
.fromUser(wxMessage.getToUserName())
.toUser(wxMessage.getFromUserName()).build();
return m;
};
WxCpMessageHandler oauth2handler = (wxMessage, context, wxService, sessionManager) -> {
String href = "<a href=\""
+ wxService.getOauth2Service().buildAuthorizationUrl(wxCpConfigStorage.getOauth2redirectUri(), null)
+ "\">测试oauth2</a>";
return WxCpXmlOutMessage.TEXT().content(href)
.fromUser(wxMessage.getToUserName())
.toUser(wxMessage.getFromUserName()).build();
};
wxCpMessageRouter = new WxCpMessageRouter(wxCpService);
wxCpMessageRouter.rule()
.async(false)
.content("哈哈") // 拦截内容为“哈哈”的消息
.handler(handler)
.end()
.rule()
.async(false)
.content("oauth")
.handler(oauth2handler)
.end()
.rule()
.event(WxCpConsts.EventType.CHANGE_CONTACT)
.handler((wxMessage, context, wxCpService, sessionManager) -> {
System.out.println("通讯录发生变更");
return null;
})
.end();
}
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java | package me.chanjar.weixin.cp.demo;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* The type Wx cp o auth 2 servlet.
*/
public class WxCpOAuth2Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* The Wx cp service.
*/
protected WxCpService wxCpService;
/**
* Instantiates a new Wx cp o auth 2 servlet.
*
* @param wxCpService the wx cp service
*/
public WxCpOAuth2Servlet(WxCpService wxCpService) {
this.wxCpService = wxCpService;
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
String code = request.getParameter("code");
try {
response.getWriter().println("<h1>code</h1>");
response.getWriter().println(code);
WxCpOauth2UserInfo res = this.wxCpService.getOauth2Service().getUserInfo(code);
response.getWriter().println("<h1>result</h1>");
response.getWriter().println(res);
} catch (WxErrorException e) {
e.printStackTrace();
}
response.getWriter().flush();
response.getWriter().close();
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java | weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java | package me.chanjar.weixin.cp.demo;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.ToString;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import java.io.InputStream;
/**
* The type Wx cp demo in memory config storage.
*
* @author Daniel Qian
*/
@XStreamAlias("xml")
@ToString
public class WxCpDemoInMemoryConfigStorage extends WxCpDefaultConfigImpl {
/**
* From xml wx cp demo in memory config storage.
*
* @param is the is
* @return the wx cp demo in memory config storage
*/
public static WxCpDemoInMemoryConfigStorage fromXml(InputStream is) {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpDemoInMemoryConfigStorage.class);
return (WxCpDemoInMemoryConfigStorage) xstream.fromXML(is);
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java | package me.chanjar.weixin.cp.util.xml;
import com.thoughtworks.xstream.XStream;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.cp.bean.WxCpTpXmlPackage;
import me.chanjar.weixin.cp.bean.message.*;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* The type X stream transformer.
*/
public class XStreamTransformer {
/**
* The constant CLASS_2_XSTREAM_INSTANCE.
*/
protected static final Map<Class<?>, XStream> CLASS_2_XSTREAM_INSTANCE = configXStreamInstance();
/**
* xml -> pojo
*
* @param <T> the type parameter
* @param clazz the clazz
* @param xml the xml
* @return the t
*/
@SuppressWarnings("unchecked")
public static <T> T fromXml(Class<T> clazz, String xml) {
T object = (T) CLASS_2_XSTREAM_INSTANCE.get(clazz).fromXML(xml);
return object;
}
/**
* From xml t.
*
* @param <T> the type parameter
* @param clazz the clazz
* @param is the is
* @return the t
*/
@SuppressWarnings("unchecked")
public static <T> T fromXml(Class<T> clazz, InputStream is) {
T object = (T) CLASS_2_XSTREAM_INSTANCE.get(clazz).fromXML(is);
return object;
}
/**
* 注册扩展消息的解析器.
*
* @param clz 类型
* @param xStream xml解析器
*/
public static void register(Class<?> clz, XStream xStream) {
CLASS_2_XSTREAM_INSTANCE.put(clz, xStream);
}
/**
* pojo -> xml.
*
* @param <T> the type parameter
* @param clazz the clazz
* @param object the object
* @return the string
*/
public static <T> String toXml(Class<T> clazz, T object) {
return CLASS_2_XSTREAM_INSTANCE.get(clazz).toXML(object);
}
private static Map<Class<?>, XStream> configXStreamInstance() {
Map<Class<?>, XStream> map = new HashMap<>();
map.put(WxCpXmlMessage.class, configWxCpXmlMessage());
map.put(WxCpXmlOutNewsMessage.class, configWxCpXmlOutNewsMessage());
map.put(WxCpXmlOutTextMessage.class, configWxCpXmlOutTextMessage());
map.put(WxCpXmlOutImageMessage.class, configWxCpXmlOutImageMessage());
map.put(WxCpXmlOutVideoMessage.class, configWxCpXmlOutVideoMessage());
map.put(WxCpXmlOutVoiceMessage.class, configWxCpXmlOutVoiceMessage());
map.put(WxCpXmlOutTaskCardMessage.class, configWxCpXmlOutTaskCardMessage());
map.put(WxCpXmlOutUpdateBtnMessage.class, configWxCpXmlOutUpdateBtnMessage());
map.put(WxCpTpXmlPackage.class, configWxCpTpXmlPackage());
map.put(WxCpTpXmlMessage.class, configWxCpTpXmlMessage());
map.put(WxCpXmlOutEventMessage.class, configWxCpXmlOutEventMessage());
return map;
}
private static XStream configWxCpXmlMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlMessage.class);
xstream.processAnnotations(WxCpXmlMessage.ScanCodeInfo.class);
xstream.processAnnotations(WxCpXmlMessage.SendPicsInfo.class);
xstream.processAnnotations(WxCpXmlMessage.SendPicsInfo.Item.class);
xstream.processAnnotations(WxCpXmlMessage.SendLocationInfo.class);
xstream.processAnnotations(WxCpXmlMessage.SelectedItem.class);
// 显式允许 String 类
xstream.allowTypes(new Class[]{String.class});
// 模板卡片事件推送独属
xstream.alias("OptionId",String.class);
return xstream;
}
private static XStream configWxCpXmlOutImageMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlOutMessage.class);
xstream.processAnnotations(WxCpXmlOutImageMessage.class);
return xstream;
}
private static XStream configWxCpXmlOutNewsMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlOutMessage.class);
xstream.processAnnotations(WxCpXmlOutNewsMessage.class);
xstream.processAnnotations(WxCpXmlOutNewsMessage.Item.class);
return xstream;
}
private static XStream configWxCpXmlOutTextMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlOutMessage.class);
xstream.processAnnotations(WxCpXmlOutTextMessage.class);
return xstream;
}
private static XStream configWxCpXmlOutVideoMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlOutMessage.class);
xstream.processAnnotations(WxCpXmlOutVideoMessage.class);
xstream.processAnnotations(WxCpXmlOutVideoMessage.Video.class);
return xstream;
}
private static XStream configWxCpXmlOutVoiceMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlOutMessage.class);
xstream.processAnnotations(WxCpXmlOutVoiceMessage.class);
return xstream;
}
private static XStream configWxCpXmlOutTaskCardMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlOutMessage.class);
xstream.processAnnotations(WxCpXmlOutTaskCardMessage.class);
return xstream;
}
private static XStream configWxCpXmlOutUpdateBtnMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlOutMessage.class);
xstream.processAnnotations(WxCpXmlOutUpdateBtnMessage.class);
return xstream;
}
private static XStream configWxCpTpXmlPackage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpTpXmlPackage.class);
return xstream;
}
private static XStream configWxCpTpXmlMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpTpXmlMessage.class);
return xstream;
}
private static XStream configWxCpXmlOutEventMessage() {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpXmlOutMessage.class);
xstream.processAnnotations(WxCpXmlOutEventMessage.class);
return xstream;
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMenuGsonAdapter.java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMenuGsonAdapter.java | package me.chanjar.weixin.cp.util.json;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.util.json.WxMenuGsonAdapter;
import java.lang.reflect.Type;
/**
* <pre>
* 企业号菜单json转换适配器
* Created by Binary Wang on 2017-6-25.
* @author <a href="https://github.com/binarywang">Binary Wang</a> </pre>
*/
public class WxCpMenuGsonAdapter extends WxMenuGsonAdapter {
@Override
public WxMenu deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return this.buildMenuFromJson(json.getAsJsonObject().get("button").getAsJsonArray());
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java | package me.chanjar.weixin.cp.util.json;
import com.google.gson.*;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Objects;
/**
* WxCpDepart的gson适配器.
*
* @author Daniel Qian
*/
public class WxCpDepartGsonAdapter implements JsonSerializer<WxCpDepart>, JsonDeserializer<WxCpDepart> {
private static final String ID = "id";
private static final String NAME = "name";
private static final String EN_NAME = "name_en";
private static final String DEPARTMENT_LEADER = "department_leader";
private static final String PARENT_ID = "parentid";
private static final String ORDER = "order";
@Override
public JsonElement serialize(WxCpDepart group, Type typeOfSrc, JsonSerializationContext context) {
JsonObject json = new JsonObject();
addPropertyIfNotNull(json, ID, group.getId());
addPropertyIfNotNull(json, NAME, group.getName());
addPropertyIfNotNull(json, EN_NAME, group.getEnName());
if (group.getDepartmentLeader() != null && group.getDepartmentLeader().length > 0) {
JsonArray jsonArray = new JsonArray();
Arrays.stream(group.getDepartmentLeader()).filter(Objects::nonNull).forEach(jsonArray::add);
json.add(DEPARTMENT_LEADER, jsonArray);
}
addPropertyIfNotNull(json, PARENT_ID, group.getParentId());
addPropertyIfNotNull(json, ORDER, group.getOrder());
return json;
}
private void addPropertyIfNotNull(JsonObject json, String key, Object value) {
if (value != null) {
if (value instanceof Number) {
json.addProperty(key, (Number) value);
} else {
json.addProperty(key, value.toString());
}
}
}
@Override
public WxCpDepart deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
WxCpDepart depart = new WxCpDepart();
JsonObject departJson = json.getAsJsonObject();
depart.setId(GsonHelper.getAsLong(departJson.get(ID)));
depart.setName(GsonHelper.getAsString(departJson.get(NAME)));
depart.setEnName(GsonHelper.getAsString(departJson.get(EN_NAME)));
JsonArray jsonArray = departJson.getAsJsonArray(DEPARTMENT_LEADER);
if (jsonArray != null && !jsonArray.isJsonNull()) {
String[] departments = new String[jsonArray.size()];
for (int i = 0; i < jsonArray.size(); i++) {
departments[i] = jsonArray.get(i).getAsString();
}
depart.setDepartmentLeader(departments);
}
depart.setOrder(GsonHelper.getAsLong(departJson.get(ORDER)));
depart.setParentId(GsonHelper.getAsLong(departJson.get(PARENT_ID)));
return depart;
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpChatGsonAdapter.java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpChatGsonAdapter.java | package me.chanjar.weixin.cp.util.json;
import com.google.gson.*;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.cp.bean.WxCpChat;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* 群聊适配器
*
* @author gaigeshen
*/
public class WxCpChatGsonAdapter implements JsonSerializer<WxCpChat>, JsonDeserializer<WxCpChat> {
public static final String FIELD_CHAT_ID = "chatid";
public static final String FIELD_NAME = "name";
public static final String FIELD_OWNER = "owner";
public static final String FIELD_USER_LIST = "userlist";
@Override
public JsonElement serialize(WxCpChat chat, Type typeOfSrc, JsonSerializationContext context) {
JsonObject json = new JsonObject();
addPropertyIfNotNull(json, FIELD_CHAT_ID, chat.getId());
addPropertyIfNotNull(json, FIELD_NAME, chat.getName());
addPropertyIfNotNull(json, FIELD_OWNER, chat.getOwner());
if (chat.getUsers() != null && !chat.getUsers().isEmpty()) {
JsonArray users = new JsonArray();
chat.getUsers().forEach(users::add);
json.add(FIELD_USER_LIST, users);
}
return json;
}
private void addPropertyIfNotNull(JsonObject json, String key, String value) {
if (value != null) {
json.addProperty(key, value);
}
}
@Override
public WxCpChat deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject chatJson = json.getAsJsonObject();
WxCpChat chat = new WxCpChat();
chat.setId(GsonHelper.getAsString(chatJson.get("chatid")));
chat.setName(GsonHelper.getAsString(chatJson.get("name")));
chat.setOwner(GsonHelper.getAsString(chatJson.get("owner")));
JsonArray usersJson = chatJson.getAsJsonArray("userlist");
if (usersJson != null && !usersJson.isEmpty()) {
List<String> users = new ArrayList<>(usersJson.size());
usersJson.forEach(e -> users.add(e.getAsString()));
chat.setUsers(users);
}
return chat;
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpGsonBuilder.java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpGsonBuilder.java | package me.chanjar.weixin.cp.util.json;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder;
import me.chanjar.weixin.common.util.json.WxErrorAdapter;
import me.chanjar.weixin.cp.bean.WxCpChat;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.kf.WxCpKfGetCorpStatisticResp;
import java.io.File;
import java.util.Objects;
/**
* The type Wx cp gson builder.
*
* @author Daniel Qian
*/
public class WxCpGsonBuilder {
private static final GsonBuilder INSTANCE = new GsonBuilder();
private static volatile Gson GSON_INSTANCE;
static {
INSTANCE.disableHtmlEscaping();
INSTANCE.registerTypeAdapter(WxCpChat.class, new WxCpChatGsonAdapter());
INSTANCE.registerTypeAdapter(WxCpDepart.class, new WxCpDepartGsonAdapter());
INSTANCE.registerTypeAdapter(WxCpUser.class, new WxCpUserGsonAdapter());
INSTANCE.registerTypeAdapter(WxError.class, new WxErrorAdapter());
INSTANCE.registerTypeAdapter(WxMenu.class, new WxCpMenuGsonAdapter());
INSTANCE.registerTypeAdapter(WxCpTag.class, new WxCpTagGsonAdapter());
INSTANCE.registerTypeAdapter(WxCpKfGetCorpStatisticResp.StatisticList.class, new StatisticListAdapter());
INSTANCE.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
return false;
}
@Override
public boolean shouldSkipClass(Class<?> aClass) {
return aClass == File.class || aClass == ApacheHttpClientBuilder.class;
}
});
}
/**
* Create gson.
*
* @return the gson
*/
public static Gson create() {
if (Objects.isNull(GSON_INSTANCE)) {
synchronized (INSTANCE) {
if (Objects.isNull(GSON_INSTANCE)) {
GSON_INSTANCE = INSTANCE.create();
}
}
}
return GSON_INSTANCE;
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/StatisticListAdapter.java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/StatisticListAdapter.java | package me.chanjar.weixin.cp.util.json;
import com.google.gson.*;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.cp.bean.kf.WxCpKfGetCorpStatisticResp;
import java.lang.reflect.Type;
/**
* The type Statistic list adapter.
*
* @author zhongjun created on 2022/4/25
*/
public class StatisticListAdapter implements JsonDeserializer<WxCpKfGetCorpStatisticResp.StatisticList> {
@Override
public WxCpKfGetCorpStatisticResp.StatisticList deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
WxCpKfGetCorpStatisticResp.StatisticList statisticList = new WxCpKfGetCorpStatisticResp.StatisticList();
JsonObject asJsonObject = jsonElement.getAsJsonObject();
statisticList.setStatTime(asJsonObject.get("stat_time").getAsLong());
JsonElement statistic = asJsonObject.get("statistic");
if (GsonHelper.isNotNull(statistic)) {
WxCpKfGetCorpStatisticResp.Statistic statisticObj = new WxCpKfGetCorpStatisticResp.Statistic();
statisticObj.setSessionCnt(GsonHelper.isNull(statistic.getAsJsonObject().get("session_cnt")) ? null : statistic.getAsJsonObject().get("session_cnt").getAsInt());
statisticObj.setCustomerCnt(GsonHelper.isNull(statistic.getAsJsonObject().get("customer_cnt")) ? null : statistic.getAsJsonObject().get("customer_cnt").getAsInt());
statisticObj.setCustomerMsgCnt(GsonHelper.isNull(statistic.getAsJsonObject().get("customer_msg_cnt")) ? null : statistic.getAsJsonObject().get("customer_msg_cnt").getAsInt());
statisticObj.setUpgradeServiceCustomerCnt(GsonHelper.isNull(statistic.getAsJsonObject().get("upgrade_service_customer_cnt")) ? null : statistic.getAsJsonObject().get("upgrade_service_customer_cnt").getAsInt());
statisticObj.setAiSessionReplyCnt(GsonHelper.isNull(statistic.getAsJsonObject().get("ai_session_reply_cnt")) ? null : statistic.getAsJsonObject().get("ai_session_reply_cnt").getAsInt());
statisticObj.setAiTransferRate(GsonHelper.isNull(statistic.getAsJsonObject().get("ai_transfer_rate")) ? null : statistic.getAsJsonObject().get("ai_transfer_rate").getAsFloat());
statisticObj.setAiKnowledgeHitRate(GsonHelper.isNull(statistic.getAsJsonObject().get("ai_knowledge_hit_rate")) ? null : statistic.getAsJsonObject().get("ai_knowledge_hit_rate").getAsFloat());
statisticObj.setMsgRejectedCustomerCnt(GsonHelper.isNull(statistic.getAsJsonObject().get("msg_rejected_customer_cnt")) ? null : statistic.getAsJsonObject().get("msg_rejected_customer_cnt").getAsInt());
statisticList.setStatistic(statisticObj);
}
return statisticList;
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpConclusionAdapter.java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpConclusionAdapter.java | package me.chanjar.weixin.cp.util.json;
import com.google.gson.*;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayInfo;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Type;
/**
* 结束语序列化转换器
*
* @author element
*/
public class WxCpConclusionAdapter implements JsonSerializer<WxCpContactWayInfo.ContactWay.Conclusion>,
JsonDeserializer<WxCpContactWayInfo.ContactWay.Conclusion> {
@Override
public WxCpContactWayInfo.ContactWay.Conclusion deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
WxCpContactWayInfo.ContactWay.Conclusion conclusion = new WxCpContactWayInfo.ContactWay.Conclusion();
if (jsonObject.get("text") != null) {
JsonObject jsonText = jsonObject.get("text").getAsJsonObject();
if (jsonText.get("content") != null) {
conclusion.setTextContent(jsonText.get("content").getAsString());
}
}
if (jsonObject.get("image") != null) {
JsonObject jsonImage = jsonObject.get("image").getAsJsonObject();
if (jsonImage.get("media_id") != null) {
conclusion.setImgMediaId(jsonImage.get("media_id").getAsString());
}
if (jsonImage.get("pic_url") != null) {
conclusion.setImgPicUrl(jsonImage.get("pic_url").getAsString());
}
}
if (jsonObject.get("link") != null) {
JsonObject jsonLink = jsonObject.get("link").getAsJsonObject();
if (jsonLink.get("title") != null) {
conclusion.setLinkTitle(jsonLink.get("title").getAsString());
}
if (jsonLink.get("picurl") != null) {
conclusion.setLinkPicUrl(jsonLink.get("picurl").getAsString());
}
if (jsonLink.get("desc") != null) {
conclusion.setLinkDesc(jsonLink.get("desc").getAsString());
}
if (jsonLink.get("url") != null) {
conclusion.setLinkUrl(jsonLink.get("url").getAsString());
}
}
if (jsonObject.get("miniprogram") != null) {
JsonObject jsonMiniProgram = jsonObject.get("miniprogram").getAsJsonObject();
if (jsonMiniProgram.get("title") != null) {
conclusion.setMiniProgramTitle(jsonMiniProgram.get("title").getAsString());
}
if (jsonMiniProgram.get("pic_media_id") != null) {
conclusion.setMiniProgramPicMediaId(jsonMiniProgram.get("pic_media_id").getAsString());
}
if (jsonMiniProgram.get("appid") != null) {
conclusion.setMiniProgramAppId(jsonMiniProgram.get("appid").getAsString());
}
if (jsonMiniProgram.get("page") != null) {
conclusion.setMiniProgramPage(jsonMiniProgram.get("page").getAsString());
}
}
return conclusion;
}
@Override
public JsonElement serialize(WxCpContactWayInfo.ContactWay.Conclusion src, Type typeOfSrc,
JsonSerializationContext context) {
JsonObject json = new JsonObject();
if (StringUtils.isNotBlank(src.getTextContent())) {
JsonObject jsonText = new JsonObject();
jsonText.addProperty("content", src.getTextContent());
json.add("text", jsonText);
}
if (StringUtils.isNotBlank(src.getImgMediaId()) || StringUtils.isNotBlank(src.getImgPicUrl())) {
JsonObject jsonImg = new JsonObject();
jsonImg.addProperty("media_id", src.getImgMediaId());
jsonImg.addProperty("pic_url", src.getImgPicUrl());
json.add("image", jsonImg);
}
if (StringUtils.isNotBlank(src.getLinkTitle())
|| StringUtils.isNotBlank(src.getLinkPicUrl())
|| StringUtils.isNotBlank(src.getLinkDesc())
|| StringUtils.isNotBlank(src.getLinkUrl())
) {
JsonObject jsonLink = new JsonObject();
jsonLink.addProperty("title", src.getLinkTitle());
jsonLink.addProperty("picurl", src.getLinkPicUrl());
jsonLink.addProperty("desc", src.getLinkDesc());
jsonLink.addProperty("url", src.getLinkUrl());
json.add("link", jsonLink);
}
if (StringUtils.isNotBlank(src.getMiniProgramTitle())
|| StringUtils.isNotBlank(src.getMiniProgramPicMediaId())
|| StringUtils.isNotBlank(src.getMiniProgramAppId())
|| StringUtils.isNotBlank(src.getMiniProgramPage())
) {
JsonObject jsonMiniProgram = new JsonObject();
jsonMiniProgram.addProperty("title", src.getMiniProgramTitle());
jsonMiniProgram.addProperty("pic_media_id", src.getMiniProgramPicMediaId());
jsonMiniProgram.addProperty("appid", src.getMiniProgramAppId());
jsonMiniProgram.addProperty("page", src.getMiniProgramPage());
json.add("miniprogram", jsonMiniProgram);
}
return json;
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
binarywang/WxJava | https://github.com/binarywang/WxJava/blob/84b5c4d2d0774f800237634e5d0336f53c004fe3/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java | package me.chanjar.weixin.cp.util.json;
import com.google.gson.*;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.cp.bean.WxCpTag;
import java.lang.reflect.Type;
/**
* The type Wx cp tag gson adapter.
*
* @author Daniel Qian
*/
public class WxCpTagGsonAdapter implements JsonSerializer<WxCpTag>, JsonDeserializer<WxCpTag> {
private static final String TAG_ID = "tagid";
private static final String TAG_NAME = "tagname";
@Override
public JsonElement serialize(WxCpTag tag, Type typeOfSrc, JsonSerializationContext context) {
JsonObject o = new JsonObject();
addPropertyIfNotNull(o, TAG_ID, tag.getId());
addPropertyIfNotNull(o, TAG_NAME, tag.getName());
return o;
}
private void addPropertyIfNotNull(JsonObject obj, String key, String value) {
if (value != null) {
obj.addProperty(key, value);
}
}
@Override
public WxCpTag deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
return new WxCpTag(GsonHelper.getString(jsonObject, TAG_ID), GsonHelper.getString(jsonObject, TAG_NAME));
}
}
| java | Apache-2.0 | 84b5c4d2d0774f800237634e5d0336f53c004fe3 | 2026-01-04T14:46:39.499027Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.