<?php
//第三方服务器与微信服务器进行消息接入,
// https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
// 接收微信服务器发送的四个验证参数
//加密签名
$signature = $_GET["signature"];
//时间戳
$timestamp = $_GET["timestamp"];
//随机数
$nonce = $_GET["nonce"];
//随机字符串
$echostr = $_GET["echostr"];
// TOKEN
define('TOKEN','weixin');
//1.进行字典序排序
$tmpArr = array(TOKEN, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
//2.将三个参数字符串拼接成一个字符串进行sha1加密
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
//3.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
if( $tmpStr == $signature ){
echo "$echostr";
}else{
return false;
}
//服务器接收微信POST发送的xml格式原生数据
// $postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
$postStr = file_get_contents("php://input");
if (!$postStr) {
echo "post data error";
exit;
}
//将xml格式转对象形式输出 LIBXML_NOCDATA - 将 CDATA 设置为文本节点
$postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
//判断消息类型 被动回复消息 严格来说,发送被动响应消息其实并不是一种接口,而是对微信服务器发过来消息的一次回复。
$MsgType = $postObj->MsgType;
switch ($MsgType) {
case 'text':
$Content = $postObj->Content;
switch ($Content) {
case 'binbin':
$xml = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%d</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>';
echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time(),'binbin is girl');
break;
default:
$xml = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%d</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>';
echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time(),$postObj->Content);
break;
}
default:
}
接收微信服务器发送的消息与被动回复消息
最新推荐文章于 2023-04-27 20:20:43 发布