php新浪登陆

 
<?php
 
/**
* 
* 新浪登陆页面
* 
 * 需要在后台系统设置中设置 META 认证资料, APPKEY, APPSKEY    与高级信息中填入相应的回调地址(重要)
 
步骤是先去取得code在去取accss_token,
获得accsss_token就是授权成功返回的,
有了accsss_token就可以用来调用所有接口了
 
* 
* 修改users表
 * ALTER TABLE `eb_users` ADD `user_sina_uid` VARCHAR(12) NOT NULL DEFAULT '0'  COMMENT '新浪登录唯一UID' ;
* 
*/
 
define('IN_360SHOP', true);
$path = './';
 
include($path . 'extension.inc');
include($path . 'global.'.$phpEx);
 
$userdata = session_pagestart($user_ip, PAGE_LOGIN);
$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);
 
$code = request_var('code', '');
$mod  = request_var('mod', '');
$do   = request_var('do', '');
$id   = request_var('id', '');
 
if( $config['wb_open'] != 1 )
{
    tip_return('/','未开启微博帐号登录');
}
if( is_null($config['wb_akey']) || is_null($config['wb_skey']) )
{
    tip_return('/','NO WEIBO CONFIG  !');
}
 
$redirect_uri = $config['server_name'];
 
if (!strpos( $redirect_uri , 'http://') ) $redirect_uri = 'http://' . $redirect_uri ;
 
//获取code的回调url
$callback_url = $redirect_uri.'/sina_login.php';
 
//获取accss_token的回调url
$redirect_uri .= '/sina_login.php';
$redirect_uri .= $mod ? '?mod='.$mod : '';
$redirect_uri .= $do ? '&do='.$do : '';
$redirect_uri .= $id ? '&id='.$id : '';
$redirect_uri  = urlencode($redirect_uri);
 
//获取code
$codeUrl  = "https://api.weibo.com/oauth2/authorize";
$codeUrl .= "?client_id=". $config['wb_akey'];
$codeUrl .= "&response_type=code";
$codeUrl .= "&redirect_uri=" . $redirect_uri ;
 
if($code)
{
    /**
     * 组织微博URL
     */
    $arrParams = array();
 
    $arrParams['client_id']        = $config['wb_akey'];
    $arrParams['client_secret'] = $config['wb_skey'];
 
    $arrParams['grant_type']    = 'authorization_code';
    $arrParams['redirect_uri']    = urlencode($callback_url);
    $arrParams['code']            = $code;
    /**
     * 组织微博请求地址
     */
    $accessTokenUrl = "https://api.weibo.com/oauth2/access_token?";
    $accessTokenUrl .= "?client_id=".$config['wb_akey'];
    $accessTokenUrl .= "&client_secret=".$config['wb_skey'];
    $accessTokenUrl .= "&grant_type=authorization_code";
    $accessTokenUrl .= "&redirect_uri=".urlencode($callback_url);
    $accessTokenUrl .= "&code=".$code;
    //构造参数
    $ArgList = '';
    foreach( $arrParams AS $key => $val )
    {
        $ArgList .= "$key=" . urlencode($val) . "&";
    }
 
    $ArgList = rtrim($ArgList, '&');
 
    /**
     * CURL获取授权码,获取accss_token
     */
    try {
 
        $headers    = array();
        $headers[]    = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR'];
 
        $ci = curl_init();
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, 'Sae T OAuth2 v0.1');
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, '30');
        curl_setopt($ci, CURLOPT_TIMEOUT, '30');
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_ENCODING, "");
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ci, CURLOPT_HEADER, FALSE);
        curl_setopt($ci, CURLOPT_POST, TRUE);
        curl_setopt($ci, CURLOPT_POSTFIELDS, $ArgList);
        curl_setopt($ci, CURLOPT_URL, $accessTokenUrl );
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );
        $Respond = curl_exec($ci);
        curl_close ($ci);
 
    }catch (Exception $e)
    {
        //echo $e->getMessage();
        $Respond = '';
    }
 
    //返回accss_token,转为对象
    $Respond = json_decode($Respond);
 
    /**
     * 异常处理
     */
    if(empty($Respond)) tip_return('./', '微博授权异常,请联系系统管理人员');
    if(isset($respond->error)) tip_return('./', '微博授权失败,重新授权');
 
 
    /**
     * 授权返回值
     */
    $access_token    = isset($Respond->access_token) ? $Respond->access_token : '' ;
    $expires_in        = isset($Respond->expires_in) ? $Respond->expires_in : 0 ;
    $uid            = isset($Respond->uid) ? $Respond->uid : 0 ;
    $expire_time    = time() + $expires_in;
 
    /**
     * 如果只是登录 在这里结束
     */
    //if( !$mod || !$do || !$id )
    //{
        //判断微博是否绑定
    if( $userdata['user_sina_uid'] != '')
    {
        tip_return('/','该帐号已经绑定了微博帐号');
    }
 
    //$res = sinaLogin($uid);
    //    
    //if($res)
    //{
    //    $msg = '登陆成功!';
    //}
    //else
    //{
    //    $msg = '对不起,登陆失败,请重试!';
    //}
    //}
 
    /**
     * 接口获得微博信息数据
     */
     /*
    include(INCLUDES . 'sina' . DS . 'sina.class.php' );
    $objSina = sina::_new_();
    $objSina->gObjApi = sina::_api_new_('users/show');
    $objSina->gObjApi->access_token($access_token);
    $objSina->gObjApi->uid($uid);
    $objSina->exec();
    $Respond = $objSina->getObjData(); //返回数组数据
    */
    if( isset($Respond->error) ) tip_return('./', $msg );
 
    /**
     * 组织微博会员信息
     */
    $arrParams = array();
    $arrParams['uid']                  = $Respond->id;
    $arrParams['screen_name']          = $Respond->screen_name;
    //$arrParams['avatar_large']       = $Respond->avatar_large;
    //$arrParams['location']              = $Respond->location;
    //$arrParams['domain']              = $Respond->domain;
    //$arrParams['followers_count']      = $Respond->followers_count;
    //$arrParams['bi_followers_count'] = $Respond->bi_followers_count;
    //$arrParams['access_token']          = $access_token;
    //$arrParams['expires_time']          = $expire_time;
    //$arrParams['add_time']               = time();
 
    //修改注册User表信息
    $Respond = sinaLogin($arrParams['uid'], $arrParams['screen_name'] );
 
    if(!$Respond) tip_return('./', '微博会员信息设置失败', 'error');
 
    //sinaUsersInfo($arrParams);
    //
    ////获取双向关注好友
    //$objSina->gObjApi = sina::_api_new_('friendships/friends/bilateral/ids');
    //$objSina->gObjApi->access_token($access_token);
    //$objSina->gObjApi->uid($uid);
    //$objSina->exec();
    //$Respond = $objSina->getObjData(); //返回数组数据
    //
    //if(isset($Respond->error)) return ;
    //
    ///**
    // * 随机获取微博好友
    // */
    //$idsTotalNum = $Respond->total_number;
    //$idsPageNum     = ceil($idsTotalNum/50)-1;
    //$idsPageNum  = $idsPageNum ? $idsPageNum : 1;
    //$randPage     = rand(1, $idsPageNum);
    //
    //$objSina->gObjApi->access_token($access_token);
    //$objSina->gObjApi->uid($uid);
    //$objSina->gObjApi->page($randPage);
    //$objSina->exec();
    //$Respond = $objSina->getObjData(); //返回数组数据
    //
    //if(isset($Respond->error)) return ;
    //
    ////获取随机的四个uid
    //if( count($Respond->ids) < 6) 
    //{
    //    $getNum = $Respond->total_number;
    //}
    //else 
    //{
    //    $getNum = 6;
    //}
    //
    //$idsAryIndex = $idsAry = array();
    //$idsAryIndex = @array_rand($Respond->ids, $getNum);
    //$idsAryIndex = empty($idsAryIndex) ? array(0) : $idsAryIndex;
    //
    //if($getNum == 1)
    //{
    //    $idsAryIndex = array();
    //    $idsAryIndex[] = '0';
    //}
    //
    //foreach ( $idsAryIndex as $val)
    //{
    //    $idsAry[] = $Respond->ids[$val];
    //}
    //
    //$arrParam = array();
    //$arrParam['uid'] = $uid;
    //$arrParam['ids'] = $idsAry;
    //
    //sinaFriendship($arrParam);
 
 
    $url = './';
    if($mod)
    {
        $url .= '?mod='.$mod;
        $url .= $do ? '&do='.$do : '';
        $url .= $id ? '&id='.$id : '';
    }
 
    tip_return( $url, '登录成功,正在为您跳转...');
 
}
 
