search
HomeBackend DevelopmentPHP TutorialWeChat Public Platform-Send Passive Response Message-PHP Example

<?php
$testObj = new Test();
if(!empty($_GET[&#39;echostr&#39;])){
$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, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
               $fromUsername = $postObj->FromUserName;//发送人
               $toUsername = $postObj->ToUserName;//接收人
               $MsgType = $postObj->MsgType;//消息类型
               $MsgId = $postObj->MsgId;//消息id
               $time = time();//当前时间做为回复时间
               
               //如果是文本消息(表情属于文本信息)
               if($MsgType == &#39;text&#39;){
               $content = trim($postObj->Content);//消息内容
if(!empty( $content )){
//如果文本内容是图文,则回复图文信息,否则回复文本信息
               if($content == "图文"){
               
               //回复图文消息,ArticleCount图文消息个数,多条图文消息信息,默认第一个item为大图
               $ArticleCount = 2; 
               $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
<item>
<Title><![CDATA[%s]]></Title> 
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
</Articles>
</xml>";
               $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, &#39;news&#39;, 
               $ArticleCount,&#39;我是图文信息&#39;,&#39;我是描述信息&#39;,&#39;http://www.test.com/DocCenterService/image?photo_id=236&#39;,
               &#39;http://www.test.com&#39;,&#39;爱城市网正式开通上线&#39;,&#39;描述2&#39;,&#39;http://jn.test.com/ac/skins/img/upload/img/20131116/48171384568991509.png&#39;,
               &#39;http://www.test.com&#39;);
               echo $resultStr;
                $this->log($resultStr);
               }else{
               //回复文本信息
               $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";             
               $contentStr = &#39;你发送的信息是:接收人:&#39;.$toUsername.&#39;,发送人:&#39;.$fromUsername.&#39;,消息类型:&#39;.$MsgType.&#39;,消息内容:&#39;.$content.&#39; www.icity365.com&#39;;
               $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, &#39;text&#39;, $contentStr);
               echo $resultStr;
               $this->log($resultStr);
               }
               }else{
               echo "Input something...";
               $this->log($resultStr);
               }
               
             //如果是图片消息
               }elseif ($MsgType == &#39;image&#39;){
           $MediaId = $postObj->MediaId;//图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
           $imageTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
               $resultStr = sprintf($imageTpl, $fromUsername, $toUsername, $time, $MsgType, $MediaId);
               echo $resultStr;
           $this->log("自动响应图片信息");
               $this->log($resultStr);
               
               //如果是视频
               }else if($MsgType == &#39;video&#39;){
               $MediaId = $postObj->MediaId;//视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
               $ThumbMediaId = $postObj->ThumbMediaId;//视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。 
$videoTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Video>
<MediaId><![CDATA[%s]]></MediaId>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video> 
</xml>";
$resultStr = sprintf($videoTpl, $fromUsername, $toUsername, $time, $MsgType, $MediaId,$ThumbMediaId,&#39;我是标题&#39;,&#39;我是描述&#39;);
               echo $resultStr;
           $this->log("自动响应视频信息".$ThumbMediaId);
               $this->log($resultStr);
               
               //如果是地理位置
               }else if($MsgType == &#39;location&#39;){
               $Location_X = $postObj->Location_X;//维度
               $Location_Y = $postObj->Location_Y;//经度
               $Scale = $postObj->Scale;//地图缩放大小
               $Label = $postObj->Label;//地里位置信息
               
               //回复文本信息
               $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";             
             $msgType = "text";
               $contentStr = &#39;经度:&#39;.$Location_Y.&#39;,维度:&#39;.$Location_X.&#39;,地图缩放大小&#39;.$Scale.&#39;,地理位置信息:&#39;.$Label;
               $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
               echo $resultStr;
               $this->log($resultStr);
               
               //如果是事件
               }else if($MsgType == &#39;event&#39;){
               
               $Event = $postObj->Event;
               
               //subscribe(关注,也叫订阅)
               if($Event == &#39;subscribe&#39;){
               
               $EventKey = $postObj->EventKey;//事件KEY值,qrscene_为前缀,后面为二维码的参数值
               
               //未关注时,扫描二维码
               if(!empty($EventKey)){
               $Ticket = $postObj->Ticket;//二维码的ticket,可用来换取二维码图片
               $this->log($fromUsername.&#39;扫描二维码关注!EventKey=&#39;.$EventKey.&#39;,Ticket=&#39;.$Ticket);
               }else{
               $this->log($fromUsername.&#39;关注我了!&#39;);
               }
               
               //unsubscribe(取消关注)
               }elseif ($Event == &#39;unsubscribe&#39;){
               $this->log($fromUsername.&#39;取消关注我了!&#39;);
               
               //已关注时,扫描二维码事件
               }elseif($Event == &#39;SCAN&#39; || $Event == &#39;scan&#39;){
               $EventKey = $postObj->EventKey;//事件KEY值,是一个32位无符号整数,即创建二维码时的二维码scene_id
                $Ticket = $postObj->Ticket;//二维码的ticket,可用来换取二维码图片
               $this->log($fromUsername.&#39;关注我了!EventKey=&#39;.$EventKey.&#39;,Ticket=&#39;.$Ticket);
               
               //菜单点击事件
               }elseif($Event == &#39;CLICK&#39;){
               $EventKey = $postObj->EventKey;//事件KEY值,与自定义菜单接口中KEY值对应
               //回复文本信息
               $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";             
               $contentStr = &#39;你点击了菜单,菜单项key=&#39;.$EventKey;
               $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, &#39;text&#39;, $contentStr);
               echo $resultStr;
               $this->log($resultStr);
               //其他事件类型
               }else{
               $this->log(&#39;事件类型:&#39;.$Event);
               }
               
               //其他消息类型,链接、语音等
               }else{
               //回复文本信息
               $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";             
               $contentStr = &#39;消息类型:&#39;.$MsgType.&#39;我们还没做处理。。。。【爱城市网】&#39;;
               $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, &#39;text&#39;, $contentStr);
               echo $resultStr;
               $this->log($resultStr);
               }
       }else {
       echo "";
       exit;
       }
    }else{
   $this->log("验证签名未通过!");
    }
    }
    /**
     * 记录请求信息
     */
    function log_request_info() {
    $post = &#39;&#39;;
    foreach($_POST   as   $key   =>   $value)   { 
$post = $post.$key.&#39; : &#39;.$value.&#39; , &#39;; 
} 
$get = &#39;&#39;;
    foreach($_GET   as   $key   =>   $value)   { 
$get = $get.$key.&#39; : &#39;.$value.&#39; , &#39;; 
} 
$this->log("get信息:".$get);
$this->log("post信息:".$post);
    }
    /**
     * 记录日志
     * @param $str
     * @param $mode
     */
    function log($str){
    $mode=&#39;a&#39;;//追加方式写
    $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;
   }
} 
}
?>

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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools