response_msg(); } } private function response_msg() { $postArr = $GLOBALS['HTTP_RAW_POST_DATA']; $postObj = simplexml_load_string($postArr); if (strtolower($postObj->MsgType) == 'event') { //回复用户消息 $toUser = $postObj->FromUserName; $fromUser = $postObj->ToUserName; //如果是关注事件(subscribe) if (strtolower($postObj->Event == 'subscribe')) { // 是否有推荐人 $referrer = $postObj->EventKey; // 关注人openid $openid = $toUser->__toString(); $referrer_str = $referrer->__toString(); if ($referrer_str) { $referrer_openid = explode('_',$referrer_str)[1]; // 判断关注人是否已关注别人 $wx_recommend = M('wx_recommend'); $exist = $wx_recommend->where(['new_openid'=>$openid])->find(); if (!$exist) { // 有效的用户 // 添加记录 $data = [ 'openid' => $referrer_openid, 'new_openid' => $openid, 'add_time'=> time(), ]; $wx_recommend->add($data); } } $arr = array( array( 'title' => '标题', 'description' => "描述", 'picUrl' => 'xxx.jpg', 'url' => 'xxx.html', ), ); $this->_send_news($arr,$toUser,$fromUser); } elseif ($postObj->Event == 'CLICK') { //------------------- 点击事件 start ------------------------ $event_key = $postObj->EventKey; // 获取key if($event_key=='V1001_PRESENT'){ $arr = array( array( 'title' => '标题', 'description' => "描述", 'picUrl' => 'xxx.jpg', 'url' => 'xxx.html', ), ); $this->_send_news($arr,$toUser,$fromUser); } //------------------- 点击事件 end ------------------------ } } //回复纯文本或单图文消息 if (($postObj->MsgType) == 'text' && (trim($postObj->Content) == '我要帽子' || trim($postObj->Content) == '帽子')) { $toUser = $postObj->FromUserName; $fromUser = $postObj->ToUserName; $arr = array( array( 'title' => '标题', 'description' => "描述", 'picUrl' => 'xxx.jpg', 'url' => 'xxx.html', ), ); $this->_send_news($arr,$toUser,$fromUser); } else if(($postObj->MsgType) == 'text' && (trim($postObj->Content) == '数量' || trim($postObj->Content) == '6')) { $fromUser = $postObj->ToUserName;//消息从哪里来 $toUser = $postObj->FromUserName;//发送给谁 // 用户openid $openid = $toUser->__toString(); // 获取推荐数量 $wx_recommend = M('wx_recommend'); $count = $wx_recommend->where(['openid'=>$openid])->count(); $content = "您当前已推荐关注人数为:".$count; $this->_send_text($content,$toUser,$fromUser); } else { $fromUser = $postObj->ToUserName;//消息从哪里来 $toUser = $postObj->FromUserName;//发送给谁 $content = "内容"; $this->_send_text($content,$toUser,$fromUser); } } private function _send_text($content,$toUser,$fromUser) { $template = " %s "; $time = time(); $msgType = 'text'; echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content); } private function _send_news($arr,$toUser,$fromUser) { $template = " %s " . count($arr) . " "; foreach ($arr as $k => $v) { $template .= " - <![CDATA[" . $v['title'] . "]]>
"; } $template .= " "; $time = time(); $msgType = "news"; echo sprintf($template, $toUser, $fromUser, $time, $msgType); }}