/**
* 随机获取6个双向关注好友
*/
//function sinaFriendship($arrParams)
//{
//    global $db;
//    
//    if( empty($arrParams)) return ;
//    if( !isset($arrParams['uid'])) return ;
//    if( !isset($arrParams['ids'])) return ;
//    
//    $sql = " SELECT * FROM " . WEIBO_RELATION_TABLE ;
//    $sql .= " WHERE uid = " . $arrParams['uid'];
//    $result = $db->sql_query($sql);
//    while ( $row = $db->sql_fetchrow( $result ) )
//    {
//        if( in_array($row['friend_id'], $row) ) unset($arrParams['ids']);
//    }
//    
//    if(empty($arrParams['ids'])) return ;
//    
//    $dataParams = array();
//    
//    foreach ( $arrParams['ids'] as $val )
//    {
//        $dataParams[] = array(
//            'uid'        => $arrParams['uid'],
//            'friend_id'    => $val
//        );
//    }
//    
//    $sql = 'INSERT INTO ' . WEIBO_RELATION_TABLE . $db->sql_build_array('MULTI_INSERT', $dataParams);
//
//    $db->sql_query($sql);
//    
//    return true;
//}
 
/**
* 记录微博登录信息
*
*/
//function sinaUsersInfo( $arrParams )
//{
//    global $db;
//    
//    $sql  = " SELECT uid FROM " . WEIBO_USERS_TABLE;
//    $sql .= " WHERE uid = " . $arrParams['uid'] ;
//    $sql .= " LIMIT 1 " ;
//    $db->sql_query($sql);
//    $uid = $db->sql_fetchfield('uid');
//    if( $uid )
//    {
//        unset($arrParams['uid']);
//        unset($arrParams['add_time']);
//        
//        $sql = 'UPDATE '. WEIBO_USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $arrParams).' WHERE uid = '.$uid ;    
//    }
//    else 
//    {
//        $sql = 'INSERT INTO ' . WEIBO_USERS_TABLE . $db->sql_build_array('INSERT', $arrParams);
//    }
//    
//    $result = $db->sql_query($sql);
//    
//    if($result) 
//    {
//        return true;
//    }
//    else 
//    {
//        return false;
//    }
//}
 
/**
* 微博帐号注册
*/
function sinaLogin($sina_id, $sina_name='新浪游客')
{
    global $db, $user_ip;
 
    if(!$sina_id) tip_return('./', '登录失败', 'error');
 
    $sql = 'SELECT * FROM ' . USERS_TABLE . " WHERE user_sina_uid = '" . $sina_id . "'";
    $query = $db->sql_query($sql);
    if (!$row = $db->sql_fetchrow($query))
    {
        $arr_params = array(
        'user_realname'        => $sina_name,
        'user_ip'            => $user_ip,
        'user_lastvisit'    => time(),
        'user_regdate'        => time(),
        'user_sina_uid'        => $sina_id,
        'role_type'            => 'ucp',
        'user_active'        => 1,
        );
 
        $sql = 'INSERT INTO ' . USERS_TABLE . $db->sql_build_array('INSERT', $arr_params);
        $result = $db->sql_query($sql);
        if(!$result) tip_return('./', "登录错误", 'error');
 
        $user_id = $db->sql_nextid();
 
        /*注册成功*/
        if($session_id = session_begin($user_id, $user_ip, PAGE_INDEX, FALSE, TRUE, 0))
        {
            call_hook_action('register_success' , array('user_id'=> $user_id));
        }
        else message_die(CRITICAL_ERROR, "Couldn't start session : register", "", __LINE__, __FILE__);
 
        return true;
    }
    else 
    {
        $arr_params = array('user_realname'=> $sina_name);
        $sql = 'UPDATE '. USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $arr_params).' WHERE user_sina_uid = ' . $sina_id ;    
        $db->sql_query($sql);
        session_begin($row['user_id'], $user_ip, PAGE_INDEX, FALSE, 0, 0);
 
        return true;
    }
 
    return false;
}
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>微博帐号登录中……</title>
<script language="javascript">
function geHash()
{
    var    StrPage    =    "<?php echo $codeUrl ?>";
    window.location.assign(StrPage);
    return ;
}
geHash();
</script>
</head>
<body>
</body>
</html>