搜尋
首頁後端開發php教程微信公众平台消息接口开发(2)-封装weixin.class.php

一、封装weixin.class.php

由于微信公众平台的通信使用的是特定格式的XML数据,每次接受和回复都要去做一大堆的数据处理。

我们就考虑在这个基础上做一次封装,weixin.class.php,代码如下:

<?phpclass 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. 扫描二维码:

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何檢查PHP會話是否已經開始?如何檢查PHP會話是否已經開始?Apr 30, 2025 am 12:20 AM

在PHP中,可以使用session_status()或session_id()來檢查會話是否已啟動。 1)使用session_status()函數,如果返回PHP_SESSION_ACTIVE,則會話已啟動。 2)使用session_id()函數,如果返回非空字符串,則會話已啟動。這兩種方法都能有效地檢查會話狀態,選擇使用哪種方法取決於PHP版本和個人偏好。

描述一個場景,其中使用會話在Web應用程序中至關重要。描述一個場景,其中使用會話在Web應用程序中至關重要。Apr 30, 2025 am 12:16 AM

sessionsarevitalinwebapplications,尤其是在commercePlatform之前。

如何管理PHP中的並發會話訪問?如何管理PHP中的並發會話訪問?Apr 30, 2025 am 12:11 AM

在PHP中管理並發會話訪問可以通過以下方法:1.使用數據庫存儲會話數據,2.採用Redis或Memcached,3.實施會話鎖定策略。這些方法有助於確保數據一致性和提高並發性能。

使用PHP會話的局限性是什麼?使用PHP會話的局限性是什麼?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

解釋負載平衡如何影響會話管理以及如何解決。解釋負載平衡如何影響會話管理以及如何解決。Apr 29, 2025 am 12:42 AM

負載均衡會影響會話管理,但可以通過會話複製、會話粘性和集中式會話存儲解決。 1.會話複製在服務器間複製會話數據。 2.會話粘性將用戶請求定向到同一服務器。 3.集中式會話存儲使用獨立服務器如Redis存儲會話數據,確保數據共享。

說明會話鎖定的概念。說明會話鎖定的概念。Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

有其他PHP會議的選擇嗎?有其他PHP會議的選擇嗎?Apr 29, 2025 am 12:36 AM

PHP會話的替代方案包括Cookies、Token-basedAuthentication、Database-basedSessions和Redis/Memcached。 1.Cookies通過在客戶端存儲數據來管理會話,簡單但安全性低。 2.Token-basedAuthentication使用令牌驗證用戶,安全性高但需額外邏輯。 3.Database-basedSessions將數據存儲在數據庫中,擴展性好但可能影響性能。 4.Redis/Memcached使用分佈式緩存提高性能和擴展性,但需額外配

在PHP的上下文中定義'會話劫持”一詞。在PHP的上下文中定義'會話劫持”一詞。Apr 29, 2025 am 12:33 AM

Sessionhijacking是指攻擊者通過獲取用戶的sessionID來冒充用戶。防範方法包括:1)使用HTTPS加密通信;2)驗證sessionID的來源;3)使用安全的sessionID生成算法;4)定期更新sessionID。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!