Simulate and test the WeChat interface and Wechat development test code

Source: Internet
Author: User

To become a public number (subscription number or service number) developer, You need to first verify the interface, this can be set after logging on to the https://mp.weixin.qq.com background. But I am too troublesome, So I developed an interface class, including the verification function (as well as the function of replying text information and text information ). In fact, Interface Verification is useless after becoming a developer.
On the code, the base class: weixin. class. php
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 );
$ 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 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.
}
}
?>

Interface code: weixin. php
Header ("Content-Type: text/html; charset = UTF-8 ");
Include_once ('weixin. class. php'); // reference the newly defined message processing class
Define ("TOKEN", "itwatch"); // mmhelper
Define ('debug', false );
$ Weixin = new Weixin (TOKEN, DEBUG); // instantiate
// $ Weixin-> valid ();
$ 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 ')
If ($ weixin-> msg ['content'] = '')
{// When the user pays attention to your account for the first time, your public account will receive a message with the content 'hello2bizuser '.
$ Reply = $ weixin-> makeText ('Welcome to the mesh view prestige public platform ');
}
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 );
$ ArrayCon = array (
Array (
"Title" => "Computer Learning Network ",
"Description" => "100,000 why-Computer Learning Network ",
"PicUrl" => "http://www.veryphp.cn/datas/userfiles/8bd108c8a01a892d129c52484ef97a0d/images/website13.jpg ",
"Url" => "http://www.why100000.com /"
),
Array (
"Title" => "very PHP Learning Network ",
"Description" => "Large PHP learning sharing community ",
"PicUrl" => "http://www.veryphp.cn/datas/userfiles/8bd108c8a01a892d129c52484ef97a0d/images/php01.jpg ",
"Url" => "http://www.veryphp.cn /"
)
);
$ Results = $ arrayCon;
$ Reply = $ weixin-> makeNews ($ results );
}
}
Elseif ($ type = 'location ')
{
// The user sends location information for later processing.
}
Elseif ($ type = 'image ')
{
// The user sends an image for processing.
} Elseif ($ type = 'voice ')
{
// The user sends the voice for processing.
}
//
$ Weixin-> reply ($ reply );
?>

The code of the verification interface is completed using the curl function. You need to enable the curl extension of PHP. Remove the comments in the/$ weixin-> valid (); statement in the weixin. php file for verification. After that, comment out the sentence.






// Header ("Content-Type: text/html; charset = UTF-8 ");
// Prepare data
Define ('Token', 'itwatch '); // The Custom TOKEN is the private key of the communication.
$ Echostr = 'the returned data indicates that it is correct. ';
$ Timestamp = (string) time (); // itself is an integer and must be converted to a string
$ Nonce = 'my-nonce ';
$ Signature = signature (TOKEN, $ timestamp, $ nonce );


Function signature ($ token, $ timestamp, $ nonce)
{
$ TmpArr = array ($ token, $ timestamp, $ nonce );
Sort ($ tmpArr );
$ TmpStr = implode ($ tmpArr );
$ TmpStr = sha1 ($ tmpStr );
Return $ tmpStr;
}
// Submit
$ Post_data = array (
"Signature = $ signature ",
"Timestamp = $ timestamp ",
"Nonce = $ nonce ",
"Echostr = $ echostr"
);
$ Post_data = implode ('&', $ post_data );
$ Url = 'HTTP: // www.veryphp.cn/tools/weixin/weixin.php ';
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url .'? '. $ Post_data); // simulate the GET Method
Ob_start ();
Curl_exec ($ ch );
$ Result = ob_get_contents ();
Ob_end_clean ();
Echo $ result;
?>

The above core code is the weixin. class. php and weixin. php files, which were successfully debugged and deployed on my server. If you want to test it, use the phone number itwatch and enter "hello" to return a string: Welcome to the public platform of mesh view prestige. Enter a text message.

Okay, I admit that the above code is very messy, because I am very sleepy and want to go to bed. But the above Code does work. It is a typical principle implementation test code. I hope to provide developers with an idea. After understanding it, I can write a fully functional information background management program in combination with the database ..
If there is a service number, you can develop a menu on this basis, and then call the message reply system developed based on the above Code. It is actually very simple.
This is a real network communication program. It is much more interesting than writing data to an enterprise site, inputting data, and then retrieving the data by page in order.

Mesh-Zhang Qing
2013-12-3?

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.