您的位置:首页 > 编程语言 > PHP开发

php 新浪微博第三方登录验证/OAuth2.0

2017-06-13 09:16 375 查看
新浪微博实现第三方网站登录

创建新浪微博账号

可用微博账号登录 登录地址:http://open.weibo.com/

网站接入



2.立即接入->添加新网站





创建成功

获取 App key  和 App Sercet

header请求

[php]
view plain
copy

public function actionSina() {  
        $url = 'https://api.weibo.com/oauth2/authorize?client_id='.$app_id.'&response_type=code&redirect_uri='.$redirect;  
        header('Location:' . $url);  
    }  

获取微博用户信息

[php]
view plain
copy

<?php  
class SinaApi{  
    private $app_id = '150*****5008';  
    private $app_secret = '27cd83ec*******e7b661f74';  
    private $redirect = 'http://www.******.cn/';  
  
    function __construct()  
    {  
  
    }  
  
    /** 
     * 获取access_token 
     * @param $code [string] $code [登陆后返回的$_GET['code']] 
     * @return mixed 
     */  
    function get_access_token($code) {  
        $url = 'https://api.weibo.com/oauth2/access_token?client_id='.$this->app_id.'&client_secret='.$this->app_secret.'&grant_type=authorization_code&code='.$code.'&redirect_uri='.$this->redirect;  
        $data = array(  
        );  
        // $token = array();  
        // parse_str($this->curl_post_content($url, $data), $token);  
        $token = $this->curl_post_content($url, $data);  
        print_R($token);  
        return $token;  
    }  
  
    /** 
     * [string] $token [授权码] 
     * @return mixed 
     */  
    function get_user_info($token) {  
        $url = 'https://api.weibo.com/2/users/show.json?access_token='.$token;  
        $info = json_decode($this->curl_get_content($url), TRUE);  
        return $info;  
    }  
    private function curl_get_content($url)  
    {  
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);  
        curl_setopt($ch, CURLOPT_URL, $url);  
        //设置超时时间为3s  
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);  
        $result = curl_exec($ch);  
        curl_close($ch);  
        return $result;  
    }  
    private function curl_post_content($url, $post_data) {  
        $ch = curl_init();  
        curl_setopt ($ch, CURLOPT_URL, $url);  
        curl_setopt ($ch, CURLOPT_POST, 1);  
        if($post_data != ''){  
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);  
        }  
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);  
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 30);  
        curl_setopt($ch, CURLOPT_HEADER, false);  
        $file_contents = curl_exec($ch);  
        curl_close($ch);  
        return $file_contents;  
    }  
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: