准备电商比赛的时候申请了个公众号,因为之前错误地申请了订阅号,还是个人类型的,所以基本也没法开发什么功能了。于是就想到之前很火的小黄鸡聊天机器人。不过小黄鸡的接口是要收费的,所以选用了图灵机器人();也能实现自动聊天。
图灵机器人后台提供了两种接入方式,一种是API接入,一种是微信接入。使用微信接入非常简单,只要在微信后台-开发-基本配置里填写图灵机器人提供的URL和token值就可以。不过这样一来整个公众号只能实现图灵机器人的功能,几乎浪费了一个公众号。所以选择使用API接入。这里使用新浪云提供的SAE。下面是代码。
valid();
}else{
$wechatObj->responseMsg();
}
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
echo $echoStr;
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;
}
}
public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);
switch ($RX_TYPE)
{
case "text":
$resultStr = $this->receiveText($postObj);
break;
case "event":
$resultStr = $this->receiveEvent($postObj);
break;
}
echo $resultStr;
}else {
echo "";
exit;
}
}
//处理接受到用户消息的事件
private function receiveText($object)
{
$funcFlag = 0;
$keyword = trim($object->Content);
$contentStr = callTuling($keyword);
$resultStr = $this->transmitText($object, $contentStr, $funcFlag);
return $resultStr;
}
//处理公众号被关注的事件
private function receiveEvent($object)
{
$contentStr = "";
switch ($object->Event)
{
case "subscribe":
$contentStr = "你终于来了";
}
$resultStr = $this->transmitText($object, $contentStr);
return $resultStr;
}
//把图灵机器人返回的数据转换成微信使用的数据格式
private function transmitText($object, $content, $flag = 0)
{
$textTpl = "
%s
%d
";
$resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
return $resultStr;
}
}//创建函数调用图灵机器人接口
function callTuling($keyword)
{
$apiKey = "******"; //填写后台提供的key
$apiURL = "http://www.tuling123.com/openapi/api?key=KEY&info=INFO";
$reqInfo = $keyword;
$url = str_replace("INFO", $reqInfo, str_replace("KEY", $apiKey, $apiURL));
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$file_contents = curl_exec($ch);
curl_close($ch);
//获取图灵机器人返回的数据,并根据code值的不同获取到不用的数据
$message = json_decode($file_contents,true);
$result = "";
if ($message['code'] == 100000){
$result = $message['text'];
}else if ($message['code'] == 200000){
$text = $message['text'];
$url = $message['url'];
$result = $text . " " . $url;
}else if ($message['code'] == 302000){
$text = $message['text'];
$url = $message['list'][0]['detailurl'];
$result = $text . " " . $url;
}else {
$result = "好好说话我们还是基佬";
}
return $result;
}
?>
评论(0)