获取请求token的url
public static getAccessToken ( $code, $redirect_uri ) : string | ||
$code | 调用authorize时返回的code | |
$redirect_uri | 回调地址,必须和请求code时的redirect_uri一致 | |
return | string |
public function actionCallback($oauth_token) { try { $login_secret = $this->getSession('oauth')->login_secret; if (!$oauth_token) { echo "Error! There is no OAuth token!"; exit; } if (!$login_secret) { echo "Error! There is no OAuth secret!"; exit; } $this->oauth->enableDebug(); $this->oauth->setToken($oauth_token, $login_secret); $access_token_info = $this->oauth->getAccessToken(self::ACCESS_TOKEN_URL); $this->getSession('oauth')->login_secret = false; $this->getSession('oauth')->token = $access_token_info['oauth_token']; $this->getSession('oauth')->secret = $access_token_info['oauth_token_secret']; $this->getUserDetailsAndLoginUser(); } catch (OAuthException $E) { Debugger::log($E); //zalogujeme for sichr echo "OAuth login failed. Please, contact administrator."; $this->terminate(); } }
protected function connect() { $this->oauth->setToken($this->token, $this->tokenSecret); $accessToken = $this->oauth->getAccessToken(self::URL_ACCESS . (Request::hasQuery('oauth_verifier') ? '?oauth_verifier=' . Request::getQuery('oauth_verifier') : '')); $this->state = self::STATE_CONNECTED; $this->token = $accessToken['oauth_token']; $this->tokenSecret = $accessToken['oauth_token_secret']; Session::set('Twitter_Token', $this->token); Session::set('Twitter_TokenSecret', $this->tokenSecret); Session::set('Twitter_State', $this->state); TwCensus::redirect('/'); }
public static function getTokenCredentials() { $result = array(); try { $access_token_url = \Fuel\Core\Config::get('evernote.evernote_server') . '/oauth'; $oauth_verifier = \Fuel\Core\Session::get('oauthVerifier'); $oauth = new \OAuth(\Fuel\Core\Config::get('evernote.consumer_key'), \Fuel\Core\Config::get('evernote.consumer_secret')); $request_token = \Fuel\Core\Session::get('requestToken'); $request_token_secret = \Fuel\Core\Session::get('requestTokenSecret'); $oauth->setToken($request_token, $request_token_secret); $access_token_info = $oauth->getAccessToken($access_token_url, null, $oauth_verifier); if ($access_token_info) { $result['status'] = 'success'; $result['access_token'] = $access_token_info['oauth_token']; $result['access_token_secret'] = $access_token_info['oauth_token_secret']; $result['shard_id'] = $access_token_info['edam_shard']; $result['user_id'] = $access_token_info['edam_userId']; } else { $result['status'] = 'failure'; } } catch (\OAuthException $e) { $result['status'] = 'failure'; } return $result; }
public function shouquan($code, $openid, $openkey, $redirect_uri) { OAuth::init($this->client_id, $this->client_secret); Tencent::$debug = $this->debug; $callback = $redirect_uri; //回调url if ($code) { //已获得code //获取授权token $url = OAuth::getAccessToken($code, $callback); $r = Http::request($url); parse_str($r, $out); //存储授权数据 if (@$out['access_token']) { $_SESSION['t_access_token'] = $out['access_token']; $_SESSION['t_refresh_token'] = $out['refresh_token']; $_SESSION['t_expire_in'] = $out['expires_in']; $_SESSION['t_code'] = $code; $_SESSION['t_openid'] = $openid; $_SESSION['t_openkey'] = $openkey; //验证授权 $r = OAuth::checkOAuthValid(); if ($r) { //echo('<h3>授权成功!!!</h3><br>'); //print_r($r);exit; //header('Location: ' . $callback);//刷新页面 return $r; } else { exit('<h3>授权失败,请重试</h3>'); } } else { exit($r); } } }
function call($command) { session_start(); if (!isset($_GET['oauth_token']) && $_SESSION['state'] == 1) { $_SESSION['state'] = 0; } try { $oauth = new \OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->enableDebug(); if (!isset($_GET['oauth_token']) && !$_SESSION['state']) { $request_token_info = $oauth->getRequestToken($this->request_url); $_SESSION['secret'] = $request_token_info['oauth_token_secret']; $_SESSION['state'] = 1; header('Location: ' . $this->authorize_url . '?oauth_token=' . $request_token_info['oauth_token']); exit; } else { if ($_SESSION['state'] == 1) { $oauth->setToken($_GET['oauth_token'], $_SESSION['secret']); $access_token_info = $oauth->getAccessToken($this->access_token_url); error_log("acc token info " . $access_token_info, 1, "*****@*****.**"); $_SESSION['state'] = 2; $_SESSION['token'] = $access_token_info['oauth_token']; $_SESSION['secret'] = $access_token_info['oauth_token_secret']; } } $oauth->setToken($_SESSION['token'], $_SESSION['secret']); $oauth->fetch("{$this->api_url}{$command}"); $json = json_decode($oauth->getLastResponse()); } catch (\OAuthException $E) { return $E->lastResponse; } return $json; }
function getAccessToken($token, $token_secret, $verifier) { $oauth = new OAuth($this->site_id, $this->secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->setToken($token, $token_secret); $token_info = $oauth->getAccessToken(ENTRECARD_API_URL . "/access_token", null, $verifier); return array($token_info['user_id'], $token_info['oauth_token'], $token_info['oauth_token_secret']); }
/** * Retrive Twitter auth data in Cookie set by Twitter JSSDK. * * @param CakeRequest $request Request object. * @return mixed Either false or an object of user information of Twitter */ public function getUser(CakeRequest $request) { $api = Configure::read('SocialSignIn.API.Twitter'); // $request_token_url = 'http://api.twitter.com/oauth/request_token'; // $access_token_url = "http://twitter.com/oauth/access_token"; // $authorize_url="http://twitter.com/oauth/authorize"; $session_name = $this->settings['session']; $s = SessionComponent::read($session_name); // if already authenticated, user object is stored in the session if (isset($s['User']) && is_object($s['User'])) { return $s['User']; } if (isset($request->query['oauth_token']) && isset($s['secret'])) { $oauth = new OAuth($this->settings['consumer_key'], $this->settings['consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->setToken($request->query['oauth_token'], $s['secret']); $access_token_info = $oauth->getAccessToken($api['access_token_url']); if ($access_token_info['oauth_token']) { $oauth->setToken($access_token_info['oauth_token'], $access_token_info['oauth_token_secret']); $data = $oauth->fetch($api['fetch_url']); $user = json_decode($oauth->getLastResponse()); return $user; } } return false; }
function authorize() { $oauth = new OAuth(Config::get('TWITTER_CONSUMER_KEY'), Config::get('TWITTER_CONSUMER_SECRET'), OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->enableDebug(); try { $request_token = $oauth->getRequestToken($this->request_token_url); } catch (OAuthException $e) { debug($oauth->debugInfo); } $url = $this->authorize_url . '?' . http_build_query(array('oauth_token' => $request_token['oauth_token'], 'callback_url')); print 'Authorize: ' . $url . "\n"; system(sprintf('open %s', escapeshellarg($url))); fwrite(STDOUT, "Enter the PIN: "); $verifier = trim(fgets(STDIN)); //$oauth->setToken($token, $request_token['oauth_token_secret']); //$access_token = $oauth->getAccessToken($this->access_token_url); $oauth->setToken($request_token['oauth_token'], $request_token['oauth_token_secret']); try { $access_token = $oauth->getAccessToken($this->access_token_url, NULL, $verifier); } catch (OAuthException $e) { debug($oauth->debugInfo); } printf("'TWITTER_TOKEN' => '%s',\n'TWITTER_TOKEN_SECRET' => '%s',\n", $access_token['oauth_token'], $access_token['oauth_token_secret']); exit; }
public static function authorize($consumer_key, $consumer_secret, $request_token, $request_secret) { $oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM); $oauth->setToken($request_token, $request_secret); $access_token_info = $oauth->getAccessToken(GOOGLE_OAUTH_ACCESS_TOKEN_API); return array("access_token" => $access_token_info["oauth_token"], "access_secret" => $access_token_info["oauth_token_secret"]); }
function setOAuth() { // pecl_oauth $oauth = new OAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM); $oauth->enableDebug(); try { if (isset($_GET['oauth_token'], $_SESSION['oauth_token_secret'])) { $oauth->setToken($_GET['oauth_token'], $_SESSION['oauth_token_secret']); $accessToken = $oauth->getAccessToken(TWITTER_ACCESS_URL); $_SESSION['oauth_token'] = $accessToken['oauth_token']; $_SESSION['oauth_token_secret'] = $accessToken['oauth_token_secret']; $response = $oauth->getLastResponse(); parse_str($response, $get); if (!isset($get['user_id'])) { throw new Exception('Authentication failed.'); } } else { $requestToken = $oauth->getRequestToken(TWITTER_REQUEST_URL); $_SESSION['oauth_token_secret'] = $requestToken['oauth_token_secret']; header('Location: ' . TWITTER_AUTHORIZE_URL . '?oauth_token=' . $requestToken['oauth_token']); die; } } catch (Exception $e) { var_dump($oauth->debugInfo); die($e->getMessage()); } }
public function checkUser($do) { // dump($_REQUEST); // dump($do); // exit; OAuth::init(QQ_KEY, QQ_SECRET); $callback = $this->getCallback('qq', $do); if ($_REQUEST['code']) { $code = $_REQUEST['code']; $openid = $_REQUEST['openid']; $openkey = $_REQUEST['openkey']; //获取授权token $url = OAuth::getAccessToken($code, $callback); $r = Http::request($url); parse_str($r, $out); //存储授权数据 if ($out['access_token']) { $_SESSION['t_access_token'] = $out['access_token']; $_SESSION['t_refresh_token'] = $out['refresh_token']; $_SESSION['t_expire_in'] = $out['expires_in']; $_SESSION['t_code'] = $code; $_SESSION['t_openid'] = $openid; $_SESSION['t_openkey'] = $openkey; $_SESSION['qq']['access_token'] = $out['access_token']; $_SESSION['qq']['refresh_token'] = $out['refresh_token']; $_SESSION['open_platform_type'] = 'qq'; //验证授权 $r = OAuth::checkOAuthValid(); if ($r) { // header('Location: ' . $callback);//刷新页面 return true; } else { // exit('<h3>授权失败,请重试</h3>'); return false; } } else { exit($r); } } else { //获取授权code if ($_GET['openid'] && $_GET['openkey']) { //应用频道 $_SESSION['t_openid'] = $_GET['openid']; $_SESSION['t_openkey'] = $_GET['openkey']; //验证授权 $r = OAuth::checkOAuthValid(); if ($r) { // header('Location: ' . $callback);//刷新页面 return true; } else { // exit('<h3>授权失败,请重试</h3>'); return false; } } else { $url = OAuth::getAuthorizeURL($callback); header('Location: ' . $url); } } }
public function getAccessToken($oauthToken, $oauthTokenSecret, $oauthVerifier) { $oauth = new \OAuth($this->consumerKey, $this->consumerSecret); $oauth->setToken($oauthToken, $oauthTokenSecret); $accessToken = $oauth->getAccessToken($this->getEndpoint('oauth'), null, $oauthVerifier); $this->token = $accessToken['oauth_token']; return $accessToken; }
public function testError() { $oauth = new OAuth('wx229aa24fa4a2xxxx', 'error_secret'); $oauth->getAccessToken('code', 'error_authorization_code'); $this->assertStringStartsWith('get access token failed: system error', $oauth->error()); $oauth = new OAuth('wx229aa24fa4a2xxxx', 'error_secret', 'error_access_token'); $oauth->api('sns/userinfo', array('openid' => 'error_openid')); $this->assertStringStartsWith('request failed: invalid credential, access_token is invalid or not latest', $oauth->error()); }
/** * @see OAuthHanlder::GetAccessToken() */ public function GetAccessToken($credentials, $verifier, $server = NULL) { $oauth = new OAuth($credentials['oauth_consumer_key'], $credentials['oauth_consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->setRequestEngine(OAUTH_REQENGINE_CURL); $oauth->setVersion('1.0a'); $oauth->setToken($credentials['oauth_token'], $credentials['oauth_token_secret']); $endpoint = $this->GetAccessEndpoint($server); $response = $oauth->getAccessToken($endpoint, NULL, $verifier); $credentials['oauth_token'] = $response['oauth_token']; $credentials['oauth_token_secret'] = $response['oauth_token_secret']; return $credentials; }
/** * Handle callback by managing oauth token, saving oauth state and calling redirect URL * * @param Request $request */ public function handleCallback(Request $request) { try { $this->api = new \OAuth($this->options['consumer_key'], $this->options['consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $this->api->setToken($request->query->get('oauth_token'), $this->secret); $accessToken = $this->api->getAccessToken($this->options['access_token_endpoint']); $this->state = 2; $this->token = $accessToken['oauth_token']; $this->secret = $accessToken['oauth_token_secret']; } catch (\Exception $e) { $this->state = null; } $this->saveState(); header('HTTP/1.1 302 Found'); header('Location: ' . $this->redirectUrl); }
protected function authorize($sKey, $sSecret) { if ($this->isAuthorized()) { return true; } try { $oConsumer = new OAuth($sKey, $sSecret); $oConsumer->setAuthType(OAUTH_AUTH_TYPE_URI); $oConsumer->enableDebug(); $bToken = bx_get('oauth_token') !== false; $mixedSecret = $this->oSession->getValue('sys_oauth_secret'); if (!$bToken && $mixedSecret !== false) { $this->oSession->unsetValue('sys_oauth_secret'); $mixedSecret = false; } //--- Get request token and redirect to authorize. if (!$bToken && $mixedSecret === false) { $aRequestToken = $oConsumer->getRequestToken(BX_DOL_OAUTH_URL_REQUEST_TOKEN); if (empty($aRequestToken)) { return _t('_adm_err_oauth_cannot_get_token'); } if ($this->isServerError($aRequestToken)) { return $this->processServerError($aRequestToken); } $this->oSession->setValue('sys_oauth_secret', $aRequestToken['oauth_token_secret']); return _t('_adm_msg_oauth_need_authorize', bx_append_url_params(BX_DOL_OAUTH_URL_AUTHORIZE, array('oauth_token' => $aRequestToken['oauth_token'], 'sid' => bx_site_hash()))); } //--- Get access token. if ($bToken && $mixedSecret !== false) { $oConsumer->setToken(bx_get('oauth_token'), $mixedSecret); $aAccessToken = $oConsumer->getAccessToken(bx_append_url_params(BX_DOL_OAUTH_URL_ACCESS_TOKEN, array('oauth_verifier' => bx_get('oauth_verifier')))); if (empty($aAccessToken)) { return _t('_adm_err_oauth_cannot_get_token'); } if ($this->isServerError($aAccessToken)) { return $this->processServerError($aAccessToken); } $this->oSession->setValue('sys_oauth_token', $aAccessToken['oauth_token']); $this->oSession->setValue('sys_oauth_secret', $aAccessToken['oauth_token_secret']); $this->oSession->setValue('sys_oauth_authorized', 1); $this->oSession->setValue('sys_oauth_authorized_user', (int) bx_get('oauth_user')); return true; } } catch (OAuthException $e) { return _t('_adm_err_oauth_cannot_get_token'); } }
public static function get_token_credentials($oauth_verifier, $request_token, $request_token_secret) { $consumer_key = Config::get('evernote.oauth_consumer_key'); $consumer_secret = Config::get('evernote.oauth_consumer_secret'); $access_token_url = Config::get('evernote.evernote_server'); $access_token_url .= Config::get('evernote.access_token_path'); try { $oauth = new OAuth($consumer_key, $consumer_secret); $oauth->setToken($request_token, $request_token_secret); $access_token_info = $oauth->getAccessToken($access_token_url, null, $oauth_verifier); if ($access_token_info) { return $access_token_info; } else { Log::error('Failed to obtain token credentials: ' . $oauth->getLastResponse()); } } catch (OAuthException $e) { Log::error('Error obtaining token credentials: ' . $e->getMessage()); } }
function actionReturn() { if ($_GET['code']) { //已获得code $code = $_GET['code']; $openid = $_GET['openid']; $openkey = $_GET['openkey']; //获取授权token $url = \OAuth::getAccessToken($code, $this->url); $access_token = $_SESSION['t_access_token']; $r = \Http::request($url); parse_str($r, $out); //存储授权数据 if ($out['access_token']) { $_SESSION['t_access_token'] = $out['access_token']; $_SESSION['t_expire_in'] = $out['expire_in']; $_SESSION['t_code'] = $code; $_SESSION['t_openid'] = $openid; $_SESSION['t_openkey'] = $openkey; //验证授权 $ret = \OAuth::checkOAuthValid(); $ret = \Tencent::api('user/info'); $uid_get = json_decode($ret, true); try { $uid = $uid_get['data']['openid']; $me['id'] = $uid; $me['name'] = $uid_get['data']['name']; $me['email'] = $uid_get['data']['email']; $me['nickname'] = $uid_get['data']['nick']; $r = $this->member_get_third_set_user($me, $this->oauth_id, $access_token); flash('success', __('login success')); $this->redirect(return_url()); } catch (OAuthException $e) { flash('error', __('login error')); $this->redirect(return_url()); } } } exit; }
function oauth_callback() { global $php_self; if (!isset($_GET['oauth_token'])) { echo "Error! There is no OAuth token!"; } elseif (!isset($_SESSION['secret'])) { echo "Error! There is no OAuth secret!"; } else { try { $oauth = new OAuth(CLIENT_ID, CLIENT_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->setToken($_GET['oauth_token'], $_SESSION['secret']); $access_token_info = $oauth->getAccessToken(OSM_OAUTH_URL . 'access_token'); unset($_SESSION['secret']); $_SESSION['osm_token'] = strval($access_token_info['oauth_token']); $_SESSION['osm_secret'] = strval($access_token_info['oauth_token_secret']); $oauth->setToken($_SESSION['osm_token'], $_SESSION['osm_secret']); try { $oauth->fetch(OSM_API_URL . 'user/details'); $user_details = $oauth->getLastResponse(); $xml = simplexml_load_string($user_details); $_SESSION['osm_user'] = strval($xml->user['display_name']); $langs = array(); foreach ($xml->user->languages->lang as $lang) { $langs[] = strval($lang); } $_SESSION['osm_langs'] = $langs; } catch (OAuthException $E) { // well, we don't need that } header("Location: " . $php_self . '?action=remember'); } catch (OAuthException $E) { echo "<pre>Exception:\n"; print_r($E); echo '</pre>'; } } exit; }
function __construct() { // In state=1 the next request should include an oauth_token. // If it doesn't go back to 0 if (!isset($_GET['oauth_token']) && $_SESSION['state'] == 1) { $_SESSION['state'] = 0; } try { $oauth = new OAuth(self::CONSKEY, self::CONSSEC, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->enableDebug(); if ($_SESSION['state'] != 2) { if (!isset($_GET['oauth_token']) && !$_SESSION['state']) { $queryString = http_build_query(array('scope' => 'https://www.googleapis.com/auth/latitude', 'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'])); $requestToken = $oauth->getRequestToken(self::REQ_URL . '?' . $queryString); $_SESSION['secret'] = $requestToken['oauth_token_secret']; $_SESSION['state'] = 1; $queryString = http_build_query(array('oauth_token' => $requestToken['oauth_token'], 'domain' => $_SERVER['HTTP_HOST'], 'location' => 'all', 'granularity' => 'best')); header('Location: ' . self::AUTH_URL . '?' . $queryString); exit; } else { if ($_SESSION['state'] == 1) { $oauth->setToken($_GET['oauth_token'], $_SESSION['secret']); $accessToken = $oauth->getAccessToken(self::ACC_URL); $_SESSION['state'] = 2; $_SESSION['token'] = $accessToken['oauth_token']; $_SESSION['secret'] = $accessToken['oauth_token_secret']; } } } $oauth->setToken($_SESSION['token'], $_SESSION['secret']); } catch (OAuthException $e) { trigger_error("OAuth fail: " . print_r($e, true)); print "Oh dear, something failed during the OAuth handshake with google!"; exit; } $this->oauth = $oauth; }
public function callbackAction() { if (!Request::get('oauth_verifier')) { return new FatalErrorResponse('Content owner did not authorize the temporary credentials'); } try { $oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET); $oauth->setToken($_SESSION['requestToken'], $_SESSION['requestTokenSecret']); $accessTokenInfo = $oauth->getAccessToken(ACCESS_TOKEN_URL, null, Request::get('oauth_verifier')); if ($accessTokenInfo) { $_SESSION['accessToken'] = $accessTokenInfo['oauth_token']; $_SESSION['accessTokenSecret'] = $accessTokenInfo['oauth_token_secret']; $_SESSION['noteStoreUrl'] = $accessTokenInfo['edam_noteStoreUrl']; $_SESSION['webApiUrlPrefix'] = $accessTokenInfo['edam_webApiUrlPrefix']; $_SESSION['tokenExpires'] = (int) ($accessTokenInfo['edam_expires'] / 1000); $_SESSION['userId'] = $accessTokenInfo['edam_userId']; return new RedirectResponse('/'); } else { return new FatalErrorResponse('Failed to obtain token credentials: ' . $oauth->getLastResponse()); } } catch (OAuthException $e) { return new FatalErrorResponse('Error obtaining token credentials: ' . $e->getMessage()); } }
$_SESSION['state'] = 0; } try { $authType = $_SESSION['state'] == 2 ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI; $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType); $oauthClient->enableDebug(); if (!isset($_GET['oauth_token']) && !$_SESSION['state']) { $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl); $_SESSION['secret'] = $requestToken['oauth_token_secret']; $_SESSION['state'] = 1; header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']); exit; } else { if ($_SESSION['state'] == 1) { $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']); $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl); $_SESSION['state'] = 2; $_SESSION['token'] = $accessToken['oauth_token']; $_SESSION['secret'] = $accessToken['oauth_token_secret']; header('Location: ' . $callbackUrl); exit; } else { $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']); $resourceUrl = "{$apiUrl}/products"; $oauthClient->fetch($resourceUrl); $productsList = json_decode($oauthClient->getLastResponse()); print_r($productsList); } } } catch (OAuthException $e) { print_r($e);
public function callback() { es_session::start(); require_once APP_ROOT_PATH . 'system/api_login/Tencent/Tencent.php'; OAuth::init($this->api['config']['app_key'], $this->api['config']['app_secret']); $code = trim(addslashes($_REQUEST['code'])); $openid = trim(addslashes($_REQUEST['openid'])); $openkey = trim(addslashes($_REQUEST['openkey'])); if ($this->api['config']['app_url'] == "") { $app_url = get_domain() . APP_ROOT . "/api_callback.php?c=Tencent"; } else { $app_url = $this->api['config']['app_url']; } $token_url = OAuth::getAccessToken($code, $app_url); $result = Http::request($token_url); $result = preg_replace('/[^\\x20-\\xff]*/', "", $result); //清除不可见字符 $result = iconv("utf-8", "utf-8//ignore", $result); //UTF-8转码 parse_str($result, $result_arr); $access_token = $result_arr['access_token']; $refresh_token = $result_arr['refresh_token']; $name = $result_arr['name']; $nick = $result_arr['nick']; $is_bind = intval(es_session::get("is_bind")); es_session::set("t_access_token", $access_token); es_session::set("t_openid", $openid); es_session::set("t_openkey", $openkey); if (es_session::get("t_access_token") || es_session::get("t_openid") && es_session::get("t_openkey")) { $msg['field'] = 'tencent_id'; $msg['id'] = $name; $msg['name'] = $name; $msg['t_access_token'] = $access_token; $msg['t_openid'] = $access_token; $msg['t_openkey'] = $openkey; es_session::set("api_user_info", $msg); if (!$msg['name']) { app_redirect(url("index")); } $user_data = $GLOBALS['db']->getRow("select * from " . DB_PREFIX . "user where tencent_id = '" . $name . "' and tencent_id <> ''"); if ($user_data) { $user_current_group = $GLOBALS['db']->getRow("select * from " . DB_PREFIX . "user_group where id = " . intval($user_data['group_id'])); $user_group = $GLOBALS['db']->getRow("select * from " . DB_PREFIX . "user_group where score <=" . intval($user_data['score']) . " order by score desc"); if ($user_current_group['score'] < $user_group['score']) { $user_data['group_id'] = intval($user_group['id']); } $GLOBALS['db']->query("update " . DB_PREFIX . "user set t_access_token ='" . $access_token . "',t_openkey = '" . $openkey . "',t_openid = '" . $openid . "', login_ip = '" . get_client_ip() . "',login_time= " . get_gmtime() . ",group_id=" . intval($user_data['group_id']) . " where id =" . $user_data['id']); $GLOBALS['db']->query("update " . DB_PREFIX . "deal_cart set user_id = " . intval($user_data['id']) . " where session_id = '" . es_session::id() . "'"); require_once APP_ROOT_PATH . "system/libs/user.php"; auto_do_login_user($user_data['user_name'], $user_data['user_pwd'], $from_cookie = false); es_session::delete("api_user_info"); app_recirect_preview(); } else { $this->create_user(); app_redirect(url("shop", "user#stepone")); } } }
<?php session_start(); require 'predloga.php'; require 'PassFunctions.php'; require 'Obrazci.php'; head(); meni(); leviStolpec(); // Vaje za preverjanje moči gesla echo "Avtentikacija na Flickr"; try { $oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET); $oauth->setToken($request_token, $request_token_secret); $access_token_info = $oauth->getAccessToken("https://example.com/oauth/access_token"); if (!empty($access_token_info)) { print_r($access_token_info); } else { print "Failed fetching access token, response was: " . $oauth->getLastResponse(); } } catch (OAuthException $E) { echo "Response: " . $E->lastResponse . "\n"; } // desniStolpec('Logiranje'); noga(); ?>
<?php require "config.inc.php"; try { $o = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION); $access_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . "/access_token_resp")); $o->setToken($access_token_info["oauth_token"], $access_token_info["oauth_token_secret"]); /* the following bit refreshes the token using the session handle (http://wiki.oauth.net/ScalableOAuth) ... you don't need it unless your original access token is invalid but you'll need to audit this yourself, for example sakes we'll pretend it has expired. */ if (!empty($access_token_info["oauth_session_handle"])) { $o->setAuthType(OAUTH_AUTH_TYPE_URI); $access_token_info = $o->getAccessToken("https://api.login.yahoo.com/oauth/v2/get_token", $access_token_info["oauth_session_handle"]); $o->setToken($access_token_info["oauth_token"], $access_token_info["oauth_token_secret"]); $o->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION); file_put_contents(OAUTH_TMP_DIR . "/access_token_resp", serialize($access_token_info)); } /* done refreshing access token, time to do some fetching! */ $query = rawurlencode("select * from social.profile where guid=me"); $o->fetch("http://query.yahooapis.com/v1/yql?q={$query}&format=xml"); $response_info = $o->getLastResponseInfo(); header("Content-Type: {$response_info["content_type"]}"); echo $o->getLastResponse(); } catch (OAuthException $E) { echo "Exception caught!\n"; echo "Response: " . $E->lastResponse . "\n"; }
<?php require "config.inc.php"; try { $o = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $request_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . "/request_token_resp")); $o->setToken($request_token_info["oauth_token"], $request_token_info["oauth_token_secret"]); $arrayResp = $o->getAccessToken("https://www.google.com/accounts/OAuthGetAccessToken"); file_put_contents(OAUTH_TMP_DIR . "/access_token_resp", serialize($arrayResp)); echo "Finished getting the access token!\n"; } catch (OAuthException $E) { echo "Response: " . $E->lastResponse . "\n"; }
public function flow() { if (isset($_GET['oauth_token'])) { $consumerKey = $_GET['oauth_consumer_key']; $consumerSecret = $_GET['oauth_consumer_secret']; $token = $_GET['oauth_token']; $tokenSecret = $_GET['oauth_token_secret']; $verifier = $_GET['oauth_verifier']; try { $consumer = getDb()->getCredential($token); $oauth = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION); $oauth->setVersion('1.0a'); $oauth->setToken($token, $tokenSecret); $accessToken = $oauth->getAccessToken(sprintf('%s://%s/v1/oauth/token/access', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST']), null, $verifier); $accessToken['oauth_consumer_key'] = $consumerKey; $accessToken['oauth_consumer_secret'] = $consumerSecret; setcookie('oauth', http_build_query($accessToken)); if (!isset($accessToken['oauth_token']) || !isset($accessToken['oauth_token_secret'])) { echo sprintf('Invalid response when getting an access token: %s', http_build_query($accessToken)); } else { echo sprintf('You exchanged a request token for an access token<br><a href="?reloaded=1">Reload to make an OAuth request</a>', $accessToken['oauth_token'], $accessToken['oauth_token_secret']); } } catch (OAuthException $e) { $message = OAuthProvider::reportProblem($e); getLogger()->info($message); OPException::raise(new OPAuthorizationOAuthException($message)); } } else { if (!isset($_GET['reloaded'])) { $callback = sprintf('%s://%s/v1/oauth/flow', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST']); $name = isset($_GET['name']) ? $_GET['name'] : 'OAuth Test Flow'; echo sprintf('<a href="%s://%s/v1/oauth/authorize?oauth_callback=%s&name=%s">Create a new client id</a>', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST'], urlencode($callback), urlencode($name)); } else { try { parse_str($_COOKIE['oauth']); $consumer = getDb()->getCredential($oauth_token); $oauth = new OAuth($oauth_consumer_key, $oauth_consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION); $oauth->setToken($oauth_token, $oauth_token_secret); $oauth->fetch(sprintf('http://%s/v1/oauth/test?oauth_consumer_key=%s', $_SERVER['HTTP_HOST'], $oauth_consumer_key)); $response_info = $oauth->getLastResponseInfo(); header("Content-Type: {$response_info["content_type"]}"); echo $oauth->getLastResponse(); } catch (OAuthException $e) { $message = OAuthProvider::reportProblem($e); getLogger()->info($message); OPException::raise(new OPAuthorizationOAuthException($message)); } } } }
# Now you must send the token portion of the temporary credential token to # the phone and authorize it using: # - ngCore/Javascript: Social.Common.Auth.authorizeToken # - iOS: [MBAuth authorizeToken:withCallbackQueue:onComplete:] # - Android: com.mobage.global.android.social.common.Auth.authorizeToken # Send the oauth_verifier from the phone back to your app server echo 'Authorize this token on the device: ' . $temporary_credentials['oauth_token']; echo "\n - ngCore/Javascript: Social.Common.Auth.authorizeToken"; echo "\n - iOS: [MBAuth authorizeToken:withCallbackQueue:onComplete:]"; echo "\n - Android: com.mobage.global.android.social.common.Auth.authorizeToken\n"; $oauth_verifier = trim(readline('Enter the oauth_verifier: ')); # # Leg 3 # $path = "/1/{$app_key}/request_token"; $params = array('oauth_verifier' => $oauth_verifier); $url = $server . $path . '?' . http_build_query($params); $token_credentials = $oauth->getAccessToken($url); echo '$token_credentials: '; print_r($token_credentials); $oauth->setToken($token_credentials['oauth_token'], $token_credentials['oauth_token_secret']); # # End of three-legged OAuth! # Now let's do something with our authorization. # Call the REST API to get the user info $url = "{$server}/1/{$app_key}/opensocial/people/@me/@self"; $oauth->fetch($url); $response = $oauth->getLastResponse(); echo 'User: '; print_r($response); echo "\n";
$request_secret = $response['oauth_token_secret']; print "Hey! Go to this URL and tell us the verifier you get at the end.\n"; print ' ' . $response['xoauth_request_auth_url'] . "\n"; } catch (OAuthException $e) { print $e->getMessage() . "\n"; } // Wait for input, then try to use it to get a new access token. if ($request_token && $request_secret) { print "Type the verifier and hit enter...\n"; $verifier = fgets(STDIN); $verifier = rtrim($verifier); print 'verifier: ' . $verifier . '<br />'; print "Here's the verifier you gave us: {$verifier}\n"; try { $o->setToken($request_token, $request_secret); $response = $o->getAccessToken('https://api.login.yahoo.com/oauth/v2/get_token', NULL, $verifier); print 'response from getaccesstoken: <br />'; print $response; print '<br />'; print "Got it!\n"; $access_token = $response['oauth_token']; $access_secret = $response['oauth_token_secret']; $access_session = $response['oauth_session_handle']; $store_access_token_data = true; print " Token: {$access_token}\n"; print " Secret: {$access_secret}\n"; print " Session Handle: {$access_session}\n\n"; } catch (OAuthException $e) { print 'Error: ' . $e->getMessage() . "<br />"; print 'Response: ' . $e->lastResponse . "<br />"; print "Shoot, couldn't get the access token. :(<br />";
/** * Create the event RSVP popup */ function meetup_event_popup() { session_start(); $header = '<html dir="ltr" lang="en-US"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <title>RSVP to a Meetup</title> <link rel="stylesheet" type="text/css" media="all" href="' . get_bloginfo('stylesheet_url') . '" /> <style> .button { padding:3%; color:white; background-color:#B03C2D; border-radius:3px; display:block; font-weight:bold; width:40%; float:left; text-align:center; } .button.no { margin-left:8%; } </style> </head> <body> <div id="page" class="hfeed meetup event" style="padding:15px;">'; if (array_key_exists('event', $_GET)) { $_SESSION['event'] = $_GET['event']; } if (!array_key_exists('state', $_SESSION)) { $_SESSION['state'] = 0; } // In state=1 the next request should include an oauth_token. // If it doesn't go back to 0 if (!isset($_GET['oauth_token']) && $_SESSION['state'] == 1) { $_SESSION['state'] = 0; } try { $oauth = new OAuth($this->key, $this->secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION); $oauth->enableDebug(); if (!isset($_GET['oauth_token']) && !$_SESSION['state']) { $request_token_info = $oauth->getRequestToken($this->req_url); $_SESSION['secret'] = $request_token_info['oauth_token_secret']; $_SESSION['state'] = 1; header('Location: ' . $this->authurl . '?oauth_token=' . $request_token_info['oauth_token'] . '&oauth_callback=' . $this->callback_url); exit; } else { if ($_SESSION['state'] == 1) { $oauth->setToken($_GET['oauth_token'], $_SESSION['secret']); $verifier = array_key_exists('verifier', $_GET) ? $_GET['verifier'] : null; $access_token_info = $oauth->getAccessToken($this->acc_url, null, $verifier); $_SESSION['state'] = 2; $_SESSION['token'] = $access_token_info['oauth_token']; $_SESSION['secret'] = $access_token_info['oauth_token_secret']; } } $oauth->setToken($_SESSION['token'], $_SESSION['secret']); if (array_key_exists('rsvp', $_GET)) { // button has been pressed. //send the RSVP. if ('yes' == $_GET['rsvp']) { $oauth->fetch("{$this->api_url}/rsvp", array('event_id' => $_SESSION['event'], 'rsvp' => 'yes'), OAUTH_HTTP_METHOD_POST); } else { $response = $oauth->fetch("{$this->api_url}/rsvp", array('event_id' => $_SESSION['event'], 'rsvp' => 'no'), OAUTH_HTTP_METHOD_POST); } $rsvp = json_decode($oauth->getLastResponse()); echo $header; echo '<h1 style="padding:20px 0 0;"><a>' . $rsvp->description . '</a></h1>'; echo '<p>' . $rsvp->details . '.</p>'; exit; } else { // Get event info to display here. $oauth->fetch("{$this->api_url}/2/events?event_id=" . $_SESSION['event']); $event = json_decode($oauth->getLastResponse()); $event = $event->results[0]; $out = '<h1 id="site-title" style="padding:20px 0 0;"><a target="_blank" href="' . $event->event_url . '">' . $event->name . '</a></h1>'; $out .= '<p style="text-align:justify;">' . $event->description . '</p>'; $out .= '<p><span class="rsvp-count">' . $event->yes_rsvp_count . ' ' . _n('attendee', 'attendees', $event->yes_rsvp_count) . '</span></p>'; if (null !== $event->venue) { $venue = $event->venue->name . ' ' . $event->venue->address_1 . ', ' . $event->venue->city . ', ' . $event->venue->state; $out .= "<h3 class='event_location'>Location: <a href='http://maps.google.com/maps?q={$venue}+%28" . $event->venue->name . "%29&z=17' target='_blank'>{$venue}</a></h3>"; } else { $out .= "<p class='event_location'>Location: TBA</p>"; } $out .= '<h2>' . date('F d, Y @ g:i a', intval($event->time / 1000 + $event->utc_offset / 1000)) . '</h2>'; echo $header . $out; $oauth->fetch("{$this->api_url}/rsvps?event_id=" . $_SESSION['event']); $rsvps = json_decode($oauth->getLastResponse()); $oauth->fetch("{$this->api_url}/members?relation=self"); $me = json_decode($oauth->getLastResponse()); $my_id = $me->results[0]->id; foreach ($rsvps->results as $user) { if ($my_id == $user->member_id) { echo "<h3 style='padding:20px 0 0; font-weight:normal; font-size:16px'>Your RSVP: <strong>{$user->response}</strong></h3>"; echo "<p>You can change your RSVP below.</p>"; } } echo "<h1 style='padding:20px 0 0; font-weight:bold; font-size:22px'>RSVP: </h1>"; echo "<p style='font-size:.9em'>Please RSVP at meetup.com if you're bringing someone.</p>"; echo "<a class='button yes' href='{$this->callback_url}&rsvp=yes'>Yes</a>"; echo "<a class='button no' href='{$this->callback_url}&rsvp=no'>No</a>"; echo "<p style='clear:both'></p>"; //echo "<pre>".print_r($event,true)."</pre>"; exit; } } catch (OAuthException $E) { echo $header; echo "<h1 class='entry-title'>There was an error processing your request. Please try again.</h1>"; if (WP_DEBUG) { echo "<pre>" . print_r($E, true) . "</pre>"; } } unset($_SESSION['state']); unset($_SESSION['event']); echo "</div> </body> </html>"; }