微信oauth2接口获取用户的openid

时间:2015-07-23 13:29:53   收藏:0   阅读:647

当微信的菜单类型是view型时,就需要通过“网页授权获取用户基本信息”接口来获取了,具体接口使用大家自己到微信公众平台去查看文档吧。这里只简述我的方法吧

如果大家view的设置链接为 http://myself.test.cn/index.php?app=weixin&act=getCode

app:是类名.

act:是方法名

以下是获取openid的方法

1、用户同意授权,获取code.这一步很简单

function getCode()

{

  //只需将文档中的链接复制过来改为自己的,redirect_uri 参数为网址的回调,切记要用urlencode()处理下,这个网址填写你想要回调的地址,用以接受code

    $redirect_uri = urlencode(‘http://jiuke_shop.eonch.cn/index.php?app=weixin&act=openid_show‘);//这里我写到控制器weixin 中的openid_show方法
        $url_getcode = ‘https://open.weixin.qq.com/connect/oauth2/authorize?appid=‘.$wxconfig[‘appid‘].‘&redirect_uri=‘.$redirect_uri.‘&response_type=code&    scope=snsapi_base&state=1#wechat_redirect‘;
        header("Location:{$url_getcode}");

}

2、这个是用来接受上面回调所传回来的code,并处理code获得openid

function openid_show()

{

  $appid = ‘.................‘;//微信公众号  ID

  $secret= ‘.................‘;//微信公众号  秘钥

  if (isset($_GET[‘code‘]) && isset($_GET[‘state‘]) ){
            $code = $_GET[‘code‘]; //获取code
            $weixin_openid = $this->GetOpenid($_GET[‘code‘],$appid,$secret); //通过GetOpenid获得openid
       }

}

 

    //获取微信的openid
    function GetOpenid($c_code,$appid,$secret)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $c_code . "&grant_type=authorization_code";

        $result = $this->getData($url);

        $jsondecode = json_decode($result);
            
        return $jsondecode->{"openid"};

    }  

     //获取https的get请求结果
    function getData($c_url)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $c_url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER[‘HTTP_USER_AGENT‘]); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    //    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    //    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
           echo ‘Errno‘.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }

看懂了也并不复杂吧,以上代码拿来就能用哦,自学的时候确实很头疼呢,现在就来造福下大家吧,为新手们造福。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!