Home  >  Article  >  WeChat Applet  >  Summary and introduction of WeChat public platform development message reply

Summary and introduction of WeChat public platform development message reply

高洛峰
高洛峰Original
2017-03-06 09:38:301459browse

1. Introduction

WeChat public platform provides three message reply formats, namely text reply, music reply and image reply. Text reply, in this article, we will briefly explain the formats of these three message replies, and then encapsulate them into functions for readers to use.

2. Idea analysis

For each POST request, the developer returns a specific xml structure in the response package , respond to the message (now supports reply text, graphics, voice, video, music).

3. Text reply

3.1 Text reply xml structure

 <xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>12345678</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[content]]></Content>
 </xml>

3.2 Structure description

Summary and introduction of WeChat public platform development message reply

3.3 Specific implementation

For the xml structure given above, we only need to fill in the content in the corresponding position, and then format the output. That's it.

Summary and introduction of WeChat public platform development message reply

Explanation:

ToUserName is filled in with $fromUsername = $postObj->FromUserName, which is to return the message to The user who sent the message is the receiver’s account.

FromUserName is filled in with $toUsername = $postObj->ToUserName, which is the developer’s WeChat account.

This is the official text reply. You only need to instantiate its responseMsg() method to reply to the "Welcome to wechat world!" message.

Here we make a slight modification and return fromUsername and toUsername messages to facilitate readers to understand the above instructions.

Summary and introduction of WeChat public platform development message reply

3.4 Test results

Summary and introduction of WeChat public platform development message reply

3.5 Encapsulate into a callable function

We can convert the above The content is encapsulated into a function and can be called directly where the reply text is needed. It is convenient and concise. The code of responseText.func.inc.php is as follows.

function _response_text($object,$content){
    $textTpl = "<xml>
                <tousername></tousername>
                <fromusername></fromusername>
                <createtime>%s</createtime>
                <msgtype></msgtype>
                <content></content>
                <funcflag>%d</funcflag>
                </xml>";
    $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
    return $resultStr;
}

In this way, as long as you pass in $object and $content, then introduce the file into the file that needs to reply to the text, and then call the _response_text() method, you can directly reply to the text.

3.6 Test code

3.6.1 Introduce the function file of reply text into the main file

require_once 'responseText.func.inc.php';

3.6.2 Ordinary message reply

public function handleText($postObj)
    {
        $keyword = trim($postObj->Content);

        if(!empty( $keyword ))
        {
            $contentStr = "微信公众平台-文本回复功能源代码";
            //$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            $resultStr = _response_text($postObj,$contentStr);
            echo $resultStr;
        }else{
            echo "Input something...";
        }
}

3.6.3 Reply when following

public function handleEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":
                $contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz";
                break;
            default :
                $contentStr = "Unknow Event: ".$object->Event;
                break;
        }
        $resultStr = _response_text($object, $contentStr);
        return $resultStr;
}

3.7 Test result

Summary and introduction of WeChat public platform development message reply

The reply text was successful.

4. Graphic reply

4.1 Graphic reply xml structure

 <xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>12345678</CreateTime>
 <MsgType><![CDATA[news]]></MsgType>
 <ArticleCount>2</ArticleCount>
 <Articles>
 <item>
 <Title><![CDATA[title1]]></Title> 
 <Description><![CDATA[description1]]></Description>
 <PicUrl><![CDATA[picurl]]></PicUrl>
 <Url><![CDATA[url]]></Url>
 </item>
 <item>
 <Title><![CDATA[title]]></Title>
 <Description><![CDATA[description]]></Description>
 <PicUrl><![CDATA[picurl]]></PicUrl>
 <Url><![CDATA[url]]></Url>
 </item>
 </Articles>
 </xml>

4.2 Structure description

Summary and introduction of WeChat public platform development message reply

Similar to the text reply format, you only need to fill in the corresponding content in the corresponding position to reply to the graphic message.

4.3 Specific Implementation

The picture-text reply can be a single picture-text or multiple pictures-text. Here we first guide the readers with the case of single picture-text, and then introduce the multi-picture-text .

We decompose the xml structure of the image and text reply into the following three structures, the image and text header, the image and text body, and the image and text tail. The image and text body is the title, description, and image URL that you see when replying to the image and text. and original URL.

$newsTplHead = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>1</ArticleCount>
                <Articles>";
$newsTplBody = "<item>
                <Title><![CDATA[%s]]></Title> 
                <Description><![CDATA[%s]]></Description>
                <PicUrl><![CDATA[%s]]></PicUrl>
                <Url><![CDATA[%s]]></Url>
                </item>";
$newsTplFoot = "</Articles>
                <FuncFlag>0</FuncFlag>
                </xml>";

Next, we insert corresponding content into the three structures:

A. $newsTplHead

$header = sprintf($newsTplHead, $object->FromUserName, $object->ToUserName, time());

B. $newsTplBody

