Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of message reply in the Development of Wechat Public platform

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the Wechat public platform development message reply example analysis, the article is very detailed, has a certain reference value, interested friends must read it!

I. brief introduction

The Wechat public platform provides three kinds of message reply formats, namely, text reply, music reply and picture and text reply. In this article, we will briefly explain the format of these three kinds of message reply, and then package them into functions for readers to use.

Second, train of thought analysis

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

III. Text reply

3.1 text reply xml structure

12345678

3.2 structure description

3.3 concrete implementation

For the xml structure given above, we just need to fill in the content in the corresponding location, and then format the output.

Description:

The ToUserName location is filled with $fromUsername = $postObj- > FromUserName, which returns the message to the user who sent the message, that is, the recipient account.

Enter $toUsername = $postObj- > ToUserName in the FromUserName location, which is the developer's WeChat account.

This is an official text reply. Just instantiate its responseMsg () method and reply "Welcome to wechat world!" I got the news.

Here we make some modifications and return fromUsername and toUsername messages to make it easier for readers to understand the above instructions.

3.4 Test results

3.5 encapsulated into callable functions

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 responseText.func.inc.php code is as follows.

Function _ response_text ($object,$content) {$textTpl = "% s% d"; $resultStr = sprintf ($textTpl, $object- > FromUserName, $object- > ToUserName, time (), $content, $flag); return $resultStr;}

In this way, just pass in $object and $content, then introduce the file in the file that needs the reply text, and then call the _ response_text () method, and you can reply the text directly.

3.6 Test code

3.6.1 A function file that introduces reply text into the main file

Require_once 'responseText.func.inc.php'

3.6.2 normal message reply

