CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-github-binarywang--weixin-java-mp

Comprehensive Java SDK for WeChat Official Account development with complete API coverage for user management, messaging, materials, menus, and WeChat platform features.

Pending
Overview
Eval results
Files

service-management.mddocs/

Service Management

Core service initialization, configuration management, and multi-account support for WeChat Official Account operations.

Service Initialization

interface WxMpService extends WxService {
  // Core token management
  String getAccessToken() throws WxErrorException;
  String getAccessToken(boolean forceRefresh) throws WxErrorException;
  String getTicket(TicketType type) throws WxErrorException;
  String getTicket(TicketType type, boolean forceRefresh) throws WxErrorException;
  String getJsapiTicket() throws WxErrorException;
  String getJsapiTicket(boolean forceRefresh) throws WxErrorException;
  
  // Configuration management
  WxMpConfigStorage getWxMpConfigStorage();
  void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider);
  
  // Multi-account support
  void addConfigStorage(String mpId, WxMpConfigStorage configStorage);
  void removeConfigStorage(String mpId);
  void setMultiConfigStorages(Map<String, WxMpConfigStorage> configStorages);
  void setMultiConfigStorages(Map<String, WxMpConfigStorage> configStorages, String defaultMpId);
  boolean switchover(String mpId);
  WxMpService switchoverTo(String mpId);
  
  // HTTP configuration
  void initHttp();
  RequestHttp getRequestHttp();
  void setRetrySleepMillis(int retrySleepMillis);
  void setMaxRetryTimes(int maxRetryTimes);
}

Service Implementations

// Default implementation using Apache HttpClient
class WxMpServiceImpl extends BaseWxMpServiceImpl {
  // Default HTTP client implementation
}

// Apache HttpClient specific implementation
class WxMpServiceHttpClientImpl extends BaseWxMpServiceImpl {
  // Apache HttpClient configuration
}

// OkHttp implementation  
class WxMpServiceOkHttpImpl extends BaseWxMpServiceImpl {
  // OkHttp configuration
}

// Jodd HTTP implementation
class WxMpServiceJoddHttpImpl extends BaseWxMpServiceImpl {
  // Jodd HTTP configuration
}

// Base implementation class
abstract class BaseWxMpServiceImpl implements WxMpService {
  // Common implementation logic
}

Configuration Storage

interface WxMpConfigStorage {
  // Access token management
  String getAccessToken();
  boolean isAccessTokenExpired();
  void expireAccessToken();
  void updateAccessToken(WxAccessToken accessToken);
  Lock getAccessTokenLock();
  
  // Stable access token API support
  boolean isStableAccessToken();
  void useStableAccessToken(boolean useStableAccessToken);
  
  // Basic configuration
  String getAppId();
  String getSecret();
  String getToken();
  String getAesKey();
  long getExpiresTime();
  
  // OAuth2 configuration
  String getOAuth2redirectUri();
  
  // HTTP proxy configuration
  String getHttpProxyHost();
  int getHttpProxyPort();
  String getHttpProxyUsername();
  String getHttpProxyPassword();
  File getTmpDirFile();
  
  // Ticket management
  String getTicket(TicketType type);
  boolean isTicketExpired(TicketType type);
  void expireTicket(TicketType type);
  void updateTicket(TicketType type, String jsapiTicketValue, int expiresInSeconds);
  
  // JSAPI ticket management
  String getJsapiTicket();
  boolean isJsapiTicketExpired();
  void expireJsapiTicket();
  void updateJsapiTicket(String jsapiTicket, int expiresInSeconds);
  
  // Card API ticket management
  String getCardApiTicket();
  boolean isCardApiTicketExpired();
  void expireCardApiTicket();
  void updateCardApiTicket(String cardApiTicket, int expiresInSeconds);
  
  // HTTP client builder configuration
  ApacheHttpClientBuilder getApacheHttpClientBuilder();
  void setApacheHttpClientBuilder(ApacheHttpClientBuilder apacheHttpClientBuilder);
}

Host Configuration

class WxMpHostConfig {
  private String apiHost;
  private String openHost;
  private String mp2Host;
  
  // Static configuration methods
  public static String buildUrl(WxMpHostConfig hostConfig, String prefix, String path);
  public static String buildUrl(WxMpHostConfig hostConfig, WxMpApiUrl apiUrl, String... paths);
  
  // Default host configurations
  public static WxMpHostConfig buildHostConfig(String apiHost, String openHost, String mp2Host);
}

Service Accessors

The main WxMpService provides access to all specialized services:

interface WxMpService {
  // Core services
  WxMpKefuService getKefuService();
  WxMpMaterialService getMaterialService();
  WxMpMenuService getMenuService();
  WxMpUserService getUserService();
  WxMpUserTagService getUserTagService();
  WxMpQrcodeService getQrcodeService();
  WxMpCardService getCardService();
  WxMpDataCubeService getDataCubeService();
  WxMpUserBlacklistService getBlackListService();
  WxMpStoreService getStoreService();
  WxMpTemplateMsgService getTemplateMsgService();
  WxMpSubscribeMsgService getSubscribeMsgService();
  WxMpDeviceService getDeviceService();
  WxMpShakeService getShakeService();
  WxMpMemberCardService getMemberCardService();
  WxMpMarketingService getMarketingService();
  WxMpMassMessageService getMassMessageService();
  WxMpAiOpenService getAiOpenService();
  WxMpWifiService getWifiService();
  WxOcrService getOcrService();
  WxImgProcService getImgProcService();
  WxMpReimburseInvoiceService getReimburseInvoiceService();
  WxMpDraftService getDraftService();
  WxMpFreePublishService getFreePublishService();
  WxMpCommentService getCommentService();
  WxOAuth2Service getOAuth2Service();
  
