0
# Messaging
1
2
Comprehensive messaging capabilities including customer service messages, subscription messages, template messages, uniform messages, and dynamic updatable messages for WeChat MiniApp communication.
3
4
## Capabilities
5
6
### Message Service Interface
7
8
Core messaging operations for different types of messages and communication channels.
9
10
```java { .api }
11
public interface WxMaMsgService {
12
// Customer Service Messages
13
boolean sendKefuMsg(WxMaKefuMessage message) throws WxErrorException;
14
15
// Subscription Messages
16
void sendSubscribeMsg(WxMaSubscribeMessage subscribeMessage) throws WxErrorException;
17
18
// Uniform Messages (MiniApp + Official Account)
19
void sendUniformMsg(WxMaUniformMessage uniformMessage) throws WxErrorException;
20
21
// Dynamic Messages
22
JsonObject createUpdatableMessageActivityId() throws WxErrorException;
23
void setUpdatableMsg(WxMaUpdatableMsg msg) throws WxErrorException;
24
}
25
```
26
27
### Subscription Message Service
28
29
Template-based subscription message management for personalized notifications.
30
31
```java { .api }
32
public interface WxMaSubscribeService {
33
// Template Management
34
PubTemplateTitleListResult getPubTemplateTitleList(String[] ids, int start, int limit) throws WxErrorException;
35
List<PubTemplateKeyword> getPubTemplateKeyWordsById(String id) throws WxErrorException;
36
String addTemplate(String id, List<Integer> keywordIdList, String sceneDesc) throws WxErrorException;
37
List<TemplateInfo> getTemplateList() throws WxErrorException;
38
boolean delTemplate(String templateId) throws WxErrorException;
39
List<CategoryData> getCategory() throws WxErrorException;
40
41
// Message Sending
42
void sendSubscribeMsg(WxMaSubscribeMessage subscribeMessage) throws WxErrorException;
43
}
44
```
45
46
### Customer Service Messages
47
48
Models and builders for different types of customer service messages.
49
50
```java { .api }
51
public class WxMaKefuMessage implements Serializable {
52
private String toUser; // User OpenID
53
private String msgType; // Message type
54
private String text; // Text content (for text messages)
55
private String mediaId; // Media ID (for media messages)
56
private String title; // Title (for link/card messages)
57
private String description; // Description
58
private String url; // URL (for link messages)
59
private String thumbUrl; // Thumbnail URL
60
private String thumbMediaId; // Thumbnail media ID
61
private String appid; // Mini program App ID (for mini program cards)
62
private String pagePath; // Mini program page path
63
64
// Builder methods
65
public static TextMessageBuilder newTextBuilder();
66
public static ImageMessageBuilder newImageBuilder();
67
public static LinkMessageBuilder newLinkBuilder();
68
public static MaPageMessageBuilder newMaPageBuilder();
69
70
// Getters and setters
71
public String getToUser();
72
public void setToUser(String toUser);
73
public String getMsgType();
74
public void setMsgType(String msgType);
75
// ... other getters/setters
76
77
// Utility methods
78
public String toJson();
79
public static WxMaKefuMessage fromJson(String json);
80
}
81
```
82
83
### Message Builders
84
85
Fluent builders for constructing different types of customer service messages.
86
87
```java { .api }
88
// Text Message Builder
89
public class TextMessageBuilder extends BaseBuilder<TextMessageBuilder> {
90
public TextMessageBuilder content(String content);
91
public WxMaKefuMessage build();
92
}
93
94
// Image Message Builder
95
public class ImageMessageBuilder extends BaseBuilder<ImageMessageBuilder> {
96
public ImageMessageBuilder mediaId(String mediaId);
97
public WxMaKefuMessage build();
98
}
99
100
// Link Message Builder
101
public class LinkMessageBuilder extends BaseBuilder<LinkMessageBuilder> {
102
public LinkMessageBuilder title(String title);
103
public LinkMessageBuilder description(String description);
104
public LinkMessageBuilder url(String url);
105
public LinkMessageBuilder thumbUrl(String thumbUrl);
106
public WxMaKefuMessage build();
107
}
108
109
// Mini Program Page Message Builder
110
public class MaPageMessageBuilder extends BaseBuilder<MaPageMessageBuilder> {
111
public MaPageMessageBuilder title(String title);
112
public MaPageMessageBuilder pagePath(String pagePath);
113
public MaPageMessageBuilder thumbMediaId(String thumbMediaId);
114
public MaPageMessageBuilder appid(String appid);
115
public WxMaKefuMessage build();
116
}
117
118
// Base Builder
119
public abstract class BaseBuilder<T extends BaseBuilder<T>> {
120
public T toUser(String toUser);
121
protected abstract WxMaKefuMessage build();
122
}
123
```
124
125
### Subscription Messages
126
127
Template-based notification messages requiring user consent.
128
129
```java { .api }
130
public class WxMaSubscribeMessage implements Serializable {
131
private String toUser; // Target user OpenID
132
private String templateId; // Template ID
133
private String page; // Mini program page to jump to
134
private Map<String, WxMaSubscribeData> data; // Template data
135
private String miniprogramState; // Mini program state
136
private String lang; // Language
137
138
// Constructors
139
public WxMaSubscribeMessage();
140
public WxMaSubscribeMessage(String toUser, String templateId, Map<String, WxMaSubscribeData> data);
141
142
// Getters and setters
143
public String getToUser();
144
public void setToUser(String toUser);
145
public String getTemplateId();
146
public void setTemplateId(String templateId);
147
public String getPage();
148
public void setPage(String page);
149
public Map<String, WxMaSubscribeData> getData();
150
public void setData(Map<String, WxMaSubscribeData> data);
151
152
// Convenience methods for data
153
public WxMaSubscribeMessage addData(String key, String value);
154
public WxMaSubscribeMessage addData(String key, String value, String color);
155
156
// Utility methods
157
public String toJson();
158
public static WxMaSubscribeMessage fromJson(String json);
159
}
160
161
public class WxMaSubscribeData {
162
private String value; // Data value
163
private String color; // Text color (optional)
164
165
public WxMaSubscribeData(String value);
166
public WxMaSubscribeData(String value, String color);
167
168
public String getValue();
169
public void setValue(String value);
170
public String getColor();
171
public void setColor(String color);
172
}
173
```
174
175
### Uniform Messages
176
177
Messages that can be sent to both mini program and official account users.
178
179
```java { .api }
180
public class WxMaUniformMessage implements Serializable {
181
private String toUser; // Target user OpenID
182
private WxMpTemplateMessage mpTemplateMsg; // Official account template message
183
private WxMaSubscribeMessage maTemplateMsg; // Mini program subscription message
184
185
public WxMaUniformMessage();
186
187
// Getters and setters
188
public String getToUser();
189
public void setToUser(String toUser);
190
public WxMpTemplateMessage getMpTemplateMsg();
191
public void setMpTemplateMsg(WxMpTemplateMessage mpTemplateMsg);
192
public WxMaSubscribeMessage getMaTemplateMsg();
193
public void setMaTemplateMsg(WxMaSubscribeMessage maTemplateMsg);
194
195
// Utility methods
196
public String toJson();
197
public static WxMaUniformMessage fromJson(String json);
198
}
199
```
200
201
### Dynamic Messages
202
203
Updatable messages that can be modified after sending (for sharing scenarios).
204
205
```java { .api }
206
public class WxMaUpdatableMsg implements Serializable {
207
private String activityId; // Activity ID from createUpdatableMessageActivityId
208
private Integer targetState; // Target state (0: not started, 1: in progress, 2: completed)
209
private List<UpdatableTemplateData> templateInfo; // Template data
210
211
public WxMaUpdatableMsg();
212
213
// Getters and setters
214
public String getActivityId();
215
public void setActivityId(String activityId);
216
public Integer getTargetState();
217
public void setTargetState(Integer targetState);
218
public List<UpdatableTemplateData> getTemplateInfo();
219
public void setTemplateInfo(List<UpdatableTemplateData> templateInfo);
220
221
// Utility methods
222
public String toJson();
223
public static WxMaUpdatableMsg fromJson(String json);
224
225
public static class UpdatableTemplateData {
226
private String parameterName; // Parameter name
227
private String parameterValue; // Parameter value
228
229
public UpdatableTemplateData(String parameterName, String parameterValue);
230
231
public String getParameterName();
232
public void setParameterName(String parameterName);
233
public String getParameterValue();
234
public void setParameterValue(String parameterValue);
235
}
236
}
237
```
238
239
## Usage Examples
240
241
### Customer Service Messages
242
243
#### Send Text Message
244
245
```java
246
// Simple text message
247
WxMaKefuMessage textMsg = WxMaKefuMessage.newTextBuilder()
248
.toUser("oLVPpjqs9BhvzwPj5A-vTYAX3GLc")
249
.content("Welcome to our service! How can we help you today?")
250
.build();
251
252
try {
253
boolean success = wxService.getMsgService().sendKefuMsg(textMsg);
254
if (success) {
255
logger.info("Text message sent successfully");
256
}
257
} catch (WxErrorException e) {
258
logger.error("Failed to send text message: {}", e.getMessage());
259
}
260
```
261
262
#### Send Image Message
263
264
```java
265
// First upload image to get media_id
266
WxMaMediaService mediaService = wxService.getMediaService();
267
File imageFile = new File("/path/to/image.jpg");
268
WxMediaUploadResult uploadResult = mediaService.uploadMedia("image", imageFile);
269
String mediaId = uploadResult.getMediaId();
270
271
// Send image message
272
WxMaKefuMessage imageMsg = WxMaKefuMessage.newImageBuilder()
273
.toUser("oLVPpjqs9BhvzwPj5A-vTYAX3GLc")
274
.mediaId(mediaId)
275
.build();
276
277
try {
278
wxService.getMsgService().sendKefuMsg(imageMsg);
279
logger.info("Image message sent successfully");
280
} catch (WxErrorException e) {
281
logger.error("Failed to send image message: {}", e.getMessage());
282
}
283
```
284
285
#### Send Link Message
286
287
```java
288
WxMaKefuMessage linkMsg = WxMaKefuMessage.newLinkBuilder()
289
.toUser("oLVPpjqs9BhvzwPj5A-vTYAX3GLc")
290
.title("Special Offer")
291
.description("Check out our latest products with 50% off!")
292
.url("https://yourstore.com/offers")
293
.thumbUrl("https://yourstore.com/images/offer-thumb.jpg")
294
.build();
295
296
try {
297
wxService.getMsgService().sendKefuMsg(linkMsg);
298
} catch (WxErrorException e) {
299
logger.error("Failed to send link message: {}", e.getMessage());
300
}
301
```
302
303
#### Send Mini Program Card
304
305
```java
306
// Upload thumbnail image first
307
File thumbFile = new File("/path/to/thumbnail.jpg");
308
WxMediaUploadResult thumbResult = mediaService.uploadMedia("thumb", thumbFile);
309
310
WxMaKefuMessage cardMsg = WxMaKefuMessage.newMaPageBuilder()
311
.toUser("oLVPpjqs9BhvzwPj5A-vTYAX3GLc")
312
.title("Product Details")
313
.pagePath("pages/product/detail?id=123")
314
.thumbMediaId(thumbResult.getMediaId())
315
.appid("your-miniprogram-appid") // Optional, defaults to current app
316
.build();
317
318
try {
319
wxService.getMsgService().sendKefuMsg(cardMsg);
320
} catch (WxErrorException e) {
321
logger.error("Failed to send mini program card: {}", e.getMessage());
322
}
323
```
324
325
### Subscription Messages
326
327
#### Send Order Notification
328
329
```java
330
// Template variables map
331
Map<String, WxMaSubscribeData> data = new HashMap<>();
332
data.put("thing1", new WxMaSubscribeData("iPhone 14 Pro")); // Product name
333
data.put("amount2", new WxMaSubscribeData("¥8999.00")); // Amount
334
data.put("date3", new WxMaSubscribeData("2023-12-01 14:30")); // Order time
335
data.put("thing4", new WxMaSubscribeData("ORD20231201001")); // Order number
336
337
WxMaSubscribeMessage subscribeMsg = new WxMaSubscribeMessage();
338
subscribeMsg.setToUser("oLVPpjqs9BhvzwPj5A-vTYAX3GLc");
339
subscribeMsg.setTemplateId("your-template-id");
340
subscribeMsg.setPage("pages/order/detail?id=123");
341
subscribeMsg.setData(data);
342
subscribeMsg.setMiniprogramState("formal"); // formal, trial, developer
343
344
try {
345
wxService.getMsgService().sendSubscribeMsg(subscribeMsg);
346
logger.info("Subscription message sent successfully");
347
} catch (WxErrorException e) {
348
int errorCode = e.getError().getErrorCode();
349
if (errorCode == 43101) {
350
logger.warn("User refused to receive subscription messages");
351
} else if (errorCode == 47003) {
352
logger.error("Template parameters error");
353
} else {
354
logger.error("Failed to send subscription message: {}", e.getMessage());
355
}
356
}
357
```
358
359
#### Convenient Data Building
360
361
```java
362
WxMaSubscribeMessage msg = new WxMaSubscribeMessage()
363
.toUser("oLVPpjqs9BhvzwPj5A-vTYAX3GLc")
364
.templateId("your-template-id")
365
.page("pages/order/detail?id=123")
366
.addData("thing1", "iPhone 14 Pro")
367
.addData("amount2", "¥8999.00", "#FF0000") // Red color
368
.addData("date3", "2023-12-01 14:30")
369
.addData("thing4", "ORD20231201001");
370
371
wxService.getMsgService().sendSubscribeMsg(msg);
372
```
373
374
### Template Management
375
376
#### Get Available Templates
377
378
```java
379
WxMaSubscribeService subscribeService = wxService.getSubscribeService();
380
381
try {
382
// Get public template categories
383
List<CategoryData> categories = subscribeService.getCategory();
384
for (CategoryData category : categories) {
385
logger.info("Category: {} - {}", category.getId(), category.getName());
386
}
387
388
// Get public template titles
389
String[] categoryIds = {"1", "2", "3"};
390
PubTemplateTitleListResult titles = subscribeService.getPubTemplateTitleList(
391
categoryIds, 0, 10
392
);
393
394
for (PubTemplateTitle title : titles.getData()) {
395
logger.info("Template: {} - {}", title.getTid(), title.getTitle());
396
397
// Get keywords for this template
398
List<PubTemplateKeyword> keywords = subscribeService.getPubTemplateKeyWordsById(title.getTid());
399
for (PubTemplateKeyword keyword : keywords) {
400
logger.info(" Keyword: {} - {}", keyword.getKid(), keyword.getName());
401
}
402
}
403
404
} catch (WxErrorException e) {
405
logger.error("Failed to get templates: {}", e.getMessage());
406
}
407
```
408
409
#### Add Personal Template
410
411
```java
412
try {
413
// Add template with selected keywords
414
List<Integer> keywordIds = Arrays.asList(1, 3, 5, 7); // Selected keyword IDs
415
String templateId = subscribeService.addTemplate(
416
"templateTitleId", // Public template title ID
417
keywordIds, // Selected keyword IDs
418
"Order notification template" // Usage scenario description
419
);
420
421
logger.info("Added template: {}", templateId);
422
423
} catch (WxErrorException e) {
424
if (e.getError().getErrorCode() == 47001) {
425
logger.error("Template parameter error");
426
}
427
}
428
```
429
430
### Uniform Messages
431
432
```java
433
// Send to both mini program and official account users
434
WxMaUniformMessage uniformMsg = new WxMaUniformMessage();
435
uniformMsg.setToUser("oLVPpjqs9BhvzwPj5A-vTYAX3GLc");
436
437
// Mini program subscription message
438
WxMaSubscribeMessage maMsg = new WxMaSubscribeMessage();
439
maMsg.setTemplateId("miniprogram-template-id");
440
maMsg.addData("thing1", "Order shipped");
441
maMsg.addData("thing2", "Your order is on the way!");
442
uniformMsg.setMaTemplateMsg(maMsg);
443
444
// Official account template message
445
WxMpTemplateMessage mpMsg = new WxMpTemplateMessage();
446
mpMsg.setTemplateId("official-account-template-id");
447
mpMsg.addData(new WxMpTemplateData("first", "Order Update"));
448
mpMsg.addData(new WxMpTemplateData("keyword1", "Order shipped"));
449
mpMsg.setUrl("https://yoursite.com/order/123");
450
uniformMsg.setMpTemplateMsg(mpMsg);
451
452
try {
453
wxService.getMsgService().sendUniformMsg(uniformMsg);
454
} catch (WxErrorException e) {
455
logger.error("Failed to send uniform message: {}", e.getMessage());
456
}
457
```
458
459
### Dynamic Messages
460
461
#### Create and Update Dynamic Message
462
463
```java
464
try {
465
// Create activity ID for dynamic message
466
JsonObject activityResult = wxService.getMsgService().createUpdatableMessageActivityId();
467
String activityId = activityResult.get("activity_id").getAsString();
468
469
// Store activityId for later updates
470
// This would be returned to client for sharing
471
472
// Later, update the message (e.g., when game status changes)
473
WxMaUpdatableMsg updateMsg = new WxMaUpdatableMsg();
474
updateMsg.setActivityId(activityId);
475
updateMsg.setTargetState(1); // 0: not started, 1: in progress, 2: completed
476
477
List<WxMaUpdatableMsg.UpdatableTemplateData> templateData = new ArrayList<>();
478
templateData.add(new WxMaUpdatableMsg.UpdatableTemplateData("member_count", "3"));
479
templateData.add(new WxMaUpdatableMsg.UpdatableTemplateData("room_limit", "6"));
480
templateData.add(new WxMaUpdatableMsg.UpdatableTemplateData("path", "pages/room/room?roomId=123"));
481
templateData.add(new WxMaUpdatableMsg.UpdatableTemplateData("version_type", "develop"));
482
483
updateMsg.setTemplateInfo(templateData);
484
485
// Update the shared message
486
wxService.getMsgService().setUpdatableMsg(updateMsg);
487
488
logger.info("Dynamic message updated successfully");
489
490
} catch (WxErrorException e) {
491
logger.error("Failed to handle dynamic message: {}", e.getMessage());
492
}
493
```
494
495
### Error Handling for Messages
496
497
```java
498
@Service
499
public class MessageService {
500
501
public void sendCustomerServiceMessage(String openid, String content) {
502
WxMaKefuMessage message = WxMaKefuMessage.newTextBuilder()
503
.toUser(openid)
504
.content(content)
505
.build();
506
507
try {
508
wxService.getMsgService().sendKefuMsg(message);
509
510
} catch (WxErrorException e) {
511
int errorCode = e.getError().getErrorCode();
512
String errorMsg = e.getError().getErrorMsg();
513
514
switch (errorCode) {
515
case 45015:
516
logger.warn("Reply time exceeded for user: {}", openid);
517
break;
518
case 45047:
519
logger.warn("Customer service interface usage limit exceeded");
520
break;
521
case 40003:
522
logger.error("Invalid openid: {}", openid);
523
break;
524
case 45006:
525
logger.warn("Cannot send messages - user has blocked messages");
526
break;
527
default:
528
logger.error("Failed to send customer service message: {} - {}",
529
errorCode, errorMsg);
530
}
531
532
throw new MessageSendException("Failed to send message", errorCode, errorMsg);
533
}
534
}
535
}
536
```
537
538
### Batch Message Service Example
539
540
```java
541
@Service
542
public class BatchMessageService {
543
544
@Async
545
public void sendBatchSubscriptionMessages(List<String> userIds, String templateId,
546
Map<String, String> templateData) {
547
for (String userId : userIds) {
548
try {
549
WxMaSubscribeMessage message = new WxMaSubscribeMessage();
550
message.setToUser(userId);
551
message.setTemplateId(templateId);
552
553
// Convert template data
554
Map<String, WxMaSubscribeData> data = new HashMap<>();
555
templateData.forEach((key, value) ->
556
data.put(key, new WxMaSubscribeData(value)));
557
message.setData(data);
558
559
wxService.getMsgService().sendSubscribeMsg(message);
560
561
// Delay to avoid rate limiting
562
Thread.sleep(100);
563
564
} catch (WxErrorException e) {
565
logger.warn("Failed to send message to user {}: {}", userId, e.getMessage());
566
} catch (InterruptedException e) {
567
Thread.currentThread().interrupt();
568
logger.error("Batch message sending interrupted");
569
break;
570
}
571
}
572
}
573
}
574
```
575
576
The messaging service provides comprehensive communication capabilities with proper error handling, template management, and support for all WeChat message types.