微信公眾平台消息接口開發(2)-封裝weixin.class.php


一、封裝weixin.class.php

由於微信公眾平台的通信使用的是特定格式的XML數據,每次接受和回復都要去做一大堆的數據處理。

我們就考慮在這個基礎上做一次封裝,weixin.class.php,代碼如下:

<?php
class Weixin
{
	public $token = '';//token
	public $debug =  false;//是否debug的狀態標示,方便我們在調試的時候記錄一些中間數據
	public $setFlag = false;
	public $msgtype = 'text';	//('text','image','location')
	public $msg = array();

	public function __construct($token,$debug)
	{
		$this->token = $token;
		$this->debug = $debug;
	}
     //獲得用戶發過來的消息(消息內容和消息類型 ) 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']); } }
     //回復文本消息 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[text]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>%s</FuncFlag> </xml>"; return sprintf($textTpl,$text,$FuncFlag); }
     //根據數組參數回復圖文消息 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;//微信公眾平台圖文回復的消息一次最多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('認證失敗'); 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){
       //這里是你記錄調試信息的地方 請自行完善 以便中間調試
    } } ?>

 二、調用weixin.class.php

把你的微信公眾平台主接口文件(如前面定義的http://www.yourdomain.com/weixin.php)中,修改代碼為:

 

include_once('weixin.class.php');//引用剛定義的微信消息處理類
define("TOKEN", "mmhelper");
define('DEBUG', true); $weixin = new Weixin(TOKEN,DEBUG);//實例化 $weixin->getMsg(); $type = $weixin->msgtype;//消息類型 $username = $weixin->msg['FromUserName'];//哪個用戶給你發的消息,這個$username是微信加密之后的,但是每個用戶都是一一對應的 if ($type==='text') { if ($weixin->msg['Content']=='Hello2BizUser') {//微信用戶第一次關注你的賬號的時候,你的公眾賬號就會受到一條內容為'Hello2BizUser'的消息 $reply = $weixin->makeText('歡迎你關注媽媽助手哦,屌絲'); }else{//這里就是用戶輸入了文本信息 $keyword = $weixin->msg['Content']; //用戶的文本消息內容 include_once("chaxun.php");//文本消息 調用查詢程序 $chaxun= new chaxun(DEBUG,$keyword,$username); $results['items'] =$chaxun->search();//查詢的代碼 $reply = $weixin->makeNews($results); } }elseif ($type==='location') { //用戶發送的是位置信息 稍后的文章中會處理 }elseif ($type==='image') { //用戶發送的是圖片 稍后的文章中會處理 }elseif ($type==='voice') { //用戶發送的是聲音 稍后的文章中會處理 } $weixin->reply($reply);

 

 三、查詢代碼

還需要將數據庫里面的查詢結果格式化為特定的形式

 

public function search(){
       $record=array();  //定義返回結果的數組
       $list = $this->search($this->keyword);//普通的根據關鍵詞查詢數據庫的操作  代碼就不用分享了
    if(is_array($list)&&!empty($list)){             	
               foreach($list as $msg){ 
                $record[]=array(//以下代碼,將數據庫中查詢返回的數組格式化為微信返回消息能接收的數組形式,即title、description、picurl、url 詳見微信官方的文檔描述
					'title' =>$msg['title'],
					'description' =>$msg['discription'],
					'picurl' => $msg['pic_url'],
					'url' =>$msg['url']
				);
        }
    }
    return $record;
}

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

承接微信公眾平台消息接口開發、PHP、.NET、javascript、html5程序開發;新浪微博應用、騰訊微博應用等各大開放平台應用開發業務

聯系QQ:1433273389 

關注媽媽助手(賬號mmhelper)方法:

1. 依次進入以下路徑:朋友們—>添加朋友—>搜號碼,輸入mmhelper,不區分大小寫,點擊查找,然后點擊關注。

2. 掃描二維碼:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM