weiphp4.0: 呼叫阿里雲小蜜
阿新 • • 發佈:2019-01-08
最近因為專案需要,需要用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