作为一个php新手,更是第一次开发公众号,为了给女票一些便利,闲暇时间能有得玩,便想做一个专属的公众号,刚开始用的python 奈何,坑太多..上手太慢了,还是转战世界上最好的语言PHP(不要打脸),爬了N朵代码,终于成功,废话不多说,直接上代码.
<pre>
<?php
//token 自己定义
define("TOKEN", "shuiyun");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
if (isset($_GET['echostr'])) {
$wechatObj -> valid();
} else {
$wechatObj -> responseMsg();
}
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
header('content-type:text');
echo $echoStr;
exit;
}
}
public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)){
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
if(!empty( $keyword ))
{
$msgType = "text";
if($keyword=="功能"){
$contentStr = "查询快递123456789\n讲个笑话\n讲个故事\n成语接龙一诺千金\n北京天气\n今天北京到上海的飞机\n今天北京到上海的火车\n天安门到王府井的公交有哪些\n北京的邮编\n脑筋急转弯\n影视搜索\n等等";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
$apiKey = "36f74a73b1084469a168858d9922f01f";
$apiURL = "http://www.tuling123.com/openapi/api?key=KEY&info=INFO";
$reqInfo = $keyword;
$url = str_replace("INFO", $reqInfo, str_replace("KEY", $apiKey, $apiURL));
$res = file_get_contents($url);
$contentStr = json_decode($res)->text;
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
}else{
echo "你还想要我怎样?";
}
}else {
echo "";
exit;
}
}
private function checkSignature()
{
if (!defined("TOKEN")) {
throw new Exception('TOKEN is not defined!');
}
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
?>
</pre>
用的是图灵机器人免费版
网友评论