首页 课程中心 读书 公众号框架 HUI H.JS 开放源 登录 & 注册
 自定义菜单创建及消息识别

创建自定义菜单
使用$hcWeChat->createMenu($menu);可以创建公众号自定义菜单。
创建 createMenu.php 并执行即可完成自定义菜单的创建工作,代码如下:

<?php
/*
 * hcWeChat 自定义菜单创建演示代码 
 */
include '../hcWeChat/hcWeChat.php';
$hcWeChat = new hcWeChat();
$menu = '
{
    "button":
    [
        {    
            "type":"click",
            "name":"php编程",
            "key":"KEY01"
        },
        {
            "name":"html",
            "sub_button":
            [
                {    
                   "type":"view",
                   "name":"网易",
                   "url":"http://www.163.com/"
                },
                {
                   "type":"view",
                   "name":"腾讯",
                   "url":"http://www.qq.com/"
                }
            ]
       },
       {
               "name":"更多",
            "sub_button":
            [
                {
                   "type":"view",
                "name":"我的",
                "url":"http://wx.hcoder.net/demo/my.php"
                },
                {
                   "type":"view",
                "name":"支付",
                "url":"http://wx.hcoder.net/demo/pay.php"
                }
            ]
       }
    ]
 }';
$hcWeChat->createMenu($menu);


识别菜单点击
用户点击自定义菜单后微信会向开发者服务器发送消息,识别次消息即可监测用户对自定义菜单的点击,代码片段:

else if($hcWeChat->msgType == 'event'){
    switch($hcWeChat->event){
        //关注
        case 'subscribe':
            //获取用户信息
            $user = $hcWeChat->getUser($hcWeChat->openId);
            $hcWeChat->reTextMsg($user['nickname'].'您好,感谢关注 ^_^');
        break;
        //取消关注
        case 'unsubscribe':
            file_put_contents('unsub.txt', $hcWeChat->openId.'取消关注');
        break;
        //自定义菜单点击事件
        case 'CLICK':
            if($hcWeChat->msg->EventKey == 'KEY01'){
                $hcWeChat->reTextMsg('您点击了第一个菜单!');
            }
        break;
    }
}


获取自定义菜单数据

<?php
/*
 * hcWeChat 获取自定义菜单数据演示代码 
 */
include '../hcWeChat/hcWeChat.php';
$hcWeChat = new hcWeChat();
$hcWeChat->getMenu();