Php-based WeChat public platform development entry instance and php public platform instance

Source: Internet
Author: User
Tags openid php example

Php-based entry-level public platform development instance and php public platform instance

This article describes the php-based public platform development method. Share it with you for your reference. The details are as follows:

I recently developed a public platform and wrote more than 20 functions in one breath, which is quite interesting ~

Let's share our development experience today ~
The interfaces provided by the public platform are simple. Let's take a look at the message interaction process:

Generally speaking, you can send a message-> send data to a developer-> process a message by a developer and return data to-> send the returned data to the user, during this period, data interaction is completed through XML.
 
Below is an example to develop an intelligent CHATBOT:
 
1. Register a public platform account

Public platform:
Https://mp.weixin.qq.com/

Note: currently, only two accounts can be registered for one ID card. The account name is subject to V authentication. Please register with caution.
 
2. Apply for servers/virtual hosts

BAE and SAE can be used for children's shoes without servers or virtual hosts.
 
3. Enable the developer Mode

The public platform has two modes: The editing mode (the dummies mode), which is simple but has a single function. The other is the developer mode, which can implement complex functions through development. The two modes are mutually exclusive. Obviously, log on to the public platform and enable the developer mode through the "advanced functions" menu.
 
4. Fill in interface configuration information

You also need to configure two parameters in the "advanced functions" menu:
URL: the developer's application access address. Currently, only port 80 is supported. The example is "http://www.yoonper.com/weixin/index.php.
TOKEN: enter it as needed to generate a signature. Take "YoonPer" as an example.
After entering the information, save the following code as index. php and upload it to the http://www.yoonper.com/weixin/directory. Click Submit to complete verification.

<? Phpdefine ("TOKEN", "YoonPer"); // TOKEN value $ wechatObj = new wechat (); $ wechatObj-> valid (); class wechat {public function valid () {$ echoStr = $ _ GET ["echostr"]; if ($ this-> checkSignature () {echo $ echoStr; exit ;}} private function checkSignature () {$ signature = $ _ GET ["signature"]; $ timestamp = $ _ GET ["timestamp"]; $ nonce = $ _ GET ["nonce"]; $ token = TOKEN; $ tmpArr = array ($ token, $ timestamp, $ nonce); sort ($ TmpArr); $ tmpStr = implode ($ tmpArr); $ tmpStr = sha1 ($ tmpStr); if ($ tmpStr ==$ signature) {return true ;} else {return false ;}}}?>

This is what the public platform verifies whether the URL is correctly accessed. The research Code has no substantive significance. After the verification, you can delete the file. This is not detailed. If you are interested, you can view the official documentation.
Public platform API documentation:
Http://mp.weixin.qq.com/wiki/index.php

5. Develop public platform Functions

OK, as mentioned above, the data interaction between the public platform and developers is completed through XML. Since XML is used, the rules must be followed, before proceeding with the development, let's take a look at the XML specifications provided in the official interface documentation. Take text messages as an example:
 
When a user sends a message to a public account, the server will POST some data to the developer:

