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

Laravel Wechat Laravel Package

overtrue/laravel-wechat

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require overtrue/laravel-wechat
    

    Publish the config file:

    php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider" --tag="wechat-config"
    
  2. Configuration: Edit .env with your WeChat app credentials (e.g., WECHAT_OFFICIAL_ACCOUNT_APP_ID, WECHAT_OFFICIAL_ACCOUNT_APP_SECRET). Update config/wechat.php to match your use case (Official Account, Mini Program, etc.).

  3. First Use Case: Send a welcome message to a user via the Official Account API:

    use Overtrue\LaravelWeChat\Facades\WeChat;
    
    $result = WeChat::official_account->message->send([
        'touser' => 'openid_or_user_id',
        'msgtype' => 'text',
        'text' => ['content' => 'Welcome to our service!'],
    ]);
    

Where to Look First

  • Documentation: Official Docs (focus on the "Usage" section).
  • Config File: config/wechat.php for service-specific settings (e.g., official_account, mini_program).
  • Facade: Overtrue\LaravelWeChat\Facades\WeChat for quick access to all services.
  • Service Examples: Check tests/ for real-world usage patterns (e.g., OfficialAccountTest.php).

Implementation Patterns

Core Workflows

  1. Service Initialization: Bind services in AppServiceProvider or use facades directly:

    WeChat::official_account->user->get('openid'); // Fetch user info
    
  2. Event Handling: Use middleware to validate and process WeChat requests (e.g., VerifyMiddleware for Official Accounts):

    Route::middleware(['wechat.official_account.verify'])->group(function () {
        Route::post('/server', 'WeChatController@server');
    });
    
  3. Menu Management: Dynamically update menus via the facade:

    WeChat::official_account->menu->create([
        'button' => [
            ['type' => 'click', 'name' => 'Help', 'key' => 'HELP'],
        ],
    ]);
    
  4. Mini Program Integration: Handle auth and user sessions:

    $code = request('code'); // From redirect
    $user = WeChat::mini_program->auth->getUserByCode($code);
    
  5. Template Messages: Send transactional messages with placeholders:

    WeChat::official_account->template->send([
        'touser' => 'openid',
        'template_id' => 'YOUR_TEMPLATE_ID',
        'data' => ['first' => ['value' => 'Hello'], 'keyword1' => ['value' => 'World']],
    ]);
    

Integration Tips

  • Laravel Events: Trigger custom events after WeChat API calls (e.g., wechat.message.sent).
  • Caching: Cache frequent API responses (e.g., user info) using Laravel’s cache driver:
    $user = cache()->remember("wechat_user_{$openid}", now()->addHours(1), fn() =>
        WeChat::official_account->user->get($openid)
    );
    
  • Queue Jobs: Offload heavy operations (e.g., media uploads) to queues:
    dispatch(new UploadMediaJob($mediaPath));
    
  • API Rate Limiting: Use Laravel’s throttle middleware for WeChat API endpoints.

Gotchas and Tips

Pitfalls

  1. Token Mismatch:

    • Official Account VerifyMiddleware requires the token in config/wechat.php to match WeChat’s server settings.
    • Fix: Double-check .env and config values; test with WECHAT_OFFICIAL_ACCOUNT_TOKEN=test123.
  2. OpenID vs. UserID:

    • Official Accounts use openid, while Mini Programs use unionid or openid. Mixing them causes errors.
    • Tip: Log the response to debug:
      dd(WeChat::official_account->user->get('openid'));
      
  3. Media Uploads:

    • Temporary media files (e.g., images) expire after 2 hours. Cache responses or re-upload if needed.
    • Workaround: Store file paths locally and re-upload when expired.
  4. Signature Validation:

    • Mini Program login endpoints require appid, timestamp, and nonce validation. Use the facade’s built-in helpers:
      WeChat::mini_program->auth->validateSignature();
      
  5. Async Processing:

    • WeChat callbacks (e.g., event_push) may time out. Use Laravel queues or return 200 OK immediately:
      return response()->json(['success' => true]);
      dispatch(new ProcessWeChatEventJob($event));
      

Debugging

  • Enable Logging: Set WECHAT_LOG_LEVEL=debug in .env to log API requests/responses to storage/logs/wechat.log.
  • Mock Responses: Use WeChat::setMock(true) in tests to bypass real API calls:
    WeChat::setMock(true);
    WeChat::official_account->user->get('openid'); // Returns mock data
    

Extension Points

  1. Custom Services: Extend the base Service class to add domain-specific logic:

    class CustomService extends \Overtrue\LaravelWeChat\Support\Service
    {
        public function customMethod()
        {
            return $this->callApi('/custom/endpoint', []);
        }
    }
    

    Register in AppServiceProvider:

    WeChat::extend('custom', function () {
        return new CustomService(config('wechat.custom'));
    });
    
  2. Middleware Overrides: Override default middleware (e.g., VerifyMiddleware) in app/Http/Kernel.php:

    protected $middlewareGroups = [
        'wechat' => [
            \App\Http\Middleware\CustomVerifyMiddleware::class,
        ],
    ];
    
  3. API Response Handling: Modify response parsing in app/Providers/WeChatServiceProvider.php:

    WeChat::extend('official_account', function ($app) {
        $config = $app['config']['wechat.official_account'];
        $service = new \Overtrue\EasyWeChat\OfficialAccount($config);
        $service->setResponseCallback(function ($response) {
            // Custom logic (e.g., error handling)
            return $response;
        });
        return $service;
    });
    

Config Quirks

  • Environment Variables: Prefix all WeChat keys with WECHAT_ (e.g., WECHAT_OFFICIAL_ACCOUNT_APP_ID). The package auto-loads them.
  • Service-Specific Configs: Each service (official_account, mini_program, etc.) has its own config block in config/wechat.php. Ensure you’re editing the correct one.
  • Default Values: The package provides defaults for optional fields (e.g., language). Override only what’s necessary.
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle