PHP WeChat public Platform Development-message reply Encapsulation _php Tutorial

Source: Internet
Author: User
Tags cdata

"PHP Public Platform Development Series"

01. Configure the interface
02. Public Platform Sample Code analysis
03. Subscription event (SUBSCRIBE) processing
04. Simple Reply Function development
05. Development of weather forecast function
06. Translation Function Development
07. Chat Robot Function Development
08. Custom Menu Functions
09. Database Operations
10. Encapsulation of message replies


This address: http://www.phpchina.com/archives/view-43418-1.html
This series by Phpchina invited author @david_tang feeds, reprint please indicate the author information and this article address.

First, Introduction

The public platform provides three kinds of message reply format, namely text reply, music reply and picture reply, in this article, we will give a brief explanation to these three kinds of message reply format, then encapsulate the function for the reader to use.

Second, the Thinking analysis

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

Third, the text reply

3.1 Text reply XML Structure

 
 
   
  
   toUser
  
    
  
   fromUser
  
    
  
   
    
   12345678
  
    
  
   text
  
    
  
   content
  
    
 
  

3.2 Structure Description

3.3 Concrete Implementation

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

Description

Tousername position is filled in is $fromusername = $postObj->fromusername, is to return the message to send the message to the user, that is, the receiver account.

The fromusername position is filled with $tousername = $POSTOBJ->tousername, which is the developer number.

This is the official text reply, just instantiate its responsemsg () method can reply "Welcome to WeChat world!" message.

Here we make a slight change, return fromusername and Tousername message, easy to understand the above explanation.

3.4 Test Results

3.5 Encapsulated as callable function

We can encapsulate the above content into a function, where the need to reply to the text directly call, convenient and concise, responseText.func.inc.php code as follows.

function _response_text ($object, $content) {    $TEXTTPL = "
 
                  
  
    %s
  
                   
  
    %s
  
                   
  
   
    
   %s
  
                   
  
    text
  
                   
  
    %s
  
                   
  
   
    
   %d
  
                   
 
  ";    $RESULTSTR = sprintf ($TEXTTPL, $object->fromusername, $object->tousername, Time (), $content, $flag);    return $RESULTSTR;}

This allows you to directly reply to the text by passing in $object and $content, then introducing the file in a file that needs to reply to the text, and then calling the _response_text () method.

3.6 Test Code

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

Require_once ' responseText.func.inc.php ';

3.6.2 General Message Reply

Public Function Handletext ($POSTOBJ)    {        $keyword = Trim ($postObj->content);        if (!empty ($keyword))        {            $contentStr = "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 you are interested

Public Function handleevent ($object)    {        $contentStr = "";        Switch ($object->event)        {case            "subscribe":                $contentStr = "Thank you for your interest in" Zhuo Jin Suzhou "." \ n "." Number: 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.

Four, the text reply

4.1 Text reply XML Structure

 
 
   
  
   toUser
  
    
  
   fromUser
  
    
  
   
    
   12345678
  
    
  2
    news
  
     
  
    
   
    <! [cdata[title1]]>  
   
    description1
   
     
   
    picurl
   
     
   
    url
   
     
  
    
  
    
   
    <! [cdata[title]]> 
   
    description
   
     
   
    picurl
   
     
   
    url
   
     
  
     
 
  

4.2 Structure Description

Similar to the format of text replies, only need to fill in the corresponding location of the corresponding content can be used to reply to text messages.

4.3 Concrete implementation

Text reply can be a single text, or can be multi-text, here we first to a single graphic case to guide the reader, and then draw more text.

We will reply to the XML structure of graphics and text into the following three structure, graphics and text, text, text, graphics and texts, the text is the reply to see the title, description, image URL and the original URL.

$newsTplHead = "
 
                  
  
    %s %s
  
                   
  
    %s
  
                   
  
   
  
                   
  
    news 1 "; $newsTplBody =
  
                   "
  
                   
   
    <! [cdata[%s]]>"                 
   ; 
    
     $newsTplFoot %s
   
                    
   
     %s
   
                    
   
     %s
   
                    
  
    = "                
  
   
    
   0
  
                   
 
  ";

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

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

Description:$newsContent is an array of graphics passed into the function from the main file.

C. $newsTplFoot

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

Then the three segments are stitched back to reply to a single text.

Return $header. $body. $footer;

Write the above into a function, named _response_news () function, for the following call to test.

4.4 Test Code

4.4.1 A function file in the main file that replies to text

Require_once ' responseNews.func.inc.php ';

4.4.2 Create an array and pass in

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

$record =array (    ' title ' = ' Shan Tang street ',    ' description ' and ' Shan Tong Street East from Street neighboring character Gate Tang, west to Suzhou Scenic Hill Hill Bridge, long about QI, so the Suzhou proverb said "Qi Li Shan to Huqiu" ... ',    ' 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 go to view

Single text reply test succeeded.

4.6 Multi-text reply

With the above guidance, the reader should be able to think of a reply to multi-text ideas, is the multidimensional array of values in the corresponding position, and then splicing up on it, the following to explain.

4.6.1 get the number of pictures and bars

$bodyCount = count ($newsContent);

4.6.2 Judging the number of graphic strips

Because limit the reply to the number of text messages is 10, so you need to determine the number of graphics and text, if less than 10, then the number of graphics and text is equal to the original text number, if greater than or equal to 10, then the mandatory limit is 10.

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

4.6.3 Organization Chart Style

Graphic and graphic head and the text of the tail and the above single text, no longer repeat, mainly the organization of graphic style.

Use a Foreach loop to iterate through the contents of the array and assign the graphic style and stitching:

foreach ($newsContent as $key = + $value) {    $body. = sprintf ($newsTplBody, $value [' title '], $value [' description '], $value [' Picurl '], $value [' url ']);}

Description:$newsContent is an array of graphics passed into the function from the main file.

4.6.4 Stitching and returning

Return $header. $body. $footer;

Write the above into a function, named _response_multinews () function, for the following call to test.

4.7 Testing Multi-graphic

4.7.1 a function file that replies to multiple texts is introduced in the main file

Require_once ' responseMultiNews.func.inc.php ';

4.7.2 Create a multidimensional array and pass in

$record [0]=array (    ' title ' = ' View Front Street ',    ' description ' = ' s ') ' View Front Street is located in Suzhou City, Jiangsu, is a street in the Qing Dynasty of the Centennial Commercial Street, the streets of the old shop name shop gathered, fame far broadcast 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 is located in the northeast of Suzhou ancient city, is a road along the river, the north of the humble political park, south of the Twin towers, the length of 1606 meters, Suzhou is a history of the classic Water Lane. Song and Yuan Times Suzhou is also known as Pingjiang, with this name road ... ',    ' 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 Testing Multi-text results

Click to go to view

Test multi-text success.

Five, music reply

also provides a message reply format, namely the music reply, below we write the program test.

Note: due to the issue of music copyright, there are now very few reply to the music API, open API query out of the music information is also a lot is not correct. So here we upload some music to our own server space test.

Local Files:

Test to play correctly:

5.1 Music Reply XML Structure

 
 
   
  
   toUser
  
    
  
   fromUser
  
    
  
   
    
   12345678
  
    
  
   music
  
    
  
    
   
    <! [cdata[title]]> 
   
    DESCRIPTION
   
     
   
    MUSIC_Url
   
     
   
    HQ_MUSIC_Url
   
     
  
    
 
  

5.2 Structure Description

5.3 Concrete Implementation

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

5.3.1 inserting the corresponding data at the appropriate location in the XML structure

 
  
  
   <! [Cdata[far away from home]]>
  
   Groove Coverage
  
   
  
   http://thinkshare.duapp.com/music/10001.mp3
  
   
  
   http://thinkshare.duapp.com/music/10001.mp3
  
   
 
  

5.3.2 Test Code

$RESULTSTR = _response_music ($POSTOBJ, $keyword); Echo $resultStr;                    

5.3.3 Test Results

5.4 Analog Song

With the above simple case guide, the reader should be able to think of the specific implementation of the simulation song, the following is a brief introduction.

idea: The song code and the corresponding song name into the database, the user input song name, in the database to find the song name corresponding song number, and then you can generate Musicurl reply users.

5.4.1 Creating a Database

http://www.bkjia.com/PHPjc/743433.html www.bkjia.com true http://www.bkjia.com/PHPjc/743433.html techarticle "PHP Public Platform Development Series" 01. Configure interface 02. Public Platform Sample Code Analysis 03. Subscription events (subscribe) processing 04. Simple reply Function Development 05. Weather Forecast Function ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.