PHP docking WeChat public Platform message Interface development process Tutorial _php Tutorial

Source: Internet
Author: User
Tags php define sha1
First, write a good interface program

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

Copy CodeThe code is as follows: Define ("token", "Weixin");//The token that you define is the private key of a 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, Dick Silk ';
$RESULTSTR = sprintf ($TEXTTPL, $fromUsername, $toUsername, $time, $msgType, $CONTENTSTR);
Echo $resultStr;
}else{
Echo ' Don't say ha ';
}
}else {
Echo ' Don't 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 public platform reply interface


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



Third, authentication interface

With your own personal attention to your public account, send a message to this account in the past, received the original message back, that the verification was successful.

Iv. starting a custom reply

Comment out $wechatobj->valid (); This line, at the same time remove//$WECHATOBJ->responsemsg (); This line of comments.
You can modify the code inside the RESPONSEMSG function to reply to the user's different content based on the user's message type (' text ', ' image ', ' location ') and the message content.
Message interface can be used, send a message to try it?

1. Package weixin.class.php

Because public platform communication uses XML data in a specific format, every acceptance and reply is done with a lot of data processing.
We'll consider doing this on the basis of a package, weixin.class.php, code as follows:
Copy CodeThe code is as follows: Class Weixin
{
Public $token = ";//token
Public $debug = false;//is the status indicator of debug, which allows us to record 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 = "
{$this->msg[' Fromusername ']}
{$this->msg[' Tousername ']}
{$CreateTime}
1
]>
%s
%s
";
Return sprintf ($TEXTTPL, $text, $FuncFlag);
}
Reply to a text message based on an array parameter
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;//public Platform message reply up to 10 records 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[' Echostr '];
Exit
}
}else{
Write_log (' certification 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) {
This is where you record the debugging information, please refine it for intermediate debugging
}
}
?>

2. Call weixin.class.php

To put your public platform Master interface file (as previously defined in http://www.yourdomain.com/weixin.php), modify the code to:
Copy CodeThe code is as follows: Include_once (' weixin.class.php ');//referencing the newly defined message processing class
Define ("TOKEN", "Mmhelper");
Define (' DEBUG ', true);
$weixin = new Weixin (token,debug);//instantiation
$weixin->getmsg ();
$type = $weixin->msgtype;//Message type
$username = $weixin->msg[' fromusername '];//which user sent you the message, this $username is encrypted, but each user is one by one corresponding
if ($type = = = ' text ') {
if ($weixin->msg[' content ']== ' Hello2bizuser ') {//When the user first pays attention to your account, your public account will be subject to a "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 ']; User's text message content
Include_once ("chaxun.php");//Text message invoke query program
$chaxun = new Chaxun (DEBUG, $keyword, $username);
$results [' items '] = $chaxun->search ();//code for 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 that will be processed later in the article
}elseif ($type = = = ' Voice ') {
The user sends 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 the Code Code as follows: Public function Search () {
$record =array (); Defines an array of returned results
$list = $this->search ($this->keyword);//Common keyword Query database operation code you don't have to share.
if (Is_array ($list) &&!empty ($list)) {
foreach ($list as $msg) {
$record []=array (//The following code, formats the array returned by the query in the database as an array of returned messages to receive, i.e. title, description, Picurl, URL see Official document description
' title ' = $msg [' title '],
' Description ' = $msg [' discription '],
' Picurl ' = $msg [' Pic_url '],
' url ' = = $msg [' URL ']
);
}
}
return $record;
}
?>

http://www.bkjia.com/PHPjc/745823.html www.bkjia.com true http://www.bkjia.com/PHPjc/745823.html techarticle first, write the interface program on your server upload good one interface program files, such as http://www.yourdomain.com/weixin.php content as follows: Copy code code as follows: PHP define ("To ...

  • 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.