微信公众号开发之语音消息识别
1.开通语音识别(默认关闭)
2.语音识别
请注意,开通语音识别后,用户每次发送语音给公众号时,微信会在推送的语音消息XML数据包中,增加一个Recognition字段(注:由于客户端缓存,开发者开启或者关闭语音识别功能,对新关注者立刻生效,对已关注用户需要24小时生效。开发者可以重新关注此帐号进行测试)。开启语音识别后的语音XML数据包如下:
1 <?php 2 /** 3 * wechat php test 4 */ 5 6 //define your token 7 define("TOKEN", "weixin"); 8 $wechatObj = new wechatCallbackapiTest(); 9 //$wechatObj->valid();//接口验证 10 $wechatObj->responseMsg();//调用回复消息方法 11 class wechatCallbackapiTest 12 { 13 public function valid() 14 { 15 $echoStr = $_GET["echostr"]; 16 17 //valid signature , option 18 if($this->checkSignature()){ 19 echo $echoStr; 20 exit; 21 } 22 } 23 24 public function responseMsg() 25 { 26 //get post data, May be due to the different environments 27 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 28 29 //extract post data 30 if (!empty($postStr)){ 31 /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, 32 the best way is to check the validity of xml by yourself */ 33 libxml_disable_entity_loader(true); 34 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 35 $fromUsername = $postObj->FromUserName; 36 $toUsername = $postObj->ToUserName; 37 $keyword = trim($postObj->Content); 38 $time = time(); 39 $msgType = $postObj->MsgType;//消息类型 40 $event = $postObj->Event;//时间类型,subscribe(订阅)、unsubscribe(取消订阅) 41 42 $textTpl = "<xml> 43 <ToUserName><![CDATA[%s]]></ToUserName> 44 <FromUserName><![CDATA[%s]]></FromUserName> 45 <CreateTime>%s</CreateTime> 46 <MsgType><![CDATA[%s]]></MsgType> 47 <Content><![CDATA[%s]]></Content> 48 <FuncFlag>0</FuncFlag> 49 </xml>"; 50 51 switch($msgType){ 52 case "event": 53 if($event=="subscribe"){ 54 $contentStr = "Hi,欢迎关注海仙日用百货!"."\n"."回复数字'1',了解店铺地址."."\n"."回复数字'2',了解商品种类."; 55 } 56 break; 57 case "text"://文本消息 58 switch($keyword){ 59 case "1": 60 $contentStr = "店铺地址:"."\n"."杭州市江干区."; 61 break; 62 case "2": 63 $contentStr = "商品种类:"."\n"."杯子、碗、棉签、水桶、垃圾桶、洗碗巾(刷)、拖把、扫把、" 64 ."衣架、粘钩、牙签、垃圾袋、保鲜袋(膜)、剪刀、水果刀、饭盒等."; 65 break; 66 default: 67 $contentStr = "对不起,你的内容我会稍后回复"; 68 } 69 break; 70 case "voice"://语音消息 71 //语音识别 72 $recognition = $postObj->Recognition; 73 $format = $postObj->Format; 74 $contentStr = "你发送的是语音消息"."\n"."语音格式为:"."\n".$format."\n"."语音内容为:"."\n".$recognition; 75 break; 76 } 77 $msgType = "text"; 78 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); 79 echo $resultStr; 80 }else { 81 echo ""; 82 exit; 83 } 84 } 85 86 private function checkSignature() 87 { 88 // you must define TOKEN by yourself 89 if (!defined("TOKEN")) { 90 throw new Exception('TOKEN is not defined!'); 91 } 92 93 $signature = $_GET["signature"]; 94 $timestamp = $_GET["timestamp"]; 95 $nonce = $_GET["nonce"]; 96 97 $token = TOKEN; 98 $tmpArr = array($token, $timestamp, $nonce); 99 // use SORT_STRING rule 100 sort($tmpArr, SORT_STRING); 101 $tmpStr = implode( $tmpArr ); 102 $tmpStr = sha1( $tmpStr ); 103 104 if( $tmpStr == $signature ){ 105 return true; 106 }else{ 107 return false; 108 } 109 } 110 } 111 112 113 ?>