WeChat public platform Message Interface PHP Development Tutorial

Source: Internet
Author: User
This series of tutorials uses the mom assistant on the public platform (account mmhelper: send the food name or the first letter of the alphabet to query which foods can be eaten by pregnant women, confinement, and babies. Send your own location to query nearby maternal and child businesses, as well as promotions, group purchases, and other information. Send photos with the baby and test with the baby

This series of tutorials uses the mom assistant on the public platform (account mmhelper: send the food name or the first letter of the alphabet to query which foods can be eaten by pregnant women, confinement, and babies. Send your own location to query nearby maternal and child businesses, as well as promotions, group purchases, and other information. Sending a photo with the baby to test the similarity with the baby's face) as an example to explain the interface development process. You are welcome to pay attention to this account. the QR code is shown in the bottom figure.

Prerequisites: you have an HTTP server host space on the Internet and the permission to create directories and upload files. We recommend Sina's SAE. Http://sae.sina.com.cn/

First, please register the account of the public platform, registration address: http://mp.weixin.qq.com/

This tutorial mainly describes the interface development process.

The official documentation is very concise: http://mp.weixin.qq.com/cgi-bin/indexpage? T = wxm-callbackapi-doc & lang = zh_CN

The case code cannot run. I did some research and finally got it done. The method is as follows:

1. write the interface program

Upload an interface file on your server, such as the http://www.yourdomain.com/weixin.php content as follows:

Valid (); // $ wechatObj-> responseMsg (); class wechatCallbackapiTest {public function valid () {$ echoStr = $ _ GET ["echostr"]; if ($ this-> checkSignature () {echo $ echoStr; exit ;}} public function responseMsg () {$ postStr = $ GLOBALS ["HTTP_RAW_POST_DATA"]; if (! Empty ($ postStr) {$ postObj = simplexml_load_string ($ postStr, 'simplexmlelement', LIBXML_NOCDATA); $ fromUsername = $ postObj-> FromUserName; $ toUsername = $ postObj-> ToUserName; $ keyword = trim ($ postObj-> Content); $ time = time (); $ textTpl =" %s %s % S %s %s 0 "; If (! Empty ($ keyword) {$ msgType = "text"; $ contentStr = 'Hello, diaosi'; $ resultStr = sprintf ($ textTpl, $ fromUsername, $ toUsername, $ time, $ msgType, $ contentStr); echo $ resultStr;} else {echo 'do not say haha';} else {echo 'do not say hahaha'; exit ;}} private function checkSignature () {$ signature =$ _ GET ["signature"]; $ timestamp =$ _ GET ["timestamp"]; $ nonce = $ _ GET ["nonce"]; $ token = TOKEN; $ tmpArr = array ($ token, $ timestamp, $ nonce); sort ($ tmp Arr); $ tmpStr = implode ($ tmpArr); $ tmpStr = sha1 ($ tmpStr); if ($ tmpStr = $ signature) {return true ;} else {return false ;}}}?>

2. configure the public platform reply interface

Set the reply interface and fill in the URL and Token (the url is filled with http://www.yourdomain.com/weixin.php, and the tokenization is consistent with the tokenization defined in the program)

III. verification interface

Use your personal attention to your public account, send a message to this account, and receive the original message, that is, the verification is successful.

4. start custom Reply

Comment out the $ wechatObj-> valid (); line, and remove the // $ wechatObj-> responseMsg (); line comment.

You can modify the code in the responseMsg function to reply different content to the user based on the user's message type ('text', 'Image', 'location') and message content.

The message interface can be used. try sending a message?

Encapsulate weixin. class. php

Because the communication on the public platform uses XML data in a specific format, a lot of data processing is required for each acceptance and reply.
We will consider doing an encapsulation on this basis, weixin. class. php, the code is as follows:

Class Weixin
{
Public $ token = ''; // token
Public $ debug = false; // indicates whether to debug the status, so that we can record some intermediate data during debugging.
Public $ setFlag = false;
Public $ msgtype = 'text'; // ('text', 'Image', 'location ')
Public $ msg = array ();

Public function _ construct ($ token, $ debug)
{
$ This-> token = $ token;
$ This-> debug = $ debug;
}
// Obtain the message sent by the user (message content and message type)
Public function getMsg ()
{
$ PostStr = $ GLOBALS ["HTTP_RAW_POST_DATA"];
If ($ this-> debug ){
$ This-> write_log ($ postStr );
}
If (! Empty ($ postStr )){
$ This-> msg = (array) simplexml_load_string ($ postStr, 'simplexmlelement', LIBXML_NOCDATA );
$ This-> msgtype = strtolower ($ this-> msg ['msgtype']);
}
}
// Reply to text message
Public function makeText ($ text = '')
{
$ CreateTime = time ();
$ FuncFlag = $ this-> setFlag? 1: 0;
$ TextTpl ="
{$this->msg['FromUserName']}
{$this->msg['ToUserName']}
{$ CreateTime}
text
%s
% S
";
Return sprintf ($ textTpl, $ text, $ FuncFlag );
}
// Reply to text message based on array parameters
Public function makeNews ($ newsData = array ())
{
$ CreateTime = time ();
$ FuncFlag = $ this-> setFlag? 1: 0;
$ NewTplHeader ="
{$this->msg['FromUserName']}
{$this->msg['ToUserName']}
{$ CreateTime}
news
%s
% S";
$ NewTplItem ="
<! [CDATA [% s]>
%s
%s
%s
";
$ NewTplFoot ="
% S
";
$ Content = '';
$ ItemsCount = count ($ newsData ['items ']);
$ ItemsCount = $ itemsCount <10? $ ItemsCount: 10; // A maximum of 10 messages can be replied to by text on the public platform at a time.
If ($ itemsCount ){
Foreach ($ newsData ['items '] as $ key => $ item ){
If ($ key <= 9 ){
$ Content. = sprintf ($ newTplItem, $ item ['title'], $ item ['description'], $ item ['picurl'], $ item ['URL']);
}
}
}
$ Header = sprintf ($ newTplHeader, $ newsData ['content'], $ itemsCount );
$ Footer = sprintf ($ newTplFoot, $ FuncFlag );
Return $ header. $ Content. $ footer;
}
Public function reply ($ data)
{
If ($ this-> debug ){
$ This-> write_log ($ data );
}
Echo $ data;
}
Public function valid ()
{
If ($ this-> checkSignature ()){
If ($ _ SERVER ['request _ method'] = 'get ')
{
Echo $ _ GET ['echo str'];
Exit;
}
} Else {
Write_log ('authentication failed ');
Exit;
}
}
Private function checkSignature ()
{
$ Signature = $ _ GET ["signature"];
$ Timestamp = $ _ GET ["timestamp"];
$ Nonce = $ _ GET ["nonce"];

$ TmpArr = array ($ this-> token, $ timestamp, $ nonce );
Sort ($ tmpArr );
$ TmpStr = implode ($ tmpArr );
$ TmpStr = sha1 ($ tmpStr );

If ($ tmpStr = $ signature ){
Return true;
} Else {
Return false;
}
}
Private function write_log ($ log ){
// Here is where you record debugging information. please complete the information for intermediate debugging.
}
}
?>

Call weixin. class. php

In your public platform main interface file (such as the http://www.yourdomain.com/weixin.php defined above), modify the code:

Include_once ('weixin. class. php'); // reference the newly defined message processing class
Define ("TOKEN", "mmhelper ");
Define ('debug', true );
$ Weixin = new Weixin (TOKEN, DEBUG); // instantiate
$ Weixin-> getMsg ();
$ Type = $ weixin-> msgtype; // message type
$ Username = $ weixin-> msg ['fromusername']; // The message sent to you by the user. The $ username is encrypted, but each user corresponds to one message.
If ($ type = 'text '){
If ($ weixin-> msg ['content'] = 'hello2bizuser') {// when the user first follows your account, your public account will receive a message containing 'hello2bizuser '.
$ Reply = $ weixin-> makeText ('welcome to pay attention to your mom's assistant, diaosi ');
} Else {// Here is the text entered by the user
$ Keyword = $ weixin-> msg ['content']; // The text message Content of the user.
Include_once ("chaxun. php"); // call the query program for text messages
$ Chaxun = new chaxun (DEBUG, $ keyword, $ username );
$ Results ['items '] = $ chaxun-> search (); // query code

$ Reply = $ weixin-> makeNews ($ results );
}
} Elseif ($ type = 'location '){
// The user sends location information which will be processed later in the article
} Elseif ($ type = 'image '){
// The user sends an image that will be processed in a later article.
} Elseif ($ type = 'Voice '){
// The user sends a message indicating that the voice will be processed in a later article.
}
$ Weixin-> reply ($ reply );

?>

Query code

You also need to format the query results in the database into a specific form.

Public function search (){
$ Record = array (); // defines the array of returned results
$ List = $ this-> search ($ this-> keyword); // You do not need to share the common operation code for querying databases based on keywords.
If (is_array ($ list )&&! Empty ($ list )){
Foreach ($ list as $ msg ){
$ Record [] = array (// the following code formats the array returned by queries in the database into an array that can be received by the returned message, for title, description, picurl, and url, see the official document description.
'Title' => $ msg ['title'],
'Description' => $ msg ['discription '],
'Picurl' => $ msg ['Pic _ url'],
'URL' => $ msg ['URL']
);
}
}
Return $ record;
}

?>

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.