微信公众号-获取用户信息

public $config = array(
                    "AppID"         =>  "",               //应用ID
            "AppSecret"     =>  "",//应用密钥
        );
    /**
     *  获取登陆url
     *  $redirect_uri           回调地址
     *  $scope                  是否授权(snsapi_userinfo:授权,snsapi_base:不授权)
    */
    public function LoginUri($redirect_uri = "",$scope = "snsapi_base",$state = "123"){
        if(!$redirect_uri){
            die("请填写回掉地址!");
        }
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->config['AppID']}&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
    }
    /**
     *  获取用户信息
     */
    function UsInfo(){
        $str = $this->get_curl("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->config['AppID']}&secret={$this->config['AppSecret']}&code={$_GET['code']}&grant_type=authorization_code");
        $arr = json_decode($str,true);
        $message = $this->get_curl("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->config['AppID']}&grant_type=refresh_token&refresh_token={$arr['refresh_token']}");
        $arr1 = json_decode($message,true);
        $us_info = $this->get_curl("https://api.weixin.qq.com/sns/userinfo?access_token={$arr1['access_token']}&openid={$arr1['openid']}&lang=zh_CN");
        return json_decode($us_info,true);
    }
    /**
     *    获取access_token
     */
    function get_access_token(){
        $path = $_SERVER['DOCUMENT_ROOT']."/volunteer_hatosy/access_token.txt";
        $arr = json_decode(file_get_contents($path),true);
        if($arr){
            $expires_in = $arr['expires_in'];
        }else{
            $expires_in = 0;
        }
        if(!$arr || time() >= $expires_in){
            $str = $this->get_curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->config['AppID']}&secret={$this->config['AppSecret']}");
            $info = json_decode($str,true);
            $info['expires_in'] = time() + 7000;
            $access_token = $info['access_token'];
            $this->fwrite_txt($path,json_encode($info));
        }else{
            $access_token = $arr['access_token'];
        }
        return $access_token;
    }
    /**
     *  获取随机数
     */
    function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            $str = "";
            for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
     }
    /**
     *  获取ticket
     */
    function get_ticket(){
        $path = $_SERVER['DOCUMENT_ROOT']."/volunteer_hatosy/tocket.txt";
        $arr = json_decode(file_get_contents($path),true);
        if(!$arr || time() >= $arr['expires_in']){
            $access_token = $this->get_access_token();
            $ticket = $this->get_curl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi");
            $info = json_decode($ticket,true);
            $info['expires_in'] = time() + 7000;
            $this->fwrite_txt($path,json_encode($info));
            return $info['ticket'];
        }else{
            return $arr['ticket'];
        }
    }
    /**
     *  获取signature
     */
    function signature(){
        $ticket = $this->get_ticket();
        $timestamp = time();
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $noncestr = $this->createNonceStr(10);
        $string = "jsapi_ticket={$ticket}&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        return array(
            'timestamp' => $timestamp,
            'noncestr' => $noncestr,
            'signature' => $signature
        );
    }
    /**
     *    获取二维码
     */
    function get_ercode($us_id = 0){
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}";
        $param = array(
                "action_name"=>"QR_LIMIT_SCENE",
                "action_info"=>array("scene"=>array("scene_id"=>intval($us_id)))
            );
        $xml = $this->post_curl($url,json_encode($param));
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode(json_decode($xml)->ticket);
    }
    function post_curl($url,$data,$agreement = 0){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if($agreement == 0){//0 https   1   http
            unset($_REQUEST['agreement']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    function get_curl($url,$agreement = 0){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if($agreement == 0){//0 https   1   http
            unset($_REQUEST['agreement']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result; 
    }
    function uploadMedia(){
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type=voice";
        $file = realpath('1482826121.amr'); //要上传的文件
        $fields['media'] = '@'.$file;
        $ch = curl_init($url) ;
        curl_setopt($ch, CURLOPT_POST, 1);
        if($agreement == 0){//0 https   1   http
            unset($_REQUEST['agreement']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch) ;
        if (curl_errno($ch)) {
            dump(curl_errno($ch));
        }
        curl_close($ch);
        dump($result);
    }
    /**
     *    获取语音
     */
    public function getVoice(){
        $media_id = '_pnBKlv6Xp7VzI28UEpxYQaEknMI7mWZ4tROP9Bvpc7QjkC9GbDUy3Yuma4J7TgT';
        $access_token = $this->get_access_token();
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
        $fileInfo = $this->downloadWeixinFile($url);
        $fileName = time().".amr";
        $this->saveWeixinFile($fileName,$fileInfo['body']);
    }
    function downloadWeixinFile($url){
        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_NOBODY,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $package = curl_exec($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header'=>$httpinfo),array('body'=>$package));
        return $imageAll;
    }
    function saveWeixinFile($filename,$filecontent){
        $local_file = fopen($filename,'w');
        if(local_file !== false){
            if(fwrite($local_file,$filecontent) !== false){
                fclose($local_file);
            }
        }
    }
    
    /*文件写入*/
    function fwrite_txt($path,$txt){
        $myfile = fopen($path,"w") or die("Unable to open file!");
        fwrite($myfile,$txt);
        fclose($myfile);
    }
    /*文件读取*/
    function fread_txt($path){
        $txt = file_get_contents($path);
        return $txt;
    }

微信公众号获取用户信息(网页授权获取)的实现步骤如下: 1. **配置公众号**: - 登录微信公众号平台,进入“开发”->“基本配置”,记录开发者ID(AppID)和开发者密钥(AppSecret)。 - 进入“公众号设置”->“功能设置”,设置“网页授权域名”,确保域名已备案并可访问。 2. **引导用户同意授权**: - 在网页中生成一个授权链接,引导用户点击该链接进行授权。授权链接的格式如下: ``` https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect ``` - `APPID`:公众号的唯一标识。 - `REDIRECT_URI`:授权后重定向的回调链接地址,需进行URL编码。 - `response_type`:返回类型,请填写code。 - `scope`:应用授权作用域,`snsapi_base`(不弹出授权页面,直接跳转,只能获取用户openid)或`snsapi_userinfo`(弹出授权页面,可通过openid拿到昵称、性别、所在地等)。 - `state`:重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节。 - `#wechat_redirect`:无论直接打开还是做页面302重定向时候,必须带此参数。 3. **用户同意授权后回调**: - 用户同意授权后,微信会重定向到`REDIRECT_URI`,并在URL中携带`code`和`state`参数。 - 在回调页面中,通过`code`参数获取`access_token`和`openid`。 4. **通过code获取access_token**: - 构造请求URL: ``` https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code ``` - `APPID`:公众号的唯一标识。 - `SECRET`:公众号的开发者密码。 - `CODE`:填写第一步获取的code参数。 - `grant_type`:填写authorization_code。 - 发送HTTP GET请求,获取`access_token`和`openid`。 5. **获取用户信息**: - 构造请求URL: ``` https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN ``` - `ACCESS_TOKEN`:网页授权接口调用凭证。 - `OPENID`:用户的唯一标识。 - `lang`:返回国家地区语言版本,zh_CN简体,zh_TW繁体,en英文。 - 发送HTTP GET请求,获取用户信息。 以下是一个简单的示例代码: ```javascript function getUserInfo() { // 假设用户在微信中点击了授权链接并重定向回来 const code = getQueryParam('code'); const state = getQueryParam('state'); if (code) { // 通过code获取access_token fetch(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=YOUR_APPID&secret=YOUR_SECRET&code=${code}&grant_type=authorization_code`) .then(response => response.json()) .then(data => { const accessToken = data.access_token; const openid = data.openid; // 通过access_token和openid获取用户信息 fetch(`https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${openid}&lang=zh_CN`) .then(response => response.json()) .then(userInfo => { console.log(userInfo); // 处理用户信息 }); }); } else { // 跳转到微信授权页面 const redirectUri = encodeURIComponent('YOUR_REDIRECT_URI'); window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=YOUR_APPID&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`; } } function getQueryParam(param) { const urlSearchParams = new URLSearchParams(window.location.search); return urlSearchParams.get(param); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魏浩浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值