search
HomeBackend DevelopmentPHP Tutorial微信公众平台-发送被动响应消息-PHP示范

微信公众平台-发送被动响应消息-PHP示例

<?php $testObj = new Test();if(!empty($_GET['echostr'])){		$testObj->valid();	}else{		$testObj->responseMsg();}exit;class Test{	/**	 * 绑定url、token信息	 */	public function valid(){        $echoStr = $_GET["echostr"];        if ($this->checkSignature()) { 			echo $echoStr;        } 		exit();    }    /**     * 检查签名,确保请求是从微信发过来的     */	private function checkSignature()	{        $signature = $_GET["signature"];        $timestamp = $_GET["timestamp"];        $nonce = $_GET["nonce"];	        				$token = "test123";//与在微信配置的token一致,不可泄露		$tmpArr = array($token, $timestamp, $nonce);		sort($tmpArr);		$tmpStr = implode( $tmpArr );		$tmpStr = sha1( $tmpStr );				if( $tmpStr == $signature ){			return true;		}else{			return false;		}	}    /**     * 接收消息,并自动发送响应信息     */    public function responseMsg(){    	    	//验证签名    	if ($this->checkSignature()){	    	$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];			$this->log_request_info();		      	//提取post数据			if (!empty($postStr)){	              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);	                $fromUsername = $postObj->FromUserName;//发送人	                $toUsername = $postObj->ToUserName;//接收人	                $MsgType = $postObj->MsgType;//消息类型	                $MsgId = $postObj->MsgId;//消息id	                $time = time();//当前时间做为回复时间	                	                //如果是文本消息(表情属于文本信息)	                if($MsgType == 'text'){		                $content = trim($postObj->Content);//消息内容						if(!empty( $content )){														//如果文本内容是图文,则回复图文信息,否则回复文本信息		                	if($content == "图文"){			                				                	//回复图文消息,ArticleCount图文消息个数,多条图文消息信息,默认第一个item为大图			                	$ArticleCount = 2; 			                	$newsTpl = "<xml>								<tousername></tousername>								<fromusername></fromusername>								<createtime>%s</createtime>								<msgtype></msgtype>								<articlecount>%s</articlecount>								<articles>								<item>								<title></title> 								<description></description>								<picurl></picurl>								<url></url>								</item>								<item>								<title></title>								<description></description>								<picurl></picurl>								<url></url>								</item>								</articles>								</xml>";			                	$resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, 'news', 			                				$ArticleCount,'我是图文信息','我是描述信息','http://www.test.com/DocCenterService/image?photo_id=236',			                				'http://www.test.com','爱城市网正式开通上线','描述2','http://jn.test.com/ac/skins/img/upload/img/20131116/48171384568991509.png',			                				'http://www.test.com');				                echo $resultStr;			                 	$this->log($resultStr);		                	}else{		                		//回复文本信息				                $textTpl = "<xml>											<tousername></tousername>											<fromusername></fromusername>											<createtime>%s</createtime>											<msgtype></msgtype>											<content></content>											<funcflag>0</funcflag>											</xml>";             			                	$contentStr = '你发送的信息是:接收人:'.$toUsername.',发送人:'.$fromUsername.',消息类型:'.$MsgType.',消息内容:'.$content.' www.icity365.com';			                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);			                	echo $resultStr;			                	$this->log($resultStr);		                	}		                }else{		                	echo "Input something...";		                	$this->log($resultStr);		                }	                			              //如果是图片消息	                }elseif ($MsgType == 'image'){			            $MediaId = $postObj->MediaId;//图片消息媒体id,可以调用多媒体文件下载接口拉取数据。			            $imageTpl = "<xml>									<tousername></tousername>									<fromusername></fromusername>									<createtime>%s</createtime>									<msgtype></msgtype>									<image>									<mediaid></mediaid>									</image>									</xml>";	                	$resultStr = sprintf($imageTpl, $fromUsername, $toUsername, $time, $MsgType, $MediaId);	                	echo $resultStr;			            $this->log("自动响应图片信息");	                	$this->log($resultStr);	                		                //如果是视频	                }else if($MsgType == 'video'){	                	$MediaId = $postObj->MediaId;//视频消息媒体id,可以调用多媒体文件下载接口拉取数据。	                	$ThumbMediaId = $postObj->ThumbMediaId;//视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。 						$videoTpl = "<xml>									<tousername></tousername>									<fromusername></fromusername>									<createtime>%s</createtime>									<msgtype></msgtype>									<video>									<mediaid></mediaid>									<thumbmediaid></thumbmediaid>									<title></title>									<description></description>									</video> 									</xml>";						$resultStr = sprintf($videoTpl, $fromUsername, $toUsername, $time, $MsgType, $MediaId,$ThumbMediaId,'我是标题','我是描述');	                	echo $resultStr;			            $this->log("自动响应视频信息".$ThumbMediaId);	                	$this->log($resultStr);	                		                //如果是地理位置	                }else if($MsgType == 'location'){	                	$Location_X = $postObj->Location_X;//维度	                	$Location_Y = $postObj->Location_Y;//经度	                	$Scale = $postObj->Scale;//地图缩放大小	                	$Label = $postObj->Label;//地里位置信息	                		                	//回复文本信息		                $textTpl = "<xml>									<tousername></tousername>									<fromusername></fromusername>									<createtime>%s</createtime>									<msgtype></msgtype>									<content></content>									<funcflag>0</funcflag>									</xml>";             	              		$msgType = "text";	                	$contentStr = '经度:'.$Location_Y.',维度:'.$Location_X.',地图缩放大小'.$Scale.',地理位置信息:'.$Label;	                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);	                	echo $resultStr;	                	$this->log($resultStr);	                		                //如果是事件	                }else if($MsgType == 'event'){	                		                	$Event = $postObj->Event;	                		                	//subscribe(关注,也叫订阅)	                	if($Event == 'subscribe'){	                			                		$EventKey = $postObj->EventKey;//事件KEY值,qrscene_为前缀,后面为二维码的参数值	                			                		//未关注时,扫描二维码	                		if(!empty($EventKey)){	                			$Ticket = $postObj->Ticket;//二维码的ticket,可用来换取二维码图片		                		$this->log($fromUsername.'扫描二维码关注!EventKey='.$EventKey.',Ticket='.$Ticket);	                		}else{	                			$this->log($fromUsername.'关注我了!');	                		}	                			                	//unsubscribe(取消关注)	                	}elseif ($Event == 'unsubscribe'){	                		$this->log($fromUsername.'取消关注我了!');	                			                	//已关注时,扫描二维码事件	                	}elseif($Event == 'SCAN' || $Event == 'scan'){	                		$EventKey = $postObj->EventKey;//事件KEY值,是一个32位无符号整数,即创建二维码时的二维码scene_id                			$Ticket = $postObj->Ticket;//二维码的ticket,可用来换取二维码图片	                		$this->log($fromUsername.'关注我了!EventKey='.$EventKey.',Ticket='.$Ticket);	                		                	//菜单点击事件	                	}elseif($Event == 'CLICK'){	                		$EventKey = $postObj->EventKey;//事件KEY值,与自定义菜单接口中KEY值对应	                		//回复文本信息			                $textTpl = "<xml>										<tousername></tousername>										<fromusername></fromusername>										<createtime>%s</createtime>										<msgtype></msgtype>										<content></content>										<funcflag>0</funcflag>										</xml>";             		                	$contentStr = '你点击了菜单,菜单项key='.$EventKey;		                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);		                	echo $resultStr;		                	$this->log($resultStr);		                //其他事件类型	                	}else{	                		$this->log('事件类型:'.$Event);	                	}	                		                //其他消息类型,链接、语音等	                }else{	                	//回复文本信息		                $textTpl = "<xml>									<tousername></tousername>									<fromusername></fromusername>									<createtime>%s</createtime>									<msgtype></msgtype>									<content></content>									<funcflag>0</funcflag>									</xml>";             	                	$contentStr = '消息类型:'.$MsgType.'我们还没做处理。。。。【爱城市网】';	                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);	                	echo $resultStr;	                	$this->log($resultStr);	                }		        }else {	        	echo "";	        	exit;	        }    	}else{			    $this->log("验证签名未通过!");		    	}    }    /**     * 记录请求信息     */    function log_request_info() {    	$post = '';    	foreach($_POST   as   $key   =>   $value)   { 			$post = $post.$key.' : '.$value.' , '; 		} 		$get = '';    	foreach($_GET   as   $key   =>   $value)   { 			$get = $get.$key.' : '.$value.' , '; 		} 		$this->log("get信息:".$get);		$this->log("post信息:".$post);    }    /**     * 记录日志     * @param $str     * @param $mode     */    function log($str){    	$mode='a';//追加方式写    	$file = "log.txt";	    $oldmask = @umask(0);	    $fp = @fopen($file,$mode);	    @flock($fp, 3);	    if(!$fp)	    {	        Return false;	    }	    else	    {	        @fwrite($fp,$str);	        @fclose($fp);	        @umask($oldmask);	        Return true;	    }	} }?>

?

更多信息查看:http://mp.weixin.qq.com/wiki/index.php?title=发送被动响应消息

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software