tourze/wechat-mini-program-server-message-bundle 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

tourze/wechat-mini-program-server-message-bundle

Composer 安装命令:

composer require tourze/wechat-mini-program-server-message-bundle

包简介

微信小程序服务端消息处理组件

README 文档

README

English | 中文

PHP Version Latest Version Downloads
License Build Status Coverage

A Symfony bundle for handling WeChat Mini Program server-side message push notifications, including message decryption, validation, and event dispatching.

Table of Contents

Features

  • WeChat Mini Program message push server endpoint
  • Message signature verification and decryption
  • Automatic message persistence to database
  • Event dispatching for custom message handling
  • Built-in deduplication mechanism
  • Support for both JSON and XML message formats
  • Automatic user synchronization
  • Configurable message retention policies

Installation

composer require tourze/wechat-mini-program-server-message-bundle

Configuration

1. Register the Bundle

Add the bundle to your bundles.php:

<?php

return [
    // ... other bundles
    WechatMiniProgramServerMessageBundle\WechatMiniProgramServerMessageBundle::class => ['all' => true],
];

2. Configure Routing

The bundle automatically registers the message handling endpoint at:

/wechat/mini-program/server/{appId}

3. Environment Variables

Configure message retention policy:

# Optional: Set message retention days (default: 180)
WECHAT_MINI_PROGRAM_SERVER_MESSAGE_PERSIST_DAY=180

4. Database Migration

Create the required database table:

CREATE TABLE wechat_mini_program_server_message (
    id INT AUTO_INCREMENT PRIMARY KEY,
    account_id INT,
    create_time DATETIME,
    msg_id VARCHAR(255),
    to_user_name VARCHAR(255),
    from_user_name VARCHAR(255),
    msg_type VARCHAR(50),
    raw_data JSON,
    INDEX idx_create_time (create_time),
    FOREIGN KEY (account_id) REFERENCES wechat_mini_program_account(id) ON DELETE SET NULL
);

Quick Start

1. Set Up WeChat Mini Program Configuration

Ensure you have a WeChat Mini Program account configured with:

  • App ID
  • App Secret
  • Server Token

2. Configure Message Push URL

In WeChat Mini Program console, set the message push URL to:

https://your-domain.com/wechat/mini-program/server/{your-app-id}

3. Handle Message Events

Create an event subscriber to handle incoming messages:

<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WechatMiniProgramServerMessageBundle\Event\ServerMessageRequestEvent;

class WechatMessageSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ServerMessageRequestEvent::class => 'onServerMessage',
        ];
    }

    public function onServerMessage(ServerMessageRequestEvent $event): void
    {
        $message = $event->getMessage();
        $account = $event->getAccount();
        $wechatUser = $event->getWechatUser();

        // Handle different message types
        switch ($message['MsgType']) {
            case 'text':
                $this->handleTextMessage($message, $account, $wechatUser);
                break;
            case 'image':
                $this->handleImageMessage($message, $account, $wechatUser);
                break;
            // ... handle other message types
        }
    }

    private function handleTextMessage(array $message, $account, $wechatUser): void
    {
        // Your text message handling logic
        $content = $message['Content'];
        // Process the message...
    }

    private function handleImageMessage(array $message, $account, $wechatUser): void
    {
        // Your image message handling logic
        $picUrl = $message['PicUrl'];
        // Process the image...
    }
}

4. Access Message History

You can access stored messages using the repository:

<?php

namespace App\Service;

use WechatMiniProgramServerMessageBundle\Repository\ServerMessageRepository;

class MessageService
{
    public function __construct(
        private ServerMessageRepository $messageRepository
    ) {
    }

    public function getRecentMessages(int $limit = 10): array
    {
        return $this->messageRepository->findBy(
            [],
            ['createTime' => 'DESC'],
            $limit
        );
    }
}

Message Types

