微信公众号开发实战:,天气预报

2025-10-10 06:44:32

1、一、准备工作

      登录微信公众平台,检查服务器配置是否已启用,URL(服务器地址) 是否已配置Token(令牌),与自己写的微信入口文件中的Token(令牌一致),如下图:然后点击提交,只至网页上提示绿色背景的提交成功信息,则完成本步骤的操作

微信公众号开发实战:,天气预报

微信公众号开发实战:,天气预报

微信公众号开发实战:,天气预报

2、二、微信天气预报数据源准备

      用已注册好的百度帐号,登录百度LBS云平台,添加一个应用,获取访问应用AK,及了解车联API V3.0,天气查询功能相应的接口说明文件,以按需调用需要的天气信息.

微信公众号开发实战:,天气预报

3、三、微信公众平台,接口文件编写 jiekou.php

<?php

/*

    无忧电脑技巧网 微信公众号功能源码

    CopyRight 2015 All Rights Reserved

*/

define("TOKEN", "weixin2015");

$wechatObj = new wechatCallbackapiTest();

if (!isset($_GET['echostr'])) {

    $wechatObj->responseMsg();

}else{

    $wechatObj->valid();

}

class wechatCallbackapiTest

{

    //验证签名

    public function valid()

    {

        $echoStr = $_GET["echostr"];

        $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){

            echo $echoStr;

            exit;

        }

    }

    public function responseMsg()

    {

       // $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        $postStr = file_get_contents("php://input");

  if (!empty($postStr)){

            $this->logger("R ".$postStr);

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            $RX_TYPE = trim($postObj->MsgType);

   $result = "";

            switch ($RX_TYPE)

            {

                case "event":

                    $result = $this->receiveEvent($postObj);

                    break;

                case "text":

                    $result = $this->receiveText($postObj);

                    break;

            }

            $this->logger("T ".$result);

            echo $result;

        }else {

            echo "";

            exit;

        }

    }

    private function receiveEvent($object)

    {

        switch ($object->Event)

        {

            case "subscribe":

                $content = "欢迎关注无忧电脑技巧网 ";

                break;

        }

        $result = $this->transmitText($object, $content);

        return $result;

    }

    private function receiveText($object)

    {

     $keyword = trim($object->Content);  //获得用户输入的信息

    //判断天气

    if(!empty( $keyword )){ //!empty 函数,判断 $keyword获得的值是否为空

     $city = mb_substr($keyword, 0, 2, 'utf-8'); //取用户输入内容前两个字符,如"黄冈天气" 最终取值"黄冈"

        include("weather.php"); //调用天气接口文件

        $content = getWeatherInfo($city); //执行天气接口文件中的 getWeatherInfo方法.查询 黄冈天气.

    } else{

        $content = date("Y-m-d H:i:s",time())."\n技术支持 无忧电脑技巧网\nwww.51pcjq.com"; //发送其它内容默认回复的内容.

    }

    if(is_array($content)){

        if (isset($content[0]['PicUrl'])){

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

  }

        $textTpl = "<xml>

<ToUserName><![CDATA[%s]]></ToUserName>

<FromUserName><![CDATA[%s]]></FromUserName>

<CreateTime>%s</CreateTime>

<MsgType><![CDATA[text]]></MsgType>

<Content><![CDATA[%s]]></Content>

</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);

        return $result;

    }

    private function transmitNews($object, $newsArray)

    {

        if(!is_array($newsArray)){

            return "";

        }

        $itemTpl = "    <item>

        <Title><![CDATA[%s]]></Title>

        <Description><![CDATA[%s]]></Description>

        <PicUrl><![CDATA[%s]]></PicUrl>

        <Url><![CDATA[%s]]></Url>

    </item>

";

        $item_str = "";

        foreach ($newsArray as $item){

            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

        }

        $newsTpl = "<xml>

<ToUserName><![CDATA[%s]]></ToUserName>

<FromUserName><![CDATA[%s]]></FromUserName>

<CreateTime>%s</CreateTime>

<MsgType><![CDATA[news]]></MsgType>

<Content><![CDATA[]]></Content>

<ArticleCount>%s</ArticleCount>

<Articles>

$item_str</Articles>

</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));

        return $result;

    }

    private function logger($log_content)

    {

     

    }

}

?>

微信公众号开发实战:,天气预报

4、四、使用百度车联API V3.0接口,及访问应用AK码,编号微信天气接口源码:

weatger.php

<?php

function getWeatherInfo($cityName){    if ($cityName == "" || (strstr($cityName, "+"))){        return "发送天气+城市,例如'天气深圳'";    }//用户查询天气,回复关键词 规则    $url = "http://api.map.baidu.com/telematics/v3/weather?location=".urlencode($cityName)."&output=json&ak=自已申请的百度车联API AK代码";//构建通过百度车联API V3.0查询天气url链接    $ch = curl_init();//初始化会话 curl_setopt($ch, CURLOPT_URL, $url);//设置会话参数 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置会话参数 $output = curl_exec($ch);//执行curl会话    curl_close($ch);//关闭curl会话    $result = json_decode($output, true);//函数json_decode() 的功能时将json数据格式转换为数组。

    if ($result["error"] != 0){        return $result["status"];    }    $curHour = (int)date('H',time());    $weather = $result["results"][0];//按照微信公众号开发文档,组建设多图文回复信息    $weatherArray[] = array("Title" => $weather['currentCity']."当前天气:"."温度:".$weather['weather_data'][0]['temperature'].",".$weather['weather_data'][0]['weather'].","."风力:".$weather['weather_data'][0]['wind'].".", "Description" =>"", "PicUrl" =>"http://weixin.51pcjq.com/img/weather_bg.jpg", "Url" =>"");    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;}?>

微信公众号开发实战:,天气预报

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