PHP微信公众号实现自动回复的功能
最近在做微信公众平台开发,公司有个需求是做自动回复的功能,也就是你说啥,对方回个啥,就像siri等功能。
首先,自己写自动回复的库显然是不可能的,然后在网站上找了这样子的库。
像小黄鸡啊,小i啊,图灵啊,等等。都有很完善的接口。
今天我们就来用小黄鸡做自动回复功能。
< ?php
$wechatObj = new wechat();
$wechatObj->responseMsg();
class wechat {
public function responseMsg() {
//---------- 接 收 数 据 ---------- //
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取POST数据
//用SimpleXML解析POST过来的XML数据
$postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID)
$toUsername = $postObj->ToUserName; //获取接收方账号
$keyword = trim($postObj->Content); //获取消息内容
$time = time(); //获取当前时间戳
//---------- 返 回 数 据 ---------- //
//返回消息模板
$textTpl = "
< ![CDATA[%s]]>
< ![CDATA[%s]]>
%s
< ![CDATA[%s]]>
< ![CDATA[%s]]>
0
";
$msgType = "text"; //消息类型
include('simsimi.php');
$contentStr = simsimi($keyword); //返回消息内容
//格式化消息模板
$resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
echo $resultStr; //输出结果
}
}
?>
把代码保存为index.php。
然后我们单独来写simsimi文件。
< ?php
function simsimi ($keyword)
{
$keyword = urlencode($keyword);
//----------- 获取COOKIE ----------//
$url = "http://www.simsimi.com/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
list($header, $body) = explode("\r\n\r\n", $content);
preg_match_all("/set\-cookie:([^\r\n]*);/iU", $header, $matches);
$cookie = implode(';', $matches[1]).";simsimi_uid=1;";
curl_close($ch);
//----------- 抓 取 回 复 ----------//
$url = "http://www.simsimi.com/func/reqN?lc=ch&ft=0.0&req=$keyword&fl=http%3A%2F%2Fwww.simsimi.com%2Ftalk.htm";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
$content = json_decode(curl_exec($ch), 1);
curl_close($ch);
if ( $content['result'] == '200' ) {
return $content['sentence_resp'];
} else {
return '我还不会回答这个问题...';
}
}
?>
把上面两段代码整合在一起就大功告成了。
其实很简单,就是获取微信发送的关键字,然后返回相应的内容在发送出去。
PHP中var_dump展示不全出现省略号的解决办法 PHP中接受变量$GLOBALS[‘HTTP_RAW_POST_DATA’] 和$_POST的区别
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.