微信開發(fā)時, 如何進行服務(wù)器驗證及接收回復(fù)信息呢? 分享原生PHP代碼如下:
if(isset($_GET["echostr"])){
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
//驗證時會傳遞這個信息
$echostr = $_GET["echostr"];
$token = "zhuangzi";
$array = array($token, $timestamp, $nonce);
//放到一個數(shù)組里
sort($array, SORT_STRING);
// 將三人參數(shù)進行字典排序
$str = implode($array);
// 將三個參數(shù)拼接成一個字符串
$str = sha1($str);
// 進行 sha1加密
if($signature == $str){
echo $echostr;
exit();
}
else{
return false;
}
}
else{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//解析post來的XML為一個對象$postObj
$postObj = simplexml_load_string($postStr,
'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
//請求消息的用戶
$toUsername = $postObj->ToUserName;
//"我"的公眾號id
$content = trim($postObj->Content);
//消息內(nèi)容
$MsgType = trim($postObj->MsgType);
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
if($MsgType == "text"){
$ret = file_put_contents("1.txt", $content);
//發(fā)送消息到 微信 begin
$contentStr = $content;
$time = time();
$resultStr = sprintf($textTpl, $fromUsername,
$toUsername, $time, $MsgType, $contentStr);
echo $resultStr;
//發(fā)送消息到 微信 end
}
elseif($MsgType == "image"){
$picurl = trim($postObj->PicUrl);
$file = file_get_contents($picurl);
$path = time().".jpg";
$ret = file_put_contents($path, $file);
}
}
微信接收及回復(fù)信息
