-
Notifications
You must be signed in to change notification settings - Fork 0
/
wxapi.php
88 lines (70 loc) · 2.09 KB
/
wxapi.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
header('content-type:text/html;charset=utf-8');
define("TOKEN", "weixin"); //define your token
$wx = new wechatCallbackapiTest();
if($_GET['echostr']){
$wx->valid(); //如果发来了echostr则进行验证
}else{
$wx->responseMsg(); //如果没有echostr,则返回消息
}
class wechatCallbackapiTest{
public function valid(){ //valid signature , option
$echoStr = $_GET["echostr"];
if($this->checkSignature()){ //调用验证字段
echo $echoStr;
exit;
}
}
public function responseMsg(){
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信发来的XML数据
//extract post data
if(!empty($postStr)){
//解析post来的XML为一个对象$postObj
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName; //请求消息的用户
$toUsername = $postObj->ToUserName; //"我"的公众号id
$keyword = trim($postObj->Content); //消息内容
$time = time(); //时间戳
$msgtype = 'text'; //消息类型:文本
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
if($keyword == 'hehe'){
$contentStr = 'hello world!!!';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
echo $resultStr;
exit();
}else{
$contentStr = '输入hehe试试';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
echo $resultStr;
exit();
}
}else {
echo "";
exit;
}
}
//验证字段
private function checkSignature(){
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
?>