孙肖宁

微信公众号开发天气自动回复
当用户输入一个地名的时候,回复该地区的当前天气预报。使用的api接口为https://www.sojson.com...
扫描右侧二维码阅读全文
21
2018/06

微信公众号开发天气自动回复

当用户输入一个地名的时候,回复该地区的当前天气预报。使用的api接口为https://www.sojson.com/open/api/weather/json.shtml?city=北京返回的数据为json。自己提取相关的信息,为了方便演示,我只是回复了天气情况,有需要的可以自己添加相关的功能。
实例代码:

<?php
namespace Wx\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        //获得参数 signature nonce token timestamp echostr
        $nonce     = $_GET['nonce'];
        $token     = 'xxxx';
        $timestamp = $_GET['timestamp'];
        $echostr   = $_GET['echostr'];
        $signature = $_GET['signature'];
        //形成数组,然后按字典序排序
        $array = array();
        $array = array($nonce, $timestamp, $token);
        sort($array);
        //拼接成字符串,sha1加密 ,然后与signature进行校验
        $str = sha1( implode( $array ) );
        if( $str  == $signature && $echostr ){
            //第一次接入weixin api接口的时候
            echo  $echostr;
            exit;
        }else{
            $this->reponseMsg();
        }
    }
    public function reponseMsg(){
        //1.获取到微信推送过来post数据(xml格式)
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        //2.处理消息类型,并设置回复类型和内容
        $postObj = simplexml_load_string( $postArr );//xml转换成对象
        //判断是否是用户回复过来的消息
        //用户发送过来消息后回复图文消息或者是单文本消息
        if( strtolower($postObj->MsgType) == 'text' ){
            $toUser = $postObj->FromUserName;
            $fromUser = $postObj->ToUserName;
            $content = $this->weather($postObj->Content);
            $toUser   = $postObj->FromUserName;
            $fromUser = $postObj->ToUserName;
            $time     = time();
            $msgType  =  'text';
            $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
             $info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
             echo $info;
    }
}
     public function weather($city){
        //1.初始化curl
        $ch = curl_init();
        $url = 'https://www.sojson.com/open/api/weather/json.shtml?city='.$city;
        //2.设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //3.采集
        $output = curl_exec($ch);
        //4.关闭
        curl_close($ch);
        $wt = (array) json_decode($output,true);
        $wet = $wt["data"]["forecast"][0]["type"];
        return $wet;
    }
}
Last modification:June 21st, 2018 at 04:33 pm
If you think my article is useful to you, please feel free to appreciate

One comment

  1. 孙肖宁

    天气接口已经更新了,这个失效了

Leave a Comment