微信_如何响应用户请求;

<img src="https://img-blog.csdn.net/20140531090044781?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTE2ODE1NA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

<?php
/*
* 第二十三小分队(23工作室)
* 感谢:方倍工作室;
* 
* CopyRight 2014-05-30 All Rights Reserved
*/

// 签名
define("TOKEN", "weixin");

$wechatObj = new wechatCallback();
// isset()检测变量是否设置;
if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}

/**
* wechatCallback类
*/
class wechatCallback
{
	// 验证
    public function valid()
    {
        $echoStr = $_GET["echostr"];	// 随机字符串;
		
        if($this->checkSignature()){	// 验证签名;
            echo $echoStr;
            exit;
        }
    }

	// 验证签名
    private function checkSignature()
    {
        $signature = $_GET["signature"];	// 微信加密签名,由token、timestamp、nonce参数加密而成;
        $timestamp = $_GET["timestamp"];	// 时间戳;
        $nonce = $_GET["nonce"];	// 随机数;
        $token = TOKEN;		//签名;
		
		// 加密签名
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);		// sort(),把值作为字符串来处理来排序数组;
        $tmpStr = implode($tmpArr);		// implode(),把数组元素组合为一个字符串;
        $tmpStr = sha1($tmpStr);		// sha1(),计算字符串的 SHA-1 散列,使用美国 Secure Hash 算法 1,如果成功,则返回所计算的 SHA-1 散列,如果失败,则返回 false;

        if($tmpStr == $signature){	//  加密签名对比;
            return true;
        }else{
            return false;
        }
    }

	// 响应信息
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];	// 包含有原始的 POST 数据;
		
        if (!empty($postStr)){	// 字符串是否为空;
            $this->logger("R ".$postStr);
			
			// simplexml_load_string(),从 XML 字符串获取 SimpleXMLElement 对象;LIBXML_NOCDATA设置为把 CDATA 设置为文本节点;
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);	
            $RX_TYPE = trim($postObj->MsgType);	// 消息类型;trim(),从字符串左侧删除空格或其他预定义字符;

            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 = "欢迎关注23工作室 ";
                break;
        }
        $result = $this->transmitText($object, $content);	// 组装XML文件;
        return $result;
    }


	// 文本处理
    private function receiveText($object)
    {
        $keyword = trim($object->Content);	// 信息内容;
		
		$url = "http://apix.sinaapp.com/weather/?appkey=".$object->ToUserName."&city=".urlencode($keyword); 	// 文件地址;包含json数组;
        $output = file_get_contents($url);	// file_get_contents()函数把整个文件读入一个字符串中;
		
        $content = json_decode($output, true);	// json_decode(), 解析中文;第二个参数为true时,返回数组;

        $result = $this->transmitNews($object, $content);	// 组装文件;
        return $result;
    }

	// 事件xml文件组装
    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>";
		// sprintf(),把格式化的字符串写写入一个变量中;
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

	// 文本xml文件组件
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){	// is_array(), 判断是否为数组;
            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)
    {
      
    }
}

/*

[{
    "Title": "深圳天气预报",
    "Description": "",
    "PicUrl": "",
    "Url": ""
}, {
    "Title": "【实况】温度30℃ 湿度76%% 西南风2级 发布时间:17:30",
    "Description": "",
    "PicUrl": "",
    "Url": ""
}, {
    "Title": "【炎热】天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。",
    "Description": "",
    "PicUrl": "",
    "Url": ""
}, {
    "Title": "05月31日 周六 多云 27℃   日出日落:05:38~19:03",
    "Description": "",
    "PicUrl": "http://discuz.comli.com/weixin/weather/icon/d01.jpg",
    "Url": ""
}, {
    "Title": "06月01日 周日 雷阵雨 27℃ 无持续风向 微风 日出日落:05:38~19:03",
    "Description": "",
    "PicUrl": "http://discuz.comli.com/weixin/weather/icon/d04.jpg",
    "Url": ""
}, {
    "Title": "06月02日 周一 阵雨 26℃ 无持续风向 微风 日出日落:05:38~19:04",
    "Description": "",
    "PicUrl": "http://discuz.comli.com/weixin/weather/icon/d03.jpg",
    "Url": ""
}]

*/


?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值