<?php
1
2 /**
3 * wechat php test
4 */
5
6 //define your token
7 define("TOKEN", "weixin");
8 $wechatObj = new wechatCallbackapiTest();
9 $wechatObj->valid();
10 $wechatObj->responseMsg();
11 class wechatCallbackapiTest
12 {
13 public function valid()
14 {
15 $echoStr = $_GET["echostr"];
16
17 //valid signature , option
18 if($this->checkSignature()){
19 echo $echoStr;
20 exit;
21 }
22 }
23
24 public function responseMsg()
25 {
26 //get post data, May be due to the different environments
27 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
28
29 //extract post data
30 if (!empty($postStr)){
31
32 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
33 $fromUsername = $postObj->FromUserName;
34 $toUsername = $postObj->ToUserName;
35 $keyword = trim($postObj->Content);
36 $id=$postObj->MsgId;
37 $type=$postObj->MsgType;
38 $time = time();
39 $conn=mysql_connect("localhost","root","111111");
40 $db=mysql_select_db("weixin");
41 mysql_query("set names utf8");
42 if($type=="text"){
43 $sql="insert into weixin SET id='$id',touser='$toUsername',fromuser='$fromUsername',content='$keyword',createtime='$time'";
44 mysql_query($sql);
45 }
46 $textTpl = "<xml>
47 <ToUserName><![CDATA[%s]]></ToUserName>
48 <FromUserName><![CDATA[%s]]></FromUserName>
49 <CreateTime>%s</CreateTime>
50 <MsgType><![CDATA[%s]]></MsgType>
51 <Content><![CDATA[%s]]></Content>
52 <FuncFlag>0</FuncFlag>
53 </xml>";
54 if(!empty( $keyword ))
55 {
56 $msgType = "text";
57 if($keyword==1){
58 $contentStr = "one";
59 }elseif($keyword==2){
60 $contentStr = "two";
61 }else{
62 $contentStr = "welcome to wechat world";
63 }
64 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
65 echo $resultStr;
66 }else{
67 echo "Input something...";
68 }
69
70 if($type=="event"){
71 $event=$postObj->Event;
72 if($event=="subscribe"){
73 $msgType = "text";
74 $contentStr = "welcome";
75 $resultStr = sprintf($textTpl, $toUsername, $fromUsername, $time, $msgType, $contentStr);
76 echo $resultStr;
77 }
78 }
79 }else {
80 echo "";
81 exit;
82 }
83 }
84
85 private function checkSignature()
86 {
87 $signature = $_GET["signature"];
88 $timestamp = $_GET["timestamp"];
89 $nonce = $_GET["nonce"];
90
91 $token = TOKEN;
92 $tmpArr = array($token, $timestamp, $nonce);
93 sort($tmpArr);
94 $tmpStr = implode( $tmpArr );
95 $tmpStr = sha1( $tmpStr );
96
97 if( $tmpStr == $signature ){
98 return true;
99 }else{
100 return false;
101 }
102 }
103 }
104
105
106
?>