微信开发后台接收和发送代码

class Wechat
{
public function __construct(){
// $this->checkSignature();
}

private function checkSignature()
{
$signature = $_GET["signature"]; // 加密签名 微信服务器
$timestamp = $_GET["timestamp"]; // 时间戳
$nonce = $_GET["nonce"]; // 随机数
$echostr = $_GET['echostr'];

$token = 'zhangxuhui';
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );

if( $tmpStr == $signature ){
echo $echostr;
}else{
return false;
}
}
// http://www.zhangxuhui.com/nav/index.php/index/Wechat/index
public function index(){
// $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];// 7-
// 接收微信服务器给我推送的数据
// $data = file_get_contents("php://input"); // 接收全局的数据 全部接收 7+
// 如何把xml 格式的字符串 解码成数组,对象 才可以使用

// file_put_contents("data.txt",$data);
// 1.获取xml字符串
/* $str = '<xml><ToUserName><![CDATA[gh_e95afa2c958c]]></ToUserName>
<FromUserName><![CDATA[odZTlt4EJkrO71qjQWigtvs6V3p0]]></FromUserName>
<CreateTime>1641437127</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[好]]></Content>
<MsgId>23499729696798541</MsgId>
</xml>';*/
$str = file_get_contents("php://input");
// 2.解码 严格区分大小写
$obj = simplexml_load_string($str ,'SimpleXMLElement', LIBXML_NOCDATA);
$toUserName = $obj->ToUserName; // 微信公众号id
$FromUserName = $obj->FromUserName; // 个人的id
$MsgType = $obj->MsgType; // 数据类型
$Content = $obj->Content; // 内容
$CreateTime = time();
// 被动回复消息
$receiveStr = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>
';
$content1 = "你说:".$Content;
echo sprintf($receiveStr,$FromUserName,$toUserName,$CreateTime,$MsgType,$content1); // 回复给用户的消息

}
}
posted @ 2022-01-06 11:30  秃头小少年  阅读(146)  评论(0)    收藏  举报