微信公众平台天气查询,火车票查询,快递查询,小黄鸡,翻译,公交查询的实现

widuu 2013-7-6 PHP技术 12,366 63 喜欢 (0)

这个是我早期做的一个东西基本功能都实现加载到一个文件里边了,所以代码本身比较臃肿,本人虽然已经重写了代码,但是代码还在另外的完善,打算完善更多的功能和开发一个系统,所以现在先放出这个单文件,下边是代码大家看看!

<?php
/**
  * wechat php test
  */
include("ABClient.php");  //爱帮网申请 然后下载的sdk
define("FANAPK", "API key");  //这个百度应用duapp.com创建一个应用获得的 API key
define("WAPK","key"); //这个key地址http://lbsyun.baidu.com/apiconsole/key?application=key来获取
//define your token
define("TOKEN", "这里写你自己的token");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
    private $model;
    private $name;
     public function __construct(){
        $this->model = new ABClient();
        $a = $this->model->test_transfer();
        $this->name = include("name.php");
    } 
    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);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $type = $postObj->MsgType;
                $event = $postObj->Event;
                $c = $postObj->Location_X;
                $d = $postObj->Location_Y;
                $keyword = trim($postObj->Content);
                $time = time();
                $msgid = $postObj->MsgId;
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";             
                if($type == "event" && $event == "subscribe")
                {
                    $msgType = "text";
                    $contentStr.= "欢迎关注微度网络,该公众平台有以下几种功能:\n\n";
                    $contentStr.= "1.直接输入汉字或者中文进行中英文翻译,如“你好”\n";
                    $contentStr.= "2.输入“天气+地区”进行天气查询,如“天气+石家庄”\n";
                    $contentStr.= "3.输入“城市+起点+终点”进行公交查询,如“石家庄+火车站+宫家庄”\n";
                    $contentStr.= "4.输入“@任何内容”跟小贱鸡聊天,如“@小贱鸡”\n";
                    $contentStr.= "5.微信发送您的地理位置进行天气查询,您可以试一试\n";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;

                }else if($type == "text"){
                    $keywords = explode("+",$keyword);
                    $b = explode("@",$keyword);
                    if(isset($b[1])){
                        $contentStr = $this->simsim($b[1]);
                        $msgType = "text";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                        exit();
                    }
                    if($keywords[0]=="火车"){
                        $city = $keywords[1];
                        $end = $keywords[2];
                        $time = $keywords[3];
                        $result = $this->doget($city,$end,$time);
                        if(!empty($result)){
                            $result = strip_tags($result['datas']);
                            $return_str = str_replace("&nbsp;","",$result);
                            $return_str = str_replace("\\n","",$return_str);
                            $a = explode(",",$return_str);
                            $name =array();
                            $c = array_chunk($a,16);
                            array_pop($c);
                            foreach($c as $k =>$v){
                                $str="余票:\n商务座:".$v[5].",特等座:".$v[6].",一等座:".$v[7].",二等座:".$v[8].",高级软卧:".$v[9].",软卧:".$v[10].",硬卧:".$v[11].",软座:".$v[12].",硬座:".$v[13].",无座:".$v[14].",其他:".$v[15];
                                $str = preg_replace("/硬座\:--,/","",$str);
                                $str = preg_replace("/商务座\:--,/","",$str);
                                $str = preg_replace("/特等座\:--,/","",$str);
                                $str = preg_replace("/一等座\:--,/","",$str);
                                $str = preg_replace("/二等座\:--,/","",$str);
                                $str = preg_replace("/高级软卧\:--,/","",$str);
                                $str = preg_replace("/软卧\:--,/","",$str);
                                $str = preg_replace("/硬卧\:--,/","",$str);
                                $str = preg_replace("/软座\:--,/","",$str);
                                $str = preg_replace("/硬座\:--,/","",$str);
                                $str = preg_replace("/其他\:--/","",$str);
                                $contentStr.="车次:{$v[1]},发站:{$v[2]},到站:{$v[3]},历时:{$v[4]}。\n{$str}\n\n";
                                if($k == 12){
                                    break;
                                }
                            }
                        }else{
                            $contentStr.="抱歉没有查到";
                        }

                        $msgType = "text";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                        exit();
                    }
                    if(isset($keywords[1])&&!isset($keywords[2])){
                        if($this->pexpress(trim($keywords[0]))){
                            $a = $this->express(trim($keywords[0]),trim($keywords[1]));
                            if($a["message"]=="ok"){
                                if($a['ischeck']==1){
                                    $contentStr.="您的包裹已经签收\n\n";
                                }else{
                                    $contentStr.="您的包裹还未签收\n\n";
                                }
                                $data = $a['data'];
                                foreach($data as $k =>$v){
                                    $contentStr.="更新时间:{$v["time"]}\n物流状态:{$v["context"]}\n\n";
                                }
                            }else{
                                    $contentStr = "查询失败,请输入正确后查询";
                            }
                                $msgType = "text";
                                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                                echo $resultStr;
                        }else{
                                $weather = $this->weather($keywords[1]);
                                if(!empty($weather))
                                {
                                    $data = $this->json2array($weather);
                                    foreach($data as $k =>$v)
                                    {
                                        $str.=$v['date'].'。天气:'.$v['weather'].'。风速:'.$v['wind'].'。温度:'.$v['temperature']."\n\n";
                                    }
                                }else{
                                    $str="请您输入正确的地址,输入方式如天气+北京";
                                }

                                $msgType = "text";
                                $contentStr = $str;
                                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                                echo $resultStr;
                        }

                    }else if(isset($keywords[2])&&($keywords[0]!=="火车")){
                        $city = $keywords[0];
                        $start = $keywords[1];
                        $end =$keywords[2];
                        $a = $this->model->test_transfer($city,$start,$end);
                        if(!empty($a)){
                             foreach($a as $k=>$v){
                                $contentStr.= "线路{$c}:".$v['dist']."米。估计耗费时间:{$v['time']}分钟。\n乘车线路:{$v['segments']["segment"][0]["line_name"]}。\n上车地点:{$v['segments']["segment"][0]["start_stat"]}。\n下车地点:{$v['segments']["segment"][0]["end_stat"]}。\n经过路线:{$v['segments']["segment"][0]["stats"]}\n\n";
                                if($k == 4){
                                    break;
                                }
                            }

                        }else{
                            $contentStr="抱歉没有查询到";
                        }

                        $msgType = "text";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                    }else{
                        $fanyi = $this->fanyi($keyword);
                        $msgType = "text";
                        $contentStr = $fanyi;
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                    }

                }else if($type == 'location'){
                    $result = $this->address($c,$d);
                    if(isset($result['district'])){
                        $weather = $this->weather($result['district']);
                        if(!$weather){
                            $weather = $this->weather($result['city']);
                        }
                    }else{
                        $weather = $this->weather($result['city']);
                    }

                    $data = $this->json2array($weather);
                    foreach($data as $k =>$v){
                        $str.=$v['date'].'。天气:'.$v['weather'].'。风速:'.$v['wind'].'。温度:'.$v['temperature']."\n\n";
                    }
                    $msgType = "text";
                    $contentStr = $str;
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }else{
                    echo "您可以输入点什么";
                }

        }else {
            echo "";
            exit;
        }
    }
    //获取地理位置的
    private function address($addx,$addy)
    {
        $arr = array();
        $result = $this->map_text("http://api.map.baidu.com/geocoder/v2/?ak=".WAPK."&callback=renderReverse&location={$addx},{$addy}&output=xml&pois=0");
        $data = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
        $result = $this->json2array($data);
        $arr = $result["result"]["addressComponent"];
        $address = $result['result']['formatted_address'];
        array_push($arr,$address);
        return $arr;
    }
    //解析json为数组
    private function json2array($json) {
            if ($json) {
                foreach ((array)$json as $k=>$v) {
                    $data[$k] = !is_string($v) ? $this->json2array($v) : $v;
                }
                return $data;
            }
        }    
    //获取天气信息
    private function weather($data)
    {
        //根据API调用输出数据
        $url="http://api.map.baidu.com/telematics/v2/weather?location={$data}&output=json&ak=".WAPK;
        $weather=$this->map_text($url);
        $data = json_decode($weather);
        return $data->results;
    }
    //调用翻译的api
    private function fanyi($data)
    {
        //根据API调用输出数据
        $url="http://openapi.baidu.com/public/2.0/bmt/translate?client_id=".FANAPK."&q={$data}&from=auto&to=auto";
        $fanyi=$this->map_text($url);
        $shuju=json_decode($fanyi);
        $result=$shuju->trans_result;
        return $result[0]->dst;
    }
    //解析地址的api
    private function map_text($url)  
    {
        if(!function_exists('file_get_contents')) {
        $file_contents = file_get_contents($url);
            } else {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt ($ch, CURLOPT_URL, $url);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $file_contents = curl_exec($ch);
            curl_close($ch);
        }
            return $file_contents;
    }
    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;
        }
    }
    private function simsim($keywords){
        $curlPost=array("txt"=>$keywords);
        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,'http://xiaohuangji.com/ajax.aspx');//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }
    private function pexpress($exname){
            $a = $this->map_text("http://www.kuaidi100.com/");
            preg_match_all("/data\-code\=\"(?P<name>\w+)\"\>\<span\>(?P<title>.*)\<\/span>/iU",$a,$b);
            $name = array();
            foreach($b['title'] as $k=>$v){
                 $name[$v] = $b['name'][$k];
            }
            if(!empty($name[$exname])){
                return true;
            }else{
                return false;
            }
    }
    private function express($keywords,$number){
            $a = $this->map_text("http://www.kuaidi100.com/");
            preg_match_all("/data\-code\=\"(?P<name>\w+)\"\>\<span\>(?P<title>.*)\<\/span>/iU",$a,$b);
            $name = array();
            foreach($b['title'] as $k=>$v){
                 $name[$v] = $b['name'][$k];
            }
            $this->name = $name;
            $keywords = $name[$keywords];
            $url = "http://www.kuaidi100.com/query?type={$keywords}&postid={$number}";
            $result = $this->map_text($url);
            $result = $this->json2array(json_decode($result));
            return $result;
    }

    private function doget ($start,$end,$time) // get获取数据使用
    {
        if(empty($time)){
            $time = date('Y-m-d',time());
        }else{
            if(substr($time,0,1)!=0){
                $time = date('Y-0',time()).$time;
            }else{
                $time = date('Y-',time()).$time;
            }
        }
        $star = $this->name[$start];
        $end = $this->name[$end];
        $url = "http://dynamic.12306.cn/otsquery/query/queryRemanentTicketAction.do?method=queryLeftTicket&orderRequest.train_date={$time}&orderRequest.from_station_telecode={$star}&orderRequest.to_station_telecode={$end}&orderRequest.train_no=&trainPassType=QB&trainClass=QB%23D%23Z%23T%23K%23QT%23&includeStudent=00&seatTypeAndNum=&orderRequest.start_time_str=00%3A00--24%3A00";
        $optionget = array('http' => array('method' => "GET", 'header' => "User-Agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.0.04506; CIBA)\r\nAccept:*/*\r\nReferer:http://dynamic.12306.cn/otsquery/query/queryRemanentTicketAction.do?method=init")); 
        $file = file_get_contents($url, false , stream_context_create($optionget));
        return $this->json2array(json_decode($file));
    }

}

