PHP code example of tourze / wechat-official-account-server-message-bundle

1. Go to this page and download the library: Download tourze/wechat-official-account-server-message-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

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




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);
        }
    }
}

// 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;

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