Xinu

微信公众平台自动回复、关注等事件监听
<?php /** * Created by PhpStorm. * User: Xiny i@xiny...
扫描右侧二维码阅读全文
27
2018/08

微信公众平台自动回复、关注等事件监听

<?php
/**
 * Created by PhpStorm.
 * User: Xiny i@xiny9.com https://xbug.top
 * Coding Standard: PSR2
 * Date: 2018-08-27
 * Time: 10:00
 */
//明文方式
define('TOKEN', 'xxx');

class Message {
    private $fromUsername;
    private $toUsername;
    private $msgType = 'text';

    //关注、取关、消息接收
    public function index() {
        if ($_GET['echostr']) {
            $this->valid(); //如果发来了echostr则进行验证
        } else {
            $this->responseMsg(); //如果没有echostr,则返回消息
        }
    }
    private function post($url, $data) {
        $opts = array('http' => array(
            'method' => 'POST',
            'header' => array('Content-type: application/x-www-form-urlencoded', 'response-json:true'),
            'content' => $data,
        ),
        );
        $context = stream_context_create($opts);
        $result = json_decode(file_get_contents($url, false, $context), true);
        return $result;
    }

    private function valid() {
        //valid signature , option
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            //调用验证字段
            echo $echoStr;
            exit;
        }
    }

    private function responseMsg() {
        //get post data, May be due to the different environments
        //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信发来的XML数据
        $postStr = $postStr = file_get_contents("php://input"); //接收微信发来的XML数据
        //extract post data
        if (!empty($postStr)) {
            //解析post来的XML为一个对象$postObj
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            $postObj = json_decode(json_encode($postObj), true);

            $this->fromUsername = $postObj['FromUserName']; //请求消息的用户
            $this->toUsername = $postObj['ToUserName']; //"我"的公众号id
            //$keyword = trim($postObj['Content']); //消息内容

            if ($postObj['MsgType'] == 'event') {
                //如果XML信息里消息类型为event
                if ($postObj['Event'] == 'subscribe') {
                    //如果是订阅事件
                    if (is_string($postObj['EventKey'])) {
                        //通过场景码来的
                    }
                    $contentStr = "欢迎您关注xxx";
                    $this->sendMess($contentStr);
                } elseif ('SCAN' == $postObj['Event']) {
                    //已关注的扫码事件
                    if ($postObj['EventKey']) {
                        //通过场景码来的
                    }
                } elseif ($postObj['Event'] == 'unsubscribe') {
                    //取关事件
                }
            }

            if ('text' == $postObj['MsgType']) {
                $this->sendMess('这里是xxx!欢迎您的到来');
            } else {
                echo "";
                exit;
            }
        } else {
            echo "";
            exit;
        }
    }

    //验证字段
    private function checkSignature() {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    private function sendMess($content) {
        //返回消息模板
        $textTpl = "<xml>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        </xml>";
        $resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, time(), $this->msgType, $content);
        echo $resultStr;
        exit();
    }
}
Last modification:August 27th, 2018 at 04:28 pm

Leave a Comment