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

新浪微博实现第三方网站登录

创建新浪微博账号

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

网站接入

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


创建成功

获取 App key  和 App Sercet

header请求

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

获取微博用户信息

<?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;
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值