PHP 接入微信公众号


<?php
//index.php 公众号后台配置的路径是这个index.php
$wechatObj = new wechat();
$wechatObj->responseMsg();
class wechat {
    //返回消息模板
    private $textTpl = [
            'text' => "
                      
                      
                      %s
                      
                      
                      0
                      ",
            
        ];
    public function responseMsg() {
        // 验证 验证完注释
        // include 'Ruolin_network.php';
        //---------- 接 收 数 据 ---------- //
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取POST数据
        //   $postStr = file_get_contents('php://input'); PHP7+ 
        
        //用SimpleXML解析POST过来的XML数据
        $postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID)
        $toUsername = $postObj->ToUserName; //获取接收方账号
        $keyword = trim($postObj->Content); //获取消息内容
        $time = time(); //获取当前时间戳
        //---------- 返 回 数 据 ---------- //
        $msgType = "text"; //消息类型 这里设置这个变量,没有设置不会返回订阅回复的消息
        
        switch($postObj->MsgType){
            case 'event':
                    if ($postObj->Event == 'subscribe') { //如果是订阅事件
                    
                        $contentStr = "欢迎订阅!";
                        $resultStr = sprintf($this->textTpl['text'],$fromUsername,$toUsername,$time,$msgType,$contentStr);
                        echo $resultStr; //输出结果
                        exit;
                    }
                break;
            case 'text':
                    $contentStr = urldecode($keyword);
                    $resultStr = sprintf($this->textTpl['text'],$fromUsername,$toUsername,$time,$msgType,$contentStr);
                    echo $resultStr; //输出结果
                    exit;
                break;
            
            
        }
        
       
    }
     

}
?>
<?php
//Ruolin_network.php

//define your token
define("TOKEN", "填写你的token,随意字符就行");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
    
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }
        else{
            return false;
        }
    }
}
PHP