欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php实现微信公众平台账号自定义菜单类

程序员文章站 2022-10-11 12:13:51
本文实例讲述了php实现微信公众平台账号自定义菜单类的方法。分享给大家供大家参考。具体分析如下: 微信公众平台服务号可申请自定义菜单了,其它的号暂时不支持自定义菜单了,这...

本文实例讲述了php实现微信公众平台账号自定义菜单类的方法。分享给大家供大家参考。具体分析如下:

微信公众平台服务号可申请自定义菜单了,其它的号暂时不支持自定义菜单了,这个不但可以使用api来操作,还可以直接在后台定义菜单与参数。

申请自定义菜单

服务号可以申请自定义菜单,使用qq登录的公众号,可以升级为邮箱登录,使用邮箱登录的公众号,可以修改登录邮箱,群发消息可以同步到腾讯微博.

微信公众平台账号api程序

复制代码 代码如下:
<?php
//define your token
define("token", "chenxiang");//改成自己的token
define('app_id', '');//改成自己的appid
define('app_secret', '');//改成自己的appsecret
 
$wechatobj = new wechatcallbackapitest(app_id,app_secret);
$wechatobj->run();
 
class wechatcallbackapitest
{
    private $fromusername;
    private $tousername;
    private $times;
    private $keyword;
    private $app_id;
    private $app_secret;
    
    public function __construct($appid,$appsecret)
    {
        # code...
        $this->app_id = $appid;
        $this->app_secret = $appsecret;
    }
    public function valid()
    {
        $echostr = $_get["echostr"];
        if($this->checksignature()){
            echo $echostr;
            exit;
        }
    }
    /**
     * 运行程序
     * @param string $value [description]
     */
    public function run()
    {
        $this->responsemsg();
        $arr[]= "您好,这是自动回复,我现在不在,有事请留言,我会尽快回复你的^_^";
        echo $this->make_xml("text",$arr);
    }
    public function responsemsg()
    {   
        $poststr = $globals["http_raw_post_data"];//返回回复数据
        if (!emptyempty($poststr)){
                $access_token = $this->get_access_token();//获取access_token
                $this->createmenu($access_token);//创建菜单
                //$this->delmenu($access_token);//删除菜单
                $postobj = simplexml_load_string($poststr, 'simplexmlelement', libxml_nocdata);
                $this->fromusername = $postobj->fromusername;//发送消息方id
                $this->tousername = $postobj->tousername;//接收消息方id
                $this->keyword = trim($postobj->content);//用户发送的消息
                $this->times = time();//发送时间
                $msgtype = $postobj->msgtype;//消息类型
                if($msgtype=='event'){
                    $msgevent = $postobj->event;//获取事件类型
                    if ($msgevent=='subscribe') {//订阅事件
                        $arr[] = "你好,我是xxx,现在我们是好友咯![愉快][玫瑰]";
                        echo $this->make_xml("text",$arr);
                        exit;
                    }elseif ($msgevent=='click') {//点击事件
                        $eventkey = $postobj->eventkey;//菜单的自定义的key值,可以根据此值判断用户点击了什么内容,从而推送不同信息
                        $arr[] = $eventkey;
                        echo $this->make_xml("text",$arr);
                        exit;
                    }
                }
        }else {
            echo "this a file for weixin api!";
            exit;
        }
    }
    /**
     * 获取access_token
     */
    private function get_access_token()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->app_id."&secret=".$this->app_secret;
        $data = json_decode(file_get_contents($url),true);
        if($data['access_token']){
            return $data['access_token'];
        }else{
            return "获取access_token错误";
        }
    }
    /**
     * 创建菜单
     * @param $access_token 已获取的access_token
     */
    public function createmenu($access_token)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
        $arr = array( 
            'button' =>array(
                array(
                    'name'=>urlencode("生活查询"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("天气查询"),
                            'type'=>'click',
                            'key'=>'vcx_weather'
                        ),
                        array(
                            'name'=>urlencode("身份证查询"),
                            'type'=>'click',
                            'key'=>'vcx_ident'
                        )
                    )
                ),
                array(
                    'name'=>urlencode("轻松娱乐"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("刮刮乐"),
                            'type'=>'click',
                            'key'=>'vcx_guahappy'
                        ),
                        array(
                            'name'=>urlencode("幸运大转盘"),
                            'type'=>'click',
                            'key'=>'vcx_luckpan'
                        )
                    )
                ),
                array(
                    'name'=>urlencode("我的信息"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("关于我"),
                            'type'=>'click',
                            'key'=>'vcx_aboutme'
                        ),
                        array(
                            'name'=>urlencode("工作信息"),
                            'type'=>'click',
                            'key'=>'vcx_jobinformation'
                        )
                    )
                )
            )
        );
        $jsondata = urldecode(json_encode($arr));
        $ch = curl_init();
        curl_setopt($ch,curlopt_url,$url);
        curl_setopt($ch,curlopt_returntransfer,1);
        curl_setopt($ch,curlopt_post,1);
        curl_setopt($ch,curlopt_postfields,$jsondata);
        curl_exec($ch);
        curl_close($ch);
    }
    /**
     * 查询菜单
     * @param $access_token 已获取的access_token
     */
    
    private function getmenu($access_token)
    {
        # code...
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$access_token;
        $data = file_get_contents($url);
        return $data;
    }
    /**
     * 删除菜单
     * @param $access_token 已获取的access_token
     */
    
    private function delmenu($access_token)
    {
        # code...
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$access_token;
        $data = json_decode(file_get_contents($url),true);
        if ($data['errcode']==0) {
            # code...
            return true;
        }else{
            return false;
        }
    }
        
    /**
     *@param type: text 文本类型, news 图文类型
     *@param value_arr array(内容),array(id)
     *@param o_arr array(array(标题,介绍,图片,超链接),...小于10条),array(条数,id)
     */
    
    private function make_xml($type,$value_arr,$o_arr=array(0)){
        //=================xml header============
        $con="<xml>
                    <tousername><![cdata[{$this->fromusername}]]></tousername>
                    <fromusername><![cdata[{$this->tousername}]]></fromusername>
                    <createtime>{$this->times}</createtime>
                    <msgtype><![cdata[{$type}]]></msgtype>";
                    
          //=================type content============
        switch($type){
          
            case "text" : 
                $con.="<content><![cdata[{$value_arr[0]}]]></content>
                    <funcflag>{$o_arr}</funcflag>";  
            break;
            
            case "news" : 
                $con.="<articlecount>{$o_arr[0]}</articlecount>
                     <articles>";
                foreach($value_arr as $id=>$v){
                    if($id>=$o_arr[0]) break; else null; //判断数组数不超过设置数
                    $con.="<item>
                         <title><![cdata[{$v[0]}]]></title> 
                         <description><![cdata[{$v[1]}]]></description>
                         <picurl><![cdata[{$v[2]}]]></picurl>
                         <url><![cdata[{$v[3]}]]></url>
                         </item>";
                }
                $con.="</articles>
                     <funcflag>{$o_arr[1]}</funcflag>";  
            break;
        } //end switch
         //=================end return============
        $con.="</xml>";
        return $con;
    }
 
    private function checksignature()
    {
        $signature = $_get["signature"];
        $timestamp = $_get["timestamp"];
        $nonce = $_get["nonce"];    
                
        $token = token;
        $tmparr = array($token, $timestamp, $nonce);
        sort($tmparr);
        $tmpstr = implode( $tmparr );
        $tmpstr = sha1( $tmpstr );
        
        if( $tmpstr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}
?>

希望本文所述对大家基于php的微信开发有所帮助。