/**
* wechat php test
*/
//define your token
define("TOKEN", "chuliabc");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();
//$wechatObj->valid();
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
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"];
//extract post data
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$event = $postObj->Event;
$textTpl = "
%s
0
";
switch ($postObj->MsgType) {
case 'event':
if ($event == 'subscribe') {
$cOntentStr= "welcome 每学网 菜单如下 \r\n\r\n 输入 新闻 返回新闻条目";
$msgType = 'text';
//把格式化的数据写入某个字符串
$textTpl = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$contentStr);
echo $textTpl;
}
break;
case 'text':
if ($keyword=='新闻') {
//链接数据库
$con = mysql_connect('localhost','a0401140227','64326237');
mysql_select_db('a0401140227',$con);
mysql_query('SET NAMES UTF8');
$sql = "SELECT title,description,pic,url FROM weixin LIMIT 0,10";
//踩过坑 desc用不了
$result = mysql_query($sql);
$newsHeader = "
%s
%s
";
$newsCOntent="-
";
$newsFooter="
";
$itemCount = 0;
while ($row = mysql_fetch_assoc($result)){
$contentStr .=sprintf($newsContent,$row['title'],$row['desc'],$row['pic'],$row['url']);
++$itemCount;
}
$newsHeader = sprintf($newsHeader,$fromUsername,$toUsername,$time,$itemCount);
$newsTpl = $newsHeader.$contentStr.$newsFooter;
echo $newsTpl;
// $result = sprintf($newsTpl, $fromUsername, $toUsername, $time, $title1,$des1,$pic1,$url1,$title2,$des2,$pic2,$url2);
// echo $result;
}
break;
default:
break;
}
//file_put_contents('abcd.text', $row.'======'.$event.'==='.$toUsername.'==='.$keyword,FILE_APPEND);
//如果用户输入不为空
// if(!empty( $keyword ))
// {
//
$msgType = "text";
// if($keyword == 'OK'){
// $cOntentStr= "Hello 每学网!!!";
// }else{
// //返回的内容是"Welcome to wechat world!"
// //$cOntentStr= "Welcome to wechat world!";
// preg_match('/(\d+)([+-])(\d+)/i', $keyword,$res);
// if($res[2] == '+'){
// $a = $res[1] + $res[3];
// }else if($res[2] == '-'){
// $a = $res[1] - $res[3];
// }else if($res[2] == '*'){
// $a = $res[1] * $res[3];
// }else{
// $a = $res[1] / $res[3];
// }
// $cOntentStr= "Welcome to wechat world!".$a;
// }
// //填充模版
//
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
//
echo $resultStr;
// }else{
//
echo "Input something...";
// }
}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;
}
}
}
?>