Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Easywechat Laravel Package

w7corp/easywechat

EasyWeChat is a PHP 8+ SDK for WeChat development by w7corp. It supports Official Accounts and more, with simple configuration and server message handling, plus active maintenance, tests, and solid documentation via easywechat.com.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require w7corp/easywechat:^6.19
    

    Register the service provider in config/app.php under providers:

    W7Corp\EasyWeChat\Foundation\Provider::class,
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="W7Corp\EasyWeChat\Foundation\Provider" --tag=config
    

    Edit .env with your WeChat app credentials (e.g., WECHAT_OFFICIAL_ACCOUNT_APP_ID, WECHAT_OFFICIAL_ACCOUNT_SECRET).

  3. First Use Case: Sending a Message

    use W7Corp\EasyWeChat\OfficialAccount\Application;
    
    $app = Application::create();
    $result = $app->customer_service->message->send([
        'touser' => 'openid_or_user_id',
        'msgtype' => 'text',
        'text' => ['content' => 'Hello, WeChat!']
    ]);
    

Implementation Patterns

Common Workflows

  1. Handling Incoming Messages Use middleware to validate and route messages:

    // app/Http/Middleware/HandleWeChat.php
    public function handle($request, Closure $next) {
        $app = Application::create();
        $message = $app->message;
        if ($message->validate()) {
            $event = $message->getEvent();
            // Route based on event type (e.g., text, scan, subscribe)
        }
        return $next($request);
    }
    
  2. Menu Management Create/update menus dynamically:

    $menu = [
        'button' => [
            [
                'type' => 'click',
                'name' => 'Click Me',
                'key' => 'CLICK_EVENT'
            ]
        ]
    ];
    $app->menu->create($menu);
    
  3. User Data Access Fetch user info via OpenID:

    $user = $app->user->get('openid123');
    
  4. Media Handling Upload/download media (e.g., images, voice):

    // Upload
    $mediaId = $app->media->upload('image', fopen('path/to/image.jpg', 'r'));
    
    // Download
    $app->media->download($mediaId, 'path/to/save.jpg');
    
  5. Template Messages Send templated notifications:

    $result = $app->template_message->send([
        'touser' => 'openid',
        'template_id' => 'YOUR_TEMPLATE_ID',
        'data' => [
            'first' => ['value' => 'Hello!', 'color' => '#FF0000'],
            // ... other fields
        ]
    ]);
    

Integration Tips

  • Laravel Events: Trigger custom events for WeChat messages:
    event(new WeChatMessageReceived($event));
    
  • Queue Jobs: Offload heavy tasks (e.g., media processing) to queues:
    dispatch(new ProcessWeChatMedia($mediaId));
    
  • Caching: Cache frequent API calls (e.g., user data) using Laravel’s cache:
    $user = Cache::remember("wechat_user_{$openid}", now()->addHours(1), fn() =>
        $app->user->get($openid)
    );
    
  • Symfony 8 Compatibility: Leverage Symfony 8 components (e.g., HttpClient, Cache) if your Laravel app uses them:
    use Symfony\Component\HttpClient\HttpClient;
    
    $client = HttpClient::create();
    

Gotchas and Tips

Pitfalls

  1. Token Validation

    • Always validate the msg_signature in middleware to prevent spoofing:
      if (!$app->message->validate()) {
          abort(403, 'Invalid WeChat request');
      }
      
    • Ensure WECHAT_OFFICIAL_ACCOUNT_TOKEN in .env matches the token set in WeChat MP.
  2. Rate Limits

    • WeChat imposes rate limits (e.g., 2000 messages/hour). Handle WxErrorException gracefully:
      try {
          $result = $app->customer_service->message->send(...);
      } catch (\W7Corp\EasyWeChat\Kernel\Exceptions\WxErrorException $e) {
          Log::error("WeChat API error: {$e->getCode()}: {$e->getMessage()}");
          // Retry or notify admin
      }
      
  3. OpenID Expiry

    • OpenIDs expire after 2 hours. Cache them with a short TTL or refresh when needed:
      $openid = Cache::get("wechat_openid_{$sessionKey}", function() use ($app, $sessionKey) {
          return $app->oauth->getUser()->getOriginal()['openid'];
      });
      
  4. Media Storage

    • Temporary media (e.g., media_id) expires in 3 days. Download and store permanently if needed.
  5. JS-SDK Configuration

    • For WeChat web pages, regenerate the jsapi_ticket if it expires (hourly):
      $ticket = $app->jssdk->getJsApiTicket();
      
  6. Symfony Dependency Conflicts

    • If using Symfony 8 components directly, ensure version constraints in composer.json align with EasyWeChat’s updated compatibility:
      "require": {
          "symfony/cache": "^6.0|^7.0|^8.0",
          "symfony/http-client": "^6.0|^7.0|^8.0"
      }
      

Debugging Tips

  1. Enable Logging Configure logging in config/easywechat.php:

    'log' => [
        'level' => 'debug',
        'file' => storage_path('logs/easywechat.log'),
    ],
    
  2. Inspect Raw Responses Use dd($result->getOriginal()) to debug API responses.

  3. Test in Sandbox Use WeChat’s official sandbox environment (https://mp.weixin.qq.com) for testing before going live.

  4. PHP 8.0+ Compatibility

    • Ensure your codebase is PHP 8.0+ compatible (e.g., named arguments, union types) to avoid CI regressions:
      // Example: Use named arguments for clarity
      $app->customer_service->message->send([
          'touser' => 'openid',
          'msgtype' => 'text',
          'text' => ['content' => 'Hello'],
      ]);
      

Extension Points

  1. Custom Message Handlers Extend the Message class to handle custom message types:

    class CustomMessage extends \W7Corp\EasyWeChat\OfficialAccount\Message
    {
        public function handleCustomEvent($event)
        {
            // Logic for custom events
        }
    }
    
  2. API Wrappers Create service classes to wrap EasyWeChat methods for your domain:

    class WeChatNotificationService
    {
        public function sendOrderConfirmation($order)
        {
            $app = Application::create();
            $app->template_message->send([
                'touser' => $order->user->openid,
                'template_id' => config('wechat.templates.order_confirmation'),
                'data' => [
                    'order_id' => ['value' => $order->id, 'color' => '#173177'],
                    // ...
                ]
            ]);
        }
    }
    
  3. Symfony Integration Use Symfony’s HttpClient or Cache components for advanced use cases:

    // Example: Using Symfony HttpClient for custom API calls
    use Symfony\Component\HttpClient\HttpClient;
    
    $client = HttpClient::create();
    $response = $client->request('GET', 'https://api.weixin.qq.com/cgi-bin/user/info', [
        'query' => [
            'access_token' => $app->access_token,
            'openid' => 'user_openid',
        ],
    ]);
    
  4. Webhook Validation For custom webhook endpoints, validate the signature manually if needed:

    $app = Application::create();
    $signature = $app->message->getSignature();
    $timestamp = $app->message->getTimestamp();
    $nonce = $app->message->getNonce();
    $token = config('wechat.official_account.token');
    $validSignature = sha1($token . $timestamp . $nonce);
    if ($validSignature !== $signature) {
        abort(403);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor