CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Comprehensive Java SDK for WeChat MiniApp development with complete platform integration

Pending
Overview
Eval results
Files

core-services.mddocs/

Core Services

Essential functionality including service configuration, authentication, access token management, and basic WeChat platform operations that form the foundation for all other services.

Capabilities

Main Service Interface

Central service interface providing access to all WeChat MiniApp functionality and coordinating access to specialized services.

public interface WxMaService {
    // Configuration Management
    WxMaConfig getWxMaConfig();
    void setWxMaConfig(WxMaConfig maConfig);
    void addConfig(String miniappId, WxMaConfig configStorage);
    boolean switchover(String mpId);
    WxMaService switchoverTo(String miniAppId);
    
    // Access Token Management
    String getAccessToken();
    String getAccessToken(boolean forceRefresh);
    
    // Authentication
    WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode);
    String getPaidUnionId(String openid, String transactionId, String mchId, String outTradeNo);
    
    // Platform Operations
    boolean checkSignature(String timestamp, String nonce, String signature);
    void setDynamicData(int lifespan, String type, int scene, String data);
    
    // Service Access Methods
    WxMaMsgService getMsgService();
    WxMaMediaService getMediaService();
    WxMaUserService getUserService();
    WxMaQrcodeService getQrcodeService();
    WxMaAnalysisService getAnalysisService();
    WxMaLiveService getLiveService();
    WxMaCloudService getCloudService();
    WxMaExpressService getExpressService();
    WxMaSecurityService getSecurityService();
    WxMaCodeService getCodeService();
    WxMaJsapiService getJsapiService();
    WxMaSchemeService getSchemeService();
    WxMaLinkService getLinkService();
    WxMaSettingService getSettingService();
    WxMaShareService getShareService();
    WxMaRunService getRunService();
    WxMaPluginService getPluginService();
    WxMaDeviceSubscribeService getDeviceSubscribeService();
    WxMaMarketingService getMarketingService();
    WxMaReimburseInvoiceService getReimburseInvoiceService();
    WxMaOrderShippingService getOrderShippingService();
    WxMaOpenApiService getOpenApiService();
    WxMaVodService getVodService();
    WxMaXPayService getXPayService();
    WxMaPromotionService getPromotionService();
    WxMaIntracityService getIntracityService();
    // E-commerce services
    WxMaShopRegisterService getShopRegisterService();
    WxMaShopAccountService getShopAccountService();
    WxMaShopSpuService getShopSpuService();
    WxMaShopOrderService getShopOrderService();
    WxMaShopDeliveryService getShopDeliveryService();
    WxMaShopAfterSaleService getShopAfterSaleService();
    WxMaShopPayService getShopPayService();
    WxMaShopCouponService getShopCouponService();
    WxMaShopCatService getShopCatService();
    WxMaShopImgService getShopImgService();
    WxMaShopAuditService getShopAuditService();
    WxMaShopSharerService getShopSharerService();
    WxMaProductService getProductService();
    WxMaProductOrderService getProductOrderService();
    WxMaLiveGoodsService getLiveGoodsService();
    WxMaLiveMemberService getLiveMemberService();
    WxMaSubscribeService getSubscribeService();
    WxMaImmediateDeliveryService getImmeDeliveryService();
    WxMaExpressDeliveryReturnService getExpressDeliveryReturnService();
    WxMaInternetService getInternetService();
}

Service Implementation

Default implementation of the main service interface with thread-safe operations and automatic token management.

public class WxMaServiceImpl implements WxMaService {
    // Configuration management
    public WxMaServiceImpl();
    public void setWxMaConfig(WxMaConfig wxMaConfig);
    public void setMultiConfigs(Map<String, WxMaConfig> configs);
    public void setMultiConfigs(Map<String, WxMaConfig> configs, String defaultMpId);
    
    // Token operations
    @Override
    public String getAccessToken() throws WxErrorException;
    @Override 
    public String getAccessToken(boolean forceRefresh) throws WxErrorException;
    
    // Multi-app support
    @Override
    public boolean switchover(String mpId);
    @Override
    public WxMaService switchoverTo(String miniAppId);
}

Authentication Data Models

Core data models for WeChat authentication and session management.

public class WxMaJscode2SessionResult implements Serializable {
    private String sessionKey;  // Session key for encryption/decryption
    private String openid;      // User's unique identifier
    private String unionid;     // User's union ID (optional)
    
    // Factory method
    public static WxMaJscode2SessionResult fromJson(String json);
    
    // Getters and setters
    public String getSessionKey();
    public void setSessionKey(String sessionKey);
    public String getOpenid(); 
    public void setOpenid(String openid);
    public String getUnionid();
    public void setUnionid(String unionid);
    
    // Utility methods
    public String toJson();
    @Override
    public String toString();
}

Constants

Essential constants used throughout the WeChat MiniApp SDK.

public class WxMaConstants {
    // API Endpoints
    String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token";
    String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid";
    
