Comprehensive Java SDK for WeChat MiniApp development with complete platform integration
npx @tessl/cli install tessl/maven-com-github-binarywang--weixin-java-miniapp@4.7.00
# WeChat MiniApp Java SDK
1
2
A comprehensive Java SDK for WeChat MiniApp development providing complete platform integration. This library enables Java developers to interact with WeChat's mini program ecosystem through well-structured interfaces covering authentication, messaging, e-commerce, analytics, live streaming, and 40+ other service areas.
3
4
## Package Information
5
6
- **Package Name**: com.github.binarywang:weixin-java-miniapp
7
- **Language**: Java
8
- **Version**: 4.7.0
9
- **Installation**: Maven/Gradle dependency
10
11
### Maven Dependency
12
13
```xml
14
<dependency>
15
<groupId>com.github.binarywang</groupId>
16
<artifactId>weixin-java-miniapp</artifactId>
17
<version>4.7.0</version>
18
</dependency>
19
```
20
21
### Gradle Dependency
22
23
```kotlin
24
implementation 'com.github.binarywang:weixin-java-miniapp:4.7.0'
25
```
26
27
## Core Imports
28
29
```java
30
import cn.binarywang.wx.miniapp.api.WxMaService;
31
import cn.binarywang.wx.miniapp.config.WxMaConfig;
32
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
33
```
34
35
## Basic Usage
36
37
```java
38
// Configure the service
39
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
40
config.setAppid("your-appid");
41
config.setSecret("your-secret");
42
config.setToken("your-token"); // For message encryption
43
config.setAesKey("your-aes-key"); // For message encryption
44
45
// Create service instance
46
WxMaService wxService = new WxMaServiceImpl();
47
wxService.setWxMaConfig(config);
48
49
// Get access token (managed automatically)
50
String accessToken = wxService.getAccessToken();
51
52
// User authentication - exchange login code for session
53
WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(jsCode);
54
String openid = session.getOpenid();
55
String sessionKey = session.getSessionKey();
56
57
// Send customer service message
58
WxMaKefuMessage message = WxMaKefuMessage.newTextBuilder()
59
.toUser(openid)
60
.content("Welcome to our mini program!")
61
.build();
62
wxService.getMsgService().sendKefuMsg(message);
63
64
// Generate QR code
65
File qrFile = wxService.getQrcodeService().createWxaCodeUnlimit(
66
"scene=user123", "pages/index/index"
67
);
68
```
69
70
## Architecture
71
72
The WeChat MiniApp SDK follows a service-oriented architecture:
73
74
- **WxMaService**: Central service interface providing access to all functionality
75
- **Specialized Services**: 40+ domain-specific services for different WeChat features
76
- **Configuration Management**: Flexible config system supporting memory and Redis storage
77
- **Data Models**: Complete bean classes for all API requests and responses
78
- **Multi-HTTP Client Support**: Apache HttpClient, OkHttp, and Jodd HTTP implementations
79
80
The SDK is designed for production use with thread-safe operations, automatic token management, built-in retry logic, and comprehensive error handling.
81
82
## Capabilities
83
84
### Core Services
85
86
Essential functionality including service configuration, authentication, access token management, and basic WeChat platform operations.
87
88
```java { .api }
89
public interface WxMaService {
90
// Configuration
91
WxMaConfig getWxMaConfig();
92
void setWxMaConfig(WxMaConfig maConfig);
93
boolean switchover(String mpId);
94
95
// Authentication & Tokens
96
String getAccessToken();
97
String getAccessToken(boolean forceRefresh);
98
WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode);
99
String getPaidUnionId(String openid, String transactionId, String mchId, String outTradeNo);
100
101
// Platform Operations
102
boolean checkSignature(String timestamp, String nonce, String signature);
103
void setDynamicData(int lifespan, String type, int scene, String data);
104
}
105
```
106
107
[Core Services](./core-services.md)
108
109
### User Management
110
111
User authentication, profile information, phone number access, and user data management for WeChat MiniApp users.
112
113
```java { .api }
114
public interface WxMaUserService {
115
WxMaJscode2SessionResult getSessionInfo(String jsCode);
116
WxMaUserInfo getUserInfo(String sessionKey, String encryptedData, String ivStr);
117
WxMaPhoneNumberInfo getPhoneNumber(String code);
118
boolean checkUserInfo(String sessionKey, String rawData, String signature);
119
void setUserStorage(Map<String, String> kvMap, String sessionKey, String openid);
120
}
121
```
122
123
[User Management](./user-management.md)
124
125
### Messaging
126
127
Comprehensive messaging capabilities including customer service messages, subscription messages, template messages, and dynamic messages.
128
129
```java { .api }
130
public interface WxMaMsgService {
131
boolean sendKefuMsg(WxMaKefuMessage message);
132
void sendSubscribeMsg(WxMaSubscribeMessage subscribeMessage);
133
void sendUniformMsg(WxMaUniformMessage uniformMessage);
134
JsonObject createUpdatableMessageActivityId();
135
void setUpdatableMsg(WxMaUpdatableMsg msg);
136
}
137
```
138
139
[Messaging](./messaging.md)
140
141
### QR Code Generation
142
143
Generate various types of QR codes and mini program codes with customizable styling and parameters.
144
145
```java { .api }
146
public interface WxMaQrcodeService {
147
// Mini Program Codes (Interface A)
148
File createWxaCode(String path, int width);
149
byte[] createWxaCodeBytes(String path, String envVersion, int width, boolean autoColor,
150
WxMaCodeLineColor lineColor, boolean isHyaline);
151
152
// Unlimited Mini Program Codes (Interface B)
153
File createWxaCodeUnlimit(String scene, String page);
154
byte[] createWxaCodeUnlimitBytes(String scene, String page, boolean checkPath,
155
String envVersion, int width, boolean autoColor,
156
WxMaCodeLineColor lineColor, boolean isHyaline);
157
158
// Traditional QR Codes (Interface C)
159
File createQrcode(String path, int width);
160
byte[] createQrcodeBytes(String path, int width);
161
}
162
```
163
164
[QR Code Generation](./qr-codes.md)
165
166
### Analytics
167
168
Comprehensive analytics and data insights including user trends, visit patterns, retention analysis, and user demographics.
169
170
```java { .api }
171
public interface WxMaAnalysisService {
172
// Trend Analysis
173
List<WxMaSummaryTrend> getDailySummaryTrend(Date beginDate, Date endDate);
174
List<WxMaVisitTrend> getDailyVisitTrend(Date beginDate, Date endDate);
175
List<WxMaVisitTrend> getWeeklyVisitTrend(Date beginDate, Date endDate);
176
List<WxMaVisitTrend> getMonthlyVisitTrend(Date beginDate, Date endDate);
177
178
// User Analysis
179
WxMaVisitDistribution getVisitDistribution(Date beginDate, Date endDate);
180
WxMaRetainInfo getDailyRetainInfo(Date beginDate, Date endDate);
181
List<WxMaVisitPage> getVisitPage(Date beginDate, Date endDate);
182
WxMaUserPortrait getUserPortrait(Date beginDate, Date endDate);
183
}
184
```
185
186
[Analytics](./analytics.md)
187
188
### E-commerce
189
190
Complete e-commerce platform integration including shop management, product catalogs, order processing, payments, and logistics.
191
192
```java { .api }
193
// Shop Management
194
public interface WxMaShopAccountService {
195
// Account operations
196
}
197
198
public interface WxMaShopSpuService {
199
// Product management
200
}
201
202
public interface WxMaShopOrderService {
203
// Order processing
204
}
205
206
public interface WxMaShopPayService {
207
// Payment handling
208
}
209
210
public interface WxMaShopDeliveryService {
211
// Logistics management
212
}
213
```
214
215
[E-commerce](./ecommerce.md)
216
217
### Live Streaming
218
219
Complete live streaming functionality including room management, broadcast control, product integration, and audience management.
220
221
```java { .api }
222
public interface WxMaLiveService {
223
// Room Management
224
WxMaCreateRoomResult createRoom(WxMaLiveRoomInfo roomInfo);
225
boolean deleteRoom(Integer roomId);
226
boolean editRoom(WxMaLiveRoomInfo roomInfo);
227
WxMaLiveResult getLiveInfo(Integer start, Integer limit);
228
229
// Room Features
230
String getPushUrl(Integer roomId);
231
WxMaLiveSharedCode getSharedCode(Integer roomId, String params);
232
boolean updatefeedpublic(Integer roomId, Integer isFeedsPublic);
233
boolean updatereplay(Integer roomId, Integer closeReplay);
234
235
// Product Management
236
boolean addGoodsToRoom(Integer roomId, List<Integer> goodsIds);
237
boolean onsale(Integer roomId, Integer goodsId, Integer onSale);
238
boolean push(Integer roomId, Integer goodsId);
239
}
240
```
241
242
[Live Streaming](./live-streaming.md)
243
244
### Media & Content
245
246
Media file management, content security, and content moderation services for images, videos, and other media types.
247
248
```java { .api }
249
public interface WxMaMediaService {
250
// Media upload and management
251
}
252
253
public interface WxMaSecurityService {
254
// Content security and moderation
255
}
256
```
257
258
[Media & Content](./media-content.md)
259
260
### Cloud Development
261
262
WeChat Cloud Development integration including cloud functions, database operations, and cloud storage management.
263
264
```java { .api }
265
public interface WxMaCloudService {
266
// Cloud development operations
267
}
268
```
269
270
[Cloud Development](./cloud-development.md)
271
272
### Express & Logistics
273
274
Express delivery integration and logistics management including shipping, tracking, and delivery services.
275
276
```java { .api }
277
public interface WxMaExpressService {
278
// Express delivery operations
279
}
280
281
public interface WxMaImmediateDeliveryService {
282
// Immediate delivery services
283
}
284
```
285
286
[Express & Logistics](./logistics.md)
287
288
### Development Tools
289
290
Comprehensive development and management tools including code deployment, API management, plugin support, and testing utilities for the complete mini program development lifecycle.
291
292
```java { .api }
293
public interface WxMaCodeService {
294
// Version Control and Deployment
295
boolean commitCode(String templateId, String userVersion, String userDesc, ExtJson extJson);
296
WxMaCodeVersionsResult getCodeVersions();
297
boolean releaseCode(String userVersion);
298
boolean rollbackRelease();
299
300
// Code Auditing
301
WxMaSubmitAuditResult submitAudit();
302
WxMaSubmitAuditResult submitAudit(List<WxMaCategory> categoryList);
303
WxMaGetAuditStatusResult getAuditStatus(String auditId);
304
WxMaGetLatestAuditStatusResult getLatestAuditStatus();
305
boolean undoCodeAudit();
306
}
307
308
public interface WxMaJsapiService {
309
// JSAPI Configuration
310
String getJsapiTicket();
311
String getJsapiTicket(boolean forceRefresh);
312
WxJsapiSignature createJsapiSignature(String url);
313
}
314
315
public interface WxMaPluginService {
316
// Plugin Management
317
boolean applyPlugin(String action, String pluginAppid, String reason);
318
WxMaPluginListResult getPluginList();
319
boolean setDevPluginList(String action, String appid, String userVersion);
320
WxMaDevPluginResult getDevPlugin();
321
}
322
323
public interface WxMaOpenApiService {
324
// API Quota Management
325
WxOpenMaQuotaGetResult getApiQuota(String cgiPath);
326
WxOpenMaQueryQuotaResult queryQuota(String cgiPath);
327
boolean clearQuota(String appid, String cgiPath);
328
}
329
```
330
331
[Development Tools](./development-tools.md)
332
333
### Video on Demand
334
335
Short drama and video content management including content publishing, review, and analytics.
336
337
```java { .api }
338
public interface WxMaVodService {
339
// Content Management
340
WxMaVodUploadDramaResult uploadDrama(WxMaVodDramaInfo dramaInfo);
341
WxMaVodSingleVideoResult singleFileTest(String mediaUrl, Integer mediaType);
342
WxMaVodListDramasResult listDramas(Integer start, Integer limit);
343
344
// Audit and Review
345
WxMaVodAuditDramaResult auditDrama(String dramaId);
346
WxMaVodGetDramaResult getDrama(String dramaId);
347
}
348
```
349
350
### Virtual Payment
351
352
Virtual goods payment processing for mini games and digital content purchases.
353
354
```java { .api }
355
public interface WxMaXPayService {
356
// Virtual Payment Operations
357
WxMaXPayCreateOrderResult createOrder(WxMaXPayCreateOrderRequest request);
358
WxMaXPayQueryOrderResult queryOrder(String orderId);
359
WxMaXPayRefundResult refundOrder(WxMaXPayRefundRequest request);
360
361
// Goods Management
362
boolean presentGoods(String openid, String billNo);
363
WxMaXPayGoodsResult queryUserGoods(String openid, String goodsType);
364
}
365
```
366
367
### Marketing & Promotion
368
369
Marketing campaign management, promotion codes, and advertising integration services.
370
371
```java { .api }
372
public interface WxMaMarketingService {
373
// Campaign Management
374
WxMaMarketingCampaignResult createCampaign(WxMaMarketingCampaignRequest request);
375
boolean pauseCampaign(String campaignId);
376
boolean resumeCampaign(String campaignId);
377
378
// Promotion Codes
379
WxMaPromotionCodeResult generatePromotionCode(String campaignId, Integer count);
380
}
381
```
382
383
### Electronic Invoice
384
385
Electronic invoice management for reimbursement and expense tracking integration.
386
387
```java { .api }
388
public interface WxMaReimburseInvoiceService {
389
// Invoice Operations
390
WxMaInvoiceResult getInvoiceInfo(String cardId, String encryptCode);
391
WxMaInvoiceBatchResult getInvoiceBatch(List<WxMaInvoiceItem> items);
392
boolean updateInvoiceStatus(String cardId, String encryptCode, String reimburseStatus);
393
}
394
```
395
396
### Order Shipping
397
398
Order shipping and logistics coordination for physical goods delivery management.
399
400
```java { .api }
401
public interface WxMaOrderShippingService {
402
// Shipping Management
403
boolean uploadShippingInfo(String orderId, WxMaShippingInfo shippingInfo);
404
WxMaShippingResult queryShipping(String orderId);
405
boolean notifyConfirmReceive(String orderId, Integer received);
406
407
// Delivery Templates
408
WxMaDeliveryTemplateResult getDeliveryTemplate();
409
}
410
```
411
412
### Configuration
413
414
Comprehensive configuration management supporting memory-based and Redis-based storage with multi-app support.
415
416
```java { .api }
417
public interface WxMaConfig {
418
// Basic Configuration
419
String getAppid();
420
String getSecret();
421
String getToken();
422
String getAesKey();
423
424
// Access Token Management
425
String getAccessToken();
426
boolean isAccessTokenExpired();
427
void updateAccessToken(String accessToken, int expiresInSeconds);
428
Lock getAccessTokenLock();
429
430
// HTTP Configuration
431
String getHttpProxyHost();
432
int getHttpProxyPort();
433
int getRetrySleepMillis();
434
int getMaxRetryTimes();
435
}
436
```
437
438
[Configuration](./configuration.md)
439
440
## Multi-App Support
441
442
```java
443
// Configure multiple mini programs
444
WxMaService wxService = new WxMaServiceImpl();
445
wxService.addConfig("app1", config1);
446
wxService.addConfig("app2", config2);
447
448
// Switch between apps dynamically
449
wxService.switchoverTo("app1");
450
// All operations now use app1's configuration
451
452
wxService.switchoverTo("app2");
453
// All operations now use app2's configuration
454
```
455
456
## Error Handling
457
458
All service methods that interact with WeChat APIs throw `WxErrorException` on failure:
459
460
```java
461
try {
462
WxMaJscode2SessionResult result = wxService.getUserService().getSessionInfo(jsCode);
463
// Process successful result
464
} catch (WxErrorException e) {
465
int errorCode = e.getError().getErrorCode();
466
String errorMsg = e.getError().getErrorMsg();
467
468
// Handle specific WeChat error codes
469
switch (errorCode) {
470
case 40029:
471
// Invalid js_code
472
break;
473
case 45011:
474
// API quota exceeded
475
break;
476
case 40001:
477
// Invalid access token
478
break;
479
}
480
}
481
```
482
483
## Thread Safety & Production Usage
484
485
The SDK is designed for production environments:
486
487
- **Thread Safety**: All service instances are thread-safe with proper synchronization
488
- **Token Management**: Automatic access token refresh with lock-based concurrency control
489
- **Retry Logic**: Built-in retry mechanism for transient failures
490
- **Connection Pooling**: Configurable HTTP client with connection pooling support
491
- **Redis Support**: Distributed configuration storage for multi-instance deployments
492
493
## Performance Considerations
494
495
- Create one `WxMaService` instance per mini program and reuse it
496
- Use Redis-based configuration in distributed systems
497
- Monitor API quota usage with `WxMaOpenApiService`
498
- Cache frequently accessed data like QR codes
499
- Configure appropriate timeout values for your use case