1 <?php
2 define("TOKEN", "woZiDingYiDe987"); // 这里改成你自己的Token,是自定义的,不过要和微信公众号后台的对应起来
3 $wechatObj = new wechatCallbackapiTest();
4 if ($_GET['echostr']) {
5 // 验证
6 $wechatObj->valid();
7 } else {
8 // 自动恢复消息
9 $wechatObj->responseMsg();
10 }
11
12 class wechatCallbackapiTest
13 {
14 public function valid()
15 {
16 $echoStr = $_GET["echostr"];
17 if ($this->checkSignature()) {
18 echo $echoStr;
19 exit;
20 }
21 }
22
23 public function responseMsg()
24 {
25 $postStr = file_get_contents('php://input'); // 接收XML数据
26 if (!empty($postStr)) {
27 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
28 $fromUsername = $postObj->FromUserName; // 用户open_id
29 $toUsername = $postObj->ToUserName; // 开发者的微信账号
30 $keyword = trim($postObj->Content);
31 $time = time();
32 $textTpl = "<xml>
33 <ToUserName><![CDATA[%s]]></ToUserName>
34 <FromUserName><![CDATA[%s]]></FromUserName>
35 <CreateTime>%s</CreateTime>
36 <MsgType><![CDATA[%s]]></MsgType>
37 <Content><![CDATA[%s]]></Content>
38 <FuncFlag>0</FuncFlag>
39 </xml>";
40 if (!empty($keyword)) {
41 $msgType = "text";
42 $contentStr = "你好,欢迎来到WEB学习";
43 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
44 echo $resultStr;
45 } else {
46 echo "";
47 }
48 } else {
49 echo "";
50 exit;
51 }
52 }
53
54 private function checkSignature()
55 {
56 $signature = $_GET["signature"];
57 $timestamp = $_GET["timestamp"];
58 $nonce = $_GET["nonce"];
59
60 $token = TOKEN;
61 $tmpArr = array($token, $timestamp, $nonce);
62 sort($tmpArr);
63 $tmpStr = implode($tmpArr);
64 $tmpStr = sha1($tmpStr);
65
66 if ($tmpStr == $signature) {
67 return true;
68 } else {
69 return false;
70 }
71 }
72 }