Public function handleText ($postObj) {$keyword = trim ($postObj- > Content); if (! empty ($keyword)) {$contentStr = "Wechat Public platform-text reply function source code"; / / $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 = "Thank you for your interest [Zhuo Jin Suzhou]."\ n "." WeChat account: zhuojinsz "; break; default: $contentStr =" Unknow Event: ". $object- > Event; break;} $resultStr = _ response_text ($object, $contentStr); return $resultStr;}

3.7 Test results

The reply text was successful.

IV. Reply with picture and text

4.1 xml structure of picture and text reply

12345678 2

4.2 structure description

Similar to the text reply format, you only need to fill in the corresponding content in the corresponding location to reply to the picture and text message.

4.3 concrete implementation

The reply of picture and text can be single picture and text, or it can be multi-picture and text. Here, we use the case of single picture and text to guide the reader, and then lead to multiple picture and text.

We decompose the xml structure of the reply into the following three structures: header, style, tail, and style are the title, description, picture URL and URL that we see when replying to the text.

$newsTplHead = "% s 1"; $newsTplBody = ""; $newsTplFoot = "0"

Next, we insert the corresponding content into the three-paragraph structure:

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)

Note: $newsContent is an array of graphics and text that is passed into the function from the main file.

C. $newsTplFoot

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

Then splice the three segments and return to reply to a single picture and text.

Return $header.$body.$footer

Write the above into a function and name it the _ response_news () function for the next call to test.

4.4 Test code

4.4.1 introduce the function file to reply to the picture and text in the main file

Require_once 'responseNews.func.inc.php'

4.4.2 create an array and pass in

In the main file, you just need to pass an array and $postObj to the _ response_news () function.

$record=array ('title' = >' Shantang Street', 'description' = >' Shantang Street starts from Shantu Monk Bridge in the east to Wangshan Bridge in Huqiu Mountain in Suzhou in the west, which is about seven li long, so as the Suzhou saying goes, "Qili Shantang to Tiger Hill", '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 test results

Click to enter to view

The single picture and text reply test was successful.

4.6 reply with more than one picture and text

With the above guidance, the reader should be able to think of the idea of replying to multiple images and text, that is, put the value loop in the multidimensional array into the appropriate position, and then splice it together, which will be explained below.

4.6.1 get the number of images and texts

$bodyCount = count ($newsContent)

4.6.2 judge the number of pictures and texts

Because Wechat limits the number of replied picture and text messages to less than 10, it is necessary to judge the number of picture and text. If it is less than 10, the number of picture and text is equal to the original number of picture and text. If it is greater than or equal to 10, the limit is forced to 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']);}

Note: $newsContent is an array of graphics and text that is passed into the function from the main file.

4.6.4 stitching and returning

Return $header.$body.$footer

Write the above into a function and name it the _ response_multiNews () function for the next call to test.

4.7 Test multiple pictures and texts

4.7.1 introduce a function file that replies to multiple images and texts in the main file

Require_once 'responseMultiNews.func.inc.php'

4.7.2 create a multidimensional array and pass in

$record [0] = array ('title' = >' Guanqian Street', 'description' = >' Guanqian Street is located in the urban area of Suzhou, Jiangsu Province. It is a century-old commercial street of Chengjie in the Qing Dynasty, where there are many famous shops. Fame spreads at home and abroad.', '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' = >' Pingjiang Road', 'description' = >' Pingjiang Road', located in the northeast of the ancient city of Suzhou, is a path near the river, connecting the Humble Administrator's Garden to the north, overlooking the Twin Towers to the south, with a total length of 1606 meters, is a classic water lane with a long history in Suzhou. Suzhou was also known as Pingjiang in the Song and Yuan dynasties.', '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 Test results of multiple pictures and texts

Click to enter to view

The test of multiple pictures and texts is successful.

Fifth, music reply

Wechat also provides a message reply format, that is, music reply, let's write a program to test it.

Note: due to the problem of music copyright, there are few API responses to music, and many of the music information queried by the open API is incorrect. So here, we upload some music to our own server space for testing.

Local file:

Test whether it can play properly:

5.1 Music reply xml structure

12345678

5.2 structure description

5.3 concrete implementation

We first do a fixed song reply to guide the reader, and then lead to a higher level of song query reply.

5.3.1 insert the appropriate data in the appropriate location of the xml structure

5.3.2 Test code

$resultStr = _ response_music ($postObj,$keyword); echo $resultStr

5.3.3 Test results

5.4 simulated song-ordering

With the above simple case guide, readers should be able to think of the specific implementation of the simulation song-on-demand bar, the following is a brief introduction.

Idea: the song code and the corresponding song name are stored in the database, the user enters the song name, finds the song number corresponding to the song name in the database, and then you can generate MusicUrl to reply to the user.

5.4.1 create a database

Build table statements and data files:

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, 'Far Away From Home',' Groove Coverage', 'far away from home'), (10002,' The Dawn', 'Dreamtale',' the dawn'), (20002, 'Miss Dong', 'Song Dongye', 'Miss Dong'), (20001, 'left', 'Rainie Yang', 'left')

5.4.2 _ response_music () function writing

a. Introduce database operation file

Require_once ('mysql_bae.func.php')

b. Database operation and data processing

$query = "SELECT * FROM tbl_music WHERE music_name LIKE'% $musicKeyword%'"; $result = _ select_data ($query); $rows = mysql_fetch_array ($result, MYSQL_ASSOC); $music_id = $rowsmusic _ id]

Note: $musicKeyword is the keyword of the song name passed in from the main file. Here, a fuzzy query is used to take only the first piece of data.

c. To determine whether the query was found.

If ($music_id'') {$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 "";}

Note: if the song information is queried, the data will be returned according to the xml structure; if not, empty will be returned for judging the main file.

Encapsulate the above code into a _ response_music () function and save it as a responseMusic.func.inc.php file for the master file to call.

5.4.3 Test Code

a. Introduce function files to reply to music and reply text

/ / introduce the function file require_once 'responseMusic.func.inc.php';// to reply to music and introduce the function file require_once' responseText.func.inc.php' to reply text

b. Call

If (! empty ($keyword)) {$resultStr = _ response_music ($postObj,$keyword); if ($resultStr'') {echo $resultStr;} else {echo _ response_text ($postObj, "song information not found for [". $keyword. "] ;}}

Note: if the song information is queried, the obtained information is returned, and if it is not found, the _ response_text () function is called to return the text information.

5.5 simulated song-on-demand test

The reply music test was successful.

The above is all the contents of the article "sample Analysis of Wechat Public platform Development message reply". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report