$title = $newsContent[&#39;title&#39;];
$desc = $newsContent[&#39;description&#39;];
$picUrl = $newsContent[&#39;picUrl&#39;];
$url = $newsContent[&#39;url&#39;];
$body = sprintf($newsTplBody, $title, $desc, $picUrl, $url);

Explanation: $newsContent is the image and text array passed into the function from the main file.

C. $newsTplFoot

$FuncFlag = 0;
$footer = sprintf($newsTplFoot, $FuncFlag);

Then you can reply to a single image and text by splicing the three paragraphs back together.

return $header.$body.$footer;

Write the above content into a function and name it _response_news() function for the following call test.

4.4 Test code

4.4.1 Introduce the function file for replying to the image and text in the main file

require_once &#39;responseNews.func.inc.php&#39;;

4.4.2 Create an array and pass it in

In the main file, you only need to pass an array and $postObj to the _response_news() function.

$record=array(
&#39;title&#39; =>&#39;山塘街&#39;,
&#39;description&#39; =>&#39;山塘街东起阊门渡僧桥,西至苏州名胜虎丘山的望山桥,长约七里,所以苏州俗语说“七里山塘到虎丘”...&#39;,
&#39;picUrl&#39; => &#39;http://thinkshare.duapp.com/images/suzhou.jpg&#39;,
&#39;url&#39; =>&#39;http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000046&itemidx=1&sign=9e7707d5615907d483df33ee449b378d#wechat_redirect&#39;
);

$resultStr = _response_news($postObj,$record);
echo $resultStr;
4.5 测试结果

Summary and introduction of WeChat public platform development message reply

点击进入查看

Summary and introduction of WeChat public platform development message reply

单图文回复测试成功。

4.6 多图文回复

有了上面的引导,读者应该能够想到回复多图文的思路了,就是将多维数组中的值循环放到相应的位置,然后拼接起来就可以了,下面进行讲解。 

4.6.1 获取图文条数


$bodyCount = count($newsContent);


4.6.2 判断图文条数

因为微信限制了回复的图文消息数为10条以内,所以需要判断图文条数,如果小于10条,则图文数等于原来的图文数,如果大于等于10条,则强制限制为10条。


$bodyCount = $bodyCount < 10 ? $bodyCount : 10;


4.6.3 组织图文体

图文头和图文尾和上面单图文一样,不再赘述,主要是图文体的组织。

用foreach 循环出数组的内容并赋予图文体,并进行拼接:


foreach($newsContent as $key => $value){
    $body .= sprintf($newsTplBody, $value[&#39;title&#39;], $value[&#39;description&#39;], $value[&#39;picUrl&#39;], $value[&#39;url&#39;]);
}


说明:$newsContent 是从主文件传入函数的图文数组。

4.6.4 拼接并返回


return $header.$body.$footer;


将以上内容写到一个函数里,命名为 _response_multiNews() 函数,以供下面调用测试。

4.7 测试多图文

4.7.1 在主文件中引入回复多图文的函数文件


require_once 'responseMultiNews.func.inc.php';


4.7.2 创建多维数组并传入

$record[0]=array(
    &#39;title&#39; =>&#39;观前街&#39;,
    &#39;description&#39; =>&#39;观前街位于江苏苏州市区,是成街于清朝时期的百年商业老街,街上老店名店云集,名声远播海内外...&#39;,
    &#39;picUrl&#39; => &#39;http://joythink.duapp.com/images/suzhou.jpg&#39;,
    &#39;url&#39; =>&#39;http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000052&itemidx=1&sign=90518631fd3e85dd1fde7f77c04e44d5#wechat_redirect&#39;
);
......
$record[11]=array(
    &#39;title&#39; =>&#39;平江路&#39;,
    &#39;description&#39; =>&#39;平江路位于苏州古城东北,是一条傍河的小路,北接拙政园,南眺双塔,全长1606米,是苏州一条历史攸久的经典水巷。宋元时候苏州又名平江,以此名路...&#39;,
    &#39;picUrl&#39; => &#39;http://joythink.duapp.com/images/suzhouScenic/pingjianglu.jpg&#39;,
    &#39;url&#39; =>&#39;http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000056&itemidx=1&sign=ef18a26ce78c247f3071fb553484d97a#wechat_redirect&#39;
);
$resultStr = _response_multiNews($postObj,$record);
echo $resultStr;

4.8 测试多图文结果

Summary and introduction of WeChat public platform development message reply

点击进入查看

Summary and introduction of WeChat public platform development message reply

测试多图文成功。

五、音乐回复

微信还提供了一种消息回复的格式,即音乐回复,下面我们编写程序测试一下。

注意:由于音乐版权的问题,现在很少有回复音乐的API,开放的API 查询出来的音乐信息也有很多是不正确的。所以在这里,我们上传几首音乐到自己的服务器空间测试。

本地文件:

Summary and introduction of WeChat public platform development message reply

测试是否能够正常播放:

Summary and introduction of WeChat public platform development message reply

5.1 音乐回复xml 结构


 <xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>12345678</CreateTime>
 <MsgType><![CDATA[music]]></MsgType>
 <Music>
 <Title><![CDATA[TITLE]]></Title>
 <Description><![CDATA[DESCRIPTION]]></Description>
 <MusicUrl><![CDATA[MUSIC_Url]]></MusicUrl>
 <HQMusicUrl><![CDATA[HQ_MUSIC_Url]]></HQMusicUrl>
 </Music>
 </xml>


5.2 结构说明

Summary and introduction of WeChat public platform development message reply

5.3 具体实施

我们先做一个固定的歌曲回复来引导读者,然后再引出更高级别的歌曲查询回复。

5.3.1 在xml 结构的相应位置插入相应数据


<Music>
<Title><![CDATA[Far Away From Home]]></Title>
<Description><![CDATA[Groove Coverage]]></Description>
<MusicUrl><![CDATA[http://thinkshare.duapp.com/music/10001.mp3]]></MusicUrl>
<HQMusicUrl><![CDATA[http://thinkshare.duapp.com/music/10001.mp3]]></HQMusicUrl>
</Music>

5.3.2 测试代码


$resultStr = _response_music($postObj,$keyword);echo $resultStr;


5.3.3 测试结果

Summary and introduction of WeChat public platform development message reply

5.4 模拟点歌

有了上面的简单案例引导,读者应该可以想到模拟点歌的具体实现了吧,下面就来简单介绍一下。

思路:将歌曲代码和对应的歌曲名存入数据库,用户输入歌曲名,在数据库中找到歌曲名对应的歌曲编号,然后就可以生成MusicUrl 回复用户了。

5.4.1 创建数据库

Summary and introduction of WeChat public platform development message reply

建表语句及数据文件:


CREATE TABLE IF NOT EXISTS `tbl_music` (
  `music_id` int(11) NOT NULL,
  `music_name` varchar(40) NOT NULL,
  `music_singer` varchar(40) NOT NULL,
  `music_lrc` text NOT NULL,  PRIMARY KEY (`music_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;INSERT INTO `tbl_music` (`music_id`, `music_name`, `music_singer`, `music_lrc`) VALUES(10001, &#39;Far Away From Home&#39;, &#39;Groove Coverage&#39;, &#39;far away from home&#39;),
(10002, &#39;The Dawn&#39;, &#39;Dreamtale&#39;, &#39;the dawn&#39;),
(20002, &#39;董小姐&#39;, &#39;宋冬野&#39;, &#39;董小姐&#39;),
(20001, &#39;左边&#39;, &#39;杨丞琳&#39;, &#39;左边&#39;);


5.4.2 _response_music() 函数编写

A. 引入数据库操作文件


require_once(&#39;mysql_bae.func.php&#39;);


B. 数据库操作及数据处理

$query = "SELECT * FROM tbl_music WHERE music_name LIKE &#39;%$musicKeyword%&#39;";
$result = _select_data($query);
$rows = mysql_fetch_array($result, MYSQL_ASSOC);
$music_id = $rows[music_id];

注: $musicKeyword 为从主文件传入的歌曲名关键字,这里使用模糊查询,只取第一条数据。

C. 判断是否查询到


if($music_id <> &#39;&#39;)
{
    $music_name = $rows[music_name];
    $music_singer = $rows[music_singer];
    $musicUrl = "http://thinkshare.duapp.com/music/".$music_id.".mp3";
    $HQmusicUrl = "http://thinkshare.duapp.com/music/".$music_id.".mp3";

    $resultStr = sprintf($musicTpl, $object->FromUserName, $object->ToUserName, time(), $music_name, $music_singer, $musicUrl, $HQmusicUrl);
    return $resultStr;
}else{
    return "";    
}


说明:如果查询到歌曲信息,按照xml 结构返回数据;如果未查询到,则返回空,用于主文件判断。

将以上代码封装成 _response_music() 函数并保存为responseMusic.func.inc.php 文件供主文件调用。

5.4.3 测试代码

A. 引入回复音乐和回复文本的函数文件


//引入回复音乐的函数文件require_once &#39;responseMusic.func.inc.php&#39;;//引入回复文本的函数文件require_once &#39;responseText.func.inc.php&#39;;


B. 调用


if(!empty( $keyword ))
{
    $resultStr = _response_music($postObj,$keyword);
    if($resultStr <> &#39;&#39;)
    {
        echo $resultStr;
    }else
    {
        echo _response_text($postObj,"未查询到【".$keyword."】的歌曲信息!");    
    }
    
}


说明:如果查询到歌曲信息,则返回所得信息,如果未查询到,则调用 _response_text() 函数返回文本信息。

5.5 模拟点歌测试

Summary and introduction of WeChat public platform development message reply

回复音乐测试成功。 

更多Summary and introduction of WeChat public platform development message reply相关文章请关注PHP中文网!

 



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn