0
# Core Services
1
2
Essential functionality including service configuration, authentication, access token management, and basic WeChat platform operations that form the foundation for all other services.
3
4
## Capabilities
5
6
### Main Service Interface
7
8
Central service interface providing access to all WeChat MiniApp functionality and coordinating access to specialized services.
9
10
```java { .api }
11
public interface WxMaService {
12
// Configuration Management
13
WxMaConfig getWxMaConfig();
14
void setWxMaConfig(WxMaConfig maConfig);
15
void addConfig(String miniappId, WxMaConfig configStorage);
16
boolean switchover(String mpId);
17
WxMaService switchoverTo(String miniAppId);
18
19
// Access Token Management
20
String getAccessToken();
21
String getAccessToken(boolean forceRefresh);
22
23
// Authentication
24
WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode);
25
String getPaidUnionId(String openid, String transactionId, String mchId, String outTradeNo);
26
27
// Platform Operations
28
boolean checkSignature(String timestamp, String nonce, String signature);
29
void setDynamicData(int lifespan, String type, int scene, String data);
30
31
// Service Access Methods
32
WxMaMsgService getMsgService();
33
WxMaMediaService getMediaService();
34
WxMaUserService getUserService();
35
WxMaQrcodeService getQrcodeService();
36
WxMaAnalysisService getAnalysisService();
37
WxMaLiveService getLiveService();
38
WxMaCloudService getCloudService();
39
WxMaExpressService getExpressService();
40
WxMaSecurityService getSecurityService();
41
WxMaCodeService getCodeService();
42
WxMaJsapiService getJsapiService();
43
WxMaSchemeService getSchemeService();
44
WxMaLinkService getLinkService();
45
WxMaSettingService getSettingService();
46
WxMaShareService getShareService();
47
WxMaRunService getRunService();
48
WxMaPluginService getPluginService();
49
WxMaDeviceSubscribeService getDeviceSubscribeService();
50
WxMaMarketingService getMarketingService();
51
WxMaReimburseInvoiceService getReimburseInvoiceService();
52
WxMaOrderShippingService getOrderShippingService();
53
WxMaOpenApiService getOpenApiService();
54
WxMaVodService getVodService();
55
WxMaXPayService getXPayService();
56
WxMaPromotionService getPromotionService();
57
WxMaIntracityService getIntracityService();
58
// E-commerce services
59
WxMaShopRegisterService getShopRegisterService();
60
WxMaShopAccountService getShopAccountService();
61
WxMaShopSpuService getShopSpuService();
62
WxMaShopOrderService getShopOrderService();
63
WxMaShopDeliveryService getShopDeliveryService();
64
WxMaShopAfterSaleService getShopAfterSaleService();
65
WxMaShopPayService getShopPayService();
66
WxMaShopCouponService getShopCouponService();
67
WxMaShopCatService getShopCatService();
68
WxMaShopImgService getShopImgService();
69
WxMaShopAuditService getShopAuditService();
70
WxMaShopSharerService getShopSharerService();
71
WxMaProductService getProductService();
72
WxMaProductOrderService getProductOrderService();
73
WxMaLiveGoodsService getLiveGoodsService();
74
WxMaLiveMemberService getLiveMemberService();
75
WxMaSubscribeService getSubscribeService();
76
WxMaImmediateDeliveryService getImmeDeliveryService();
77
WxMaExpressDeliveryReturnService getExpressDeliveryReturnService();
78
WxMaInternetService getInternetService();
79
}
80
```
81
82
### Service Implementation
83
84
Default implementation of the main service interface with thread-safe operations and automatic token management.
85
86
```java { .api }
87
public class WxMaServiceImpl implements WxMaService {
88
// Configuration management
89
public WxMaServiceImpl();
90
public void setWxMaConfig(WxMaConfig wxMaConfig);
91
public void setMultiConfigs(Map<String, WxMaConfig> configs);
92
public void setMultiConfigs(Map<String, WxMaConfig> configs, String defaultMpId);
93
94
// Token operations
95
@Override
96
public String getAccessToken() throws WxErrorException;
97
@Override
98
public String getAccessToken(boolean forceRefresh) throws WxErrorException;
99
100
// Multi-app support
101
@Override
102
public boolean switchover(String mpId);
103
@Override
104
public WxMaService switchoverTo(String miniAppId);
105
}
106
```
107
108
### Authentication Data Models
109
110
Core data models for WeChat authentication and session management.
111
112
```java { .api }
113
public class WxMaJscode2SessionResult implements Serializable {
114
private String sessionKey; // Session key for encryption/decryption
115
private String openid; // User's unique identifier
116
private String unionid; // User's union ID (optional)
117
118
// Factory method
119
public static WxMaJscode2SessionResult fromJson(String json);
120
121
// Getters and setters
122
public String getSessionKey();
123
public void setSessionKey(String sessionKey);
124
public String getOpenid();
125
public void setOpenid(String openid);
126
public String getUnionid();
127
public void setUnionid(String unionid);
128
129
// Utility methods
130
public String toJson();
131
@Override
132
public String toString();
133
}
134
```
135
136
### Constants
137
138
Essential constants used throughout the WeChat MiniApp SDK.
139
140
```java { .api }
141
public class WxMaConstants {
142
// API Endpoints
143
String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
144
String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token";
145
String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
146
String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid";
147
148
// Environment Constants
149
public static class EnvVersion {
150
public static final String DEFAULT = "release";
151
public static final String DEVELOP = "develop";
152
public static final String TRIAL = "trial";
153
public static final String RELEASE = "release";
154
}
155
156
// Message Types
157
public static class KefuMsgType {
158
public static final String TEXT = "text";
159
public static final String IMAGE = "image";
160
public static final String LINK = "link";
161
public static final String MA_PAGE = "miniprogrampage";
162
}
163
164
// Data Formats
165
public static class MsgDataFormat {
166
public static final String XML = "XML";
167
public static final String JSON = "JSON";
168
}
169
170
// Mini Program States
171
public static class MiniProgramState {
172
public static final String DEVELOPER = "developer";
173
public static final String TRIAL = "trial";
174
public static final String FORMAL = "formal";
175
}
176
177
// Languages
178
public static class MiniProgramLang {
179
public static final String ZH_CN = "zh_CN";
180
public static final String EN_US = "en_US";
181
public static final String ZH_HK = "zh_HK";
182
public static final String ZH_TW = "zh_TW";
183
}
184
}
185
```
186
187
## Usage Examples
188
189
### Basic Service Setup
190
191
```java
192
import cn.binarywang.wx.miniapp.api.WxMaService;
193
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
194
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
195
196
// Create and configure the service
197
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
198
config.setAppid("your-appid");
199
config.setSecret("your-secret");
200
201
WxMaService wxService = new WxMaServiceImpl();
202
wxService.setWxMaConfig(config);
203
204
// Service is now ready for use
205
String accessToken = wxService.getAccessToken();
206
```
207
208
### Multi-App Configuration
209
210
```java
211
// Configure multiple mini programs
212
WxMaDefaultConfigImpl config1 = new WxMaDefaultConfigImpl();
213
config1.setAppid("app1-id");
214
config1.setSecret("app1-secret");
215
216
WxMaDefaultConfigImpl config2 = new WxMaDefaultConfigImpl();
217
config2.setAppid("app2-id");
218
config2.setSecret("app2-secret");
219
220
WxMaService wxService = new WxMaServiceImpl();
221
wxService.addConfig("app1", config1);
222
wxService.addConfig("app2", config2);
223
224
// Switch between applications
225
wxService.switchoverTo("app1");
226
String app1Token = wxService.getAccessToken(); // Uses app1 credentials
227
228
wxService.switchoverTo("app2");
229
String app2Token = wxService.getAccessToken(); // Uses app2 credentials
230
```
231
232
### User Login Flow
233
234
```java
235
// Client sends login code from wx.login()
236
String jsCode = "061XaW100MIVdh1U8l000qdncT3XaW1g";
237
238
try {
239
// Exchange code for session info
240
WxMaJscode2SessionResult sessionInfo = wxService.jsCode2SessionInfo(jsCode);
241
242
String openid = sessionInfo.getOpenid(); // User unique ID
243
String sessionKey = sessionInfo.getSessionKey(); // For decryption
244
String unionid = sessionInfo.getUnionid(); // Cross-app user ID (optional)
245
246
// Store session info for subsequent operations
247
// sessionKey is needed for decrypting user data
248
249
} catch (WxErrorException e) {
250
// Handle authentication errors
251
int errorCode = e.getError().getErrorCode();
252
String errorMsg = e.getError().getErrorMsg();
253
254
if (errorCode == 40029) {
255
// Invalid js_code - code expired or already used
256
} else if (errorCode == 40013) {
257
// Invalid appid
258
}
259
}
260
```
261
262
### Signature Verification
263
264
```java
265
// Verify WeChat server signature (for webhook callbacks)
266
String timestamp = request.getParameter("timestamp");
267
String nonce = request.getParameter("nonce");
268
String signature = request.getParameter("signature");
269
270
boolean isValid = wxService.checkSignature(timestamp, nonce, signature);
271
if (isValid) {
272
// Request is from WeChat servers
273
// Process the callback safely
274
} else {
275
// Invalid signature - reject the request
276
response.sendError(HttpServletResponse.SC_FORBIDDEN);
277
}
278
```
279
280
### Dynamic Data Import
281
282
```java
283
// Import dynamic data for search optimization
284
wxService.setDynamicData(
285
300, // lifespan in seconds
286
"text", // data type
287
1001, // scene ID
288
"product catalog updated" // data content
289
);
290
```
291
292
### Access Token Management
293
294
```java
295
// Automatic token management (recommended)
296
String token1 = wxService.getAccessToken(); // Gets cached token
297
298
// Force refresh token
299
String token2 = wxService.getAccessToken(true); // Forces new token request
300
301
// Check token status from config
302
WxMaConfig config = wxService.getWxMaConfig();
303
boolean isExpired = config.isAccessTokenExpired();
304
String currentToken = config.getAccessToken();
305
```
306
307
### Error Handling
308
309
```java
310
import me.chanjar.weixin.common.error.WxErrorException;
311
312
try {
313
// Any WeChat API operation
314
String result = wxService.getAccessToken();
315
316
} catch (WxErrorException e) {
317
int errorCode = e.getError().getErrorCode();
318
String errorMsg = e.getError().getErrorMsg();
319
String json = e.getError().getJson();
320
321
// Common error codes
322
switch (errorCode) {
323
case 40001:
324
// Invalid access token - will auto-refresh
325
break;
326
case 40013:
327
// Invalid appid
328
break;
329
case 45009:
330
// API quota reached
331
break;
332
case 48001:
333
// API unauthorized - check API permissions
334
break;
335
default:
336
// Handle other errors
337
logger.error("WeChat API error: {} - {}", errorCode, errorMsg);
338
}
339
}
340
```
341
342
This core services module provides the foundation that all other WeChat MiniApp functionality builds upon, with robust error handling, multi-app support, and production-ready features.