0
# Service Management
1
2
Core service initialization, configuration management, and multi-account support for WeChat Official Account operations.
3
4
## Service Initialization
5
6
```java { .api }
7
interface WxMpService extends WxService {
8
// Core token management
9
String getAccessToken() throws WxErrorException;
10
String getAccessToken(boolean forceRefresh) throws WxErrorException;
11
String getTicket(TicketType type) throws WxErrorException;
12
String getTicket(TicketType type, boolean forceRefresh) throws WxErrorException;
13
String getJsapiTicket() throws WxErrorException;
14
String getJsapiTicket(boolean forceRefresh) throws WxErrorException;
15
16
// Configuration management
17
WxMpConfigStorage getWxMpConfigStorage();
18
void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider);
19
20
// Multi-account support
21
void addConfigStorage(String mpId, WxMpConfigStorage configStorage);
22
void removeConfigStorage(String mpId);
23
void setMultiConfigStorages(Map<String, WxMpConfigStorage> configStorages);
24
void setMultiConfigStorages(Map<String, WxMpConfigStorage> configStorages, String defaultMpId);
25
boolean switchover(String mpId);
26
WxMpService switchoverTo(String mpId);
27
28
// HTTP configuration
29
void initHttp();
30
RequestHttp getRequestHttp();
31
void setRetrySleepMillis(int retrySleepMillis);
32
void setMaxRetryTimes(int maxRetryTimes);
33
}
34
```
35
36
## Service Implementations
37
38
```java { .api }
39
// Default implementation using Apache HttpClient
40
class WxMpServiceImpl extends BaseWxMpServiceImpl {
41
// Default HTTP client implementation
42
}
43
44
// Apache HttpClient specific implementation
45
class WxMpServiceHttpClientImpl extends BaseWxMpServiceImpl {
46
// Apache HttpClient configuration
47
}
48
49
// OkHttp implementation
50
class WxMpServiceOkHttpImpl extends BaseWxMpServiceImpl {
51
// OkHttp configuration
52
}
53
54
// Jodd HTTP implementation
55
class WxMpServiceJoddHttpImpl extends BaseWxMpServiceImpl {
56
// Jodd HTTP configuration
57
}
58
59
// Base implementation class
60
abstract class BaseWxMpServiceImpl implements WxMpService {
61
// Common implementation logic
62
}
63
```
64
65
## Configuration Storage
66
67
```java { .api }
68
interface WxMpConfigStorage {
69
// Access token management
70
String getAccessToken();
71
boolean isAccessTokenExpired();
72
void expireAccessToken();
73
void updateAccessToken(WxAccessToken accessToken);
74
Lock getAccessTokenLock();
75
76
// Stable access token API support
77
boolean isStableAccessToken();
78
void useStableAccessToken(boolean useStableAccessToken);
79
80
// Basic configuration
81
String getAppId();
82
String getSecret();
83
String getToken();
84
String getAesKey();
85
long getExpiresTime();
86
87
// OAuth2 configuration
88
String getOAuth2redirectUri();
89
90
// HTTP proxy configuration
91
String getHttpProxyHost();
92
int getHttpProxyPort();
93
String getHttpProxyUsername();
94
String getHttpProxyPassword();
95
File getTmpDirFile();
96
97
// Ticket management
98
String getTicket(TicketType type);
99
boolean isTicketExpired(TicketType type);
100
void expireTicket(TicketType type);
101
void updateTicket(TicketType type, String jsapiTicketValue, int expiresInSeconds);
102
103
// JSAPI ticket management
104
String getJsapiTicket();
105
boolean isJsapiTicketExpired();
106
void expireJsapiTicket();
107
void updateJsapiTicket(String jsapiTicket, int expiresInSeconds);
108
109
// Card API ticket management
110
String getCardApiTicket();
111
boolean isCardApiTicketExpired();
112
void expireCardApiTicket();
113
void updateCardApiTicket(String cardApiTicket, int expiresInSeconds);
114
115
// HTTP client builder configuration
116
ApacheHttpClientBuilder getApacheHttpClientBuilder();
117
void setApacheHttpClientBuilder(ApacheHttpClientBuilder apacheHttpClientBuilder);
118
}
119
```
120
121
## Host Configuration
122
123
```java { .api }
124
class WxMpHostConfig {
125
private String apiHost;
126
private String openHost;
127
private String mp2Host;
128
129
// Static configuration methods
130
public static String buildUrl(WxMpHostConfig hostConfig, String prefix, String path);
131
public static String buildUrl(WxMpHostConfig hostConfig, WxMpApiUrl apiUrl, String... paths);
132
133
// Default host configurations
134
public static WxMpHostConfig buildHostConfig(String apiHost, String openHost, String mp2Host);
135
}
136
```
137
138
## Service Accessors
139
140
The main WxMpService provides access to all specialized services:
141
142
```java { .api }
143
interface WxMpService {
144
// Core services
145
WxMpKefuService getKefuService();
146
WxMpMaterialService getMaterialService();
147
WxMpMenuService getMenuService();
148
WxMpUserService getUserService();
149
WxMpUserTagService getUserTagService();
150
WxMpQrcodeService getQrcodeService();
151
WxMpCardService getCardService();
152
WxMpDataCubeService getDataCubeService();
153
WxMpUserBlacklistService getBlackListService();
154
WxMpStoreService getStoreService();
155
WxMpTemplateMsgService getTemplateMsgService();
156
WxMpSubscribeMsgService getSubscribeMsgService();
157
WxMpDeviceService getDeviceService();
158
WxMpShakeService getShakeService();
159
WxMpMemberCardService getMemberCardService();
160
WxMpMarketingService getMarketingService();
161
WxMpMassMessageService getMassMessageService();
162
WxMpAiOpenService getAiOpenService();
163
WxMpWifiService getWifiService();
164
WxOcrService getOcrService();
165
WxImgProcService getImgProcService();
166
WxMpReimburseInvoiceService getReimburseInvoiceService();
167
WxMpDraftService getDraftService();
168
WxMpFreePublishService getFreePublishService();
169
WxMpCommentService getCommentService();
170
WxOAuth2Service getOAuth2Service();
171
172
// Guide services
173
WxMpGuideService getGuideService();
174
WxMpGuideBuyerService getGuideBuyerService();
175
WxMpGuideTagService getGuideTagService();
176
WxMpGuideMaterialService getGuideMaterialService();
177
WxMpGuideMassedJobService getGuideMassedJobService();
178
179
// Invoice services
180
WxMpMerchantInvoiceService getMerchantInvoiceService();
181
}
182
```
183
184
## Utility Methods
185
186
```java { .api }
187
interface WxMpService {
188
// Signature verification
189
boolean checkSignature(String timestamp, String nonce, String signature);
190
191
// JSAPI signature creation
192
WxJsapiSignature createJsapiSignature(String url) throws WxErrorException;
193
194
// URL shortening
195
String genShorten(String longData, Integer expireSeconds) throws WxErrorException;
196
WxMpShortKeyResult fetchShorten(String shortKey) throws WxErrorException;
197
198
@Deprecated
199
String shortUrl(String longUrl) throws WxErrorException;
200
201
// OAuth2 URL building
202
String buildQrConnectUrl(String redirectUri, String scope, String state);
203
204
// Network utilities
205
String[] getCallbackIP() throws WxErrorException;
206
WxNetCheckResult netCheck(String action, String operator) throws WxErrorException;
207
208
// Auto-reply info
209
WxMpCurrentAutoReplyInfo getCurrentAutoReplyInfo() throws WxErrorException;
210
211
// API quota management
212
void clearQuota(String appid) throws WxErrorException;
213
214
// Semantic query
215
WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) throws WxErrorException;
216
}
217
```
218
219
## Generic API Methods
220
221
For APIs not yet implemented by specific service methods:
222
223
```java { .api }
224
interface WxMpService {
225
// Generic request execution
226
<T, E> T execute(RequestExecutor<T, E> executor, String url, E data) throws WxErrorException;
227
<T, E> T execute(RequestExecutor<T, E> executor, WxMpApiUrl url, E data) throws WxErrorException;
228
229
// Generic GET requests
230
String get(WxMpApiUrl url, String queryParam) throws WxErrorException;
231
232
// Generic POST requests
233
String post(WxMpApiUrl url, String postData) throws WxErrorException;
234
String post(WxMpApiUrl url, Object obj) throws WxErrorException;
235
String post(WxMpApiUrl url, JsonObject jsonObject) throws WxErrorException;
236
}
237
```
238
239
## Usage Examples
240
241
### Basic Single Account Setup
242
243
```java
244
import me.chanjar.weixin.mp.api.WxMpService;
245
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
246
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
247
248
// Create configuration
249
WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
250
config.setAppId("your-app-id");
251
config.setSecret("your-app-secret");
252
config.setToken("your-token");
253
config.setAesKey("your-aes-key");
254
255
// Create service
256
WxMpService wxService = new WxMpServiceImpl();
257
wxService.setWxMpConfigStorage(config);
258
259
// Get access token
260
String accessToken = wxService.getAccessToken();
261
```
262
263
### Multi-Account Setup
264
265
```java
266
import java.util.HashMap;
267
import java.util.Map;
268
269
// Create multiple configurations
270
Map<String, WxMpConfigStorage> configs = new HashMap<>();
271
272
WxMpDefaultConfigImpl config1 = new WxMpDefaultConfigImpl();
273
config1.setAppId("app-id-1");
274
config1.setSecret("secret-1");
275
configs.put("account1", config1);
276
277
WxMpDefaultConfigImpl config2 = new WxMpDefaultConfigImpl();
278
config2.setAppId("app-id-2");
279
config2.setSecret("secret-2");
280
configs.put("account2", config2);
281
282
// Set up service with multiple accounts
283
WxMpService wxService = new WxMpServiceImpl();
284
wxService.setMultiConfigStorages(configs, "account1");
285
286
// Switch between accounts
287
wxService.switchover("account2");
288
// or
289
WxMpService account2Service = wxService.switchoverTo("account2");
290
```
291
292
### Custom HTTP Client Configuration
293
294
```java
295
import me.chanjar.weixin.mp.api.impl.WxMpServiceOkHttpImpl;
296
297
// Using OkHttp implementation
298
WxMpService wxService = new WxMpServiceOkHttpImpl();
299
wxService.setWxMpConfigStorage(config);
300
301
// Configure retry behavior
302
wxService.setMaxRetryTimes(3);
303
wxService.setRetrySleepMillis(1000);
304
```
305
306
### Host Configuration for Different Environments
307
308
```java
309
import me.chanjar.weixin.mp.config.WxMpHostConfig;
310
311
// Custom host configuration
312
WxMpHostConfig hostConfig = WxMpHostConfig.buildHostConfig(
313
"https://custom-api-host.com",
314
"https://custom-open-host.com",
315
"https://custom-mp2-host.com"
316
);
317
318
// Apply to configuration
319
config.setHostConfig(hostConfig);
320
```
321
322
## Thread Safety
323
324
The SDK is designed to be thread-safe:
325
326
- Access token refresh is synchronized using locks
327
- Multiple threads can safely use the same WxMpService instance
328
- Configuration storage implementations handle concurrent access
329
- Service method calls are stateless and thread-safe
330
331
## Error Handling
332
333
All service methods can throw `WxErrorException`:
334
335
```java
336
try {
337
String accessToken = wxService.getAccessToken();
338
// Use access token
339
} catch (WxErrorException e) {
340
WxError error = e.getError();
341
int errorCode = error.getErrorCode();
342
String errorMsg = error.getErrorMsg();
343
344
// Handle specific error codes
345
if (errorCode == 40001) {
346
// Invalid credential, regenerate access token
347
} else if (errorCode == 45009) {
348
// API rate limit exceeded, wait and retry
349
}
350
}