1 package com.foxinmy.weixin4j.mp.api;
2
3 import java.util.List;
4
5 import com.alibaba.fastjson.JSONObject;
6 import com.foxinmy.weixin4j.exception.WeixinException;
7 import com.foxinmy.weixin4j.http.weixin.ApiResult;
8 import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
9 import com.foxinmy.weixin4j.model.Token;
10 import com.foxinmy.weixin4j.mp.message.NotifyMessage;
11 import com.foxinmy.weixin4j.token.TokenManager;
12 import com.foxinmy.weixin4j.tuple.MpArticle;
13 import com.foxinmy.weixin4j.tuple.MpNews;
14 import com.foxinmy.weixin4j.tuple.NotifyTuple;
15 import com.foxinmy.weixin4j.util.StringUtil;
16
17
18
19
20
21
22
23
24
25 public class NotifyApi extends MpApi {
26
27 private final TokenManager tokenManager;
28 private final MassApi massApi;
29
30 public NotifyApi(TokenManager tokenManager) {
31 this.tokenManager = tokenManager;
32 this.massApi = new MassApi(tokenManager);
33 }
34
35
36
37
38
39
40
41
42
43
44 public ApiResult sendNotify(NotifyMessage notify) throws WeixinException {
45 return sendNotify(notify, null);
46 }
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 public ApiResult sendNotify(NotifyMessage notify, String kfAccount)
68 throws WeixinException {
69 NotifyTuple tuple = notify.getTuple();
70 if (tuple instanceof MpNews) {
71 MpNews _news = (MpNews) tuple;
72 List<MpArticle> _articles = _news.getArticles();
73 if (StringUtil.isBlank(_news.getMediaId())) {
74 if (_articles.isEmpty()) {
75 throw new WeixinException(
76 "notify fail:mediaId or articles is required");
77 }
78 tuple = new MpNews(massApi.uploadArticle(_articles));
79 }
80 }
81 String msgtype = tuple.getMessageType();
82 JSONObject obj = new JSONObject();
83 obj.put("touser", notify.getTouser());
84 obj.put("msgtype", msgtype);
85 obj.put(msgtype, tuple);
86 if (StringUtil.isNotBlank(kfAccount)) {
87 JSONObject kf = new JSONObject();
88 kf.put("kf_account", kfAccount);
89 obj.put("customservice", kf);
90 }
91 String custom_notify_uri = getRequestUri("custom_notify_uri");
92 Token token = tokenManager.getCache();
93 WeixinResponse response = weixinExecutor.post(
94 String.format(custom_notify_uri, token.getAccessToken()),
95 obj.toJSONString());
96
97 return response.getAsResult();
98 }
99 }