cleargo 2017-04-16 12:26:07 3741次浏览 0条回复 1 3 0
<?php

//define your token
define("TOKEN", "WEIXINGONGZHONG");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $wechatObj->responseMsg();
}

//if($_GET['action'] == 'weixin'){
//    $wechatObj = new wechatCallbackapiTest();
//    $wechatObj->responseText();
//}


class wechatCallbackapiTest{

    public function valid()
    {
        $echoStr = $_GET["echostr"];
 
        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);


            switch($RX_TYPE)
            {
                case "text":
//                    $resultStr = $this->handleText($postObj);
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "event":
                   $resultStr = $this->handleEvent($postObj);
//                    $resultStr = $this->receiveEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }
    

    //接收文本消息
     private function receiveText($object)
     {
         $keyword = trim($object->Content);
          
         //多客服人工回复模式
        if (strstr($keyword, "请问在吗") || strstr($keyword, "在线客服")){
             $result = $this->transmitService($object);
            return $result;
        }

         //自动回复模式
         if (strstr($keyword, "文本")){
             $content = "这是个文本消息";
         }else if (strstr($keyword, "表情")){
             $content = "中国:".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌:".$this->bytes_to_emoji(0x1F335);
         }else if (strstr($keyword, "领红包")){
            $content = array();
             $content[] = array("Title"=>"带鱼舞台:发红包啦!",  "Description"=>"点击进入,查看红包领取规则...", "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/8IeMKicicK2JzcicOe3hLunyaXGMyyCQibWXJCVf3x7e0I6F7ZLqoiaiayOmZxeechMZ1I0pOluSTKoo4zibTpOnwdYtQ/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1", "Url" =>"http://mp.weixin.qq.com/s/h5X2I-kCX2CtxbtJaWHkLw");
         }else if(strstr($keyword, "天气")){
            $city = str_replace('天气','',$keyword);    
            $content = $this->getWeatherInfo($city);  
            
         }else if (strstr($keyword, "历史消息") || strstr($keyword, "历史")){
//                $content[] = array(
//                    "Title"=>"哎呦我去,带鱼舞台派发现金红包咯",
//                    "Description"=>"点击进入,查看现金红包.....",
//                    'picUrl' =>'http://mmbiz.qpic.cn/mmbiz_jpg/8IeMKicicK2JzcicOe3hLunyaXGMyyCQibWXJCVf3x7e0I6F7ZLqoiaiayOmZxeechMZ1I0pOluSTKoo4zibTpOnwdYtQ/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1',
//                    'url' =>'http://mp.weixin.qq.com/s?biz=MzI2MjU3MjIzNQ==&tempkey=navMAp52gp%2FZlBF7IKZ3WimqPylBX%2FS5D3NNk9B2NF%2BtKEgem8aVjGSUNIGFL2BmahB6xDAKRNftUiVWPQ4MmWtqjQOrb7abFh0ASGmAHMSMV8w6tu4AOhLd9vstMkGBmwsnWevRxxqEGsJUN6GZtg%3D%3D&chksm=6a4850b65d3fd9a082e2e36b01e88df7cb849a8f0393cd113787b20b05c92cd538deb0eef88a#wechat_redirect'
//                );

                $content[] = array(
                    "Title"=>"带鱼舞台:同道大叔喊你来看舞台剧啦!",
                    "Description"=>"大叔喊你快到碗里来.....",
                    "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/8IeMKicicK2JywcEHH5gicia8z5yeholo3zZw4telmuqpAWPu3t9K7T0htI7qTCCJoGiazAP1USzKExhsL8a6PBKhdw/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1",
                    "Url" =>"http://mp.weixin.qq.com/s/h5X2I-kCX2CtxbtJaWHkLw"
                );
                $content[] = array(
                    "Title"=>"带鱼舞台,休闲娱乐新平台!",
                    "Description"=>"娱乐由此进入.....-",
                    "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_png/8IeMKicicK2JwqmGnib8FnyTEEU0NX4NicDOBJaoBGLggshqKO0murNyxKTyuUibHicfoI6JB2h5CM5tYtggLB7rGhDQ/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1",
                    "Url" =>"http://mp.weixin.qq.com/s/hCYpuBdve3YUlBrsh-ZlOg"
                );
                }else if (strstr($keyword, "音乐")){
             $content = array();
             $content = array("Title"=>"最炫民族风", "Description"=>"歌手:凤凰传奇", "MusicUrl"=>"http://play.baidu.com/?m=mboxCtrl.playSong&a=353261&o=song/353261", "HQMusicUrl"=>"http://play.baidu.com/?m=mboxCtrl.playSong&a=353261&o=song/353261");
        }else{
             $content = date("Y-m-d H:i:s",time())."\n感谢关注 【带鱼舞台】";
        }

         if(is_array($content)){
             if (isset($content[0])){
                 $result = $this->transmitNews($object, $content);
             }else if (isset($content['MusicUrl'])){
                 $result = $this->transmitMusic($object, $content);
             }
         }else{
             $result = $this->transmitText($object, $content);
         }
         return $result;
     }
     
     
     
     
     //回复文本消息
     private function transmitText($object, $content)
     {
         if (!isset($content) || empty($content)){
             return "";
        }
         $xmlTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
         $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);

         return $result;
     }
    