?>

有人说跟爱帮网的报错,我把我的代码公布一下有一小点点改变

<?php

//爱帮的http请求类,用于和服务器通信
class ABHttp {
    const ENCRYPT_URLENCODE = 0;
    const ENCRYPT_MULTIPART = 1;
    const METHOD_GET = 0;
    const METHOD_POST = 1;

    /**
     * 发送get请求
     * @param string $url 请求url
     * @param array $params 请求附带的参数数组
     * @return array $ret 结构:array($code, $arr), $code为http_code的值,$arr为返回的数组对象
     */
    public static function get($url, $params = array()) {
        if ($params) {
            if (strpos($url, "?") !== false) {
                $url .= "&".self::encodeParams($params);
            } else {
                $url .= "?".self::encodeParams($params);
            }
        }
        list($code, $ret) = self::curl(self::METHOD_GET, $url);
        $arr = json_decode($ret, true);
        return array($code, $arr);
    }

    /**
     * 发送post请求
     * @param string $url 请求url
     * @param array $params 请求附带的参数数组
     * @param int $encrypt 普通的post请求或者是multipart/form-data(主要用于上传二进制数据,比如图片)
     * @return array $ret array($code, $arr), $code为http_code的值,$arr为返回的数组对象
     */
    public static function post($url, $params = array(), $encrypt = self::ENCRYPT_URLENCODE) {
        $fields = $params;
        if ($encrypt == self::ENCRYPT_URLENCODE) {
            $fields = self::encodeParams($params);
        }
        list($code, $ret) = self::curl(self::METHOD_POST, $url, $fields);
        $arr = json_decode($ret, true);
        return array($code, $arr);
    }

