


[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

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
