EasyWeChat Documentation

repository·6.x·Indexed 27 days ago

https://github.com/w7corp/easywechat

A PHP SDK for WeChat development designed to streamline interactions with WeChat services, including Official Accounts. Supports PHP >= 8.0.2 and Composer >= 2.0. Key features include Official Account server management, Access Token handling with Redis caching via doctrine/cache, data statistics and analysis, broadcast messaging, and WeChat Card (卡券) management.

Tokens
172.7K
Snippets
602
Records
1K
Agent score
94%

What's inside EasyWeChat

  1. Understand default cache behavior in EasyWeChat 6.x

    6.x

    In EasyWeChat 6.x, application instances (e.g., OfficialAccount\Application, MiniApp\Application) use the InteractWithCache trait to provide a unified cache interface. By default, all caching uses the file system, with the path determined by the PHP temporary directory.

    You can retrieve the current cache instance, lifetime, and namespace using the following methods:

    • getCache(): Returns the cache instance.
    • getCacheLifetime(): Returns the cache lifetime in seconds (default is 1500).
    • getCacheNamespace(): Returns the cache namespace (default is 'easywechat').
    use EasyWeChat\OfficialAccount\Application;
    
    $app = new Application([
        'app_id' => 'your-app-id',
        'secret' => 'your-app-secret',
        // ...
    ]);
    
    // Get default cache instance
    $cache = $app->getCache();
    
    // Get default configuration
    echo $app->getCacheLifetime(); // 1500 seconds
    echo $app->getCacheNamespace(); // 'easywechat'
  2. Understand Official Account Message Types

    6.x

    Official Account messages are categorized into two distinct scenarios. It is critical to distinguish between them as they use different data formats and structures:

    1. Server-side Passive Reply Messages: These are messages sent from the user to your server. They use an XML structure.
    2. Customer Service Messages: These are messages sent from your server to the user. They use a JSON structure.

    Always verify the specific field names and structures based on which scenario you are implementing.

  3. Important constraints for Group Welcome Templates

    6.x

    When using the Group Welcome Template API, keep the following in mind:

    • Quantity Limit: Each enterprise can create a maximum of 100 welcome templates.
    • Media Resources: Images and mini-program covers require a media_id obtained via prior upload.
    • Permissions: Requires WeChat Work administrator permissions.
    • Content Compliance: Ensure all content adheres to WeChat Work guidelines.
    • Rate Limiting: Avoid frequent modifications to the same template.
  4. Understand the 6.x Architecture Changes

    6.x

    EasyWeChat 6.x is a complete rewrite of the SDK with a different design philosophy compared to older versions. Key architectural shifts include:

    • No Business Interface Encapsulation: The SDK no longer provides built-in high-level business interfaces. Instead, it focuses on low-level foundational components such as authentication, authorization, and the API client. This reduces learning costs and ensures users can use official WeChat API names directly. It also improves update timeliness, as users can call underlying API endpoints directly without waiting for SDK updates.
    • De-containerization: Unlike versions 3.x and 5.x which used silexphp/Pimple as a service container, 6.x has removed the container layer. Modules now exist as pure, independent classes. Dependencies are passed via dependency injection.
    • High Customizability: Almost every module is dependent on an interface, allowing you to replace any module (including the underlying HTTP Client) with your own implementation.
  5. Use Sandbox Mode for WeChat Pay

    6.x

    EasyWeChat supports a sandbox mode to simulate payments and callback notifications. To enable it, set 'sandbox' => true in your configuration array during instantiation. You can check if the current instance is in sandbox mode using inSandbox().

    Note: Sandbox mode has strict requirements for test cases. If your test cases do not comply with official requirements, tests will fail.

  6. Generate Pre-Authorization URL for PC version (v6.3.0+)

    6.x

    For WeChat Open Platform PC version authorization, use createPreAuthorizationUrl to generate the redirect URL.

    Options:

    • auth_type:
      • 1: Show only Official Accounts.
      • 2: Show only Mini Programs.
      • 3: Show both (default if not specified).
    • category_id_list: A list of permission set IDs. If not specified, it defaults to all permission sets published by the current third-party account.
  7. Implement Scan Pay Mode 1: Generate product QR code first

    6.x

    In this mode, you generate a product-specific URL/scheme first. The user scans this to initiate an order.

    1. Generate the content: Use $app->scheme($productId) to get the scheme string. The $productId is your internal identifier used to track the product during the callback.
    2. Generate QR Code: The SDK does not include a QR code generator. Use a third-party library (e.g., endroid/qr-code or SimpleSoftwareIO/simple-qrcode) to turn the scheme string into a QR code.
    3. Handle the Scan Callback: When a user scans the code, WeChat will notify your callback endpoint. Use $app->handleScannedNotify to process this. Inside the callback, call the unify method to create the actual order and return the prepay_id.
    4. Handle Payment Result: After the user pays, you will receive a separate payment result notification. Follow the standard payment notification handling guide to update your order status.
  8. Handle Shake Around user shake events

    6.x

    When a user enters the 'Shake Around' interface and shakes their device while on the 'Nearby' (周边) tab, WeChat pushes an event to your configured developer URL.

    Event Details:

    • Event Type: ShakearoundUserShake
    • Payload: Contains information about the device corresponding to the page displayed on the 'Nearby' tab, as well as information for up to five nearby devices belonging to the same official account.
    • Note: If the shake results in an empty list, no event is pushed.

    Ensure your developer URL is correctly configured in the WeChat Official Account Platform developer center to receive these push notifications.

  9. Handle Enterprise WeChat Third-Party Platform Push Events

    6.x

    The Enterprise WeChat third-party platform pushes various events to your server. EasyWeChat provides built-in message handlers to process these events.

    Available event types include:

    • suite_ticket: SuiteTicket updates
    • create_auth: Authorization successful
    • change_auth: Authorization changed
    • cancel_auth: Authorization cancelled
    • change_contact: Contact information changed (InfoType)
      • create_user: New member
      • update_user: Updated member
      • delete_user: Deleted member
      • create_party: New department
      • update_party: Updated department
      • delete_party: Deleted department
      • update_tag: Member tag updated
    • share_agent_change: Shared application event
    • reset_permanent_code: Permanent authorization code reset notification
    • change_app_admin: Application administrator change notification
  10. Replace service modules using rebind

    6.x

    EasyWeChat uses a container pattern to organize module instances. This allows you to replace existing services with your own custom implementations using the rebind method. For example, you can replace the default request service in an Official Account application with a custom request class.

    $app = Factory::officialAccount($config);
    
    // Replace the 'request' service with a custom implementation
    $app->rebind('request', new MyCustomRequest(...));