    public function handleEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":
                $contentStr=array();
                $contentStr[] = array(
                    "Title"=>"带鱼舞台:发红包啦!",
                    "Description"=>"点击进入,快快领取红包....",
                    "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_png/8IeMKicicK2JxmHJUz3B4kdbodYr1qpmSDZzD9GXFbOvIMbwsQN931r0qVej6tTgrRIQHCpXQTBVHhOkiaXvuPH4w/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1",
                    "Url" =>"http://mp.weixin.qq.com/s/EQ9faD7l3gYAay7FhIBmfg"
                );
                break;
            case "LOCATION":
            $contentStr = '';
            break;
            default :
                $contentStr = "Unknow Event: ".$object->Event;
                break;
        }
        
        if(is_array($contentStr)){
            if (isset($contentStr[0])){
                $resultStr = $this->transmitNews($object, $contentStr);
            }else if (isset($content['MusicUrl'])){
                $resultStr = $this->transmitMusic($object, $contentStr);
            }
        }else{
            $resultStr = $this->responseText($object, $contentStr);
        }

        return $resultStr;
    }
    
    
    //单图文消息消息
    public function _response_news(){
        $newsTplHead = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[news]]></MsgType>
                        <ArticleCount>1</ArticleCount>
                        <Articles>";
        $newsTplBody = "<item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>";
       $newsTplFoot = "</Articles>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
       $header = sprintf($newsTplHead, $object->FromUserName, $object->ToUserName, time());
       $title = $newsContent['title'];
        $desc = $newsContent['description'];
        $picUrl = $newsContent['picUrl'];
        $url = $newsContent['url'];
        $body = sprintf($newsTplBody, $title, $desc, $picUrl, $url);
        $FuncFlag = 0;
        $footer = sprintf($newsTplFoot, $FuncFlag);
        return $header.$body.$footer;
    }
    
    //回复音乐消息
     private function transmitMusic($object, $musicArray)
     {
         if(!is_array($musicArray)){
         }
         $itemTpl = "<Music>
                    <Title><![CDATA[%s]]></Title>
                    <Description><![CDATA[%s]]></Description>
                    <MusicUrl><![CDATA[%s]]></MusicUrl>
                    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                    </Music>";
        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $xmlTpl = "<xml>
                   <ToUserName><![CDATA[%s]]></ToUserName>
                   <FromUserName><![CDATA[%s]]></FromUserName>
                   <CreateTime>%s</CreateTime>
                   <MsgType><![CDATA[music]]></MsgType>
                   $item_str
                   </xml>";

         $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
         return $result;
     }

    public function _response_multiNews($object,$content){
        $newsTplHead = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[news]]></MsgType>
                        <ArticleCount>1</ArticleCount>
                        <Articles>";
        $newsTplBody = "<item>
                        <Title><![CDATA[%s]]></Title>
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>";
        $newsTplFoot = "</Articles>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
        $header = sprintf($newsTplHead, $object->FromUserName, $object->ToUserName, time());
        $bodyCount = count($content);
        $bodyCount = $bodyCount < 10 ? $bodyCount : 10;
        $body = "";
        foreach($content as $key => $value){
            $body.= sprintf($newsTplBody, $value['title'], $value['description'], $value['picUrl'], $value['url']);
        }
        $FuncFlag = 0;
        $footer = sprintf($newsTplFoot, $FuncFlag);
        return $header.$body.$footer;
    }
    
    


    public function https_request($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}
        curl_close($curl);
        return $data;
    }



    public function sign($param){
        $authkey = '82a21fabc58aa9da';
        ksort($param);
        $paramstring = "";
        foreach($param as $key => $value)
        {
            if(strlen($paramstring) == 0)
                $paramstring .= $key . "=" . $value;
            else
                $paramstring .= "&" . $key . "=" . $value;
        }

        $paramstring.='&'.$authkey;
        $datastr = sha1($paramstring);
        $datastr = base64_encode($datastr);
        return $datastr;
    }

    public function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        $result = curl_errno($oCurl);
        // var_dump($result);
        $result = curl_error($oCurl);
        // var_dump($result);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    public function http_post($url,$param,$post_file=false){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            echo $aStatus["http_code"];exit;
            return false;
        }
    }

    // 根据Openid获取单个用户信息,如nickname
     public function getInfo($access_token,$openid){
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $output = $this->https_request($url);
        $jsoninfo = json_decode($output);
         return $jsoninfo;

    }

    /**
     *  作用:array转xml
     */
    public  function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            /*if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else*/
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    /**
     *  作用:将xml转为array
     */
    public function xmlToArray($xml)
    {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    public function responseText($object, $content, $flag=0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        $result = $this->xmlToArray($resultStr);
       $result = var_export($result,true);

        $openid= $object->FromUserName;
//        echo file_put_contents('/data/website/html5/test.log',"{$openid}");
        $appid = "wx36ef7b87e2a41836";
        $appsecret = "501cafc41778f3c5272778123643dce0";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $jsoninfo = json_decode($output, true);
        $access_token = $jsoninfo["access_token"];
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $output = $this->https_request($url);
        $jsoninfos = json_decode($output,true);
        $resultinfo = $this->arrayToXml($jsoninfos);
        $postObj = simplexml_load_string($resultinfo, 'SimpleXMLElement', LIBXML_NOCDATA);
        $unionid = trim($postObj->unionid);
        $openids = trim($postObj->openid);
        
        $GLOBALS['temp'] = 'http://app.daiyutv.com';

        //获取系统时间
        $result = $this->http_get($GLOBALS['temp'].'/index.php?r=api/time/index');
        $timeobj = json_decode($result,true);
        $timespan = $timeobj['data'] - time();

        
        $url = $GLOBALS['temp'].'/index.php?r=api/wechatcallback/index';
        
        $param['unionid'] = $unionid;
        $param['openid'] = $openids;
        $param['lat'] = trim($object->Latitude);
        $param['lng'] = trim($object->Longitude);

        $param['_timestamp'] = time() + $timespan;
        $param['_signature'] = $this->sign($param);
        $temp = json_encode($param);


        //提交接口地址,传参数值取数据
        $result = $this->http_post($url,$temp,true);
        print_r($result);


       return $resultStr;
    }
    
     //获取城市天气信息  
    private function getWeatherInfo($cityName){  
        if($cityName == "" || (strstr($cityName,"+"))){  
            return "发送城市加天气,例如上海天气";  
        }  
        //获取到的ak  
        $ak = 'wx36ef7b87e2a41836';  
        //获取到的sk  
        $sk = '501cafc41778f3c5272778123643dce0';  
        //调用接口  
        $url = 'http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sk=%s';  
        $uri = '/telematics/v3/weather';  
  
        $location = $cityName;  
        $output = 'json';  
        $querystring_arrays = array(  
            'ak' => $ak,  
            'location' => $location,  
            'output' => $output  
        );  
  
        $querystring = http_build_query($querystring_arrays);  
       //生成sn  
        $sn = md5(urlencode($uri.'?'.$querystring.$sk));  
        $targetUrl = sprintf($url,$ak,urlencode($location),$output,$sn);  
  
        $ch = curl_init();  
        curl_setopt($ch,CURLOPT_URL,$targetUrl);  
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  
        $result = curl_exec($ch);  
        curl_close($ch);  
        $result = json_decode($result,true);  
  
        if($result["error"]!=0){  
            return $result["status"];  
        }  
  
        $curHour = (int)date('H',time());  
        $weather = $result["results"][0];  
        $weatherArray[]=array("Title"=>$weather['currentCity']."天气预报","Description"=>"","PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/8IeMKicicK2JySxFiaW8NLaOrdq82vgbia4zbiaXzzZJHianJt7FWic5zmx9AZKygIskEtuEbSn60yY2Tbialy6UvEEAHA/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1","Url"=>"http://www.weather.com.cn/weather1d/101020100.shtml#input");  
        for($i = 0;$i<count($weather["weather_data"]);$i++){  
            $weatherArray[] = array("Title"=>  
                $weather["weather_data"][$i]["date"]."\n".  
                $weather["weather_data"][$i]["weather"].  
                $weather["weather_data"][$i]["wind"].  
                $weather["weather_data"][$i]["temperature"],  
                "Description"=>"",  
                "PicUrl"=>(($curHour>=6)&&($curHour<  
                18))?$weather["weather_data"][$i]["dayPictureUrl"]:$weather["weather_data"][$i]["nightPictureUrl"],"URL"=>""  
            );  
        }  
        return $weatherArray;  
    }  
 
         
    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;
        }
    }
}


?>
觉得很赞
    没有找到数据。
您需要登录后才可以回复。登录 | 立即注册