<?php
$testObj = new Test();
if(!empty($_GET['echostr'])){
$testObj->valid();
}else{
$testObj->responseMsg();
}
exit;
class Test
{
/**
* 绑定url、token信息
*/
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 = "test123";//与在微信配置的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(){
//验证签名
if ($this->checkSignature()){
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
$this->log_request_info();
//提取post数据
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;//发送人
$toUsername = $postObj->ToUserName;//接收人
$MsgType = $postObj->MsgType;//消息类型
$MsgId = $postObj->MsgId;//消息id
$time = time();//当前时间做为回复时间
//如果是文本消息(表情属于文本信息)
if($MsgType == 'text'){
$content = trim($postObj->Content);//消息内容
if(!empty( $content )){
//如果文本内容是图文,则回复图文信息,否则回复文本信息
if($content == "图文"){
//回复图文消息,ArticleCount图文消息个数,多条图文消息信息,默认第一个item为大图
$ArticleCount = 2;
$newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
</Articles>
</xml>";
$resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, 'news',
$ArticleCount,'我是图文信息','我是描述信息','http://www.test.com/DocCenterService/image?photo_id=236',
'http://www.test.com','爱城市网正式开通上线','描述2','http://jn.test.com/ac/skins/img/upload/img/20131116/48171384568991509.png',
'http://www.test.com');
echo $resultStr;
$this->log($resultStr);
}else{
//回复文本信息
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
$contentStr = '你发送的信息是:接收人:'.$toUsername.',发送人:'.$fromUsername.',消息类型:'.$