PHP WeChat development interface message code parsing

Source: Internet
Author: User
Tags php define
1. Write the interface program and upload an interface program file on your server as follows :? Phpdefine (TOKEN, weixin); the defined token is the private key for communication $ wechatObjnewwechatCallbackapiTest (); $ wechatObj-valid (); $ wechatObj-responseMsg (); classwechatCallbackapiTest {

1. Write the interface program and upload an interface program file on your server as follows :? Php define (TOKEN, weixin); // The Custom token is the private key of the communication. $ wechatObj = newwechatCallbackapiTest (); $ wechatObj-valid (); // $ wechatObj-responseMsg (); classwechatCallbackapiTest {

1. Write the interface program

Upload an interface program file on your server with the following content:

Define ("TOKEN", "weixin"); // The Custom token is the private key of the communication.

$ WechatObj = new wechatCallbackapiTest ();

$ WechatObj-> 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 .;

$ ResultStr = sprintf ($ textTpl, $ fromUsername, $ toUsername, $ time, $ msgType, $ contentStr );

Echo $ resultStr;

} Else {

Echo 'let's talk ';

}

} Else {

Echo 'let's talk ';

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;

}

}

}

?>

2. Configure the public platform reply Interface

Set the reply interface and fill in the URL and Token (the token must be consistent with the Token defined in the above 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?

The code for encapsulating weixin. class. php is as follows:

Token = $ token; $ this-> debug = $ debug ;}
// Obtain the user-sent message (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 the 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 the 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 if ($ itemsCount) {foreach ($ newsData ['items '] as $ key => $ item) messages can be replied to by text on the public platform at a time) {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 ['echostr']; 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']; // which user sends the message to you? The $ username is encrypted, however, each user corresponds to an if ($ type = 'text') {if ($ weixin-> msg ['content'] = 'hello2bizuser ') {// when the user first follows your account, your public account will receive a message with the content 'hello2bizuser' $ reply = $ weixin-> makeText ('Welcome to the micro-market navigation ');} else {// here is the text information you have entered $ keyword = $ weixin-> msg ['content']; // your text message Content include_once ("chaxun. php "); // query program for calling text messages $ chaxun = new chaxun (DEBUG, $ keyword, $ username ); $ results ['items '] = $ chaxun-> search (); // query code $ reply = $ weixin-> makeNews ($ results );}} elseif ($ type = 'location') {// The user sends the location information which will be processed later in the article} elseif ($ type = 'image ') {// The user sends an image that will be processed later in the 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 if (is_array ($ list )&&! Empty ($ list) {foreach ($ list as $ msg) {$ record [] = array (// the following code, format 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 ;}

?>

Go to the micro-market navigation and submit your public account

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.