Esempio n. 1
0
 public function action_test()
 {
     try {
         $resource = Remote::get('http://docs/api', array(CURLOPT_POST => TRUE, CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded;charset=UTF-8'), CURLOPT_POSTFIELDS => Oauth::build_query(array())));
     } catch (Exception $e) {
         $resource = $e->getMessage();
     }
     echo '<pre>' . print_r($resource, TRUE) . '</pre>';
 }
Esempio n. 2
0
 public function public_accesstoken($platdata, $get_user_data = true, $url = '')
 {
     $code = $this->input[$platdata['response_type']];
     $openid = $this->input['openid'];
     if ($code) {
         $keys = array();
         $keys[$platdata['response_type']] = $code;
         $keys['redirect_uri'] = $platdata['callback'];
         $o = new Oauth($platdata['akey'], $platdata['skey'], $platdata['response_type']);
         $access_token = $o->getAccessToken($url ? $url : $this->settings['share_plat'][$platdata['type']]['accessurl'], $keys);
         //根据uid,name,access_token获取用户头像,名称
         $uid = empty($access_token['uid']) ? '' : $access_token['uid'];
         $name = empty($access_token['name']) ? '' : $access_token['name'];
         if ($get_user_data) {
             $data['userdata'] = $this->get_user->show_user($platdata, $access_token, $uid, $name, $openid, $url);
             if ($this->input['uid'] && $data['userdata']['id'] != $this->input['uid']) {
                 return false;
             }
             if ($data['userdata']['error']) {
                 return false;
             }
         }
         if (!empty($access_token['access_token'])) {
             //更新到数据库中
             if ($this->obj->updatetoken($platdata['token'], array('access_token' => json_encode($access_token), 'openid' => $openid, 'addTime' => TIMENOW))) {
                 $data['openid'] = $openid;
                 $data['access_token'] = $access_token;
                 $data['access_plat_token'] = $platdata['token'];
                 return $data;
             } else {
                 return 'GET_FAILD';
             }
         } else {
             return 'NO_ACCESS_TOKEN';
         }
     } else {
         return 'NO_RESPONSE_TYPE';
     }
 }
Esempio n. 3
0
 /**
  * 合并默认参数和额外参数
  * @param array $params  默认参数
  * @param array/string $param 额外参数
  * @return array:
  */
 protected function param($params, $param)
 {
     $params = parent::param($params, $param);
     /* 签名 */
     ksort($params);
     $param = array();
     foreach ($params as $key => $value) {
         $param[] = "{$key}={$value}";
     }
     $sign = implode('', $param) . $this->appSecret;
     $params['sig'] = md5($sign);
     return $params;
 }
Esempio n. 4
0
 private static function handleAction()
 {
     if (!isset($_POST['action'])) {
         return;
     }
     $auth = new Oauth(self::$authData);
     if ($_POST['action'] == 'doconf') {
         $auth->doConf($_POST['id'], $_POST['key'], $_POST['op']);
         $_POST['action'] = 'get_conf';
     }
     if ($_POST['action'] == 'get_code') {
         $code = SteamGuard::generateSteamGuardCode(self::$authData->shared_secret);
         $out = ['code' => $code[0], 'rcode' => self::$authData->revocation_code, 'time' => $code[1]];
     } elseif ($_POST['action'] == 'get_conf') {
         $out = ['success' => true, 'conf' => $auth->getConfirmations()];
     } elseif ($_POST['action'] == 'revoke_code') {
         $out = $auth->revoke();
     }
     $authData = $auth->getEnc($_POST['ekey']);
     if ($authData != $_POST['authdata']) {
         $out['authdata'] = $authData;
     }
     return $out;
 }
Esempio n. 5
0
 /**
  * _construct
  *
  * 构造方法
  * @access public 
  * @since 5
  * @param string $access_token  access_token value
  * @param string $openid        openid value
  * @return Object QC
  */
 public function __construct($access_token = "", $openid = "")
 {
     parent::__construct();
     //如果access_token和openid为空,则从session里去取,适用于demo展示情形
     if ($access_token === "" || $openid === "") {
         $this->keysArr = array("oauth_consumer_key" => (int) $this->recorder->readInc("appid"), "access_token" => $this->recorder->read("access_token"), "openid" => $this->recorder->read("openid"));
     } else {
         $this->keysArr = array("oauth_consumer_key" => (int) $this->recorder->readInc("appid"), "access_token" => $access_token, "openid" => $openid);
     }
     //初始化APIMap
     /*
      * 加#表示非必须,无则不传入url(url中不会出现该参数), "key" => "val" 表示key如果没有定义则使用默认值val
      * 规则 array( baseUrl, argListArr, method)
      */
     $this->APIMap = array("add_blog" => array("https://graph.qq.com/blog/add_one_blog", array("title", "format" => "json", "content" => null), "POST"), "add_topic" => array("https://graph.qq.com/shuoshuo/add_topic", array("richtype", "richval", "con", "#lbs_nm", "#lbs_x", "#lbs_y", "format" => "json", "#third_source"), "POST"), "get_user_info" => array("https://graph.qq.com/user/get_user_info", array("format" => "json"), "GET"), "add_one_blog" => array("https://graph.qq.com/blog/add_one_blog", array("title", "content", "format" => "json"), "GET"), "add_album" => array("https://graph.qq.com/photo/add_album", array("albumname", "#albumdesc", "#priv", "format" => "json"), "POST"), "upload_pic" => array("https://graph.qq.com/photo/upload_pic", array("picture", "#photodesc", "#title", "#albumid", "#mobile", "#x", "#y", "#needfeed", "#successnum", "#picnum", "format" => "json"), "POST"), "list_album" => array("https://graph.qq.com/photo/list_album", array("format" => "json")), "add_share" => array("https://graph.qq.com/share/add_share", array("title", "url", "#comment", "#summary", "#images", "format" => "json", "#type", "#playurl", "#nswb", "site", "fromurl"), "POST"), "check_page_fans" => array("https://graph.qq.com/user/check_page_fans", array("page_id" => "314416946", "format" => "json")), "add_t" => array("https://graph.qq.com/t/add_t", array("format" => "json", "content", "#clientip", "#longitude", "#compatibleflag"), "POST"), "add_pic_t" => array("https://graph.qq.com/t/add_pic_t", array("content", "pic", "format" => "json", "#clientip", "#longitude", "#latitude", "#syncflag", "#compatiblefalg"), "POST"), "del_t" => array("https://graph.qq.com/t/del_t", array("id", "format" => "json"), "POST"), "get_repost_list" => array("https://graph.qq.com/t/get_repost_list", array("flag", "rootid", "pageflag", "pagetime", "reqnum", "twitterid", "format" => "json")), "get_info" => array("https://graph.qq.com/user/get_info", array("format" => "json")), "get_other_info" => array("https://graph.qq.com/user/get_other_info", array("format" => "json", "#name", "fopenid")), "get_fanslist" => array("https://graph.qq.com/relation/get_fanslist", array("format" => "json", "reqnum", "startindex", "#mode", "#install", "#sex")), "get_idollist" => array("https://graph.qq.com/relation/get_idollist", array("format" => "json", "reqnum", "startindex", "#mode", "#install")), "add_idol" => array("https://graph.qq.com/relation/add_idol", array("format" => "json", "#name-1", "#fopenids-1"), "POST"), "del_idol" => array("https://graph.qq.com/relation/del_idol", array("format" => "json", "#name-1", "#fopenid-1"), "POST"), "get_tenpay_addr" => array("https://graph.qq.com/cft_info/get_tenpay_addr", array("ver" => 1, "limit" => 5, "offset" => 0, "format" => "json")));
 }
Esempio n. 6
0
 /**
  * _construct
  *
  * 构造方法
  * @access public 
  * @since 5
  * @param string $access_token  access_token value
  * @param string $openid        openid value
  * @return Object QC
  */
 public function __construct($access_token = "", $openid = "")
 {
     parent::__construct();
     //如果access_token和openid为空,则从session里去取,适用于demo展示情形
     if ($access_token === "" || $openid === "") {
         $this->keysArr = array("oauth_consumer_key" => (int) $this->recorder->readInc("appid"), "access_token" => $this->recorder->read("access_token"), "openid" => $this->recorder->read("openid"));
     } else {
         $this->keysArr = array("oauth_consumer_key" => (int) $this->recorder->readInc("appid"), "access_token" => $access_token, "openid" => $openid);
     }
     //初始化APIMap
     /*
      * 加#表示非必须,无则不传入url(url中不会出现该参数), "key" => "val" 表示key如果没有定义则使用默认值val
      * 规则 array( baseUrl, argListArr, method)
      */
     $this->APIMap = array("get_user_info" => array("https://api.weixin.qq.com/sns/userinfo", array("format" => "json"), "GET"));
 }
Esempio n. 7
0
 /**
  * Осуществляет авторизацию в github. В случае, если пользователь авторизован в первый раз - добавляет новую запись
  * в таблицу Users. Модель пользователя помещается в сессию "profile". Далее проиходит редирект на /auth/callback
  */
 public function action_github()
 {
     if ($error = $this->request->query('error_code')) {
         $this->generate_auth_error();
     }
     $gh = Oauth::instance('github');
     if ($gh->login()) {
         $profile = $gh->get_user();
         if ($profile) {
             $token = $gh->get_token();
             Cookie::set("auth_token", $token);
             $user = Model_User::findByAttribute('github_id', $profile->id);
             if ($user->is_empty()) {
                 $user = new Model_User();
                 if ($profile->name) {
                     $user->name = $profile->name;
                 } else {
                     $user->name = $profile->login;
                 }
                 $user->github_id = $profile->id;
                 $user->github_uri = $profile->login;
                 $user->photo = $profile->avatar_url;
                 if ($result = $user->save()) {
                     $inserted_id = $result[0];
                     $new_session = new Model_Sessions();
                     $new_session->save($inserted_id, $token);
                 }
             } else {
                 $new_session = new Model_Sessions();
                 if (!$new_session->get_user_id($token)) {
                     $new_session->save($user->id, $token);
                 }
             }
         }
     } else {
     }
     $this->auth_callback('/');
 }
Esempio n. 8
0
 public function oauth_edit_act()
 {
     $id = IFilter::act(IReq::get('id'));
     if ($id == 0) {
         $this->redirect('oauth_list', false);
         Util::showMessage('请选择要修改的登录平台');
         exit;
     }
     $oauthDBObj = new IModel('oauth');
     $oauthRow = $oauthDBObj->getObj('id = ' . $id);
     if (empty($oauthRow)) {
         $this->redirect('oauth_list', false);
         Util::showMessage('请选择要修改的登录平台');
         exit;
     }
     $dataArray = array('name' => IFilter::act(IReq::get('name')), 'is_close' => IFilter::act(IReq::get('is_close')), 'description' => IFilter::act(IReq::get('description')), 'config' => array());
     //获取字段数据
     $oauthObj = new Oauth($id);
     $oauthFields = $oauthObj->getFields();
     if (!empty($oauthFields)) {
         $parmsArray = array_keys($oauthFields);
         foreach ($parmsArray as $val) {
             $dataArray['config'][$val] = IFilter::act(IReq::get($val));
         }
     }
     $dataArray['config'] = serialize($dataArray['config']);
     $oauthDBObj->setData($dataArray);
     $oauthDBObj->update('id = ' . $id);
     $this->redirect('oauth_list');
 }
Esempio n. 9
0
<?php

include_once 'config.php';
$type = $_GET['type'];
$sns = Oauth::getInstance($type, $config);
//跳转到授权页面
header('Location: ' . $sns->getRequestCodeURL());
#!/usr/bin/php
<?php 
// NOTE - You must have special access to use this endoint. To request access, please submit the form here - https://www.shapeways.com/contact/contact-form?email_to=service%2Bbizdev@shapeways.com
require "consumer_key.php";
require "access_token.php";
require "api_url_base.php";
require "error.php";
try {
    $oauth = new Oauth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauth->enableDebug();
    $oauth->setToken($access_token, $access_secret);
} catch (OAuthException $E) {
    Error("setup exception", $E->getMessage(), null, null, $E->debugInfo);
}
try {
    $orderId = 12345;
    // CHANGEME
    $data = array("orderId" => $orderId);
    $data_string = json_encode($data);
    $oauth->fetch($api_url_base . "/orders/{$orderId}/v1", null, OAUTH_HTTP_METHOD_GET, array("Accept" => "application/json"));
    $response = $oauth->getLastResponse();
    $json = json_decode($response);
    if (null == $json) {
        PrintJsonLastError();
        var_dump($response);
    } else {
        print_r($json);
    }
} catch (OAuthException $E) {
    Error("fetch exception", $E->getMessage(), null, $oauth->getLastResponseInfo(), $E->debugInfo);
}
<?php

$a = array();
$a['oauth_token'] = null;
$a['oauth_token_secret'] = null;
$a['authentification_url'] = null;
$oauth_client = new Oauth("key", "secret");
$oauth_client->enableDebug();
try {
    $info = $oauth_client->getRequestToken("http://192.168.187.132/oauth/request_token?oauth_callback=http://192.168.187.132/client/callback.php");
    // Merge in the dummy values, to surpress missing index warnings.
    $info = array_merge($a, $info);
    echo "<h1>We have a request token !</h1>";
    echo "<strong>Request token</strong> : " . $info['oauth_token'] . "<br />";
    echo "<strong>Request token secret</strong> : " . $info['oauth_token_secret'] . "<br />";
    echo "to authenticate go <a href=\"" . $info['authentification_url'] . "?oauth_token=" . $info['oauth_token'] . "\">here</a>";
} catch (OAuthException $E) {
    echo "<pre>" . print_r($E->debugInfo, true) . "</pre>";
}
<?php

if (isset($_REQUEST['oauth_token']) && isset($_REQUEST['oauth_verifier'])) {
    if (isset($_POST['oauth_token'])) {
        try {
            $oauth_client = new Oauth("key", "secret");
            $oauth_client->enableDebug();
            print_r($oauth_client);
            $oauth_client->setToken($_POST['oauth_token'], $_POST['oauth_token_secret']);
            $info = $oauth_client->getAccessToken("http://192.168.187.132/oauth/access_token", null, $_POST['oauth_verifier']);
            echo "<h1>Congrats !</h1>";
            echo "<strong>AccessToken</strong> " . $info['oauth_token'] . "<br />";
            echo "<strong>AccessToken Secret</strong> " . $info['oauth_token_secret'];
            echo "<a href=\"apicall.php?token=" . $info['oauth_token'] . "&token_secret=" . $info['oauth_token_secret'] . "\">get your user id with an api call</a>";
        } catch (OAuthException $E) {
            echo print_r($E->debugInfo);
        }
    } else {
        ?>
			<form method="post" action="callback.php">
				<label>token</label>
				<input type="text" name="oauth_token" value="<?php 
        echo $_REQUEST['oauth_token'];
        ?>
" /><br />
				<label>secret</label>
				<input type="text" name="oauth_token_secret" value="" />
				<span>This is not passed by url, a real client would have stored this somewhere, you can get it from the db</span>
				<br />
				<label>verifier</label>
				<input type="text" name="oauth_verifier" value="<?php 
Esempio n. 13
0
 public function public_oauthlogin($platdata, $wap = '', $url = '')
 {
     $o = new Oauth($platdata['akey'], $platdata['skey'], $platdata['response_type']);
     $loginurl = $o->getAuthorizeURL($url ? $url : $this->settings['share_plat'][$platdata['type']]['oauthurl'], $platdata['callback']);
     return $loginurl;
 }
Esempio n. 14
0
 /**
  * Normalized request string for signature verify
  *
  * @access  public
  * @param   string    $method
  * @param   string    $uri
  * @param   array     $params
  * @return  string
  */
 public static function normalize($method, $uri, array $params)
 {
     // ~ The oauth_signature parameter MUST be excluded.
     unset($params['signature']);
     return $method . '&' . Oauth::urlencode($uri) . '&' . Oauth2::build_query($params);
 }
<?php

if (isset($_POST['token'])) {
    try {
        $oauth_client = new Oauth("key", "secret");
        $oauth_client->enableDebug();
        $oauth_client->setToken($_POST['token'], $_POST['token_secret']);
        $oauth_client->fetch("http://192.168.187.132/oauth/api/user");
        echo "API RESULT : " . $oauth_client->getLastResponse();
    } catch (OAuthException $E) {
        echo $E->debugInfo;
    }
} else {
    ?>
	<form method="post">
		Access token : <input type="text" name="token" value="<?php 
    echo $_REQUEST['token'];
    ?>
" /> <br />
		Access token secret : <input type="text" name="token_secret" value="<?php 
    echo $_REQUEST['token_secret'];
    ?>
" /> <br />
		<input type="submit" value="do An api call" />
	</form>
	<?php 
}
Esempio n. 16
0
 /**
  * @ignore
  */
 public static function build_http_query_multi($params)
 {
     if (!$params) {
         return '';
     }
     uksort($params, 'strcmp');
     $pairs = array();
     self::$boundary = $boundary = uniqid('------------------');
     $MPboundary = '--' . $boundary;
     $endMPboundary = $MPboundary . '--';
     $multipartbody = '';
     foreach ($params as $parameter => $value) {
         if (in_array($parameter, array('pic', 'image')) && $value[0] == '@') {
             $url = ltrim($value, '@');
             $content = file_get_contents($url);
             $array = explode('?', basename($url));
             $filename = $array[0];
             $multipartbody .= $MPboundary . "\r\n";
             $multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"' . "\r\n";
             $multipartbody .= "Content-Type: image/unknown\r\n\r\n";
             $multipartbody .= $content . "\r\n";
         } else {
             $multipartbody .= $MPboundary . "\r\n";
             $multipartbody .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
             $multipartbody .= $value . "\r\n";
         }
     }
     $multipartbody .= $endMPboundary;
     return $multipartbody;
 }
#!/usr/bin/php
<?php 
require "consumer_key.php";
require "api_url_base.php";
require "error.php";
$verbose_debug = true;
try {
    $oauth_client = new Oauth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauth_client->enableDebug();
} catch (OAuthException $E) {
    Error("setup exception", $E->getMessage(), null, null, $E->debugInfo);
}
try {
    $info = $oauth_client->getRequestToken("{$api_url_base}/oauth1/request_token/v1", "oob");
    # work around our Pecl getRequestToken->array bug https://bugs.php.net/bug.php?id=63572 :
    if (array_key_exists('oauth_token_secret', $info) && array_key_exists('authentication_url', $info) && !array_key_exists('oauth_token', $info)) {
        $urlArray = parse_url($info['authentication_url']);
        $info['authentication_url'] = $urlArray['scheme'] . '://' . $urlArray['host'] . $urlArray['path'];
        parse_str($urlArray['query']);
        $info['oauth_token'] = $oauth_token;
    }
    if (array_key_exists('oauth_token', $info) && array_key_exists('oauth_token_secret', $info) && array_key_exists('authentication_url', $info)) {
        echo "Request token        : " . $info['oauth_token'] . "\n";
        echo "Request token secret : " . $info['oauth_token_secret'] . "\n";
        echo "Next please authenticate yourself at " . $info['authentication_url'] . "?oauth_token=" . $info['oauth_token'] . " and collect the PIN for the next step.\n";
        $oauth_client->setToken($info['oauth_token'], $info['oauth_token_secret']);
    } else {
        Error("getRequestToken", null, $info, $oauth_client->getLastResponseInfo(), null);
    }
} catch (OAuthException $E) {
    Error("getRequestToken", $E->getMessage(), null, $oauth_client->getLastResponseInfo(), $E->debugInfo);
Esempio n. 18
0
 public function public_oauthlogin($platdata, $wap = '')
 {
     $o = new Oauth($platdata['akey'], $platdata['skey'], $platdata['oauthurl'], $platdata['shareurl'], $platdata['callback'], $platdata['userurl'], $platdata['response_type']);
     $loginurl = $o->getAuthorizeURL();
     return $loginurl;
 }
Esempio n. 19
0
 protected function requestAccessToken($method = 'POST', array $params = array('grant_type' => 'authorization_code'), $returnType = 'json', array $values = array('access_token', 'expires_in'))
 {
     parent::requestAccessToken($method, $params, $returnType, $values);
 }
<h1>OAuth Test Client</h1>
<p>Note: we don't store any of the information you type in.</p>
<?php 
if ($authorized) {
    $redirect_uri = Oauth::parse_query($query, 'redirect_uri');
    ?>
do you want to let the <strong><?php 
    echo $redirect_uri;
    ?>
</strong> to access your information?
    <br /><br /><a href="<?php 
    echo Oauth::grant_access_uri('http://docs/oauth/authorize');
    ?>
" title="">Approve access</a>
    <a href="<?php 
    echo Oauth::access_denied_uri();
    ?>
" title="">Deny access</a><?php 
} else {
    ?>
<form method="POST" name="oauth_client">
    <input type="hidden" name="oauth_consumer_key" value="<?php 
    echo $oauth_consumer_key;
    ?>
" />
    <input type="hidden" name="oauth_token" value="<?php 
    echo $oauth_token;
    ?>
" />
    <input type="hidden" name="oauth_token_secret" value="<?php 
    echo $oauth_token_secret;
Esempio n. 21
0
        if ($DB->query('INSERT INTO `' . $Prefix . 'app_users`
			 (`ID`, `AppID`, `OpenID`, `AppUserName`, `UserID`, `Time`) 
			VALUES (:ID, :AppID, :OpenID, :AppUserName, :UserID, :Time)', array('ID' => null, 'AppID' => $AppID, 'OpenID' => $OauthObject->OpenID, 'AppUserName' => htmlspecialchars($OauthObject->NickName), 'UserID' => $CurUserID, 'Time' => $TimeStamp))) {
            AlertMsg($Lang['Binding_Success'], $Lang['Binding_Success']);
        } else {
            AlertMsg($Lang['Binding_Failure'], $Lang['Binding_Failure']);
        }
    }
}
$AppID = intval(Request('Get', 'app_id'));
$AppInfo = $DB->row('SELECT * FROM ' . $Prefix . 'app WHERE ID=:ID', array('ID' => $AppID));
if (!file_exists(__DIR__ . '/includes/Oauth.' . $AppInfo['AppName'] . '.class.php') || !$AppInfo) {
    AlertMsg('404 Not Found', '404 Not Found', 404);
} else {
    require __DIR__ . '/includes/Oauth.' . $AppInfo['AppName'] . '.class.php';
    $OauthObject = new Oauth($AppInfo['AppKey']);
}
$Code = Request('Get', 'code');
$State = Request('Get', 'state');
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    //如果不是认证服务器跳转回的回调页,则跳转回授权服务页
    if (!$Code || !$State || empty($_SESSION[$Prefix . 'OauthState']) || $State != $_SESSION[$Prefix . 'OauthState']) {
        //生成State值防止CSRF
        $SendState = md5(uniqid(rand(), TRUE));
        $_SESSION[$Prefix . 'OauthState'] = $SendState;
        // 授权地址
        $AuthorizeURL = Oauth::AuthorizeURL($CurProtocol . $_SERVER['HTTP_HOST'] . $Config['WebsitePath'], $AppID, $AppInfo['AppKey'], $SendState);
        header("HTTP/1.1 301 Moved Permanently");
        header("Status: 301 Moved Permanently");
        header("Location: " . $AuthorizeURL);
Esempio n. 22
0
<?php

require dirname(__FILE__) . '/common.php';
require dirname(__FILE__) . '/language/' . ForumLanguage . '/oauth.php';
$AppID = intval(Request('Get', 'app_id'));
$AppInfo = $DB->row('SELECT * FROM ' . $Prefix . 'app WHERE ID=:ID', array('ID' => $AppID));
if (!file_exists(dirname(__FILE__) . '/includes/Oauth.' . $AppInfo['AppName'] . '.class.php') || !$AppInfo) {
    AlertMsg('404 Not Found', '404 Not Found', 404);
} else {
    require dirname(__FILE__) . '/includes/Oauth.' . $AppInfo['AppName'] . '.class.php';
    $OauthObject = new Oauth($AppInfo['AppKey']);
}
$Code = Request('Get', 'code');
$State = Request('Get', 'state');
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    //如果不是认证服务器跳转回的回调页,则跳转回授权服务页
    if (!$Code || !$State || empty($_SESSION[$Prefix . 'OauthState']) || $State != $_SESSION[$Prefix . 'OauthState']) {
        //生成State值防止CSRF
        $SendState = md5(uniqid(rand(), TRUE));
        $_SESSION[$Prefix . 'OauthState'] = $SendState;
        // 授权地址
        $AuthorizeURL = Oauth::AuthorizeURL('http://' . $_SERVER['HTTP_HOST'] . $Config['WebsitePath'], $AppID, $AppInfo['AppKey'], $SendState);
        header("HTTP/1.1 301 Moved Permanently");
        header("Status: 301 Moved Permanently");
        header("Location: " . $AuthorizeURL);
        exit;
    }
    $Message = '';
    //下面是回调页面的处理
    if (!$OauthObject->GetAccessToken('http://' . $_SERVER['HTTP_HOST'] . $Config['WebsitePath'], $AppID, $AppInfo['AppSecret'], $Code)) {
Esempio n. 23
0
 private function getOauthAccessToken($hostId, array $data)
 {
     $data = ProviderAbstract::getExtension($data, Extension\Oauth::NS);
     $token = isset($data['request_token']) ? $data['request_token'] : null;
     $verifier = isset($data['verifier']) ? $data['verifier'] : null;
     if ($hostId > 0 && !empty($token) && !empty($verifier)) {
         $row = $this->hm->getTable('AmunService\\Core\\Host')->select(array('consumerKey', 'consumerSecret', 'url'))->where('id', '=', $hostId)->where('status', '=', Host\Record::NORMAL)->getRow();
         if (!empty($row)) {
             $url = $this->discoverOauthAcessUrl(new Url($row['url']));
             $oauth = new Oauth($this->http);
             return $oauth->accessToken($url, $row['consumerKey'], $row['consumerSecret'], $token, '', $verifier);
         } else {
             throw new Exception('Invalid host id');
         }
     }
 }
<?php

if (isset($_REQUEST['oauth_token']) && isset($_REQUEST['oauth_verifier'])) {
    if (isset($_POST['oauth_token'])) {
        try {
            $oauth_client = new Oauth("key", "secret");
            $oauth_client->enableDebug();
            $oauth_client->setToken($_POST['oauth_token'], $_POST['oauth_token_secret']);
            $info = $oauth_client->getAccessToken("http://192.168.187.132/oauth/access_token", null, $_POST['oauth_verifier']);
            echo "<h1>Congrats !</h1>";
            echo "<strong>AccessToken</strong> " . $info['oauth_token'] . "<br />";
            echo "<strong>AccessToken Secret</strong> " . $info['oauth_token_secret'];
            echo "<a href=\"apicall.php?token=" . $info['oauth_token'] . "&token_secret=" . $info['oauth_token_secret'] . "\">get your user id with an api call</a>";
        } catch (OAuthException $E) {
            echo print_r($E->debugInfo);
        }
    } else {
        ?>
			<form method="post" action="callback.php">
				<label>token</label>
				<input type="text" name="oauth_token" value="<?php 
        echo $_REQUEST['oauth_token'];
        ?>
" /><br />
				<label>secret</label>
				<input type="text" name="oauth_token_secret" value="" />
				<span>This is not passed by url, a real client would have stored this somewhere, you can get it from the db</span>
				<br />
				<label>verifier</label>
				<input type="text" name="oauth_verifier" value="<?php 
        echo $_REQUEST['oauth_verifier'];
Esempio n. 25
0
 public function __construct($clientId, $clientSecret, $redirectUrl, $state = null)
 {
     parent::__construct($clientId, $clientSecret, $redirectUrl, $state);
 }
Esempio n. 26
0
 protected function connectSamebookUser($samebookUser)
 {
     $user = User::model()->findByAttributes(array('email' => $samebookUser['email']));
     if (!$user) {
         $user = new User();
         $user->email = $samebookUser['email'];
         $user->password = $samebookUser['pwd'];
         $user->salt = $samebookUser['salt'];
         if ($user->save()) {
             $userInfo = new UserInfo();
             $userInfo->name = $samebookUser['username'];
             $userInfo->id = $user->getPrimaryKey();
             $userInfo->email = $user->email;
             $userInfo->introduction = $samebookUser['bio'];
             $userInfo->addTime = time();
             $userInfo->status = 'ok';
             $userInfo->save();
         }
     }
     $userInfo = UserInfo::model()->findByAttributes(array('email' => $samebookUser['email']));
     //列入oauth表
     if (empty($userInfo->oauth)) {
         $oauth = new Oauth();
         $oauth->userId = $user->id;
         $oauth->save();
     }
     $userInfo = UserInfo::model()->findByAttributes(array('email' => $samebookUser['email']));
     //在oauth表中加sbid
     if (!$userInfo->oauth->sbid) {
         $userInfo->oauth->sbid = $samebookUser['userId'];
         $userInfo->oauth->save();
         $userInfo = User::model()->findByAttributes(array('email' => $samebookUser['email']));
     }
 }
Esempio n. 27
0
<?php

@(require_once 'config.inc.php');
$oauth_client = new Oauth(CLIENT_KEY, CLIENT_SECRET);
$oauth_client->enableDebug();
echo "created oauth_client object";
try {
    $info = $oauth_client->getRequestToken("http://localhost/oauth/pages/oauthhandler.php?query=request_token&oauth_callback=http://localhost/oauth/client/callback.php");
    print_r($info);
    echo "<br/><br/><br/><br/>";
    echo "Request token has been obtained";
    echo "Request token:" . $info['oauth_token'];
    echo "Request token secret:" . $info['oauth_token_secret'];
    echo "visit <a href='" . $info['auth_url'] . "&request_token=" . $info['request_token'] . "'>this page</a> to authenticate";
} catch (OAuthException $e) {
    print_r($e);
}
Esempio n. 28
0
 public function oauth_callback()
 {
     $id = intval(ISession::get('oauth'));
     if (!$id) {
         $this->redirect('login');
         exit;
     }
     $oauthObj = new Oauth($id);
     $result = $oauthObj->checkStatus($_GET);
     if ($result === true) {
         $oauthObj->getAccessToken($_GET);
         $userInfo = $oauthObj->getUserInfo();
         if (isset($userInfo['id']) && isset($userInfo['name']) && $userInfo['id'] != '' && $userInfo['name'] != '') {
             $this->bindUser($userInfo, $id);
         } else {
             $this->redirect('login');
         }
     } else {
         $this->redirect('login');
     }
 }
Esempio n. 29
0
 public function requestAccessToken($method = 'GET', array $params = array(), $returnType = 'flat', array $values = array('oauth_token', 'oauth_token_secret'))
 {
     parent::requestAccessToken($method, $params, $returnType, $values);
 }
Esempio n. 30
0
<?php

require_once 'function.php';
require_once 'Connect2.1/qqConnectAPI.php';
//请求accessToken
$oauth = new Oauth();
$accessToken = $oauth->qq_callback();
$openid = $oauth->get_openid();
setcookie('qq_accesstoken', $accessToken, time() + 86400);
setcookie('qq_openid', $openid, time() + 86400);
echo "succeed!";