PHP Docking Micro-trust public platform Message Interface development process Tutorial _php instance

Source: Internet
Author: User
Tags cdata sha1 sprintf

First, write a good interface program

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

Copy Code code as follows:
<?php
Define ("TOKEN", "Weixin");/the TOKEN that you define 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, Dick Silk ';
$RESULTSTR = sprintf ($TEXTTPL, $fromUsername, $toUsername, $time, $msgType, $CONTENTSTR);
Echo $resultStr;
}else{
Echo ' Why not say ha ';
}
}else {
Echo ' Why not say ha ';
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;
}
}
}
?>


Second, configure the micro-trust public platform reply interface


Set up the reply interface, fill in the URL and token (URL to fill the above Http://www.yourdomain.com/weixin.php,token must be in accordance with the above program defined token)



Third, verify the interface

Use your personal micro-letter to pay attention to your public account, send a message to the account in the past, received the original message back, that the validation succeeded.

Iv. Start a custom reply

Comment off $wechatobj->valid (); This line, while removing//$WECHATOBJ->responsemsg (), the comment for this line.
You can modify the code in the RESPONSEMSG function to reply to the user's different content based on the user's message type (' text ', ' image ', ' location ') and message content.
The message interface can be used, send a message to try?

1. Package weixin.class.php

Because the communication of the micro-credit public platform uses the XML data in a particular format, every acceptance and reply is done with a large number of data processing.
Let's consider doing a package on this basis, weixin.class.php, code as follows:

Copy Code code as follows:
<?php
Class Weixin
{
Public $token = ';//token
Public $debug = false;//Whether debug status is marked to facilitate the recording of some intermediate data while debugging
Public $setFlag = false;
Public $msgtype = ' text '; (' text ', ' image ', ' location ')
Public $msg = Array ();

Public function __construct ($token, $debug)
{
$this->token = $token;
$this->debug = $debug;
}
Get messages from users (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 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 a 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;//Public platform text reply message at most 10
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[' Echostr '];
Exit
}
}else{
Write_log (' Authentication failure ');
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 the debugging information please make your own perfect for intermediate debugging
}
}
?>

2. Call weixin.class.php

In the main interface file of your micro-credit public platform (as defined in http://www.yourdomain.com/weixin.php), modify the code to:

Copy Code code as follows:
<?php
Include_once (' weixin.class.php '); reference just-defined micro-mail message processing class
Define ("TOKEN", "Mmhelper");
Define (' DEBUG ', true);
$weixin = new Weixin (token,debug);//instantiated
$weixin->getmsg ();
$type = $weixin->msgtype;//Message type
$username = $weixin->msg[' fromusername '];//which user sent you the message, this $username is after the micro-letter encryption, but each user is one by one corresponding
if ($type = = = ' text ') {
if ($weixin->msg[' content ']== ' Hello2bizuser ') {//micro-trust users first attention to your account, your public account will be a content of the ' hello2bizuser ' message
$reply = $weixin->maketext (' Welcome to your attention Oh, Dick Silk ');
}else{//This is where the user entered the text message
$keyword = $weixin->msg[' Content ']; Text message content for the user
Include_once ("chaxun.php");//Text message invoke query program
$chaxun = new Chaxun (DEBUG, $keyword, $username);
$results [' items '] = $chaxun->search ()//The Code of the query

$reply = $weixin->makenews ($results);
}
}elseif ($type = = = ' Location ') {
The user sends the location information that will be processed later in the article
}elseif ($type = = = ' Image ') {
The user sends a picture later in the article that will be processed
}elseif ($type = = = ' Voice ') {
The user is sending a sound that will be processed later in the article
}
$weixin->reply ($reply);
?>

3. Query code

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

Copy Code code as follows:
<?php
Public Function Search () {
$record =array (); Defines an array of returned results
$list = $this->search ($this->keyword); The operation code of the query database based on the keyword is not to be shared.
if (Is_array ($list) &&!empty ($list)) {
foreach ($list as $msg) {
$record []=array (//below) format the array returned by the query in the database into the array form that the message can receive, namely title, Description, Picurl, URL, as described in the official document of the micro-letter.
' 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.