    //对array进行urlencode
    private static function encodeParams($params) {
        if (!$params) {
            return "";
        }
        $arr = array();
        foreach ($params as $k => $v) {
            $arr[] =urlencode($k)."=".urlencode($v);
        }
        return implode("&", $arr);
    }

    /**
     * 调用curl获取实际的post或者get请求
     * @param int $method 请求方法,get/post
     * @param string $url 请求url
     * @param mixed $fields 如果是post并且Content-Type是multipart/form-data,则为array, 否则为urlencode编码后的字符串(和curl保持一致); get请求时为空
     */
    private static function curl($method, $url, $fields = NULL) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($method == self::METHOD_POST && $fields) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        }
        $ret = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        return array($info['http_code'], $ret);
    }
}


/***
 * 客户端调用接口类
 * 调用方式说明:
 * $appKey = "xxxxxxxx";
 * $client = new ABClient($appKey);
 * list($httpCode, $arr) = $client->methd(...)
 * 结果说明:
 * $httpCode: http状态码:200,400,401,404,500
 * $arr: 返回的数据,php数组格式,对于非200的状态码,该数组的message字段包含错误消息;对于200的状态码,则返回标准格式的结果
 * 注意:关于调用方法相关参数,请参考文档说明,方法只是列出了必要参数。
 */
