


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

<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
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.

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; }

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 '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 results
Reply text successful.
4. Graphic reply
4.1 Image and text 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
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.

$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>";

接下来,我们对三段结构分别插入对应内容:
A. $newsTplHead
$header = sprintf($newsTplHead, $object->FromUserName, $object->ToUserName, time());
B. $newsTplBody
$title = $newsContent['title']; $desc = $newsContent['description']; $picUrl = $newsContent['picUrl']; $url = $newsContent['url']; $body = sprintf($newsTplBody, $title, $desc, $picUrl, $url);
说明:$newsContent 是从主文件传入函数的图文数组。
C. $newsTplFoot
$FuncFlag = 0; $footer = sprintf($newsTplFoot, $FuncFlag);
然后将三段进行拼接返回就可以回复单条图文了。
return $header.$body.$footer;
将以上内容写到一个函数里,命名为 _response_news() 函数,以供下面调用测试。
4.4 测试代码
4.4.1 在主文件中引入回复图文的函数文件
require_once 'responseNews.func.inc.php';
4.4.2 创建数组并传入
在主文件中,只需要向 _response_news() 函数中传入一个数组和$postObj 即可。

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

4.5 测试结果
点击进入查看
单图文回复测试成功。
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['title'], $value['description'], $value['picUrl'], $value['url']); }
说明:$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( 'title' =>'观前街', 'description' =>'观前街位于江苏苏州市区,是成街于清朝时期的百年商业老街,街上老店名店云集,名声远播海内外...', 'picUrl' => 'http://joythink.duapp.com/images/suzhou.jpg', 'url' =>'http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000052&itemidx=1&sign=90518631fd3e85dd1fde7f77c04e44d5#wechat_redirect' ); ...... $record[11]=array( 'title' =>'平江路', 'description' =>'平江路位于苏州古城东北,是一条傍河的小路,北接拙政园,南眺双塔,全长1606米,是苏州一条历史攸久的经典水巷。宋元时候苏州又名平江,以此名路...', 'picUrl' => 'http://joythink.duapp.com/images/suzhouScenic/pingjianglu.jpg', 'url' =>'http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000056&itemidx=1&sign=ef18a26ce78c247f3071fb553484d97a#wechat_redirect' ); $resultStr = _response_multiNews($postObj,$record); echo $resultStr;

4.8 测试多图文结果
点击进入查看
测试多图文成功。
五、音乐回复
微信还提供了一种消息回复的格式,即音乐回复,下面我们编写程序测试一下。
注意:由于音乐版权的问题,现在很少有回复音乐的API,开放的API 查询出来的音乐信息也有很多是不正确的。所以在这里,我们上传几首音乐到自己的服务器空间测试。
本地文件:
测试是否能够正常播放:
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 结构说明
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 测试结果
5.4 模拟点歌
有了上面的简单案例引导,读者应该可以想到模拟点歌的具体实现了吧,下面就来简单介绍一下。
思路:将歌曲代码和对应的歌曲名存入数据库,用户输入歌曲名,在数据库中找到歌曲名对应的歌曲编号,然后就可以生成MusicUrl 回复用户了。
5.4.1 Create database

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
