開發代碼全

index.phpphp

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.phphtml

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.phpjson

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']);
相關文章
相關標籤/搜索