程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php版微信公眾平台賬號自定義菜單類

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 (!empty($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;
        }
    }
}

?>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved