Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?php
class WechatAccess
{
private $token = TOKEN;
public function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$echostr = $_GET["echostr"];
// $token = TOKEN;
$tmpArr = array($this->token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if ($tmpStr == $signature) {
return $echostr;
} else {
return false;
}
}
}
class Message extends WechatAccess
{
function postText()
{
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$this->checkSignature();
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$xml = file_get_contents('php://input');
if (!empty($xml)) {
$postObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$time = time();
if ($postObj->MsgType == 'event') {
if ($postObj->Event == 'subscribe') {
$content = '你这么好看,关注我就对了';
$this->text($toUser, $fromUser, $time, $content);
}
} elseif ($postObj->MsgType == 'text' && preg_match('/\d/S', $postObj->Content)) {
$content = '您好,有什么需要帮助你的吗?';
$this->text($toUser, $fromUser, $time, $content);
} elseif ($postObj->MsgType == 'text' && preg_match('/^文章/', $postObj->Content)) {
$title = '叮!请查收『Dr.Yu开学护肤指南』· 文末正装礼';
$description = '新学期,玩点厉害的,宠粉开始...';
$picurl = 'https://img.zcool.cn/community/0114705c45d80ea801213f26f0c42c.gif';
$url = 'https://php.cn';
$this->ImgText($toUser, $fromUser, $time, $title, $description, $picurl, $url);
} elseif ($postObj->MsgType == 'text' && preg_match('/^aa/', $postObj->Content)) {
$title = '叮!请查收『Dr.Yu开学护肤指南』· 文末正装礼';
$description = '新学期,玩点厉害的,宠粉开始...';
$picurl = 'https://img.zcool.cn/community/0114705c45d80ea801213f26f0c42c.gif';
$url = 'https://php.cn';
$content = '随机';
$arr = array($this->ImgText($toUser, $fromUser, $time, $title, $description, $picurl, $url), $this->text($toUser, $fromUser, $time, $content));
array_rand($arr);
} elseif ($postObj->MsgType == 'image') {
}
}
}
}
private function text($toUser, $fromUser, $time, $content)
{
$str = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>
";
echo sprintf($str, $toUser, $fromUser, $time, $content);
}
private function ImgText($toUser, $fromUser, $time, $title, $description, $picurl, $url)
{
$str = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
</Articles>
</xml>
";
echo sprintf($str, $toUser, $fromUser, $time, $title, $description, $picurl, $url);
}
}