search
HomeBackend DevelopmentPHP Tutorial微信公众平台消息接口开发(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. 扫描二维码:

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.