PHP code example of tourze / wechat-official-account-menu-bundle

1. Go to this page and download the library: Download tourze/wechat-official-account-menu-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-menu-bundle example snippets


use WechatOfficialAccountMenuBundle\Service\MenuService;

// Create top-level menu
$menuData = [
    'name' => 'Products',
    'type' => MenuType::VIEW,
    'url' => 'https://example.com/products',
    'position' => 0,
    'enabled' => true,
];
$menuButton = $menuService->createMenuButton($account, $menuData);

// Create sub-menu
$subMenuData = [
    'name' => 'Product Details',
    'type' => MenuType::VIEW,
    'url' => 'https://example.com/product/detail',
    'parent' => $parentMenuButton,
];
$subMenuButton = $menuService->createMenuButton($account, $subMenuData);

$menuService->updateMenuButton($menuButton, [
    'name' => 'New Products',
    'url' => 'https://example.com/new-products',
]);

$positions = [
    'button_id_1' => 0,
    'button_id_2' => 1,
    'button_id_3' => 2,
];
$menuService->updateMenuPositions($positions);

use WechatOfficialAccountMenuBundle\Service\MenuVersionService;

// Create version from current menu
$version = $menuVersionService->createVersion(
    $account,
    '2024 Spring Festival Menu'
);

// Create from existing version
$newVersion = $menuVersionService->createVersion(
    $account,
    'Adjusted from Spring Festival version',
    $existingVersion
);

try {
    $menuVersionService->publishVersion($version);
    echo "Menu published successfully!";
} catch (MenuVersionException $e) {
    echo "Publishing failed: " . $e->getMessage();
}

$rollbackVersion = $menuVersionService->rollbackToVersion($oldVersion);

$changes = $menuVersionService->compareVersions($version1, $version2);
// Returns: added, removed, modified

use WechatOfficialAccountMenuBundle\Service\WechatMenuApiService;

// Create personalized menu for specific user groups
$personalizedMenu = [
    'button' => $menuButtons,
    'matchrule' => [
        'tag_id' => '101',  // User tag ID
        'sex' => '1',       // Gender: 1=Male, 2=Female
        'country' => 'CN',  // Country
        'province' => 'Guangdong',  // Province
        'city' => 'Guangzhou',      // City
        'client_platform_type' => '1', // Platform: 1=iOS, 2=Android, 3=Others
        'language' => 'zh_CN'       // Language
    ]
];

$wechatMenuApiService->addConditionalMenu($account, $personalizedMenu);

// Batch create menus
$menuBatchData = [
    ['name' => 'Menu 1', 'type' => MenuType::VIEW, 'url' => 'https://example.com/1'],
    ['name' => 'Menu 2', 'type' => MenuType::VIEW, 'url' => 'https://example.com/2'],
    ['name' => 'Menu 3', 'type' => MenuType::CLICK, 'key' => 'MENU_3_KEY'],
];

foreach ($menuBatchData as $index => $data) {
    $data['position'] = $index;
    $menuService->createMenuButton($account, $data);
}

// Batch enable/disable menus
$menuService->batchUpdateStatus($menuIds, true); // Enable all
$menuService->batchUpdateStatus($menuIds, false); // Disable all

// Get menu click statistics (uClickStats($account, $startDate, $endDate);

// Monitor menu synchronization status
$syncStatus = $wechatMenuApiService->getCurrentMenuInfo($account);
if ($syncStatus['is_menu_open'] === 1) {
    echo "Menu is enabled on WeChat";
}

use WechatOfficialAccountMenuBundle\Exception\WechatApiException;

try {
    $menuVersionService->publishVersion($version);
} catch (WechatApiException $e) {
    // Log the error
    $logger->error('Menu publish failed', [
        'error_code' => $e->getErrorCode(),
        'error_msg' => $e->getMessage(),
        'version_id' => $version->getId()
    ]);
    
    // Attempt recovery
    if ($e->getErrorCode() === 48001) { // API unauthorized
        // Refresh access token and retry
        $accessTokenService->refreshToken($account);
        $menuVersionService->publishVersion($version);
    }
}

// Always validate account ownership
if ($menu->getAccount()->getId() !== $currentUserAccountId) {
    throw new AccessDeniedException('Insufficient permissions');
}

// Validate URLs before setting
if (!filter_var($url, FILTER_VALIDATE_URL)) {
    throw new InvalidArgumentException('Invalid URL format');
}

use WechatOfficialAccountMenuBundle\Exception\MenuValidationException;
use WechatOfficialAccountMenuBundle\Exception\MenuVersionException;
use WechatOfficialAccountMenuBundle\Exception\WechatApiException;

try {
    // Menu operations
} catch (MenuValidationException $e) {
    // Menu validation failed
} catch (MenuVersionException $e) {
    // Version operation failed
} catch (WechatApiException $e) {
    // WeChat API call failed
    $errorCode = $e->getErrorCode();
}