开发代码全

index.php

header('Content-type:text');
define("APPID","xxxxxxxxxxxxx");
define("APPSECRET","xxxxxxxxxxx");
define("TOKEN","weixin");
require("./wechat.inc.php");
$wechat=new WeChat(APPID,APPSECRET,TOKEN);
//var_dump($wechat->_getUserList());//获取用户列表
//$data=array("oGdzvwDnmrgTy2DLjYvpH42j6YuE","oGdzvwDnmrgTy2DLjYvpH42j6YuE");
//echo  $wechat->_sendAll($data,"quanfa2");

var_dump($wechat->_getImagelist());
//var_dump($wechat->_getUserInfo("oGdzvwDnmrgTy2DLjYvpH42j6YuE"));//获取用户信息

//$wechat->responseMsg();//处理信息或事件
//$wechat->_getmenu();//查询菜单 浏览器直接访问即可
//$wechat->_delmenu();//删除菜单 浏览器直接访问即可
/*
$menu='{
    "button": [
        {
            "type": "click", 
            "name": "今日歌曲", 
            "key": "V1001_TODAY_MUSIC"
        }, 
        {
            "name": "菜单", 
            "sub_button": [
                {
                    "type": "view", 
                    "name": "搜索", 
                    "url": "http://www.soso.com/"
                }, 
                {
                    "type": "click", 
                    "name": "赞一下我们", 
                    "key": "V1001_GOOD"
                }, 
                {
                    "type": "click", 
                    "name": "新闻", 
                    "key": "news"
                }
            ]
        }
    ]
}';
$wechat->_addmenu($menu);
*/

wechat.inc.php

class WeChat {

    private $_appid;
    private $_appsecret;
    private $_token;

    //回复信息
    public function responseMsg() {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        switch ($postObj->MsgType) {
            case "event":
                $this->_doevent($postObj);
                break;

            case "text":
                $this->_dotext($postObj);
                break;

            case "image":
                $this->_doimage($postObj);
                break;
            default:exit;
        }
    }

    //接受文字信息
    public function _dotext($postObj) {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
        if ($keyword == "id") {//获取用户ID
            $contentStr = $fromUsername;
            $msgType = "text";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
            return;
        }
        if ($keyword == "音乐") {//返回音乐一首
            $this->_domusic($postObj);
            return;
        }
        $data = "txt=" . $keyword;
        $contentStr = $this->_request("http://www.niurenqushi.com/api/simsimi/", false, "post", $data);
        $contentStr = json_decode($contentStr);
        $contentStr = $contentStr->text;

        $msgType = "text";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        echo $resultStr;
    }

    //接收图片信息
    public function _doimage($postObj) {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->PicUrl);
        $time = time();
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";

