Home > Backend Development > PHP Tutorial > PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

WBOY
Release: 2016-07-13 10:35:32
Original
1197 people have browsed it

[PHP WeChat public platform development series]

01. Configure WeChat interface
02. Public platform sample code analysis
03. Subscription event (subscribe) processing
04. Development of simple reply function
05. Weather forecast function development
06.Translation function development
07. Chatbot function development
08. Custom menu function
09. Database operations
10. Encapsulation of message reply


URL of this article: http://www.phpchina.com/archives/view-43418-1.html
This series is contributed by PHPChina's specially invited author @David_Tang. Please indicate the author's information and the address of this article when reprinting.

1. Introduction

WeChat public platform provides three message reply formats, namely text reply, music reply and graphic reply. In this article, we will briefly explain these three message reply formats, and then encapsulate them into functions. For readers’ use.

2. Idea analysis

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

3. Text reply

3.1 Text reply xml structure

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
 <xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>12345678</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[content]]></Content>
 </xml>
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

3.2 Structure Description

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.

Description:

Fill in the ToUserName position is $fromUsername = $postObj->FromUserName, which is to return the message to the user who sent the message, that is, the receiver account.

Fill in the FromUserName position is $toUsername = $postObj->ToUserName, which is the developer’s WeChat ID.

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

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

3.4 Test results

3.5 Encapsulated into a callable function

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

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
function _response_text($object,$content){
    $textTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                <FuncFlag>%d</FuncFlag>
                </xml>";
    $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
    return $resultStr;
}
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

In this way, as long as you pass in $object and $content, then introduce the file in 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 &#39;responseText.func.inc.php&#39;;
Copy after login

3.6.2 Ordinary message reply

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
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...";
        }
}
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

3.6.3 Reply when following

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
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;
}
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

3.7 Test results

Reply text successful.

4. Graphic reply

4.1 Image and text reply xml structure

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
 <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> 
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

4.2 Structure Description

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

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

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

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
$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>";
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

接下来,我们对三段结构分别插入对应内容:

A. $newsTplHead

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

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);
Copy after login

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

C. $newsTplFoot

$FuncFlag = 0;
$footer = sprintf($newsTplFoot, $FuncFlag);
Copy after login

然后将三段进行拼接返回就可以回复单条图文了。

return $header.$body.$footer;
Copy after login
Copy after login

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

4.4 测试代码

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

require_once &#39;responseNews.func.inc.php&#39;;
Copy after login

4.4.2 创建数组并传入

在主文件中,只需要向 _response_news() 函数中传入一个数组和$postObj 即可。

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
$record=array(
    &#39;title&#39; =>&#39;山塘街&#39;,
    &#39;description&#39; =>&#39;山塘街东起阊门渡僧桥,西至苏州名胜虎丘山的望山桥,长约七里,所以苏州俗语说&ldquo;七里山塘到虎丘&rdquo;...&#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;
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

4.5 测试结果

点击进入查看

单图文回复测试成功。

4.6 多图文回复

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

4.6.1 获取图文条数

$bodyCount = count($newsContent);
Copy after login

4.6.2 判断图文条数

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

$bodyCount = $bodyCount < 10 ? $bodyCount : 10;
Copy after login

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;]);
}
Copy after login

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

4.6.4 拼接并返回

return $header.$body.$footer;
Copy after login
Copy after login

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

4.7 测试多图文

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

require_once &#39;responseMultiNews.func.inc.php&#39;;
Copy after login

4.7.2 创建多维数组并传入

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
$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;
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

4.8 测试多图文结果

点击进入查看

测试多图文成功。

五、音乐回复

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

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

本地文件:

测试是否能够正常播放:

5.1 音乐回复xml 结构

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
 <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>
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

5.2 结构说明

5.3 具体实施

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

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

PHP WeChat public platform development - encapsulation of message replies_PHP tutorial
<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>
Copy after login
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

5.3.2 测试代码

$resultStr = _response_music($postObj,$keyword);
echo $resultStr;                    
Copy after login

5.3.3 测试结果

5.4 模拟点歌

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

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

5.4.1 Create database
PHP WeChat public platform development - encapsulation of message replies_PHP tutorial

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/743433.htmlTechArticle[PHP WeChat public platform development series] 01. Configure WeChat interface 02. Public platform sample code analysis 03. Subscribe to events (subscribe) processing 04. Simple reply function development 05. Weather forecast function...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template