0
# Advanced Services
1
2
Additional specialized services for extended WeChat Official Account functionality including QR codes, customer service, analytics, OAuth2, and other advanced features.
3
4
## QR Code Management
5
6
```java { .api }
7
interface WxMpQrcodeService {
8
// Temporary QR codes
9
WxMpQrCodeTicket qrCodeCreateTmp(int sceneId, Integer expireSeconds) throws WxErrorException;
10
WxMpQrCodeTicket qrCodeCreateTmp(String sceneStr, Integer expireSeconds) throws WxErrorException;
11
12
// Permanent QR codes
13
WxMpQrCodeTicket qrCodeCreateLastTicket(int sceneId) throws WxErrorException;
14
WxMpQrCodeTicket qrCodeCreateLastTicket(String sceneStr) throws WxErrorException;
15
16
// QR code images
17
File qrCodePicture(WxMpQrCodeTicket ticket) throws WxErrorException;
18
String qrCodePictureUrl(String ticket) throws WxErrorException;
19
String qrCodePictureUrl(String ticket, boolean needShortUrl) throws WxErrorException;
20
}
21
22
class WxMpQrCodeTicket implements Serializable {
23
private String ticket;
24
private Integer expireSeconds;
25
private String url;
26
27
public String getTicket();
28
public void setTicket(String ticket);
29
public Integer getExpireSeconds();
30
public void setExpireSeconds(Integer expireSeconds);
31
public String getUrl();
32
public void setUrl(String url);
33
}
34
```
35
36
## Customer Service (Kefu)
37
38
```java { .api }
39
interface WxMpKefuService {
40
// Send customer service messages
41
boolean sendKfMessage(WxMpKefuMessage message) throws WxErrorException;
42
boolean sendKfTyping(String openid) throws WxErrorException;
43
boolean sendKfMessage(WxMpKefuMessage message, String kfAccount) throws WxErrorException;
44
45
// Customer service account management
46
WxMpKfList kfList() throws WxErrorException;
47
WxMpKfOnlineList kfOnlineList() throws WxErrorException;
48
boolean kfAccountAdd(WxMpKfAccount account) throws WxErrorException;
49
boolean kfAccountUpdate(WxMpKfAccount account) throws WxErrorException;
50
boolean kfAccountInviteWorker(WxMpKfAccount kfAccount) throws WxErrorException;
51
boolean kfAccountUploadHeadImg(String media, String kfAccount) throws WxErrorException;
52
boolean kfAccountDel(String kfAccount) throws WxErrorException;
53
54
// Session management
55
WxMpKfSessionList kfSessionList(String kfAccount) throws WxErrorException;
56
WxMpKfSessionList kfSessionGetWaitCase() throws WxErrorException;
57
boolean kfSessionCreate(String kfAccount, String openid) throws WxErrorException;
58
boolean kfSessionClose(String kfAccount, String openid) throws WxErrorException;
59
WxMpKfSession kfSessionGetSession(String openid) throws WxErrorException;
60
61
// Message records
62
WxMpKfMsgList kfMsgList(Date startTime, Date endTime, Long msgId, Integer number) throws WxErrorException;
63
}
64
65
class WxMpKefuMessage implements Serializable {
66
private String toUser;
67
private String msgType;
68
private String content;
69
private String mediaId;
70
private String thumbMediaId;
71
private String title;
72
private String description;
73
private String musicUrl;
74
private String hqMusicUrl;
75
private List<WxMpKefuMessage.WxArticle> articles;
76
private String kfAccount;
77
private WxMpKefuMessage.KfMaInfo maInfo;
78
79
// Static factory methods
80
public static WxMpKefuMessage TEXT();
81
public static WxMpKefuMessage IMAGE();
82
public static WxMpKefuMessage VOICE();
83
public static WxMpKefuMessage VIDEO();
84
public static WxMpKefuMessage MUSIC();
85
public static WxMpKefuMessage NEWS();
86
public static WxMpKefuMessage MPNEWS();
87
public static WxMpKefuMessage WXCARD();
88
public static WxMpKefuMessage MINIPROGRAMPAGE();
89
90
public static class WxArticle implements Serializable {
91
private String title;
92
private String description;
93
private String url;
94
private String picUrl;
95
96
// Getters and setters
97
}
98
99
public static class KfMaInfo implements Serializable {
100
private String appid;
101
private String pagepath;
102
103
// Getters and setters
104
}
105
}
106
```
107
108
## Data Analytics
109
110
```java { .api }
111
interface WxMpDataCubeService {
112
// User analytics
113
List<WxDataCubeUserSummary> getUserSummary(Date beginDate, Date endDate) throws WxErrorException;
114
List<WxDataCubeUserCumulate> getUserCumulate(Date beginDate, Date endDate) throws WxErrorException;
115
116
// Article analytics
117
List<WxDataCubeArticleSummary> getArticleSummary(Date beginDate, Date endDate) throws WxErrorException;
118
List<WxDataCubeArticleTotal> getArticleTotal(Date beginDate, Date endDate) throws WxErrorException;
119
List<WxDataCubeUserRead> getUserRead(Date beginDate, Date endDate) throws WxErrorException;
120
List<WxDataCubeUserReadHour> getUserReadHour(Date beginDate, Date endDate) throws WxErrorException;
121
List<WxDataCubeUserShare> getUserShare(Date beginDate, Date endDate) throws WxErrorException;
122
List<WxDataCubeUserShareHour> getUserShareHour(Date beginDate, Date endDate) throws WxErrorException;
123
124
// Interface analytics
125
List<WxDataCubeInterfaceSummary> getInterfaceSummary(Date beginDate, Date endDate) throws WxErrorException;
126
List<WxDataCubeInterfaceSummaryHour> getInterfaceSummaryHour(Date beginDate, Date endDate) throws WxErrorException;
127
128
// Message analytics
129
List<WxDataCubeMsgDistMonth> getUpstreamMsgDistMonth(Date beginDate, Date endDate) throws WxErrorException;
130
List<WxDataCubeMsgDistWeek> getUpstreamMsgDistWeek(Date beginDate, Date endDate) throws WxErrorException;
131
List<WxDataCubeMsgDist> getUpstreamMsgDist(Date beginDate, Date endDate) throws WxErrorException;
132
List<WxDataCubeMsgDistHour> getUpstreamMsgDistHour(Date beginDate, Date endDate) throws WxErrorException;
133
}
134
```
135
136
## OAuth2 Authentication
137
138
```java { .api }
139
interface WxOAuth2Service {
140
// Authorization URL building
141
String buildAuthorizationUrl(String redirectUri, String scope, String state);
142
143
// Access token operations
144
WxOAuth2AccessToken getAccessToken(String code) throws WxErrorException;
145
WxOAuth2AccessToken refreshAccessToken(String refreshToken) throws WxErrorException;
146
boolean validateAccessToken(WxOAuth2AccessToken accessToken);
147
148
// User information
149
WxOAuth2UserInfo getUserInfo(WxOAuth2AccessToken accessToken, String lang) throws WxErrorException;
150
151
// Check access token validity
152
boolean checkAccessToken(String accessToken, String openid) throws WxErrorException;
153
}
154
155
class WxOAuth2AccessToken implements Serializable {
156
private String accessToken;
157
private Integer expiresIn;
158
private String refreshToken;
159
private String openId;
160
private String scope;
161
private String unionId;
162
163
// Getters and setters
164
}
165
166
class WxOAuth2UserInfo implements Serializable {
167
private String openId;
168
private String nickname;
169
private Integer sex;
170
private String province;
171
private String city;
172
private String country;
173
private String headImgUrl;
174
private List<String> privilege;
175
private String unionId;
176
177
// Getters and setters
178
}
179
```
180
181
## Mass Messaging
182
183
```java { .api }
184
interface WxMpMassMessageService {
185
// Group messaging
186
WxMpMassSendResult massGroupMessageSend(WxMpMassGroupMessage message) throws WxErrorException;
187
WxMpMassSendResult massOpenIdsMessageSend(WxMpMassOpenIdsMessage message) throws WxErrorException;
188
WxMpMassSendResult massMessagePreview(WxMpMassPreviewMessage message) throws WxErrorException;
189
190
// Media upload for mass messages
191
WxMpMassUploadResult massVideoUpload(WxMpMassVideo video) throws WxErrorException;
192
WxMpMassSendResult massNewsUpload(WxMpMassNews news) throws WxErrorException;
193
194
// Mass message status
195
WxMpMassSendResult massMessageGet(String msgId) throws WxErrorException;
196
void massMessageDelete(String msgId, Integer articleIdx) throws WxErrorException;
197
}
198
199
class WxMpMassGroupMessage extends WxMpMassMessage {
200
private WxMpMassTagMessage filter;
201
202
public static class WxMpMassTagMessage {
203
private Boolean isToAll;
204
private String tagId;
205
206
// Getters and setters
207
}
208
}
209
210
class WxMpMassOpenIdsMessage extends WxMpMassMessage {
211
private List<String> toUsers;
212
213
// Getters and setters
214
}
215
```
216
217
## Store Management
218
219
```java { .api }
220
interface WxMpStoreService {
221
// Store operations
222
void storeAdd(WxMpStoreBaseInfo storeBaseInfo) throws WxErrorException;
223
WxMpStoreBaseInfo storeGet(String poiId) throws WxErrorException;
224
void storeDelete(String poiId) throws WxErrorException;
225
void storeUpdate(WxMpStoreBaseInfo storeBaseInfo) throws WxErrorException;
226
227
// Store list
228
WxMpStoreListResult storeList(int begin, int limit) throws WxErrorException;
229
230
// Category management
231
List<WxMpStoreCategory> storeCategoryList() throws WxErrorException;
232
}
233
234
class WxMpStoreBaseInfo implements Serializable {
235
private String sid;
236
private String businessName;
237
private String branchName;
238
private String province;
239
private String city;
240
private String district;
241
private String address;
242
private String telephone;
243
private List<String> categories;
244
private Double offsetType;
245
private Double longitude;
246
private Double latitude;
247
private List<WxMpStorePhoto> photoList;
248
private String introduction;
249
private String recommend;
250
private String special;
251
private String openTime;
252
private Integer avgPrice;
253
254
// Getters and setters
255
}
256
```
257
258
## Card Management
259
260
```java { .api }
261
interface WxMpCardService {
262
// Card creation and management
263
WxMpCardCreateResult createCard(WxMpCardCreateRequest request) throws WxErrorException;
264
WxMpCard getCard(String cardId) throws WxErrorException;
265
boolean updateCard(WxMpCardUpdateRequest request) throws WxErrorException;
266
boolean deleteCard(String cardId) throws WxErrorException;
267
268
// Card codes
269
WxMpCardResult getCardDetail(String cardId, String code) throws WxErrorException;
270
WxMpCardResult consumeCard(String code, String cardId) throws WxErrorException;
271
WxMpCardResult decryptCardCode(String encryptCode) throws WxErrorException;
272
273
// QR code for cards
274
WxMpCardQrcodeCreateResult createQrcode(WxMpCardQrcodeCreateRequest request) throws WxErrorException;
275
276
// Card colors and locations
277
List<WxMpCardColor> getCardColors() throws WxErrorException;
278
WxMpCardLocationResult getCardLocations(int offset, int count) throws WxErrorException;
279
280
// Batch operations
281
List<String> batchGetCardList(int offset, int count, String statusList) throws WxErrorException;
282
WxMpCardResult updateCardStock(String cardId, Integer increase) throws WxErrorException;
283
}
284
```
285
286
## Device Management (IoT)
287
288
```java { .api }
289
interface WxMpDeviceService {
290
// Device authorization
291
WxDeviceAuthorizeResult authorize(List<WxDevice> deviceList) throws WxErrorException;
292
293
// Device operations
294
WxDeviceSearchResult search(List<String> deviceIds) throws WxErrorException;
295
boolean bind(String openid, String deviceId) throws WxErrorException;
296
boolean unbind(String openid, String deviceId) throws WxErrorException;
297
boolean compelBind(String openid, String deviceId) throws WxErrorException;
298
boolean compelUnbind(String openid, String deviceId) throws WxErrorException;
299
300
// Device status
301
WxDeviceStatusResult getStatus(String deviceId) throws WxErrorException;
302
303
// Message transmission
304
boolean transmitMessage(WxDeviceMessage deviceMessage) throws WxErrorException;
305
}
306
307
class WxDevice implements Serializable {
308
private String deviceId;
309
private String deviceType;
310
311
// Getters and setters
312
}
313
314
class WxDeviceMessage implements Serializable {
315
private String deviceType;
316
private String deviceId;
317
private String openId;
318
private String content;
319
320
// Getters and setters
321
}
322
```
323
324
## AI Services
325
326
```java { .api }
327
interface WxMpAiOpenService {
328
// Voice recognition
329
WxMpAiOpenVoiceToTextResult voiceToText(String voiceFileMediaId, String format, Integer rate, String lang) throws WxErrorException;
330
331
// Text translation
332
WxMpAiOpenTranslateResult translate(String lfrom, String lto, String sourceContent) throws WxErrorException;
333
334
// Image operations
335
WxMpAiOpenResult qrCodeScan(String imgUrl) throws WxErrorException;
336
WxMpAiOpenResult superResolution(String imgUrl) throws WxErrorException;
337
}
338
```
339
340
## WiFi Services
341
342
```java { .api }
343
interface WxMpWifiService {
344
// WiFi device management
345
WxMpWifiShopListResult listShop(int pageIndex, int pageSize) throws WxErrorException;
346
WxMpWifiShopResult getShop(Integer shopId) throws WxErrorException;
347
void updateShop(Integer shopId, String ssid, String password) throws WxErrorException;
348
void clearShopPassword(Integer shopId) throws WxErrorException;
349
350
// Device operations
351
WxMpWifiDeviceResult addDevice(Integer shopId, String ssid, String password) throws WxErrorException;
352
void deleteDevice(String mac) throws WxErrorException;
353
WxMpWifiDeviceListResult listDevice(Integer shopId, Integer pageIndex, Integer pageSize) throws WxErrorException;
354
}
355
```
356
357
## Subscribe Message Service
358
359
```java { .api }
360
interface WxMpSubscribeMsgService {
361
// Subscribe message operations
362
WxMpSubscribeMsgSendResult sendSubscribeMsg(WxMpSubscribeMsgSendRequest request) throws WxErrorException;
363
List<WxMpSubscribeMessage> getSubscribeTemplateList() throws WxErrorException;
364
String addSubscribeTemplate(String shortTemplateId, List<Integer> kidList, String sceneDesc) throws WxErrorException;
365
boolean deleteSubscribeTemplate(String priTmplId) throws WxErrorException;
366
List<WxMpSubscribeCategory> getSubscribeCategoryList() throws WxErrorException;
367
}
368
369
class WxMpSubscribeMsgSendRequest implements Serializable {
370
private String touser;
371
private String template_id;
372
private String page;
373
private String miniprogram_state;
374
private String lang;
375
private Map<String, TemplateData> data;
376
377
public static class TemplateData {
378
private String value;
379
}
380
}
381
```
382
383
## Usage Examples
384
385
### QR Code Operations
386
387
```java
388
// Create temporary QR code with scene ID
389
WxMpQrCodeTicket tempTicket = wxService.getQrcodeService()
390
.qrCodeCreateTmp(12345, 600); // 10 minutes expiry
391
392
// Create permanent QR code with scene string
393
WxMpQrCodeTicket permTicket = wxService.getQrcodeService()
394
.qrCodeCreateLastTicket("user_register");
395
396
// Download QR code image
397
File qrCodeFile = wxService.getQrcodeService().qrCodePicture(tempTicket);
398
399
// Get QR code URL
400
String qrCodeUrl = wxService.getQrcodeService()
401
.qrCodePictureUrl(tempTicket.getTicket(), true);
402
```
403
404
### Customer Service Messages
405
406
```java
407
// Send text message
408
WxMpKefuMessage textMsg = WxMpKefuMessage.TEXT()
409
.toUser("user_openid")
410
.content("Hello, how can I help you?")
411
.build();
412
wxService.getKefuService().sendKfMessage(textMsg);
413
414
// Send image message
415
WxMpKefuMessage imageMsg = WxMpKefuMessage.IMAGE()
416
.toUser("user_openid")
417
.mediaId("media_id")
418
.build();
419
wxService.getKefuService().sendKfMessage(imageMsg);
420
421
// Send news message
422
WxMpKefuMessage newsMsg = WxMpKefuMessage.NEWS()
423
.toUser("user_openid")
424
.addArticle("Title", "Description", "https://example.com", "https://example.com/pic.jpg")
425
.build();
426
wxService.getKefuService().sendKfMessage(newsMsg);
427
```
428
429
### OAuth2 Authentication Flow
430
431
```java
432
// Step 1: Build authorization URL
433
String authUrl = wxService.getOAuth2Service().buildAuthorizationUrl(
434
"https://yoursite.com/callback",
435
"snsapi_userinfo",
436
"state123"
437
);
438
439
// Step 2: Handle callback and get access token
440
public void handleCallback(String code, String state) {
441
try {
442
WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
443
444
// Step 3: Get user information
445
WxOAuth2UserInfo userInfo = wxService.getOAuth2Service()
446
.getUserInfo(accessToken, "zh_CN");
447
448
System.out.println("User: " + userInfo.getNickname());
449
System.out.println("OpenID: " + userInfo.getOpenId());
450
System.out.println("UnionID: " + userInfo.getUnionId());
451
452
} catch (WxErrorException e) {
453
System.err.println("OAuth2 error: " + e.getError().getErrorMsg());
454
}
455
}
456
```
457
458
### Analytics Data Retrieval
459
460
```java
461
// Get user summary data
462
Calendar cal = Calendar.getInstance();
463
cal.add(Calendar.DAY_OF_MONTH, -7);
464
Date beginDate = cal.getTime();
465
Date endDate = new Date();
466
467
List<WxDataCubeUserSummary> userSummary = wxService.getDataCubeService()
468
.getUserSummary(beginDate, endDate);
469
470
for (WxDataCubeUserSummary summary : userSummary) {
471
System.out.println("Date: " + summary.getRefDate());
472
System.out.println("New users: " + summary.getNewUser());
473
System.out.println("Cancel users: " + summary.getCancelUser());
474
}
475
476
// Get article analytics
477
List<WxDataCubeArticleSummary> articleSummary = wxService.getDataCubeService()
478
.getArticleSummary(beginDate, endDate);
479
480
for (WxDataCubeArticleSummary article : articleSummary) {
481
System.out.println("Article reads: " + article.getIntPageReadUser());
482
System.out.println("Article shares: " + article.getIntPageShareUser());
483
}
484
```
485
486
### Mass Messaging
487
488
```java
489
// Send to all users
490
WxMpMassGroupMessage groupMessage = WxMpMassGroupMessage.builder()
491
.msgType(WxConsts.MassMsgType.MPNEWS)
492
.mediaId("news_media_id")
493
.sendIgnoreReprint(false)
494
.build();
495
496
// Set filter for all users
497
WxMpMassGroupMessage.WxMpMassTagMessage filter =
498
new WxMpMassGroupMessage.WxMpMassTagMessage();
499
filter.setIsToAll(true);
500
groupMessage.setFilter(filter);
501
502
WxMpMassSendResult result = wxService.getMassMessageService()
503
.massGroupMessageSend(groupMessage);
504
505
// Send to specific users
506
List<String> openIds = Arrays.asList("openid1", "openid2", "openid3");
507
WxMpMassOpenIdsMessage openIdsMessage = WxMpMassOpenIdsMessage.builder()
508
.msgType(WxConsts.MassMsgType.TEXT)
509
.content("Hello everyone!")
510
.toUsers(openIds)
511
.build();
512
513
wxService.getMassMessageService().massOpenIdsMessageSend(openIdsMessage);
514
```
515
516
### Store Management
517
518
```java
519
// Add new store
520
WxMpStoreBaseInfo store = new WxMpStoreBaseInfo();
521
store.setBusinessName("My Store");
522
store.setBranchName("Main Branch");
523
store.setProvince("Beijing");
524
store.setCity("Beijing");
525
store.setAddress("123 Main Street");
526
store.setTelephone("010-12345678");
527
store.setLatitude(39.9042);
528
store.setLongitude(116.4074);
529
530
wxService.getStoreService().storeAdd(store);
531
532
// Get store list
533
WxMpStoreListResult storeList = wxService.getStoreService().storeList(0, 20);
534
for (WxMpStoreBaseInfo storeInfo : storeList.getBusinessList()) {
535
System.out.println("Store: " + storeInfo.getBusinessName());
536
}
537
```
538
539
### Device Management
540
541
```java
542
// Authorize devices
543
List<WxDevice> devices = Arrays.asList(
544
new WxDevice("device_id_1", "device_type_1"),
545
new WxDevice("device_id_2", "device_type_2")
546
);
547
548
WxDeviceAuthorizeResult authResult = wxService.getDeviceService().authorize(devices);
549
550
// Bind device to user
551
wxService.getDeviceService().bind("user_openid", "device_id_1");
552
553
// Send message to device
554
WxDeviceMessage deviceMsg = new WxDeviceMessage();
555
deviceMsg.setDeviceType("device_type_1");
556
deviceMsg.setDeviceId("device_id_1");
557
deviceMsg.setOpenId("user_openid");
558
deviceMsg.setContent("Hello device!");
559
560
wxService.getDeviceService().transmitMessage(deviceMsg);
561
```
562
563
## Best Practices
564
565
1. **QR Codes**: Use meaningful scene values for tracking and analytics
566
2. **Customer Service**: Implement proper session management for better user experience
567
3. **OAuth2**: Always validate tokens and handle refresh token scenarios
568
4. **Analytics**: Regularly fetch and analyze data for business insights
569
5. **Mass Messages**: Respect frequency limits and user preferences
570
6. **Error Handling**: Implement comprehensive error handling for all services
571
7. **Rate Limiting**: Monitor API usage to avoid hitting rate limits
572
8. **Data Privacy**: Handle user data responsibly and comply with privacy regulations
573
574
## Error Handling
575
576
```java
577
public class AdvancedServiceErrorHandler {
578
579
public static void handleQrCodeError(WxErrorException e) {
580
switch (e.getError().getErrorCode()) {
581
case 45001:
582
System.err.println("QR code limit exceeded");
583
break;
584
case 45002:
585
System.err.println("QR code refresh frequency exceeded");
586
break;
587
default:
588
System.err.println("QR code error: " + e.getError().getErrorMsg());
589
}
590
}
591
592
public static void handleOAuth2Error(WxErrorException e) {
593
switch (e.getError().getErrorCode()) {
594
case 40029:
595
System.err.println("Invalid OAuth2 code");
596
break;
597
case 40030:
598
System.err.println("Invalid refresh token");
599
break;
600
case 42001:
601
System.err.println("Access token expired");
602
break;
603
default:
604
System.err.println("OAuth2 error: " + e.getError().getErrorMsg());
605
}
606
}
607
}
608
```