PHP connection to WeChat public platform message interface development process tutorial

Source: Internet
Author: User

1. Write the interface program

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

Copy codeThe Code is as follows: <? Php
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 = "<xml>
<ToUserName> <! [CDATA [% s]> </ToUserName>
<FromUserName> <! [CDATA [% s]> </FromUserName>
<CreateTime> % s </CreateTime>
<MsgType> <! [CDATA [% s]> </MsgType>
<Content> <! [CDATA [% s]> </Content>
<FuncFlag> 0 <FuncFlag>
</Xml> ";
If (! Empty ($ keyword ))
{
$ MsgType = "text ";
$ ContentStr = 'hello, diaosi ';
$ ResultStr = sprintf ($ textTpl, $ fromUsername, $ toUsername, $ time, $ msgType, $ contentStr );
Echo $ resultStr;
} Else {
Echo 'didn't you say that ';
}
} Else {
Echo 'didn't you say that ';
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 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?

1. 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:
Copy codeThe Code is as follows: <? 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 = "<xml>
<ToUserName> <! [CDATA [{$ this-> msg ['fromusername']}]> </ToUserName>
<FromUserName> <! [CDATA [{$ this-> msg ['tousername']}]> </FromUserName>
<CreateTime >{$ CreateTime} </CreateTime>
<MsgType> <! [CDATA
1
]> </MsgType>
<Content> <! [CDATA [% s]> </Content>
<FuncFlag> % s </FuncFlag>
</Xml> ";
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 = "<xml>
<ToUserName> <! [CDATA [{$ this-> msg ['fromusername']}]> </ToUserName>
<FromUserName> <! [CDATA [{$ this-> msg ['tousername']}]> </FromUserName>
<CreateTime >{$ CreateTime} </CreateTime>
<MsgType> <! [CDATA [news]> </MsgType>
<Content> <! [CDATA [% s]> </Content>
<ArticleCount> % s </ArticleCount> <Articles> ";
$ NewTplItem = "<item>
<Title> <! [CDATA [% s]> </Title>
<Description> <! [CDATA [% s]> </Description>
<PicUrl> <! [CDATA [% s]> </PicUrl>
<Url> <! [CDATA [% s]> </Url>
</Item> ";
$ NewTplFoot = "</Articles>
<FuncFlag> % s </FuncFlag>
</Xml> ";
$ 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.
}
}
?>

2. 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:
Copy codeThe Code is as follows: <? Php
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 your attention, 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 );
?>

3. query code

You also need to format the query results in the database into a specific form.
Copy codeThe Code is as follows: <? Php
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.