<Xml> <! -- Developer id --> <ToUserName> <! [CDATA [toUser]> </ToUserName> <! -- Sender account (OpenID) --> <FromUserName> <! [CDATA [fromUser]> </FromUserName> <! -- Creation Time (integer) --> <CreateTime> 12345678 </CreateTime> <! -- Message Type (text MESSAGE) --> <MsgType> <! [CDATA1]> </MsgType> <! -- Message Content --> <Content> <! [CDATA [content]> </Content> <! -- Message ID (64-bit integer) --> <MsgId> 1234567890123456 </MsgId> </xml>

After processing the message, the developer must return the data to the server:

<Xml> <! -- Acceptor account (OpenID) --> <ToUserName> <! [CDATA [toUser]> </ToUserName> <! -- Developer id --> <FromUserName> <! [CDATA [fromUser]> </FromUserName> <! -- Creation Time (integer) --> <CreateTime> 12345678 </CreateTime> <! -- Message Type (text MESSAGE) --> <MsgType> <! [CDATA1]> </MsgType> <! -- Reply to message Content --> <Content> <! [CDATA [content]> </Content> <! -- Star operation (Message received when star is marked as 0x0001) --> <FuncFlag> 0 </FuncFlag> </xml>

In addition to text messages, the public platform also allows users to send image messages, geographic location messages, link messages, and event pushes. developers can also reply music messages and text messages to the public platform, for more information about Message XML specifications, see the official documentation.
 
Let's take a look at an official PHP example. I have made some streamlining:

<? Php/* ------------------------------------------------- | index. php [public platform interface] + response | Author: limyonper + response */$ wechatObj = new wechat (); $ wechatObj-> responseMsg (); class wechat {public function responseMsg () {// ---------- receive data ---------- // $ postStr = $ GLOBALS ["HTTP_RAW_POST_DATA"]; // obtain POST data // parse P with SimpleXML XML data from OST $ postObj = simplexml_load_string ($ postStr, 'simplexmlelement', LIBXML_NOCDATA); $ fromUsername = $ postObj-> FromUserName; // obtain the sender's account (OpenID) $ toUsername = $ postObj-> ToUserName; // get the receiver account $ keyword = trim ($ postObj-> Content); // get the message Content $ time = time (); // obtain the current timestamp // ---------- return data ---------- // return message template $ textTpl = "<xml> <ToUserName> <! [CDATA [% s]> </ToUserName> <FromUserName> <! [CDATA [% s]> </FromUserName> <CreateTime> % s </CreateTime> <MsgType> <! [CDATA [% s]> </MsgType> <Content> <! [CDATA [% s]> </Content> <FuncFlag> 0 </FuncFlag> </xml> "; $ msgType =" text "; // Message Type include ('simsimi. php '); $ contentStr = simsimi ($ keyword); // return the message content // format the message template $ resultStr = sprintf ($ textTpl, $ fromUsername, $ toUsername, $ time, $ msgType, $ contentStr); echo $ resultStr; // output result }?>

Save the code as index. php and upload it to the http://www.yoonper.com/weixin/directory. If the file is not deleted, the file will be directly overwritten.
 
Now users send any message through the public platform the public account returns a message with the content of "http://www.YoonPer.com.
What needs to be done next is to dynamically return results based on user messages ~
 
SimSimi (xiaohuang chicken) is currently a popular chatbot. I used CURL to develop a free SimSimi (xiaohuang chicken) interface, and a text reply will be returned when a keyword is passed in, this part is not the focus of this article, so I will not describe it much. Go directly to the Code (updated on January 28 ):

<? Php/* ------------------------------------------------- | simsimi. php [intelligent chat (simsimi)] + response | Author: limyonper + ------------------------------------------------ */function simsimi ($ keyword) {$ keyword = urlencode ($ keyword ); // ----------- get COOKIE ---------- // $ url = "http://www.simsimi.com/"; $ ch = curl_init ($ url); curl_setopt ($ ch, CURLOPT_HEADER, 1); cur Rochelle setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); $ content = curl_exec ($ ch); list ($ header, $ body) = explode ("\ r \ n", $ content); preg_match_all ("/set \-cookie :( [^ \ r \ n] *); /iU ", $ header, $ matches); $ cookie = implode (';', $ matches [1]). "; simsimi_uid = 1;"; curl_close ($ ch); // ----------- capture back and forth ---------- // $ url = "http://www.simsimi.com/func/reqN? Response "; $ ch = curl_init ($ url); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ ch, CURLOPT_COOKIE, $ cookie ); $ content = json_decode (curl_exec ($ ch), 1); curl_close ($ ch); if ($ content ['result'] = '20140901 ') {return $ content ['sentence _ resp '];} else {return' I will not answer this question yet... ';}}?>

The above two pieces of code are integrated, and the connection will be disconnected if the server fails to receive the response within five seconds. This interface may cause timeout, simSimi has blocked the crawling requests on the BAE and SAES. We recommend that you use the official billing API of SimSimi, which is faster ~

I hope this article will help you develop php-based public platforms.

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.