class ABClient {
    const SERVER_ADDR = "http://openapi.aibang.com";
    const ALT = "json"; //输出参数,固定为json
    private $appKey = "6ffb46b36acf68edd7fd7056cadfbeab"; //申请的爱帮key

    public function __construct() {

    }

    //发送get请求
    private function get($url, $params=false) {
        $params['app_key'] = $this->appKey;
        $params['alt'] = self::ALT;
        return ABHttp::get($url, $params);
    }

    //发送post请求
    private function post($url, $params) {
        $params['app_key'] = $this->appKey;
        $params['alt'] = self::ALT;
        return ABHttp::post($url, $params);
    }

    //发送multipart/form-data格式的post请求
    private function postMP($url, $params) {
        $params['app_key'] = $this->appKey;
        $params['alt'] = self::ALT;
        return ABHttp::post($url, $params, ABHttp::ENCRYPT_MULTIPART);
    }

    /**
     * 搜索接口
     * @param string $city 城市
     * @param array $params 附加查询参数
     * @return array $ret
     */
    public function search($city, $params) {
        $url = self::SERVER_ADDR."/search";
        $params['city'] = $city;
        return $this->get($url, $params);
    }

    /**
     * 地址定位接口
     * @param string $city 城市
     * @param string $addr 地址
     * @return array $ret
     */
    public function getLocation($city, $addr) {
        $url = self::SERVER_ADDR."/locate";
        $params['city'] = $city;
        $params['addr'] = $addr;
        return $this->get($url, $params);
    }
    /**
     * 公交换乘查询接口
     * @param string $city 城市
     * @param array $params 附加查询参数
     * @return array $ret
     */
    public function getBusTransfer($city, $params) {
        $url = self::SERVER_ADDR."/bus/transfer";
        $params['city'] = $city;
        return $this->get($url, $params);
    }

    /**
     * 公交线路查询接口
     * @param string $city 城市
     * @param string $q 线路名称
     * @param int $withXY 是否包含坐标经纬度
     * @return array $ret
     */
    public function getBusLines($city, $q, $withXY=0) {
        $url = self::SERVER_ADDR."/bus/lines";
        $params['city'] = $city;
        $params['q'] = $q;
        $params['with_xys'] = $withXY;
        return $this->get($url, $params);
    }

    /**
     * 公交站点查询接口
     * @param string $city 城市
     * @param string $q 站点名称
     * @return array $ret
     */
    public function getBusStats($city, $q) {
        $url = self::SERVER_ADDR."/bus/stats";
        $params['city'] = $city;
        $params['q'] = $q;
        return $this->get($url, $params);
    }

    /**
     * 周边公交站点查询接口
     * @param string $city 城市
     * @param string $lng 地点经度
     * @param string $lat 地点纬度
     * @param int $dist 限制距离
     * @return array $ret
     */
    public function getBusStatsXY($city, $lng, $lat, $dist) {
        $url = self::SERVER_ADDR."/bus/stats_xy";
        $params['city'] = $city;
        $params['lng'] = $lng;
        $params['lat'] = $lat;
        $params['dist'] = $dist;
        return $this->get($url, $params);
    }
    public function test_transfer($city,$start,$end) {
        $result = list($code, $arr) = $this->getBusTransfer($city, array("start_addr" => $start, "end_addr" => $end));
        return $result[1]['buses']["bus"];
    }
}

//$a = $new ->test_transfer();


?>

上边这些大家开发的时候可以模拟使用,用我前边文章提到的postXML微信助手这个类做本地的模拟测试,或者服务器测试!下边是我的微信的二维码大家可以扫一扫试试功能!
微信二维码

转载请注明来自微度网络,本文标题:《微信公众平台天气查询,火车票查询,快递查询,小黄鸡,翻译,公交查询的实现》

喜欢 0 发布评论
Top