  // Guide services
  WxMpGuideService getGuideService();
  WxMpGuideBuyerService getGuideBuyerService();
  WxMpGuideTagService getGuideTagService();
  WxMpGuideMaterialService getGuideMaterialService();
  WxMpGuideMassedJobService getGuideMassedJobService();
  
  // Invoice services
  WxMpMerchantInvoiceService getMerchantInvoiceService();
}

Utility Methods

interface WxMpService {
  // Signature verification
  boolean checkSignature(String timestamp, String nonce, String signature);
  
  // JSAPI signature creation
  WxJsapiSignature createJsapiSignature(String url) throws WxErrorException;
  
  // URL shortening
  String genShorten(String longData, Integer expireSeconds) throws WxErrorException;
  WxMpShortKeyResult fetchShorten(String shortKey) throws WxErrorException;
  
  @Deprecated
  String shortUrl(String longUrl) throws WxErrorException;
  
  // OAuth2 URL building
  String buildQrConnectUrl(String redirectUri, String scope, String state);
  
  // Network utilities
  String[] getCallbackIP() throws WxErrorException;
  WxNetCheckResult netCheck(String action, String operator) throws WxErrorException;
  
  // Auto-reply info
  WxMpCurrentAutoReplyInfo getCurrentAutoReplyInfo() throws WxErrorException;
  
  // API quota management
  void clearQuota(String appid) throws WxErrorException;
  
  // Semantic query
  WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) throws WxErrorException;
}

Generic API Methods

For APIs not yet implemented by specific service methods:

interface WxMpService {
  // Generic request execution
  <T, E> T execute(RequestExecutor<T, E> executor, String url, E data) throws WxErrorException;
  <T, E> T execute(RequestExecutor<T, E> executor, WxMpApiUrl url, E data) throws WxErrorException;
  
  // Generic GET requests
  String get(WxMpApiUrl url, String queryParam) throws WxErrorException;
  
  // Generic POST requests
  String post(WxMpApiUrl url, String postData) throws WxErrorException;
  String post(WxMpApiUrl url, Object obj) throws WxErrorException;
  String post(WxMpApiUrl url, JsonObject jsonObject) throws WxErrorException;
}

Usage Examples

Basic Single Account Setup

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;

// Create configuration
WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
config.setAppId("your-app-id");
config.setSecret("your-app-secret");
config.setToken("your-token");
config.setAesKey("your-aes-key");

// Create service
WxMpService wxService = new WxMpServiceImpl();
wxService.setWxMpConfigStorage(config);

// Get access token
String accessToken = wxService.getAccessToken();

Multi-Account Setup

import java.util.HashMap;
import java.util.Map;

// Create multiple configurations
Map<String, WxMpConfigStorage> configs = new HashMap<>();

WxMpDefaultConfigImpl config1 = new WxMpDefaultConfigImpl();
config1.setAppId("app-id-1");
config1.setSecret("secret-1");
configs.put("account1", config1);

WxMpDefaultConfigImpl config2 = new WxMpDefaultConfigImpl();
config2.setAppId("app-id-2");
config2.setSecret("secret-2");
configs.put("account2", config2);

// Set up service with multiple accounts
WxMpService wxService = new WxMpServiceImpl();
wxService.setMultiConfigStorages(configs, "account1");

// Switch between accounts
wxService.switchover("account2");
// or
WxMpService account2Service = wxService.switchoverTo("account2");

Custom HTTP Client Configuration

import me.chanjar.weixin.mp.api.impl.WxMpServiceOkHttpImpl;

// Using OkHttp implementation
WxMpService wxService = new WxMpServiceOkHttpImpl();
wxService.setWxMpConfigStorage(config);

// Configure retry behavior
wxService.setMaxRetryTimes(3);
wxService.setRetrySleepMillis(1000);

Host Configuration for Different Environments

import me.chanjar.weixin.mp.config.WxMpHostConfig;

// Custom host configuration
WxMpHostConfig hostConfig = WxMpHostConfig.buildHostConfig(
    "https://custom-api-host.com",
    "https://custom-open-host.com", 
    "https://custom-mp2-host.com"
);

// Apply to configuration
config.setHostConfig(hostConfig);

Thread Safety

The SDK is designed to be thread-safe:

  • Access token refresh is synchronized using locks
  • Multiple threads can safely use the same WxMpService instance
  • Configuration storage implementations handle concurrent access
  • Service method calls are stateless and thread-safe

Error Handling

All service methods can throw WxErrorException:

try {
    String accessToken = wxService.getAccessToken();
    // Use access token
} catch (WxErrorException e) {
    WxError error = e.getError();
    int errorCode = error.getErrorCode();
    String errorMsg = error.getErrorMsg();
    
    // Handle specific error codes
    if (errorCode == 40001) {
        // Invalid credential, regenerate access token
    } else if (errorCode == 45009) {
        // API rate limit exceeded, wait and retry
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-com-github-binarywang--weixin-java-mp

docs

advanced-services.md

index.md

material-management.md

menu-management.md

message-handling.md

service-management.md

shopping-guide.md

template-messaging.md

user-management.md

tile.json