微信开发时, 如何进行服务器验证及接收回复信息呢? 分享原生PHP代码如下:
作者:互联网
if(isset($_GET["echostr"])){
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
//验证时会传递这个信息
$echostr = $_GET["echostr"];
$token = "zhuangzi";
$array = array($token, $timestamp, $nonce);
//放到一个数组里
sort($array, SORT_STRING);
// 将三人参数进行字典排序
$str = implode($array);
// 将三个参数拼接成一个字符串
$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);
//消息内容
$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);
//发送消息到 微信 begin
$contentStr = $content;
$time = time();
$resultStr = sprintf($textTpl, $fromUsername,
$toUsername, $time, $MsgType, $contentStr);
echo $resultStr;
//发送消息到 微信 end
}
elseif($MsgType == "image"){
$picurl = trim($postObj->PicUrl);
$file = file_get_contents($picurl);
$path = time().".jpg";
$ret = file_put_contents($path, $file);
}
}
标签:原生,GET,微信,echostr,MsgType,file,服务器,postObj,array 来源: https://blog.csdn.net/qq_49947317/article/details/122023607