


Detailed explanation and examples of the development process of PHP docking WeChat public platform message interface
May 15, 2018 pm 02:59 PMThis article mainly introduces the development process of PHP docking WeChat public platform message interface, how to use the PHP version of the interface to operate public platform messages, friends in need can refer to the following
1. Write the interface program
Upload an interface program file on your server with the following content:
The code is as follows:
<?php define("TOKEN", "weixin");//自己定義的token 就是個(gè)通信的私鑰 $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 = '你好啊,屌絲'; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else{ echo '咋不說哈呢'; } }else { echo '咋不說哈呢'; 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 WeChat public platform reply interface
Set the reply interface, fill in the URL and Token (the URL is filled in http://www.yourdomain.com/weixin.php above, and the token must be consistent with the Token defined in the above program)
3. Verification interface
Use your personal WeChat to follow your public account, send a message to this account, and receive the original message The message is returned, indicating that the verification was successful.
4. Start custom reply
Comment out the line $wechatObj->valid(); and remove //$wechatObj->responseMsg() ;Comments for this line.
You can modify the code in the responseMsg function to reply to the user with different content based on the user's message type ('text', 'image', 'location') and message content.
The message interface is ready for use. Let’s try sending a message?
1. Encapsulate weixin.class.php
Since the communication on the WeChat public platform uses XML data in a specific format, it must be done every time it is accepted and replied A lot of data processing.
We will consider making an encapsulation on this basis, weixin.class.php, the code is as follows:
The code is as follows:
<?php class Weixin { public $token = '';//token public $debug = false;//是否debug的狀態(tài)標(biāo)示,方便我們?cè)谡{(diào)試的時(shí)候記錄一些中間數(shù)據(jù) public $setFlag = false; public $msgtype = 'text'; //('text','image','location') public $msg = array(); public function __construct($token,$debug) { $this->token = $token; $this->debug = $debug; } //獲得用戶發(fā)過來的消息(消息內(nèi)容和消息類型 ) 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']); } } //回復(fù)文本消息 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); } //根據(jù)數(shù)組參數(shù)回復(fù)圖文消息 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;//微信公眾平臺(tái)圖文回復(fù)的消息一次最多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('認(rèn)證失敗'); 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){ //這里是你記錄調(diào)試信息的地方 請(qǐng)自行完善 以便中間調(diào)試 } } ?>
2. Call weixin. class.php
Put your WeChat public platform main interface file and modify the code to:
The code is as follows:
<?php include_once('weixin.class.php');//引用剛定義的微信消息處理類 define("TOKEN", "mmhelper"); define('DEBUG', true); $weixin = new Weixin(TOKEN,DEBUG);//實(shí)例化 $weixin->getMsg(); $type = $weixin->msgtype;//消息類型 $username = $weixin->msg['FromUserName'];//哪個(gè)用戶給你發(fā)的消息,這個(gè)$username是微信加密之后的,但是每個(gè)用戶都是一一對(duì)應(yīng)的 if ($type==='text') { if ($weixin->msg['Content']=='Hello2BizUser') {//微信用戶第一次關(guān)注你的賬號(hào)的時(shí)候,你的公眾賬號(hào)就會(huì)受到一條內(nèi)容為'Hello2BizUser'的消息 $reply = $weixin->makeText('歡迎你關(guān)注哦,屌絲'); }else{//這里就是用戶輸入了文本信息 $keyword = $weixin->msg['Content']; //用戶的文本消息內(nèi)容 include_once("chaxun.php");//文本消息 調(diào)用查詢程序 $chaxun= new chaxun(DEBUG,$keyword,$username); $results['items'] =$chaxun->search();//查詢的代碼 $reply = $weixin->makeNews($results); } }elseif ($type==='location') { //用戶發(fā)送的是位置信息 稍后的文章中會(huì)處理 }elseif ($type==='image') { //用戶發(fā)送的是圖片 稍后的文章中會(huì)處理 }elseif ($type==='voice') { //用戶發(fā)送的是聲音 稍后的文章中會(huì)處理 } $weixin->reply($reply); ?>
3 .Query code
You also need to format the query results in the database into a specific form
The code is as follows:
<?php public function search(){ $record=array(); //定義返回結(jié)果的數(shù)組 $list = $this->search($this->keyword);//普通的根據(jù)關(guān)鍵詞查詢數(shù)據(jù)庫的操作 代碼就不用分享了 if(is_array($list)&&!empty($list)){ foreach($list as $msg){ $record[]=array(//以下代碼,將數(shù)據(jù)庫中查詢返回的數(shù)組格式化為微信返回消息能接收的數(shù)組形式,即title、description、picurl、url 詳見微信官方的文檔描述 'title' =>$msg['title'], 'description' =>$msg['discription'], 'picurl' => $msg['pic_url'], 'url' =>$msg['url'] ); } } return $record; } ?>
The above is the detailed content of Detailed explanation and examples of the development process of PHP docking WeChat public platform message interface. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
