zoukankan      html  css  js  c++  java
  • 微信公众号开发 回复事件(测试账号)

    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."谢谢你的关注
    ";
    
                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."
    ";
    
                $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
    /**
     * 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();//点击自定义菜单市出发内容
    
    
    
  • 相关阅读:
    flask项目部署
    FastDFS分布式文件系统
    《app》团队冲刺二
    《APP》团队开发一
    软工二年级团队项目----自律小助手
    团队项目新闻app的需求分析
    团队成员及团队项目
    团队冲刺第八天
    团队冲刺第七天
    团队冲刺第六天
  • 原文地址:https://www.cnblogs.com/fps2tao/p/9058425.html
Copyright © 2011-2022 走看看