        $contentStr = $keyword;
        $msgType = "text";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        echo $resultStr;
    }

    //回复音乐信息
    public function _domusic($postObj) {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->PicUrl);
        $time = time();
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
</Music>
</xml>";
        $contentStr = $keyword;
        $msgType = "music";
        $Title = "yinyue";
        $Description = "卡看好听吗";
        $MusicURL = "http://www.msxzjt.com/wei/ss.mp3";
        $HQMusicUrl = "http://www.msxzjt.com/wei/ss.mp3";
        $ThumbMediaId = "iXXpDo9PRl0lZC0N-JjLi37GsiJCOPnoo4-G6LPObPA";

        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $Title, $Description, $MusicURL, $HQMusicUrl, $ThumbMediaId);
        file_put_contents("./ss", $resultStr);
        echo $resultStr;
    }

    //接收事件信息
    public function _doevent($postObj) {
        //事件处理
        switch ($postObj->Event) {
            case "subscribe": //处理订阅
                $this->_dosubscribe($postObj);
                break;

            case "unsubscribe": //处理取消订阅
                $this->_dounsubscribe($postObj);
                break;

            case "CLICK"://处理菜单点击事件
                $this->_click($postObj);
                break;

            default:exit;
        }
    }

    //处理订阅
    public function _dosubscribe($postObj) {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $time = time();
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";

        $msgType = "text";
        $contentStr = "欢迎关注";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        //file_put_contents("./tmp",$resultStr);
        //可以在此处将用户信息保存到数据库
        echo $resultStr;
    }

    //处理取消订阅
    public function _dounsubscribe($postObj) {
        //可以将用户信息删除
    }

    //处理菜单点击事件
    public function _click($postObj) {
        if ($postObj->EventKey == "news") {
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $time = time();
            $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>";
            $item = "<item>
<Title><![CDATA[%s]]></Title> 
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
            $end = "</xml>";

            $news = array(
                array('Title' => "全系统干部职工坐火车一律都要买票", 'Description' => "针对日常监督中发现国家铁路局系统工作人员持有中国铁路总公司制发的铁路乘车证可以免费乘坐火车,以及铁路乘车证管理不严", 'PicUrl' => "http://cms-bucket.nosdn.127.net/catchpic/3/3c/3cac76845e0ca485b911a65e8d7324b7.jpg", 'Url' => "http://news.163.com/17/1202/12/D4LC3SE2000189FH.html"),
                array('Title' => "引领推动网络强国战略", 'Description' => "行生于己,名生于人。“只有富有爱心的财富才是真正有意义的财富,只有积极承担社会责任的企业才是最有竞争力和生命力的企", 'PicUrl' => "http://cms-bucket.nosdn.127.net/catchpic/9/93/932eacb3997bd422bcd114572da0cf89.jpg", 'Url' => "http://news.163.com/17/1202/12/D4LC3AT30001875P.html")
            );
            $count = count($news);
            $list = "";
            for ($i = 0; $i < $count; $i++) {
                $list .= sprintf($item, $news[$i]["Title"], $news[$i]["Description"], $news[$i]["PicUrl"], $news[$i]["Url"]);
            }
            $text = sprintf($textTpl, $fromUsername, $toUsername, $time, $count);
            $content = $text . $list . $end;
            file_put_contents("./tmp", $content);
            echo $content;
        }
    }

    public function __construct($appid, $appsecret, $token) {
        $this->_appid = $appid;
        $this->_appsecret = $appsecret;
        $this->_token = $token;
    }

    private function _request($curl, $https = true, $method = 'get', $data = null) {
        $ch = curl_init(); //初始化
        curl_setopt($ch, CURLOPT_URL, $curl);
        curl_setopt($ch, CURLOPT_HEADER, false); //设置不需要头信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //获取页面内容,但不输出
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //不做服务器认证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //不做客户端认证
        }

        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, true); //设置请求是post方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置post请求数据
        }

        $str = curl_exec($ch); //执行访问
        curl_close($ch); //关闭curl,释放资源
        return $str;
    }

    //获取用户列表    
    public function _getUserList() {
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . $this->_getAccesstoken();
        $content = $this->_request($url);
        $content = json_decode($content);
        $users = $content->data->openid;
        return $users;
    }

    //批量发送信息
    public function _sendAll($user, $text) {
        //如果只有一个user ,需要在 touser 加一个空用户  %s,""
        $tpl = '{
   "touser":[
    %s    
   ],
    "msgtype": "text",
    "text": { "content": "%s"}
}';
        $users = "";
        for ($i = 0; $i < count($user); $i++) {
            $users .= '"' . $user[$i] . '"';
            if ($i < count($user) - 1) {
                $users .= ',';
            }
        }

        $curl = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=' . $this->_getAccesstoken();
        $data = sprintf($tpl, $users, $text);
        $res = $this->_request($curl, true, "post", $data);
        $res = json_decode($res);
        if ($res->errcode == 0) {
            return "发送成功";
        } else {
            return "发送成功";
        }
    }

    //获取用户基本信息(包括UnionID机制)
    public function _getUserInfo($userid) {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->_getAccesstoken() . "&openid=" . $userid . "&lang=zh_CN";
        return $this->_request($url);
    }

    //添加临时素材  本地服务器需要https
    public function _addImages() {
        $curl = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $this->_getAccesstoken() . '&type=image';
        $file = "./1.jpg";
        $data["type"] = 'image';
        $data['media'] = '@' . $file;
        $result = $this->_request($curl, true, "post", $data);
        $result = json_decode($result);
        return $result->$result;
    }

    //获取素材列表
    public function _getImagelist() {
        $curl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" . $this->_getAccesstoken();
        $data = '{
   "type":"image",
   "offset":1,
   "count":20
}';
        $res = $this->_request($curl, true, "post", $data);
        $res = json_decode($res);
        return $res->item;
    }

    //获取Access_token
    private function _getAccesstoken() {
        $file = "./accesstoken";
        if (file_exists($file)) {
            $content = file_get_contents($file);
            $content = json_decode($content);
            if (time() - filemtime($file) < $content->expires_in) {
                return $content->access_token;
            }
        }
        $content = $this->_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->_appid . "&secret=" . $this->_appsecret);
        file_put_contents($file, $content);
        $content = json_decode($content);
        return $content->access_token;
    }

    /* 获取ticket
      expire_seconds:二维码有效期(秒)
      type:二维码类型(临时或永久)
      scene:场景编号
     */

    public function _getTicket($expire_seconds = 604800, $type = "temp", $scene = 1) {
        if ($type == "temp") {
            $data = '{"expire_seconds": ' . $expire_seconds . ', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}';
            return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data);
        } else {
            $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}';
            return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data);
        }
    }

    /* 通过ticket获取二维码 */

    public function _getQRCode($expire_seconds = 604800, $type = "temp", $scene = 1) {
        $content = json_decode($this->_getTicket($expire_seconds, $type, $scene));
        $ticket = $content->ticket;
        $image = $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket));
        //$file="./".$type.$scene.".jpg"; //设置图片名字
        //file_put_contents($file,$content); //二维码保存到本地
        return $image;
    }

    /* 获取自定义菜单 */

    public function _getmenu() {
        $url = $this->_request("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $this->_getAccesstoken());
        return $url;
    }

    /* 删除自定义菜单 */

    public function _delmenu() {
        $url = $this->_request("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" . $this->_getAccesstoken());
        $content = json_decode($url);
        if ($content->errcode == 0) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    /* 添加自定义菜单 */

    public function _addmenu($menu) {

        $url = $this->_request("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $this->_getAccesstoken(), true, "post", $menu);
        $content = json_decode($url);
        if ($content->errcode == 0) {
            return "创建成功";
        } else {
            return "创建失败";
        }
    }

    //无弹窗授权
    public function _wshouquan($code) {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->_appid . "&secret=" . $this->_appsecret . "&code=" . $code . "&grant_type=authorization_code";
        $res = $this->_request($url);
        return $res;
        //access_token    网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
        //expires_in    access_token接口调用凭证超时时间,单位(秒)
        //refresh_token    用户刷新access_token
        //openid    用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
        //scope    用户授权的作用域,使用逗号(,)分隔
    }
    //弹窗授权
    public function _yshouquan($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->_appid . "&secret=" . $this->_appsecret . "&code=" . $code . "&grant_type=authorization_code";
        $res = $this->_request($url);
        $res= json_decode($res);
        $url2="https://api.weixin.qq.com/sns/userinfo?access_token=".$res->access_token."&openid=".$res->openid."&lang=zh_CN";
        $res2 = $this->_request($url2);
        //var_dump($res2);
         return $res2;
    }
    
    

}

授权登陆

header("Content-type: text/html; charset=utf-8"); 
define("APPID","wxf828e5399fbf1919");
define("APPSECRET","49cf2ca86f04a7a356da72420908809c");
define("TOKEN","weixin");
require("./wechat.inc.php");
$wechat=new WeChat(APPID,APPSECRET,TOKEN);
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".urlEncode('http://www.xxx.com/wei/indexs.php')."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
$url2="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".urlEncode('http://www.xxx.com/wei/indexs.php')."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
?>
<a href="<?php echo $url ?>">无弹窗登陆</a> <a href="<?php echo $url2 ?>">弹窗登陆</a>

indexs.php

header("Content-type: text/html; charset=utf-8"); 
define("APPID","wxf828e5399fbf1919");
define("APPSECRET","49cf2ca86f04a7a356da72420908809c");
define("TOKEN","weixin");
require("./wechat.inc.php");
$wechat=new WeChat(APPID,APPSECRET,TOKEN);
//echo $wechat->_wshouquan($_GET['code']);
$wechat->_yshouquan($_GET['code']);

 

posted @ 2017-12-06 20:21  自由无风  阅读(1049)  评论(0编辑  收藏  举报