    // Environment Constants
    public static class EnvVersion {
        public static final String DEFAULT = "release";
        public static final String DEVELOP = "develop";
        public static final String TRIAL = "trial"; 
        public static final String RELEASE = "release";
    }
    
    // Message Types
    public static class KefuMsgType {
        public static final String TEXT = "text";
        public static final String IMAGE = "image";
        public static final String LINK = "link";
        public static final String MA_PAGE = "miniprogrampage";
    }
    
    // Data Formats
    public static class MsgDataFormat {
        public static final String XML = "XML";
        public static final String JSON = "JSON";
    }
    
    // Mini Program States
    public static class MiniProgramState {
        public static final String DEVELOPER = "developer";
        public static final String TRIAL = "trial";
        public static final String FORMAL = "formal";
    }
    
    // Languages
    public static class MiniProgramLang {
        public static final String ZH_CN = "zh_CN";
        public static final String EN_US = "en_US"; 
        public static final String ZH_HK = "zh_HK";
        public static final String ZH_TW = "zh_TW";
    }
}

Usage Examples

Basic Service Setup

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;

// Create and configure the service
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid("your-appid");
config.setSecret("your-secret");

WxMaService wxService = new WxMaServiceImpl();
wxService.setWxMaConfig(config);

// Service is now ready for use
String accessToken = wxService.getAccessToken();

Multi-App Configuration

// Configure multiple mini programs
WxMaDefaultConfigImpl config1 = new WxMaDefaultConfigImpl();
config1.setAppid("app1-id");
config1.setSecret("app1-secret");

WxMaDefaultConfigImpl config2 = new WxMaDefaultConfigImpl();  
config2.setAppid("app2-id");
config2.setSecret("app2-secret");

WxMaService wxService = new WxMaServiceImpl();
wxService.addConfig("app1", config1);
wxService.addConfig("app2", config2);

// Switch between applications
wxService.switchoverTo("app1");
String app1Token = wxService.getAccessToken(); // Uses app1 credentials

wxService.switchoverTo("app2");
String app2Token = wxService.getAccessToken(); // Uses app2 credentials

User Login Flow

// Client sends login code from wx.login()
String jsCode = "061XaW100MIVdh1U8l000qdncT3XaW1g";

try {
    // Exchange code for session info
    WxMaJscode2SessionResult sessionInfo = wxService.jsCode2SessionInfo(jsCode);
    
    String openid = sessionInfo.getOpenid();      // User unique ID
    String sessionKey = sessionInfo.getSessionKey(); // For decryption
    String unionid = sessionInfo.getUnionid();    // Cross-app user ID (optional)
    
    // Store session info for subsequent operations
    // sessionKey is needed for decrypting user data
    
} catch (WxErrorException e) {
    // Handle authentication errors
    int errorCode = e.getError().getErrorCode();
    String errorMsg = e.getError().getErrorMsg();
    
    if (errorCode == 40029) {
        // Invalid js_code - code expired or already used
    } else if (errorCode == 40013) {
        // Invalid appid
    }
}

Signature Verification

// Verify WeChat server signature (for webhook callbacks)
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");  
String signature = request.getParameter("signature");

boolean isValid = wxService.checkSignature(timestamp, nonce, signature);
if (isValid) {
    // Request is from WeChat servers
    // Process the callback safely
} else {
    // Invalid signature - reject the request
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
}

Dynamic Data Import

// Import dynamic data for search optimization
wxService.setDynamicData(
    300,        // lifespan in seconds
    "text",     // data type
    1001,       // scene ID  
    "product catalog updated"  // data content
);

Access Token Management

// Automatic token management (recommended)
String token1 = wxService.getAccessToken(); // Gets cached token

// Force refresh token
String token2 = wxService.getAccessToken(true); // Forces new token request

// Check token status from config
WxMaConfig config = wxService.getWxMaConfig();
boolean isExpired = config.isAccessTokenExpired();
String currentToken = config.getAccessToken();

Error Handling

import me.chanjar.weixin.common.error.WxErrorException;

try {
    // Any WeChat API operation
    String result = wxService.getAccessToken();
    
} catch (WxErrorException e) {
    int errorCode = e.getError().getErrorCode();
    String errorMsg = e.getError().getErrorMsg();
    String json = e.getError().getJson();
    
    // Common error codes
    switch (errorCode) {
        case 40001:
            // Invalid access token - will auto-refresh
            break;
        case 40013:
            // Invalid appid
            break;
        case 45009:
            // API quota reached
            break;
        case 48001:
            // API unauthorized - check API permissions
            break;
        default:
            // Handle other errors
            logger.error("WeChat API error: {} - {}", errorCode, errorMsg);
    }
}

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.

Install with Tessl CLI

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

docs

analytics.md

cloud-development.md

configuration.md

core-services.md

development-tools.md

ecommerce.md

index.md

live-streaming.md

logistics.md

media-content.md

messaging.md

qr-codes.md

user-management.md

tile.json