The bundle supports all WeChat Mini Program message types:

  • text: Text messages
  • image: Image messages
  • voice: Voice messages
  • video: Video messages
  • location: Location messages
  • link: Link messages
  • event: Event messages (subscribe, unsubscribe, etc.)

Event System

The bundle dispatches ServerMessageRequestEvent for each incoming message, containing:

  • $message: The parsed message data
  • $account: The WeChat Mini Program account
  • $wechatUser: The WeChat user information

Advanced Features

Message Deduplication

The bundle automatically handles message deduplication using:

  • Database unique constraints
  • Cache-based deduplication (1-hour TTL)

User Synchronization

Automatically creates and updates user records when messages are received, ensuring user data is always current.

Message Retention

Configure automatic message cleanup using the WECHAT_MINI_PROGRAM_SERVER_MESSAGE_PERSIST_DAY environment variable.

Advanced Usage

Custom Message Processing

For complex message processing scenarios, you can extend the default behavior:

<?php

namespace App\Service;

use WechatMiniProgramServerMessageBundle\Event\ServerMessageRequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AdvancedMessageProcessor implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ServerMessageRequestEvent::class => ['processMessage', 100], // High priority
        ];
    }

    public function processMessage(ServerMessageRequestEvent $event): void
    {
        $message = $event->getMessage();
        
        // Implement advanced processing logic
        if ($this->requiresSpecialHandling($message)) {
            $this->performAdvancedProcessing($message);
            // Optionally stop propagation to prevent other listeners
            $event->stopPropagation();
        }
    }

    private function requiresSpecialHandling(array $message): bool
    {
        // Your custom logic to determine if message needs special handling
        return isset($message['SpecialFlag']);
    }

    private function performAdvancedProcessing(array $message): void
    {
        // Your advanced processing implementation
    }
}

Custom Validation

You can add custom validation for incoming messages:

<?php

namespace App\Validator;

use WechatMiniProgramServerMessageBundle\Event\ServerMessageRequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class MessageValidator implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ServerMessageRequestEvent::class => ['validateMessage', 200], // Very high priority
        ];
    }

    public function validateMessage(ServerMessageRequestEvent $event): void
    {
        $message = $event->getMessage();
        
        if (!$this->isValidMessage($message)) {
            throw new BadRequestHttpException('Invalid message format');
        }
    }

    private function isValidMessage(array $message): bool
    {
        // Your custom validation logic
        return isset($message['FromUserName']) && isset($message['ToUserName']);
    }
}

Security

Message Verification

The bundle automatically verifies message signatures to ensure authenticity:

  • All incoming messages are validated against WeChat's signature algorithm
  • Invalid signatures are rejected with appropriate error responses
  • Message decryption is performed using your configured App Secret

Data Protection

  • All message data is validated before storage
  • Sensitive information is properly encrypted during transmission
  • User data is handled according to privacy best practices

Rate Limiting

Consider implementing rate limiting for your message endpoints:

<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;

class RateLimitSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            RequestEvent::class => 'onKernelRequest',
        ];
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();
        
        if (str_contains($request->getPathInfo(), '/wechat/mini-program/server/')) {
            if ($this->isRateLimited($request)) {
                throw new TooManyRequestsHttpException();
            }
        }
    }

    private function isRateLimited($request): bool
    {
        // Implement your rate limiting logic
        return false;
    }
}

Requirements

  • PHP 8.1+
  • Symfony 7.3+
  • Doctrine ORM 3.0+
  • Doctrine DBAL 4.0+
  • WeChat Mini Program Account

Contributing

Please see CONTRIBUTING.md for details.

License

The MIT License (MIT). Please see License File for more information.

tourze/wechat-mini-program-server-message-bundle 适用场景与选型建议

tourze/wechat-mini-program-server-message-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 523 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 05 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 tourze/wechat-mini-program-server-message-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 tourze/wechat-mini-program-server-message-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 tourze/wechat-mini-program-server-message-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 523
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 10
  • 依赖项目数: 4
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-05-10