thinkphp微信公众号php开发,thinkphp 之微信公众号(自定义菜单开发)

本文详细介绍了如何在PHP中实现微信公众号的接口对接,包括消息接收、文本回复、事件处理以及菜单创建,展示了如何使用cURL和JSON处理微信服务器的请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// public function __construct(){  //  }    public function index(){//获得参数 signature nonce token timestamp echostr        $nonce    = $_GET['nonce'];        $token    = 'mk_weixin';        $timestamp = $_GET['timestamp'];        $echostr  = $_GET['echostr'];        $signature = $_GET['signature'];        //形成数组,然后按字典序排序        $array = array();        $array = array($nonce, $timestamp, $token);        sort($array);        //拼接成字符串,sha1加密 ,然后与signature进行校验        $str = sha1( implode( $array ) );        if( $str  == $signature && $echostr ){            //第一次接入weixin api接口的时候            // echo  $echostr;            exit;        }else{            $this->definedItem();            $this->reponseMsg();        }// echo 'window.location.href="'.__ROOT__.'/Game/bingtong/index.html"';exit;// //系统常量定义  // //去THinkPHP手册中进行查找    //      //  echo "

"."网站的根目录地址".__ROOT__." ";  // echo 'window.location.href="http://localhost/MAKUN/Game/bingtong/index.html"';//$this->display();}public function  show(){        echo 'imooc';    }    //消息处理函数    public function reponseMsg(){        //1.获取到微信推送过来post数据(xml格式)        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];        //2.处理消息类型,并设置回复类型和内容        $postObj = simplexml_load_string( $postArr );                        $access_token=$this ->getWxAccessToken();            $fromUser = $postObj->ToUserName;            $ToUser = $postObj->FromUserName;            $url='https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$ToUser;            $result=$this->http_curl($url,'get','json');            //存入session            // session_start();            $_SESSION['weixin_openid']=$result['openid'];                  if( strtolower( $postObj->MsgType) == 'event'){            //如果是关注 subscribe 事件            if( strtolower($postObj->Event == 'subscribe') ){                //回复用户消息(纯文本格式)                $toUser  = $postObj->FromUserName;                $fromUser = $postObj->ToUserName;                $time    = time();                $msgType  =  'text';                $content  = '欢迎关注我们的微信公众账号'.$postObj->FromUserName.'-'.$postObj->ToUserName;                $template = "%s";                $info    = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);            }        }        //根据用户输入消息进行回复        else if(strtolower( $postObj->MsgType) == 'text'){            $toUser  = $postObj->FromUserName;            $fromUser = $postObj->ToUserName;            $time    = time();            $msgType  =  'text';            //$content  = 'imooc is very good'.$postObj->FromUserName.'-'.$postObj->ToUserName;            $template = "%s";            switch( trim($postObj->Content)){                case 1:                    $content = '您输入的数字是1';                break;                case 2:                    $content = '您输入的数字是2';                break;                case 3:                    $content = '百度';                break;                case tuwen:                        $arr=array(                            array('title'=>'imooc',                                'description'=>'imooc描述',                                'picUrl'=>'http://www.imooc.com/static/img/common/logo.png',                                'url'=>'http://www.baidu.com'),                            array('title'=>'hao123',                                'description'=>'hao123描述',                                'picUrl'=>'http://www.imooc.com/static/img/common/logo.png',                                'url'=>'http://www.hao123.com'),                            array('title'=>'baidu',                                'description'=>'baidu描述',                                'picUrl'=>'http://www.imooc.com/static/img/common/logo.png',                                'url'=>'http://www.baidu.com'),                        );                    $content = '百度';                    $template_tuWen = "%s".count($arr)."";                    foreach($arr as $k=>$v){                        $template_tuWen .= "";                    }                    $template_tuWen .="";                    $info    = sprintf($template_tuWen, $toUser,$fromUser,$time,'news');                    // echo $info;                    break;            }            $info    = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);            echo $info;        }}    //$url  接口url string    //$type 请求类型string    //$res  返回类型string    //$arr= 请求参数string    public function http_curl($url,$type='get',$res='json',$arr=''){        //1.初始化curl        $ch  =curl_init();        //2.设置curl的参数        curl_setopt($ch,CURLOPT_URL,$url);        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);        if($type == 'post'){            curl_setopt($ch,CURLOPT_POST,1);            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);        }        //3.采集        $output =curl_exec($ch);        //4.关闭        curl_close($ch);        if($res=='json'){            if(curl_error($ch)){                //请求失败,返回错误信息                return curl_error($ch);            }else{                //请求成功,返回错误信息                return json_decode($output,true);            }        }        echo var_dump( $output );    }    /*    //获取测试号微信AccessToken    function  getWxAccessToken(){        //2初始化        $ch  =curl_init();        //3设置参数        curl_setopt($ch,CURLOPT_URL,$url);        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);        //4.调用接口        $res =curl_exec($ch);        //5.关闭curl        curl_close($ch);        if(curl_error($ch)){            var_dump(curl_error($ch));        }        $arr=json_decode($res,true);        var_dump($arr);    }*/    //获取微信服务器IP地址    function  getWxServerIp(){        $accessToken=$this ->getWxAccessToken();        // $accessToken ="Y7cYto0UvJz1U-9NpN04lhQuBkO5BO7Sim6hCZ0GkZlLLfisnvXLjg6VTX_v7veESGX24zAIlu31GD5YXjQFWd5AYXkQTv5a1iGIwk9oxL4gPeWC3fCciWTp2e5ftVZvUXFcAHAHKS";        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$accessToken;        $ch  =curl_init();        curl_setopt($ch,CURLOPT_URL,$url);        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);        $res =curl_exec($ch);        //5.关闭curl        curl_close($ch);        if(curl_error($ch)){            var_dump(curl_error($ch));        }        $arr=json_decode($res,true);        echo "

