WeChat公衆号が開発した音声メッセージ識別phpコード
本論文の例では、php WeChat音声メッセージ識別コードを共有しています。ご参考までに、具体的な内容は以下の通りです。
1.音声認識の開通(デフォルトクローズ)
2.音声認識
音声認識を開通した後、ユーザーが音声を公衆番号に送信するたびに、マイクロメッセージはプッシュされた音声メッセージXMLパケットにRecognitionフィールドを追加します。開発者はこのアカウントに注目してテストを行うことができます。音声認識をオンにした後の音声XMLデータパッケージは以下の通りです。
1.音声認識の開通(デフォルトクローズ)
2.音声認識
音声認識を開通した後、ユーザーが音声を公衆番号に送信するたびに、マイクロメッセージはプッシュされた音声メッセージXMLパケットにRecognitionフィールドを追加します。開発者はこのアカウントに注目してテストを行うことができます。音声認識をオンにした後の音声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, !"."
"." '1', ."."
"." '2', .";
}
break;
case "text"://
switch($keyword){
case "1":
$contentStr = " :"."
"." .";
break;
case "2":
$contentStr = " :"."
"." 、 、 、 、 、 ( )、 、 、"
." 、 、 、 、 ( )、 、 、 .";
break;
default:
$contentStr = " , ";
}
break;
case "voice"://
//
$recognition = $postObj->Recognition;
$format = $postObj->Format;
$contentStr = " "."
"." :"."
".$format."
"." :"."
".$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;
}
}
}
?>
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。