最近因为项目需要,需要用PHP写一个调用云小蜜的程序,我发现网上还没有相关的实现版本,我这里给一个示例。我这里做的是一个接入公众号聊天的程序
function reply($dataArr, $keywordArr = array()) {
$config = getAddonConfig ( 'NoAnswer' ); // 获取后台插件的配置参数
// $this->material_reply ( $config ['stype'] );
// $this->replyText($dataArr['Content']); //接收微信服务器传来的消息内容
date_default_timezone_set("GMT");
$accessKeyId="your id";
$accessSecret="your secret;
$publicParams = array(
"Format" => "JSON",
"Version" => "2017-10-11",
"AccessKeyId" => $accessKeyId,
"Timestamp" => date("Y-m-d\TH:i:s\Z"),
"SignatureMethod" => "HMAC-SHA1",
"SignatureVersion" => "1.0",
"SignatureNonce" => substr(md5(rand(1,99999999)),rand(1,9),14),
"Action" => "Chat",
"InstanceId" => "your instance id",
// "Utterance" => "电脑",
);
// $publicParams["Utterance"]="电脑";
$publicParams["Utterance"]="电脑坏了怎么办"; //这里填向阿里云发送的内容
$params = $publicParams;
$params['Signature']=$this->sign($params, $accessSecret);
$uri = http_build_query($params);
$url="https://chatbot.cn-shanghai.aliyuncs.com/?".$uri; //调用阿里云服务
$result=$this->curl($url);
// dump($url);
// dump($result);
$content_type=$result->Messages[0]->Type;
if($content_type=="Recommend"){
$_recommend=$result->Messages[0]->Recommends;
$_reply="您可以这样问:\n";
foreach ($_recommend as $value) {
// echo $value->Title . "<br>";
$_reply.=$value->Title."\n";
}
$this->replyText($_reply);
}else if($content_type=="Knowledge"){
$_knowledge=$result->Messages[0]->Knowledge;
// echo $_knowledge->Content. "<br>";
$this->replyText($_knowledge->Content);
}
}
private function curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
$result=curl_exec ($ch);
return json_decode($result);
}
private function sign($params, $accessSecrec, $method="GET"){
ksort($params);
$stringToSign = strtoupper($method).'&'.$this->percentEncode('/').'&';
$tmp = "";
foreach($params as $key=>$val){
$tmp .= '&'.$this->percentEncode($key).'='.$this->percentEncode($val);
}
$tmp = trim($tmp, '&');
$stringToSign = $stringToSign.$this->percentEncode($tmp);
$key = $accessSecrec.'&';
$hmac = hash_hmac("sha1", $stringToSign, $key, true);
return base64_encode($hmac);
}
public function percentEncode($value=null){
$en = urlencode($value);
$en = str_replace("+", "%20", $en);
$en = str_replace("*", "%2A", $en);
$en = str_replace("%7E", "~", $en);
return $en;
}
参考文献
[1].php中数组遍历的四种方式.http://blog.csdn.net/wks19891215/article/details/51615384
[2].微信公众号开发之文本消息自动回复,以及系统关注自动回复,php代码.https://www.cnblogs.com/xqschool/p/6745113.html
[3].PHP阿里云云解析签名, 通过API 绑定域名到动态 ip.http://www.cnblogs.com/hanyouchun/p/5382709.html