研究微信公众平台开发模式下的菜单加消息处理

<?php 

//define your token 

define("TOKEN", "");//改成自己的TOKEN 

define('APP_ID', '');//改成自己的APPID 

define('APP_SECRET', '');//改成自己的APPSECRET 

 

$wechatObj = new wechatCallbackapiTest(APP_ID,APP_SECRET); 

//$wechatObj->valid();

$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(); 

     /*

       $access_token = $this->get_access_token();//获取access_token 

       var_dump($access_token);

       $this->createmenu($access_token);//创建菜单

        */

       // $arr[]= "您好,这是自动回复,我现在不在,有事请留言,我会尽快回复你的^_^"; 

       // echo $this->make_xml("text",$arr); 

    } 

    public function responseMsg() 

    {

        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//返回回复数据 

        if (!empty($postStr)){ 

            libxml_disable_entity_loader(true);

            //$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;//消息类型 

            

            $strWelcome = "问题开始!请根据提示回复数字!\n

                回复1:软件咨询\n

                回复2:会员信息查询\n

                回复3:软件购买咨询\n

                ";

            

            if($MsgType=='event'){ 

                $MsgEvent = $postObj->Event;//获取事件类型 

                if ($MsgEvent=='subscribe') {//订阅事件 

                    $arr[] = "欢迎归来!在这里我们一起见证 奇点妙思,思想从这里重新出发!服务从此刻起飞!"; 

                    echo $this->make_xml("text",$arr); 

                    exit; 

                }elseif ($MsgEvent=='CLICK') {//点击事件 

                    $EventKey = $postObj->EventKey;//菜单的自定义的key值,可以根据此值判断用户点击了什么内容,从而推送不同信息 

                    $arr[] = $EventKey; 

                    echo $this->make_xml("text",$arr); 

                    exit; 

                } 

            } 

            else if($MsgType=='text')

            {

                if(!empty( $this->keyword ))

                    {

                        $type = "text";

                        if($this->keyword=="1")

                            $arr[] = "进入网站-><a href='http://www.100home.net'>点我出发</a>";    

                        else if($this->keyword=="2")

                            $arr[] = "请在软件的登陆界面中的”查询“中查询!";    

                        else if($this->keyword=="3")

                        {

                            $arr[] ="请联系QQ 116327160 客服为你服务!";

                        }

                        else

                        {

                            $arr[] = $strWelcome;    

                        }

                        echo $this->make_xml("text",$arr);

                    }else{

                        echo "put someing!";

                    }

            }

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

        $dataSrc = $this->curl_get_contents($url);

        $data = json_decode($dataSrc,true); 

        if($data['access_token']){ 

        {

            return $data['access_token']; 

        }

        }else{ 

            return "获取access_token错误"; 

        } 

    } 

    /*比file_get_contents稳定的多!$timeout为超时时间,单位是秒,默认为1s。*/ 

    private function curl_get_contents($url,$timeout=1) { 

        $curlHandle = curl_init(); 

        curl_setopt( $curlHandle, CURLOPT_URL, $url ); 

        curl_setopt( $curlHandle, CURLOPT_SSL_VERIFYPEER, FALSE); 

        curl_setopt( $curlHandle, CURLOPT_SSL_VERIFYHOST, FALSE); 

        curl_setopt( $curlHandle, CURLOPT_RETURNTRANSFER, 1 ); 

        curl_setopt( $curlHandle, CURLOPT_TIMEOUT, $timeout ); 

        $result = curl_exec( $curlHandle ); 

        curl_close( $curlHandle ); 

        return $result; 

    } 



    /** 

     * 创建菜单 

     * @param $access_token 已获取的ACCESS_TOKEN 

     */ 

    public function createmenu($access_token) 

    { 

      //  $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;

        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;

       $jsonmenu = '{

              "button":[

              {

                    "name":"微生活",

                   "sub_button":[

                    {

                       "type":"view",

                       "name":"微社区",

                       "url":"http://m.wsq.qq.com/264524583"

                    },

                    {

                       "type":"view",

                       "name":"微游戏",

                       "url":"http://www.icallme.cn/callme/game.do?g=qidian_ms"

                    }

                    ]

         

         

               },

               {

                   "name":"精彩直达",

                   "sub_button":[

                    {

                       "type":"view",

                       "name":"往期回顾",

                       "url":"http://mp.weixin.qq.com/mp/getmasssendmsg?__biz=MzAxMDMzODUxMw==&scene=18#wechat_webview_type=1&wechat_redirect"

                    },

                    {

                       "type":"view",

                       "name":"天气详报",

                       "url":"http://m.wsq.qq.com/app?sId=264524583&appId=wsqa1591378601045"

                    }

                    ]

         

         

               },

               {

                   "name":"微店",

                   "type":"view",

                   "url":"http://weidian.com/?userid=254914516"

               }

               ]

         }';

         $result = $this->https_request($url,$jsonmenu);

        //var_dump($result);

    } 

    

    private function https_request($url,$data = null)

    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)){

            curl_setopt($curl, CURLOPT_POST, 1);

            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($curl);

        curl_close($curl);

        return $output;

    }

    /** 

     * 查询菜单 

     * @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() 

    { 

        if (!defined("TOKEN")) {

            throw new Exception('TOKEN is not defined!');

        }

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

        } 

    } 

} 

?>

 

这段代码正在使用,经过改良的,现共享给大家,希望对新手有些帮助,有不明白的加微信讨论!

研究微信公众平台开发模式下的菜单加消息处理

 

你可能感兴趣的:(微信公众平台)