WeChat public Platform Message Interface PHP version development tutorial

Source: Internet
Author: User
Tags cdata sha1
Public platform Message Interface PHP version development tutorial


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:

 Valid ();//$WECHATOBJ->responsemsg (); Class wechatcallbackapitest{Public Function valid () {$echoStr = $_ge        t["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 ' I 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?

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:


 token = $token;    $this->debug = $debug; }
Get 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 ', LIB Xml_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} %s %s "; Return sprintf ($TEXTTPL, $text, $FuncFlag); }
Reply text message according to array parameter public function makenews ($newsData =array ()) {$CreateTime = time (); $FuncFlag = $this->setflag? 1:0; $newTplHeader = " msg[' fromusername ']}]]> msg[' tousername ']}]]> {$CreateTime} news %s %s "; $newTplItem = " <![ Cdata[%s]]> %s %s /picurl> %s "; $newTplFoot = " %s "; $Content = "; $itemsCount = count ($newsData [' Items ']); $itemsCount = $itemsCount < 10? $itemsCount: 10;//Public platform text reply message up to 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 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
}}?>

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:


 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 sent you the message, this $username is encrypted, but each user is one by one corresponding if ($type = = = ' text ') {if ($ weixin->msg[' content ']== ' Hello2bizuser ') {//The first time a user is concerned about your account, your public account will receive a message that reads ' hello2bizuser ' $reply = $weixin-& Gt;maketext (' Welcome to your attention Oh, Dick Silk '); }else{//here is the user input text message $keyword = $weixin->msg[' Content ']; The text message content of the user include_once ("chaxun.php");//The text message invokes the query program $chaxun = new Chaxun (DEBUG, $keyword, $US Ername); $results [' items '] = $chaxun->search ();//The Code of the query $reply = $weixin->makenews ($results); }}elseif ($type = = = ' Location ') {//the user is sending position information later in the article will be processed}elseif ($type = = = ' image ') {//the user is sending a picture slightly After the article will be processed}elseif ($type = = = ' Voice ') {//the user is sending a sound later in the article will be processed} $weixin->reply ($reply); >


Query code

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


 
  Search ($this->keyword);//Common keyword Query database operation  code without sharing the 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 into the form of an array that the return message can receive, that is, title, description, Picurl, url details See official documentation describing                    ' title ' and ' $msg [' title '],                    ' description ' and ' $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.