WxJava SDK

repository·develop·Indexed 12 days ago

https://github.com/binarywang/wxjava

A comprehensive Java SDK for WeChat development. It provides server-side support for Official Accounts (MP), Mini Programs (MiniApp), WeChat Pay, Enterprise WeChat (CP), Open Platform, and Video Accounts (Channel). The SDK includes modules such as weixin-java-mp, weixin-java-miniapp, and weixin-java-pay, with support for multi-tenant configurations and Spring @ConfigurationProperties integration.

Tokens
67.8K
Snippets
159
Records
233
Agent score
96%

What's inside WxJava

  1. Use the weixin-java-open module for WeChat Third-Party Platform development

    develop

    The weixin-java-open module is designed for developing WeChat Third-Party Platforms. It allows you to manage and develop on behalf of multiple Official Accounts or Mini Programs through authorization.

    Key Use Cases:

    1. Third-Party Platform Development: Acting as a platform to manage multiple WeChat entities.
    2. Official Account Management: Performing message and material management via authorization.
    3. Mini Program Management: Managing code and basic information settings via authorization.
  2. Important considerations for CommonUploadParam

    develop

    When using CommonUploadParam for WeChat uploads, keep the following in mind:

    • JSON Fields: If an API requires a JSON-formatted field (like description), you must manually serialize your object into a JSON string before passing it to addFormField.
    • Encoding: All form field values are encoded using UTF-8.
    • Optionality: Extra form fields are optional; if your specific API call doesn't require them, you can omit addFormField calls.
    • Compatibility:
      • Code using fromFile or fromBytes is backward compatible.
      • If you were previously using the new CommonUploadParam(name, data) constructor directly, you may need to update your code to use the factory methods or the updated constructor signature due to the addition of the formFields property.
  3. Manage Session Archive SDK lifecycle with ThreadLocal mode

    develop

    The Session Archive (会话存档) SDK has been refactored to use a ThreadLocal pattern. Instead of a shared SDK with reference counting, each thread now maintains its own independent SDK instance. This ensures thread safety and allows multiple calls within the same thread (e.g., fetching records, decrypting data, and downloading media) to reuse the same SDK instance without repeated initialization.

    Key Lifecycle Rules:

    • Lazy Initialization: The SDK is initialized automatically on the first call within a thread.
    • Thread-Bound: The SDK instance is tied to the current thread.
    • Manual Cleanup Required: Because the SDK uses native resources, you must explicitly release the SDK when a thread's task is finished to prevent native memory and connection leaks.
    // Typical usage pattern
    WxCpMsgAuditService msgAuditService = wxCpService.getMsgAuditService();
    
    try {
        // Multiple calls reuse the same SDK instance within this thread
        List<WxCpChatDatas.WxCpChatData> records = msgAuditService.getChatRecords(seq, 100L, null, null, 30L);
        for (WxCpChatDatas.WxCpChatData record : records) {
            WxCpChatModel model = msgAuditService.getDecryptChatData(record, 2);
            // ...
        }
    } finally {
        // CRITICAL: Always call this in a finally block to release native resources
        msgAuditService.closeThreadLocalSdk();
    }
  4. Compare Multi-tenant Modes in wx-java-miniapp-multi-spring-boot-starter

    develop

    Starting from version 4.8.0, the wx-java-miniapp-multi-spring-boot-starter supports two multi-tenant implementation modes. Choosing the right mode depends on your tenant count and programming model.

    1. Isolated Mode (ISOLATED - Default)

    Each tenant gets its own WxMaService instance and its own independent HTTP client.

    • Pros: Thread-safe, no ThreadLocal dependency (ideal for asynchronous/reactive programming), and complete isolation between tenants.
    • Cons: Higher resource consumption because each tenant creates a new HTTP client.
    • Best for: SaaS applications with a small number of tenants (recommended < 50), or environments using asynchronous/reactive programming.

    2. Shared Mode (SHARED)

    A single WxMaService instance manages all tenant configurations, sharing one HTTP client across all tenants.

    • Pros: Significantly lower resource usage and smaller memory footprint. Supports large-scale scenarios (100+ tenants).
    • Cons: Relies on ThreadLocal to switch configurations. Requires careful handling of thread context in asynchronous scenarios.
    • Best for: Large-scale applications (> 50 tenants) using synchronous programming where resource optimization is critical.
  5. Use WxMaKefuService for WeChat Mini Program Customer Service Management

    develop

    The WxMaKefuService provides comprehensive management for WeChat Mini Program customer service accounts and sessions. It is accessed via the main WxMaService instance. This service replaces the need for manual calls to WxMaCustomserviceWorkService or WxMaMsgService.sendKefuMsg() for management tasks.

    Key capabilities include:

    • Account Management: Adding, updating, deleting, and listing customer service accounts.
    • Session Management: Creating, closing, getting status, and listing customer service sessions.
    // Access the service through the main WxMaService instance
    WxMaKefuService kefuService = wxMaService.getKefuService();
  6. Understand Receipt Authorization Modes

    develop

    The new TransferService supports two modes for how users receive funds:

    1. Confirm Receipt Mode (Default):

      • Constant: WxPayConstants.ReceiptAuthorizationMode.CONFIRM_RECEIPT_AUTHORIZATION
      • Behavior: Users must manually click to confirm the receipt before funds arrive.
      • Pros/Cons: High security, but requires extra user action.
    2. No-Confirm Receipt Mode:

      • Constant: WxPayConstants.ReceiptAuthorizationMode.NO_CONFIRM_RECEIPT_AUTHORIZATION
      • Behavior: Funds arrive directly if the user has previously authorized this mode.
      • Pros/Cons: Seamless user experience; ideal for high-frequency scenarios like commissions or cashback.
      • Requirement: Users must perform authorization beforehand.
  7. Use WxPayMultiServices to manage multiple accounts

    develop

    The starter automatically injects WxPayMultiServices. Use this bean to retrieve a specific WxPayService instance by its configuration key.

    Key Concept: The configKey passed to getWxPayService(configKey) must match the key used in your configuration file (e.g., wx.pay.configs.<configKey>), not necessarily the appId unless you used the appId as the key.

    @Service
    public class PayService {
      @Autowired
      private WxPayMultiServices wxPayMultiServices;
    
      public void createOrder(String configKey, String openId, Integer totalFee, String body) throws Exception {
        // Retrieve the specific service for the given config key
        WxPayService wxPayService = wxPayMultiServices.getWxPayService(configKey);
    
        if (wxPayService == null) {
          throw new IllegalArgumentException("Config not found: " + configKey);
        }
        
        // Use the service as usual
        WxPayUnifiedOrderV3Request request = new WxPayUnifiedOrderV3Request();
        // ... set request parameters ...
        wxPayService.createOrderV3(TradeTypeEnum.JSAPI, request);
      }
    }
  8. Migrate Enterprise WeChat (CP) Message Audit APIs

    develop

    When upgrading to version 4.8.0 or higher, the following legacy methods are deprecated/removed and must be replaced according to the ThreadLocal lifecycle migration pattern:

    • getChatDatas
    • getDecryptData
    • getChatPlainText
    • getMediaFile
    • Manual calls to Finance.DestroySdk()

    Critical Lifecycle Management: Because the ThreadLocal SDK does not automatically release when a thread ends, you must manage the lifecycle manually to avoid memory leaks, especially in thread pools or scheduled tasks.

    1. In tasks (Thread/ThreadPool/Scheduled): You MUST call msgAuditService.closeThreadLocalSdk() inside a finally block.
    2. On Application Shutdown: Use closeAllSdks() as a global fallback.
    3. Warning: Do not call Finance.DestroySdk() directly in your business logic.
  9. Manage Mini Program Audit Quotas in Third-Party Platforms

    develop

    When using a Third-Party Platform to submit Mini Programs for audit, you are subject to monthly quota limits.

    Quota Rules:

    • Default Quota: 20 audits per month per Third-Party Platform account.
    • Consumption: Each call to submitAudit() consumes 1 quota.
    • Reset: Quotas reset automatically at the beginning of each month.

    Best Practice: Always check the remaining quota using queryQuota() before attempting to submit an audit to avoid runtime errors.

    // 1. Check remaining quota
    WxOpenMaQueryQuotaResult quota = wxOpenMaService.queryQuota();
    if (quota.getRest() <= 0) {
      throw new RuntimeException("Insufficient audit quota. Remaining: " + quota.getRest());
    }
    
    // 2. Submit for audit
    WxOpenMaSubmitAuditMessage message = new WxOpenMaSubmitAuditMessage();
    message.setItemList(itemList);
    WxOpenMaSubmitAuditResult result = wxOpenMaService.submitAudit(message);
  10. Best practices for multi-tenant and multi-appId scenarios

    develop

    When implementing complex WeChat Pay logic, follow these recommended patterns:

    1. Multi-tenant SaaS Scenarios: Use custom keys (such as a tenantId) to manage configurations. Register them using addConfig(String configKey, WxPayConfig) and switch contexts using switchover(tenantId).
    2. One Merchant with Multiple AppIDs: Use the mchId_appId format for keys. Switch contexts precisely using switchover(mchId, appId).
    3. Asynchronous/Thread Pool Scenarios: Avoid relying on ThreadLocal (which switchover uses). Instead, use getConfig(mchId, appId) to retrieve the required configuration directly in the worker thread.

    Important Notes:

    • Thread Safety: switchover uses WxPayConfigHolder (based on ThreadLocal), making it thread-safe for the current thread. Direct retrieval via getConfig(mchId, appId) does not depend on ThreadLocal and is safe in any context.
    • Notification Callbacks: The SDK automatically handles cases where appId might be missing in a callback by falling back to mchId matching during a switchover(mchId, appId) call.
    • Backward Compatibility: Existing single-appId usage remains fully supported and requires no code changes.
  11. Understand the Legacy Ecommerce API Compatibility Layer

    develop

    To maintain backward compatibility for users of the 收付通 (Ecommerce) payment module, WxJava provides a compatibility layer that maps old API models to the current unified V3 API.

    Key Architectural Concepts:

    • Legacy Models: Old data structures are restored in the com.github.binarywang.wxpay.bean.ecommerce package. These classes are marked with @Deprecated to signal that users should migrate to the unified V3 API.
    • Service Adapters: The EcommerceService provides deprecated method overloads. These overloads accept legacy request/response types, map them to the current unified request/enums, invoke the standard V3 methods, and then map the results back to the legacy formats.
    • Unified Logic: The compatibility layer does not reimplement HTTP transport, signature verification, or notification logic. It strictly acts as a mapping layer over the existing unified implementation.