补充: (之前只是解决了这个问题,但是不知道问题所在)
如下图所示,HTTP_RAW_POST_DATA
只支持php5.6以下,所以如果你的环境是php7只能使用file_get_contents
最近开始自己捣鼓微信公众号,在用测试号验证token时没有出错,但是发送消息后并没有接收到消息.
之后通过测试才知道是 , $GLOBALS['HTTP_RAW_POST_DATA']
无法获取到信息:
用 file_get_contents('test.text',$xml_str)
输出数据才有
$xml_str = $GLOBALS['HTTP_RAW_POST_DATA']; // 无法获取到数据
// 因为很多都设置了register_globals禁止,不能用$GLOBALS["HTTP_RAW_POST_DATA"];
$xml_str = file_get_contents('php://input'); //可以获取到数据
下面附 微信验证token并实现自动回复源代码:
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "junior");
traceHttp(); // 打印日志
$wechatObj = new wechatCallbackapiTest();
if(isset($_GET['echostr'])) {
$wechatObj->valid(); // 验证token
}else{
$wechatObj->responseMsg(); // 回复消息
}
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
public function responseMsg()
{
$postStr = file_get_contents('php://input');
// $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //无法获取到数据
// file_put_contents('test.txt',$postStr);
if (!empty($postStr)){
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$msgType = $postObj->MsgType;
$keyword = trim($postObj->Content);
$time = time();
$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>";
if($msgType == 'text') {
$msgType = "text";
$contentStr = date('Y-m-d H:i:s',time());
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something..";
}
}else {
echo "";
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;
}
}
}
function traceHttp() {
$content = date('Y-m-d H:i:s')."\nREMOTE_ADDR:".$_SERVER["REMOTE_ADDR"]."\nQUERY_STRING:".$_SERVER["QUERY_STRING"]."\n\n";
if (isset($_SERVER['HTTP_APPNAME'])){ //SAE
sae_set_display_errors(false);
sae_debug(trim($content));
sae_set_display_errors(true);
}else {
$max_size = 100000;
$log_filename = "log.xml";
if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
file_put_contents($log_filename, $content, FILE_APPEND);
}
}
?>