微信公衆號開發 回覆事件(測試帳號)

WinxinSdk.class.php
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/28
 * Time: 18:56
 *
 */

class WinxinSdk
{

    private $appID = "wx***2d";
    private $appsecret = "51***80";
    public static $access_token = "";//也能夠寫入session
    public static $expires_in = 0;//token失效時間

    public function WinxinSdk($appID,$appsecret)
    {
        $this->appID = $appID;
        $this->appsecret = $appsecret;


    }
    public function getToken()
    {//獲取token
        $token = '';

        if(self::$access_token=="" && time()>self::$expires_in-360)//差十分鐘獲取就從新獲取新的
        {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appID&secret=$this->appsecret";
            $token = $this->curlGet($url);
            $token = json_decode($token);
            if(isset($token->access_token))
            {
                self::$access_token = $token->access_token;
                self::$expires_in = time()+$token->expires_in;
                return  $token->access_token;
            }
            else
            {
                return false;
            }
        }

        return false;

    }
    /*
     * reposeMsg 沒封裝好呢
     */
    public function reposeMsg()
    {//接收事件推送過來的數據,並回復
        //文案地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140453
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        //獲取到xml數據後,處理消息類型,並設置回覆消息內容(回覆就是直接打印xml數據)
        //數據格式
        $arr = simplexml_load_string($postArr);
        if(strtolower($arr->MsgType)=="event")
        {
            $toUser = $arr->ToUserName;
            $foUser = $arr->FromUserName;
            $msgType = 'text';
            $createTime = time();
            $content = '尊敬的'.$foUser."謝謝你的關注\n";

            if(strtolower($arr->Event)=="subscribe")
            {//訂閱
                $temp = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
                $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
                return $temp;
            }
        }
    }
    /*
   * textMsg 沒封裝好呢
   */
    public function textMsg()
    {//接收文本,並回復
        //文案地址:
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        //獲取到xml數據後,處理消息類型,並設置回覆消息內容(回覆就是直接打印xml數據)
        //數據格式
        $arr = simplexml_load_string($postArr);
        if(strtolower($arr->MsgType)=='text')
        {
            $toUser = $arr->ToUserName;
            $foUser = $arr->FromUserName;
            $msgType = 'text';
            $createTime = time();
            $content = $arr->Content."888888".$toUser."\n";

            $temp = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
            $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
            return $temp;

        }

    }
    /*
    * getQR 沒封裝好呢
    */
    public function  getQR($data = null)
    {//獲取二維碼
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".self::$access_token;
        $jsonData = '{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}';
        $res = $this->curlPost2($url,$jsonData);
        return $res;
    }

    public function customMenu($data)
    {//自定義菜單
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".self::$access_token;

        $res = $this->curlPost2($url,$data);
        return $res;
    }
    public function onclickMenu()
    {//點擊自定義菜單市出發內容
        //$postArr = file_get_contents("php://input");
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        $arr = simplexml_load_string($postArr);
        //$this->logs('inclickMenu.txt',(array)$arr->ToUserName);
        if(strtolower($arr->MsgType)=="event")
        {
            if(strtolower($arr->Event)=="click")
            {
                //接受消息格式
                $rtemp = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[FromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[CLICK]]></Event><EventKey><![CDATA[EVENTKEY]]></EventKey></xml>";
                //推送文本格式
                $temp = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
                $toUser = $arr->ToUserName;
                $foUser = $arr->FromUserName;
                $msgType = 'text';
                $content = '你點擊了--'.$arr->EventKey;
                $createTime = time();
                $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
                return $temp;


            }
        }


    }





    public function curlGet($url)
    {//get請求接口
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data = curl_exec($ch);
        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ($httpCode>=200 && $httpCode<300) ? $data:false;
    }
    public function curlPost($url,$data = null)
    {//post請求接口
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return  $output;

    }
    public function curlPost2($url,$data)
    {//第一個post方法
        //$data = http_build_query($data);
        $opts = array (
            'http' => array (
                'method' => 'POST',
                'header'=> "Content-type: application/x-www-form-urlencodedrn",
                "Content-Length: " . strlen($data) . "rn",
                'content' => $data
            )
        );

        $context = stream_context_create($opts);
        $html = file_get_contents($url, false, $context);
        return $html;

    }
    public function logs($file,$data)
    {//打印日誌
        (is_array($data))?$data = print_r($data,true):$data;
        file_put_contents($file,$data);
    }




}

 

後臺接口配置信息文件,用來接收微信發送的xml消息openweixin.php:php

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/27
 * Time: 20:16
 */
//此處簡單的實現一個自動加載
spl_autoload_register(function($class){
    include_once ("./".$class.".class.php");
});
//文檔網址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319

//1.將timestamp,nonce,token按字典序排序 (參數名ASCII碼從小到大排序(字典序))
    $timestamp = @$_GET['timestamp'];
    $nonce = @$_GET['nonce'];
    $token= "fps2";
    $signature = @$_GET['signature'];

    $arr = array($timestamp,$nonce,$token);
    sort($arr);

//2.將排序後的三個參數拼接後用sha1加密
    $tmpstr = implode('',$arr);
    $tmpstr = sha1($tmpstr);
//3.將加密後的字符串與signature進行對比,判斷該請求是否來自微信

    if($tmpstr == $signature && isset($_GET['echostr']))
    {//微信服務器配置 第一次接入會驗證合法性,以後接收事件的區別是少傳 $_GET['echostr'] 這個參數
        echo $_GET['echostr'];
        exit;
    }
    else
    {//這裏能夠接收微信服務器傳遞的事件

        $appID = "wx***2d";
        $appsecret = "51****80";


        $wxSdk = new WinxinSdk($appID,$appsecret);
        $wxSdk->getToken();

        //echo WinxinSdk::$access_token;
        //下面只是測試,其實訂閱和發文字消息不可能同時觸發,下面的兩條同一時間只會觸發一個(可是仍是不建議這樣寫,最好判斷分開)
        echo $wxSdk->reposeMsg();//訂閱回覆的內容
        echo $wxSdk->textMsg();//發消息回覆的內容
        echo $wxSdk->onclickMenu();//點擊自定義菜單市出發內容
相關文章
相關標籤/搜索