在微信公众号开发中,要经历一个自动回复消息的设置,在接口文件中,responseMsg()里是这样的
public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//extract post data<br />
//判断XML数据是否为空<br />
if (!empty($postStr)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,<br />
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
//通过simplexml进行xml解析<br />
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//手机端<br />
$fromUsername = $postObj->FromUserName;
//微信公众平台<br />
$toUsername = $postObj->ToUserName;
//接受用户发送的关键词<br />
$keyword = trim($postObj->Content);
//实践戳<br />
$time = time();
//文本发送模板<br />
$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>";
//判断XML数据是否为空 <br />
if(!empty( $keyword ))
{
//回复类型,如果是"text",代表文本类型<br />
$msgType = "text";
//回复内容<br />
$contentStr = "Welcome to wechat world!";
//格式化字符串<br />
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
//返回XML数据给手机端<br />
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
}
}
我这样设置好后,给测试号发消息时得不到回应,因为我用的是php7.0以上版本,所以,将
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 改为file_get_contents("php://input");即可
网友评论