第四节 微信调用天气接口

一.注册

免费接口地址:
1.百度apistore(注册后手机验证不通过,估计是服务器挂掉了)
2.聚合数据

二.思路

1.客户向微信服务器发送[位置].

2.微信服务器发送xml格式的数据到服务器上

3.服务器接收xml格式的数据,

并获取客户发过来的经度和纬度.

4.调用天气接口

①传递AppKey到类中,实例化对象.
②把经度和纬度传递到类的方法中,返回天气信息的array数组

5.把array数组,拆分,拼接字符串,加入到

微信规定的xml格式中.

6.发送给微信服务器,微信服务器发送给用户.

<?php 
//调用接口的凭证
define("AppKey","a26ba150973de0279c0b5930a6d60662");
//接收地理位置消息 并返回天气情况
private function receiveLocation($obj)
{
    //把经纬度转换成字符串
    $LocationArr=array(
        'Location_X'   => strval($obj->Location_X),
        'Location_Y'   => strval($obj->Location_Y),
        'FromUserName' => strval($obj->FromUserName),
        'ToUserName'   => strval($obj->ToUserName),
        );

    //调用天气接口
    return $this->replyLocation($LocationArr);

}

//调用天气接口,回复天气情况
private function replyLocation($LocationArr){
    $weather = new weather(AppKey);
    $arr=$weather->getWeatherByGeo($LocationArr['Location_Y'],$LocationArr['Location_X']);
    if($arr['error_code'] == 0){
        $data = $arr['result'];
        $content  ="当前城市:     ".$data['today']['city']."\r\n";
        $content .= "\r\n";
        $content .= "=====当前天气实况=====\r\n";
        $content .= "温度:    ".$data['sk']['temp']."\r\n";
        $content .= "风向:    ".$data['sk']['wind_direction']."    (".$data['sk']['wind_strength'].")"."\r\n";
        $content .= "湿度:    ".$data['sk']['humidity']."\r\n";
        $content .= "\r\n";
        $content .= "====未来几天天气预报====\r\n";
        foreach($data['future'] as $wkey =>$f){
            $content .= "日期:   ".$f['date']."    ".$f['week']."\r\n"."    ".$f['weather']."     ".$f['temperature']."\r\n";
        }
        $content .= "\r\n";

        $content .= "======相关天气指数======\r\n";
        $content .= "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."\r\n";
        $content .= "紫外线强度:".$data['today']['uv_index']."\r\n";
        $content .= "舒适指数:".$data['today']['comfort_index']."\r\n";
        $content .= "洗车指数:".$data['today']['wash_index'];   
        //echo $content;die;
        }else{
            $content = $arr['error_code'].":".$arr['reason'];
        }
        $replyXml = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        //返回一个进行xml数据包

        $resultStr = sprintf($replyXml,$LocationArr['FromUserName'],$LocationArr['ToUserName'],time(),$content);
        return $resultStr;     
}

//----------------------------------
// 聚合数据天气预报接口请求类
//----------------------------------
class weather{
    private $appkey = false; //申请的聚合天气预报APPKEY

    private $cityUrl = 'http://v.juhe.cn/weather/citys'; //城市列表API URL

    private $weatherUrl = 'http://v.juhe.cn/weather/index'; //根据城市请求天气API URL

    private $weatherIPUrl = 'http://v.juhe.cn/weather/ip'; //根据IP地址请求天气API URL

    private $weatherGeoUrl = 'http://v.juhe.cn/weather/geo'; //根据GPS坐标获取天气API URL

    private $forecast3hUrl = 'http://v.juhe.cn/weather/forecast3h'; //获取城市天气3小时预报API URL

    public function __construct($appkey){
        $this->appkey = $appkey;
    }

    /**
     * 获取天气预报支持城市列表
     * @return array
     */
    public function getCitys(){
        $params = 'key='.$this->appkey;
        $content = $this->juhecurl($this->cityUrl,$params);
        return $this->_returnArray($content);
    }

    /**
     * 根据城市名称/ID获取详细天气预报
     * @param string $city [城市名称/ID]
     * @return array
     */
    public function getWeather($city){
        $paramsArray = array(
            'key'   => $this->appkey,
            'cityname'  => $city,
            'format'    => 2
        );
        $params = http_build_query($paramsArray);
        $content = $this->juhecurl($this->weatherUrl,$params);
        return $this->_returnArray($content);
    }

    /**
     * 根据IP地址获取当地天气预报
     * @param string $ip [IP地址]
     * @return array
     */
    public function getWeatherByIP($ip){
         $paramsArray = array(
            'key'   => $this->appkey,
            'ip'  => $ip,
            'format'    => 2
        );
        $params = http_build_query($paramsArray);
        $content = $this->juhecurl($this->weatherIPUrl,$params);
        return $this->_returnArray($content);
    }

    /**
     * 根据GPS坐标获取当地的天气预报
     * @param  string $lon [经度]
     * @param  string $lat [纬度]
     * @return array
     */
    public function getWeatherByGeo($lon,$lat){
        $paramsArray = array(
            'key'   => $this->appkey,
            'lon'  => $lon,
            'lat'   => $lat,
            'format'    => 2
        );
        $params = http_build_query($paramsArray);
        $content = $this->juhecurl($this->weatherGeoUrl,$params);
        return $this->_returnArray($content);
    }

    /**
     * 获取城市三小时预报
     * @param  string $city [城市名称]
     * @return array
     */
    public function getForecast($city){
        $paramsArray = array(
            'key'   => $this->appkey,
            'cityname'  => $city,
            'format'    => 2
        );
        $params = http_build_query($paramsArray);
        $content = $this->juhecurl($this->forecast3hUrl,$params);
        return $this->_returnArray($content);
    }

    /**
     * 将JSON内容转为数据,并返回
     * @param string $content [内容]
     * @return array
     */
    public function _returnArray($content){
        return json_decode($content,true);
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }

}

 ?>

这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值