찾다
백엔드 개발PHP 튜토리얼微信公众平台-发送被动响应消息-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=发送被动响应消息

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
세션을 저장하기 위해 데이터베이스를 사용하면 어떤 장점이 있습니까?세션을 저장하기 위해 데이터베이스를 사용하면 어떤 장점이 있습니까?Apr 24, 2025 am 12:16 AM

데이터베이스 스토리지 세션 사용의 주요 장점에는 지속성, 확장 성 및 보안이 포함됩니다. 1. 지속성 : 서버가 다시 시작 되더라도 세션 데이터는 변경되지 않아도됩니다. 2. 확장 성 : 분산 시스템에 적용하여 세션 데이터가 여러 서버간에 동기화되도록합니다. 3. 보안 : 데이터베이스는 민감한 정보를 보호하기 위해 암호화 된 스토리지를 제공합니다.

PHP에서 사용자 정의 세션 처리를 어떻게 구현합니까?PHP에서 사용자 정의 세션 처리를 어떻게 구현합니까?Apr 24, 2025 am 12:16 AM

SessionHandlerInterface 인터페이스를 구현하여 PHP에서 사용자 정의 세션 처리 구현을 수행 할 수 있습니다. 특정 단계에는 다음이 포함됩니다. 1) CustomsessionHandler와 같은 SessionHandlerInterface를 구현하는 클래스 만들기; 2) 인터페이스의 방법 (예 : Open, Close, Read, Write, Despare, GC)의 수명주기 및 세션 데이터의 저장 방법을 정의하기 위해 방법을 다시 작성합니다. 3) PHP 스크립트에 사용자 정의 세션 프로세서를 등록하고 세션을 시작하십시오. 이를 통해 MySQL 및 Redis와 같은 미디어에 데이터를 저장하여 성능, 보안 및 확장 성을 향상시킬 수 있습니다.

세션 ID 란 무엇입니까?세션 ID 란 무엇입니까?Apr 24, 2025 am 12:13 AM

SessionId는 웹 애플리케이션에 사용되는 메커니즘으로 사용자 세션 상태를 추적합니다. 1. 사용자와 서버 간의 여러 상호 작용 중에 사용자의 신원 정보를 유지하는 데 사용되는 무작위로 생성 된 문자열입니다. 2. 서버는 쿠키 또는 URL 매개 변수를 통해 클라이언트로 생성하여 보낸다. 3. 생성은 일반적으로 임의의 알고리즘을 사용하여 독창성과 예측 불가능 성을 보장합니다. 4. 실제 개발에서 Redis와 같은 메모리 내 데이터베이스를 사용하여 세션 데이터를 저장하여 성능 및 보안을 향상시킬 수 있습니다.

무국적 환경 (예 : API)에서 세션을 어떻게 처리합니까?무국적 환경 (예 : API)에서 세션을 어떻게 처리합니까?Apr 24, 2025 am 12:12 AM

JWT 또는 쿠키를 사용하여 API와 같은 무국적 환경에서 세션을 관리 할 수 ​​있습니다. 1. JWT는 무국적자 및 확장 성에 적합하지만 빅 데이터와 관련하여 크기가 크다. 2. 쿠키는보다 전통적이고 구현하기 쉽지만 보안을 보장하기 위해주의해서 구성해야합니다.

세션과 관련된 크로스 사이트 스크립팅 (XSS) 공격으로부터 어떻게 보호 할 수 있습니까?세션과 관련된 크로스 사이트 스크립팅 (XSS) 공격으로부터 어떻게 보호 할 수 있습니까?Apr 23, 2025 am 12:16 AM

세션 관련 XSS 공격으로부터 응용 프로그램을 보호하려면 다음 조치가 필요합니다. 1. 세션 쿠키를 보호하기 위해 Httponly 및 Secure 플래그를 설정하십시오. 2. 모든 사용자 입력에 대한 내보내기 코드. 3. 스크립트 소스를 제한하기 위해 컨텐츠 보안 정책 (CSP)을 구현하십시오. 이러한 정책을 통해 세션 관련 XSS 공격을 효과적으로 보호 할 수 있으며 사용자 데이터가 보장 될 수 있습니다.

PHP 세션 성능을 어떻게 최적화 할 수 있습니까?PHP 세션 성능을 어떻게 최적화 할 수 있습니까?Apr 23, 2025 am 12:13 AM

PHP 세션 성능을 최적화하는 방법 : 1. 지연 세션 시작, 2. 데이터베이스를 사용하여 세션을 저장, 3. 세션 데이터 압축, 4. 세션 수명주기 관리 및 5. 세션 공유 구현. 이러한 전략은 높은 동시성 환경에서 응용의 효율성을 크게 향상시킬 수 있습니다.

SESSION.GC_MAXLIFETIME 구성 설정은 무엇입니까?SESSION.GC_MAXLIFETIME 구성 설정은 무엇입니까?Apr 23, 2025 am 12:10 AM

THESESSION.GC_MAXLIFETIMESETTINGINSTTINGTINGSTINGTERMINESTERMINESTERSTINGSESSIONDATA, SETINSECONDS.1) IT'SCONFIGUDEDINPHP.INIORVIAINI_SET ()

PHP에서 세션 이름을 어떻게 구성합니까?PHP에서 세션 이름을 어떻게 구성합니까?Apr 23, 2025 am 12:08 AM

PHP에서는 Session_Name () 함수를 사용하여 세션 이름을 구성 할 수 있습니다. 특정 단계는 다음과 같습니다. 1. Session_Name () 함수를 사용하여 Session_Name ( "my_session")과 같은 세션 이름을 설정하십시오. 2. 세션 이름을 설정 한 후 세션을 시작하여 세션을 시작하십시오. 세션 이름을 구성하면 여러 응용 프로그램 간의 세션 데이터 충돌을 피하고 보안을 향상시킬 수 있지만 세션 이름의 독창성, 보안, 길이 및 설정 타이밍에주의를 기울일 수 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)