Home Backend Development PHP Tutorial PHP implements WeChat real-time weather query

PHP implements WeChat real-time weather query

Mar 14, 2018 am 09:08 AM
php Weather query real time

When we develop WeChat applications such as WeChat public accounts, we all hope that the more functions the better, so today we will talk about how to implement WeChat weather query with PHP. It is actually not too complicated. You only need to call Baidu. The weather interface is enough. Without further ado, let’s take a look!

The effect we want to achieve is as shown in the figure below. When you enter the weather of a certain place such as "Shenzhen Weather" in WeChat, the following page will appear:

PHP implements WeChat real-time weather query##ps :
Let me state here that the backend server I use is Sina sae server. I won’t introduce too much here.

The first page code

This One page of code is mainly used for token verification and responding to WeChat user requests through the backend server. The code on this page is relatively simple and will not be introduced.

<?php
header("content-Type:text;charset=utf8;")
define("TOKEN", "weixin");

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

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

    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;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $this->logger("R ".$postStr);
            $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            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)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注,查询天气,发送天气加城市名,如“深圳天气”";
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }
  //str_replace(str1,str2,str3)用str3包含str1,用str2取代str1.
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
        if (strstr($keyword, "天气")){
            $city = str_replace(&#39;天气&#39;, &#39;&#39;, $keyword);//这里用空格取代$keyword中的天气二字。
            include("weather2.php");
            $content = getWeatherInfo($city);
        //判断笑话
        }
        $result = $this->transmitNews($object, $content);
        return $result;
    }


    private function transmitText($object, $content)
    {
        $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, $arr_item)
    {
        if(!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item[&#39;Title&#39;], $item[&#39;Description&#39;], $item[&#39;PicUrl&#39;], $item[&#39;Url&#39;]);

        $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($arr_item));
        return $result;
    }

    private function transmitMusic($object, $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[&#39;Title&#39;], $musicArray[&#39;Description&#39;], $musicArray[&#39;MusicUrl&#39;], $musicArray[&#39;HQMusicUrl&#39;]);

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

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    //这里主要用于在服务器端生成日志
    private function logger($log_content)
    {
        if(isset($_SERVER[&#39;HTTP_BAE_ENV_APPID&#39;])){   //BAE
            require_once "BaeLog.class.php";
            $logger = BaeLog::getInstance();
            $logger ->logDebug($log_content);
        }else if(isset($_SERVER[&#39;HTTP_APPNAME&#39;])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER[&#39;REMOTE_ADDR&#39;] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date(&#39;H:i:s&#39;)." ".$log_content."\r\n", FILE_APPEND);
        }
    }
}


?>
Copy after login

The second page of code

This page of code is mainly about the process of calling Baidu weather interface and their data transmission method.

1. If we want to call Baidu's weather interface, we need to register on the Baidu Map Open Platform, and then create an application to obtain the ak and sk of the application.

PHP implements WeChat real-time weather queryAfter obtaining ak (i.e. access key), click Settings, the page is as follows:

PHP implements WeChat real-time weather querySelect the sn verification method where the verification method is requested, it will automatically The sk code (ie Security Key) below appears.

For the specific role of sk and the sn calculation algorithm, please refer to the following article

http://lbsyun.baidu.com/index.php?title=lbscloud/api/appendix

<?php

// var_dump(getWeatherInfo("桃江"));
getWeatherInfo("深圳");
function getWeatherInfo($cityName)
{
    if ($cityName == "" || (strstr($cityName, "+"))){
        return "发送天气加城市,例如&#39;天气深圳&#39;";
    }

    $ak = &#39;Plev804CmHUMwPXVcehCcB14Ths0zuat&#39;;//从百度地图开发平台获取的ak
    $sk = &#39;Iv3vSPCd2jnIlMlCrCgywGSkP9PaXiDC&#39;;//从百度地图开发平台获取的sk

//向百度地图开发平台请其数据的url如http://api.map.baidu.com/geocoder/v2/?address=百度大厦&output=json&ak=yourak**&sn=7de5a22212ffaa9e326444c75a58f9a0。包含4个参数,address(查询地址),output(请求数据的恢复格式)、ak(验证密钥)、sn是经过加密后的数据。

    $url = &#39;http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sn=%s&#39;;
    $uri = &#39;/telematics/v3/weather&#39;;
    $location = $cityName;
    $output = &#39;json&#39;;
    $querystring_arrays = array(
        &#39;ak&#39; => $ak,
        &#39;location&#39; => $location,
        &#39;output&#39; => $output
    );
    $querystring = http_build_query($querystring_arrays);//使用关联数组生成一个urlencode请求字符串。格式如下:ak=Plev804CmHUMwPXVcehCcB14Ths0zuat&location=深圳&output=json;
   // var_dump($querystring);
//urlencode()   url中的一些特殊字符和中文字符可能不被服务器所识别,需要经过urlencode()编码才能被识别。
    $sn = md5(urlencode($uri.&#39;?&#39;.$querystring.$sk));//md5()对url中的数据进行加密。
    $targetUrl = sprintf($url, $ak, urlencode($location), $output, $sn);
    // var_dump($targetUrl);

//curl用于与接口服务器建立会话获取 接口传递过来的数据。
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $targetUrl);//与接口简历会话
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//获取的数据存储在一个变量上,而不是直接输出。如果为o或false则直接输出。
    $result = curl_exec($ch);//执行会话,获取数据。
    echo $result;//字符串格式加数个json格式的数据类型
    curl_close($ch);
    $result = json_decode($result, true);//参数带true返回一个数组
    echo "</br>";
     echo "</br>";
      echo "</br>";
       echo "</br>";

        echo "</br>";
         echo "</br>";
          echo "</br>";
           echo "</br>";
    var_dump($result);
    if ($result["error"] != 0){
        return $result["status"];
    }
    $curHour = (int)date(&#39;H&#39;,time());
     echo "</br>";
         echo "</br>";
          echo "</br>";
           echo "</br>";
    echo $curHour;
    $weather = $result["results"][0];
    $weatherArray[] = array("Title" =>$weather[&#39;currentCity&#39;]."天气预报", "Description" =>"", "PicUrl" =>"", "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;
}


?>
Copy after login
The above is all the content of this article. Please take a good look at it. This article may be a bit difficult for students who have just started to contact WeChat development!


Related recommendations:

PHP WeChat development to obtain city weather

The above is the detailed content of PHP implements WeChat real-time weather query. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles