本文實例為大家分享了php微信語音消息識別代碼,供大家參考,具體內容如下
1.開通語音識別(默認關閉)
2.語音識別
請注意,開通語音識別後,用戶每次發送語音給公眾號時,微信會在推送的語音消息XML數據包中,增加一個Recognition字段(注:由於客戶端緩存,開發者開啟或者關閉語音識別功能,對新關注者立刻生效,對已關注用戶需要24小時生效。開發者可以重新關注此帳號進行測試)。開啟語音識別後的語音XML數據包如下:
<?php /** * wechat php test */ //define your token define("TOKEN", "weixin"); $wechatObj = new wechatCallbackapiTest(); //$wechatObj->valid();//接口驗證 $wechatObj->responseMsg();//調用回復消息方法 class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, 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(); $msgType = $postObj->MsgType;//消息類型 $event = $postObj->Event;//時間類型,subscribe(訂閱)、unsubscribe(取消訂閱) $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>"; switch($msgType){ case "event": if($event=="subscribe"){ $contentStr = "Hi,歡迎關注海仙日用百貨!"."\n"."回復數字'1',了解店鋪地址."."\n"."回復數字'2',了解商品種類."; } break; case "text"://文本消息 switch($keyword){ case "1": $contentStr = "店鋪地址:"."\n"."杭州市江干區."; break; case "2": $contentStr = "商品種類:"."\n"."杯子、碗、棉簽、水桶、垃圾桶、洗碗巾(刷)、拖把、掃把、" ."衣架、粘鉤、牙簽、垃圾袋、保鮮袋(膜)、剪刀、水果刀、飯盒等."; break; default: $contentStr = "對不起,你的內容我會稍後回復"; } break; case "voice"://語音消息 //語音識別 $recognition = $postObj->Recognition; $format = $postObj->Format; $contentStr = "你發送的是語音消息"."\n"."語音格式為:"."\n".$format."\n"."語音內容為:"."\n".$recognition; break; } $msgType = "text"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else { echo ""; exit; } } private function checkSignature() { // you must define TOKEN by yourself 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); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } } ?>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。