【微信开发】-发送位置线路规划Direction API v1.0, 主要代码在private function receiveLocation($object)

Direction API是一套以HTTP/HTTPS形式提供的公交、驾车、 骑行、步行查询检索接口,返回xml或json格式的检索数据,可用于实现开发线路规划功能。
该套API免费对外开放,您需先申请密钥(ak),未认证开发者默认支持2000次/天(http和https共享配额),若需更高配额,请申请开发者认证获取更高配额以及更优技术支持.
详见官网:http://lbsyun.baidu.com/index.php?title=webapi/direction-api


    header("Content-type: text/html; charset=utf-8");
    define("TOKEN","自填");
    define("APPID","自填");
    define("APPSECRET","自填");

    $wechatObj = new wechatCallbackapiTest();
    if(!isset($_GET["echostr"])){
        $wechatObj -> responseMsg();
    }else{
        $wechatObj ->valid();
    }

    class wechatCallbackapiTest{
        public function valid(){
            $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature(){
        if(!defined("TOKEN")){
            throw new Exception();
        }
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token,$timestamp,$nonce);
        sort($tmpArr,SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                case "shortvideo":
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type: ".$RX_TYPE;
                    break;
            }
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    private function receiveEvent($object)
    {
        include("locationinfoUpload.php");
        $resInsert = insertLocationinfo($object);
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注通州-羽我同行俱乐部!\n请回复以下关键字:文本 表情 单图文 多图文 音乐\n请按住说话 或 点击 + 再分别发送以下内容:语音 图片 小视频 我的收藏 位置";
                $content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
                $content .= "\n\n".'技术支持 大米';
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "78":
                        $content = array();
                        $content[] = array(

                     "Title"=>"天气在手,羽球无忧,输入“天气北京”", 

                     "Description"=>"天气在手,羽球无忧,羽我同行!

输入“天气北京”即可轻松查询,支持全国城市!", 

                     "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/iahAbv73KOLFiafyCbpibBD4Igiag9XLpAnvgcCkyGYtwLDBFktS3aywkmhR8GibEs4HrNoicok4zKIQGJJBqxk5knicQ/0?wx_fmt=jpeg", 

                     "Url" =>"http://mp.weixin.qq.com/s?__biz=MzI3NTQwODE3OQ==&mid=100000024&idx=1&sn=63d36f4d6258a2a7df7260cd37333b66#rd"

                  );
                        $content[] = array(

                     "Title"=>"特色功能:输入“附近餐饮”查询", 

                     "Description"=>"输入“附近餐饮”即可轻松查询附近周边!

需开启\"提供位置信息\"功能,点右上角图标查看", 

                     "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/iahAbv73KOLFiafyCbpibBD4Igiag9XLpAnvD1QwJOFibNWCETbiaz1cKzj5MXTrGpXTq6RsqDnuCIAfcycGomuOFcwg/0?wx_fmt=jpeg", 

                     "Url" =>"http://mp.weixin.qq.com/s?__biz=MzI3NTQwODE3OQ==&mid=100000024&idx=2&sn=d3021285753f96c6a199b3b0479d34f7#rd"

                  );
                        $content[] = array(

                     "Title"=>"特色功能:输入“附近超市”查询", 

                     "Description"=>"输入“附近超市”即可轻松查询附近周边!

需开启\"提供位置信息\"功能,点右上角图标查看", 

                     "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/iahAbv73KOLFiafyCbpibBD4Igiag9XLpAnvt3EmZTIg0nmeUYZAwwibJzSErNP1s8ib3Hruj0Aiarfx8oIGGtRfI1HCQ/0?wx_fmt=jpeg", 

                     "Url" =>"http://mp.weixin.qq.com/s?__biz=MzI3NTQwODE3OQ==&mid=100000024&idx=3&sn=07821ccb872e2f123d223b9373c29cdb#rd"

                  );
                        $content[] = array(

                     "Title"=>"特色功能:输入“附近药店”查询", 

                     "Description"=>"输入“附近药店”即可轻松查询附近周边!

需开启\"提供位置信息\"功能,点右上角图标查看", 

                     "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/iahAbv73KOLFiafyCbpibBD4Igiag9XLpAnvYmm520Picj7r7F8rUXicMrSoTUgDYHiaqYYicziaibrdO10CA8CoCTgpicnjQ/0?wx_fmt=jpeg", 

                     "Url" =>"http://mp.weixin.qq.com/s?__biz=MzI3NTQwODE3OQ==&mid=100000024&idx=4&sn=7c93ed6fd81ae0c7ffdb639964903f97#rd"

                  );
                        $content[] = array(

                     "Title"=>"特色功能:输入“附近”+“名称”", 

                     "Description"=>"输入“附近”+“名称”即可轻松查询附近周边!



需开启\"提供位置信息\"功能,点右上角图标查看", 

                     "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/iahAbv73KOLFiafyCbpibBD4Igiag9XLpAnvYe3tICkGPBBckzCSt9bwIXPYyZGicqdNLAh5TibYsVWpJecoT7LoNibNQ/0?wx_fmt=jpeg", 

                     "Url" =>"http://mp.weixin.qq.com/s?__biz=MzI3NTQwODE3OQ==&mid=100000024&idx=5&sn=08ea56fd170e2faefc0438b2a7ed7dac#rd"

                  );
                        break;
                        break;
                }
                break;
            case "VIEW":
                $content = "跳转链接 ".$object->EventKey;
                break;
            case "SCAN":
                $content = "扫描场景 ".$object->EventKey;
                break;
            case "LOCATION":
                $content = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                break;
            case "scancode_waitmsg":
                if ($object->ScanCodeInfo->ScanType == "qrcode"){
                    $content = "扫码带提示:类型 二维码 结果:".$object->ScanCodeInfo->ScanResult;
                }else if ($object->ScanCodeInfo->ScanType == "barcode"){
                    $codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
                    $codeValue = $codeinfo[1];
                    $content = "扫码带提示:类型 条形码 结果:".$codeValue;
                }else{
                    $content = "扫码带提示:类型 ".$object->ScanCodeInfo->ScanType." 结果:".$object->ScanCodeInfo->ScanResult;
                }
                break;
            case "scancode_push":
                $content = "扫码推事件";
                break;
            case "pic_sysphoto":
                $content = "系统拍照";
                break;
            case "pic_weixin":
                $content = "相册发图:数量 ".$object->SendPicsInfo->Count;
                break;
            case "pic_photo_or_album":
                $content = "拍照或者相册:数量 ".$object->SendPicsInfo->Count;
                break;
            case "location_select":
                $content = "发送位置:标签 ".$object->SendLocationInfo->Label;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        if(is_array($content)){
            $result = $this->transmitNews($object, $content);
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    private function receiveText($object)
    {
        $keyword = trim($object->Content);
        $findKeywordText = mb_substr($keyword,0,2,'UTF-8');
        if($findKeywordText == "天气"){
            $findKeyword = mb_substr($keyword,2,strlen($keyword),'UTF-8');
            $keyword = trim($object->Content);
            include("weather.php");  
            $content = getWeatherInfo($keyword); 
            $result = $this->transmitNews($object, $content);  
            return $result; 
        }//if 天气完
        if($findKeywordText == "位置"){
            $keyword = trim($object->Content);
            include("locationinfo.php");
            $content = getLocationInfo($keyword,$object);
            if(is_array($content)){
                $result = $this->transmitNews($object, $content);
            }else if(!is_array($content)){
                $result = $this->transmitText($object, $content);
            }
            return $result;
        }//if 位置完
        if($findKeywordText == "附近"){
            $keyword = trim($object->Content);
            include("nearbyinfo.php");
            $content = getNearbyInfo($keyword,$object);
            if(is_array($content)){
                $result = $this->transmitNews($object, $content);
            }else if(!is_array($content)){
                $result = $this->transmitText($object, $content);
            }
            return $result;
        }
        if (strstr($keyword, "请问在吗") || strstr($keyword, "在线客服")){
            $result = $this->transmitService($object);
            return $result;
        }
        if (strstr($keyword, "文本")){
            $content = "这是个文本消息";
        }else if (strstr($keyword, "表情")){
            $content = "微笑:/::)\n乒乓:/:oo\n中国:".$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://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
        }else if (strstr($keyword, "图文") || strstr($keyword, "多图文")){
            $content = array();
            $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
            $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
            $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
        }else if (strstr($keyword, "音乐")){
            $content = array();
            $content = array("Title"=>"最炫民族风", "Description"=>"歌手:凤凰传奇", "MusicUrl"=>"http://mascot-music.stor.sinaapp.com/zxmzf.mp3", "HQMusicUrl"=>"http://mascot-music.stor.sinaapp.com/zxmzf.mp3"); 
        }else{
            $content = '欢迎来到通州-羽我同行俱乐部!'."\n\n".'通州-羽我同行 官方网站'."\n\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 receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }

    private function receiveLocation($object)
    {   
        $lat = $object->Location_X;  //纬度
        $lng = $object->Location_Y;  //经度
        $q = "http://api.map.baidu.com/geoconv/v1/?coords={$lng},{$lat}&from=3&to=5&ak=YourBaiduKey";
        $resultQ = json_decode(file_get_contents($q));
        $content = array();
        $content[] = array("Title"=>"百度地图导航至健龙森羽毛球馆","Description"=>"","PicUtl"=>"","Url"=>"");
        $content[] = array("Title"=>"点击查看驾车线路导航","Description"=>"","PicUrl"=>"http://www.limikezhan.cn/weixin/1.jpg","Url"=>"http://api.map.baidu.com/direction?origin=".$resultQ->result[0]->y.",".$resultQ->result[0]->x."&destination=健龙森羽毛球馆&mode=driving®ion=北京&output=html");
        $content[] = array("Title"=>"点击查看公交线路导航","Description"=>"","PicUrl"=>"http://www.limikezhan.cn/weixin/2.jpg","Url"=>"http://api.map.baidu.com/direction?origin=".$resultQ->result[0]->y.",".$resultQ->result[0]->x."&destination=健龙森羽毛球馆&mode=transit®ion=北京&output=html");
        $content[] = array("Title"=>"点击查看步行线路导航","Description"=>"","PicUrl"=>"http://www.limikezhan.cn/weixin/3.jpg","Url"=>"http://api.map.baidu.com/direction?origin=".$resultQ->result[0]->y.",".$resultQ->result[0]->x."&destination=健龙森羽毛球馆&mode=walking®ion=北京&output=html");
        $result = $this->transmitNews($object, $content);
        return $result;
    }

    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)){
            $content = "你刚才说的是:".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }else{
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }
        return $result;
    }

    private function receiveVideo($object)
    {
        $content = "上传视频类型:".$object->MsgType;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function receiveLink($object)
    {
        $content = "你发送的是链接,标题为:".$object->Title.";内容为:".$object->Description.";链接地址为:".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }
        $xmlTpl = "

    

    

    %s

    

    

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

    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return "";
        }
        $itemTpl = "        

            <![CDATA[%s]]>

            

            

            

        

";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "

    

    

    %s

    

    %s

    

$item_str    

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

    private function transmitMusic($object, $musicArray)
    {
        if(!is_array($musicArray)){
            return "";
        }
        $itemTpl = "

        <![CDATA[%s]]>

        

        

        

    ";
        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
        $xmlTpl = "

    

    

    %s

    

    $item_str

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

    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "

        

    ";
        $item_str = sprintf($itemTpl, $imageArray['MediaId']);
        $xmlTpl = "

    

    

    %s

    

    $item_str

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

    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "

        

    ";
        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);
        $xmlTpl = "

    

    

    %s

    

    $item_str

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

    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "";
        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
        $xmlTpl = "

    

    

    %s

    

    $item_str

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

    private function transmitService($object)
    {
        $xmlTpl = "

    

    

    %s

    

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

    private function relayPart3($url, $rawData)
    {
        $headers = array("Content-Type: text/xml; charset=utf-8");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function bytes_to_emoji($cp)
    {
        if ($cp > 0x10000){       # 4 bytes
            return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x800){   # 3 bytes
            return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x80){    # 2 bytes
            return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else{                    # 1 byte
            return chr($cp);
        }
    }

}

?>

你可能感兴趣的:(微信开发)