tourze/wechat-official-account-server-message-bundle

微信公众号服务端消息处理组件

Installs: 96

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

Type:symfony-bundle

pkg:composer/tourze/wechat-official-account-server-message-bundle

This package is auto-updated.

Last update: 2025-11-03 06:27:45 UTC


README

English | 中文

Latest Version PHP Version License Build Status Quality Score Code Coverage Total Downloads

A Symfony bundle for handling WeChat Official Account server messages and webhooks.

Features

  • Message Processing: Handle incoming WeChat Official Account server messages
  • Webhook Support: Process WeChat server callbacks with signature validation
  • Message Persistence: Store server messages in database with automatic cleanup
  • Event Dispatching: Dispatch events for custom message handling
  • Async Processing: Support for asynchronous message handling via Symfony Messenger
  • Lock Management: Prevent duplicate message processing
  • User Synchronization: Automatically sync user information from WeChat

Installation

composer require tourze/wechat-official-account-server-message-bundle

Requirements

  • PHP 8.1+
  • Symfony 6.4+
  • Doctrine ORM

Quick Start

<?php

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WechatOfficialAccountServerMessageBundle\Event\WechatOfficialAccountServerMessageRequestEvent;

class MessageHandler implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            WechatOfficialAccountServerMessageRequestEvent::class => 'handleMessage',
        ];
    }

    public function handleMessage(WechatOfficialAccountServerMessageRequestEvent $event): void
    {
        $message = $event->getMessage();
        
        if ($message->getMsgType() === 'text') {
            $response = [
                'ToUserName' => $message->getFromUserName(),
                'FromUserName' => $message->getToUserName(),
                'CreateTime' => time(),
                'MsgType' => 'text',
                'Content' => 'Hello, World!',
            ];
            
            $event->setResponse($response);
        }
    }
}

Advanced Usage

Custom Message Processing

For more complex message handling scenarios:

// Configure async processing for specific message types
if (in_array($message->getMsgType(), ['TEMPLATESENDJOBFINISH', 'VIEW', 'view_miniprogram'])) {
    // Message will be processed asynchronously
}

// Access full message context
$context = $message->getContext();
$customData = $context['CustomField'] ?? null;

Configuration

Bundle Registration

The bundle will be automatically registered if you use Symfony Flex. Otherwise, add it to your config/bundles.php:

return [
    // ...
    WechatOfficialAccountServerMessageBundle\WechatOfficialAccountServerMessageBundle::class => ['all' => true],
];

Environment Variables

Configure message retention period:

# Number of days to keep server messages (default: 7)
WECHAT_OFFICIAL_ACCOUNT_MESSAGE_PERSIST_DAY_NUM=7

Usage

Webhook Endpoint

The bundle provides a webhook endpoint at /wechat/official-account/server/{id} where {id} can be either:

  • Account ID
  • WeChat App ID

Message Types Supported

  • Text messages
  • Image messages
  • Voice messages
  • Video messages
  • Location messages
  • Link messages
  • Event messages (subscribe, unsubscribe, click, etc.)

Event Handling

The bundle automatically handles all message types and dispatches events for custom processing. See the Quick Start section for basic usage.

Async Processing

Some message types are processed asynchronously via Symfony Messenger:

  • TEMPLATESENDJOBFINISH
  • VIEW
  • view_miniprogram

Database Schema

The bundle creates a wechat_official_account_message table to store server messages with the following fields:

  • id: Primary key
  • account_id: Reference to WeChat account
  • msg_id: Unique message identifier
  • to_user_name: Recipient OpenID
  • from_user_name: Sender OpenID
  • msg_type: Message type
  • create_time: Message timestamp
  • context: Full message context (JSON)

Automatic Cleanup

Server messages are automatically cleaned up using the Schedule Entity Clean Bundle. Messages older than the configured retention period are deleted daily at 5:26 AM.

Security

  • Message signature validation for encrypted messages
  • IP validation (TODO: implement WeChat IP whitelist check)
  • Lock-based duplicate message prevention

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

License

This bundle is released under the MIT License. See the LICENSE file for details.