";

var_dump($arr);

echo "

";    }//返回access_token *session解决办法 存mysql memcache    public function  getWxAccessToken(){        if( $_SESSION['access_token'] && $_SESSION['expire_time']>time()){          //如果access_token在session没有过期            echo "111";            // echo $_SESSION['access_token'];;            return $_SESSION['access_token'];        }        else{            //如果access_token比存在或者已经过期,重新取access_token            //1 请求url地址            $AppId='你的AppId';            $AppSecret='你的AppSecret';            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$AppId."&secret=".$AppSecret;            $res=$this->http_curl($url,'get','json');            echo "res";            // echo $res;grant_type            $access_token =$res['access_token'];            //将重新获取到的aceess_token存到session            $_SESSION['access_token']=$access_token;            $_SESSION['expire_time']=time()+7000;            echo "2222";                      // echo $access_token;            return $access_token;        }    }    public function  definedItem(){        //创建微信菜单        //目前微信接口的调用方式都是通过 curl post/get        header('content-type:text/html;charset=utf-8');        $access_token=$this ->getWxAccessToken();        $url ='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;        $postArr=array(            'button'=>array(                array(                    'name'=>urlencode('坚果糖果'),                    // 'type'=>'click',                    'type'=>'view',                    // 'key'=>'item1',                    'url'=>'http://www.baidu.com'                ),                array(                    'name'=>urlencode('点外卖'),                    'type'=>'view',                      'url'=>'http://www.baidu.com'                    // 'sub_button'=>array(                    //    array(                    //        'name'=>urlencode('歌曲'),                    //        'type'=>'view',                    //        // 'key'=>'songs',                    //        'url'=>'http://www.baidu.com'                    //    ),//第一个二级菜单                    //    array(                    //        'name'=>urlencode('电影'),                    //        'type'=>'view',                    //        'url'=>'http://www.baidu.com'                    //    ),//第二个二级菜单                    // )                ),                array(                    'name'=>urlencode('视频游戏'),                    'type'=>'view',                    'url'=>'http://www.baidu.com',                ),//第三个一级菜单        ));        echo  $postJson = urldecode(json_encode($postArr));        $res = $this->http_curl($url,'post','json',$postJson);        var_dump($res);    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值