protected function getUserDetailsAndLoginUser() { $this->oauth->setToken($this->getSession('oauth')->token, $this->getSession('oauth')->secret); //fetch user datail XML $this->oauth->fetch(self::API_URL . "user/details"); $user_details = $this->oauth->getLastResponse(); $xml = simplexml_load_string($user_details); $user = array('id' => $xml->user['id'], 'username' => $xml->user['display_name'], 'account_created' => $xml->user['account_created'], 'img' => $xml->user->img['href'], 'changesets' => $xml->user->changesets['count'], 'traces' => $xml->user->traces['count'], 'description' => $xml->user->description, 'home_lat' => $xml->user->home['lat'], 'home_lon' => $xml->user->home['lon'], 'last_login' => date("Y-m-d H:i:s")); // convert xml-nodes to strings foreach ($user as &$val) { $val = strval($val); } // update db $row = dibi::fetch('SELECT * FROM users WHERE id = %i', $user['id']); if ($row) { //better dont change usernames, we use it as primary key unset($user['username']); dibi::query('UPDATE users SET ', $user, ' WHERE id = %i', $user['id']); } else { $user['first_login'] = new DateTime(); dibi::query('INSERT INTO users ', $user); } // load complete row from db $dbuser = dibi::fetch('SELECT * FROM users WHERE id = %i', $user['id']); if ($dbuser['webpages'] != 'admin' and $dbuser['webpages'] != 'all') { $dbuser['webpages'] = '14' . ($dbuser['webpages'] ? ',' : '') . $dbuser['webpages']; } $this->user->login(new Identity($dbuser['username'], array($dbuser['webpages'] == 'admin' ? 'admin' : 'user'), $dbuser)); // remove all tokens - TODO if tokens to be used, save them in DB $this->redirectUrl('//' . $_SERVER['HTTP_HOST'] . $this->getSession('oauth')->back_url); }
function do_recharge_request($param) { $random_number = rand(5, 10); $transaction_id = "abc" . $random_number; // string. Number not allowed //$db->insert("recharge_test_table",array("trans_id" => $transaction_id,"time"=>time())); $oauth_consumer_key = $client_id = $consumer_key = "spacepoint_nigeria_demo_user1"; $oauth_consumer_secret = $client_secret = $consumer_secret = "wltJSD3ztLKfBQmIW32iSGfcrwe3okS0"; $username = "******"; // $msisdn = "2348059827239"; // mobile number +234-8059827239 // $msisdn = "2340123456789"; $msisdn = "234" . $param['mobile_no']; // $face_value = 5000; $face_value = (int) $param['amount']; //$face_value *= 100; $supplier_api = "ttdemo_v1"; $product_info = array("product" => "airtime"); // echo $face_value; // echo " "; // echo $msisdn;exit; try { $params = array("username" => $username, "msisdn" => $msisdn, "transaction_id" => $transaction_id, "face_value" => $face_value, "supplier_api" => $supplier_api, "product_info" => $product_info); $request = new OAuth($oauth_consumer_key, $oauth_consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); //print_r($request); $request->disableSSLChecks(); $request->fetch("https://hsc16.miranetworks.net:16000/v1/recharge", json_encode($params), OAUTH_HTTP_METHOD_POST, array("Content-Type" => "application/json")); return $response = $request->getLastResponse(); //echo $response; // echo "<pre>"; // print_r($response); // return $response; } catch (Exception $e) { return 'Message: ' . $e->getMessage(); } }
/** * Call Twitter API methods * * @param string $method * @param array $accessToken * @param OAuth $oauth * @param array $params (include oauth_method = POST/GET if need to override) * @return string */ public static function call($method, $accessToken = null, OAuth $oauth, $params = array()) { $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']); $resource = sprintf('%s/%s.json', 'https://api.twitter.com/1.1', $method); // POST or GET $method = OAUTH_HTTP_METHOD_GET; if (isset($params['oauth_method'])) { if ('POST' == strtoupper($params['oauth_method'])) { $method = OAUTH_HTTP_METHOD_POST; } } else { // If resource contains update, retweet (not retweets), filter, destroy, new, create - then POST not GET foreach (array('update', 'retweet/', 'filter', 'destroy', 'new', 'create') as $resourcePart) { if (false !== strpos($resource, $resourcePart)) { $method = OAUTH_HTTP_METHOD_POST; break; } } } if ($method == OAUTH_HTTP_METHOD_GET) { if (count($params)) { $resource = sprintf('%s?%s', $resource, http_build_query($params)); } $params = null; } // Get back bad response if don't specify method where needs to be POST if ($oauth->fetch($resource, $params, $method)) { return $oauth->getLastResponse(); } else { return null; } }
function getTwitterFriendIds($user) { $cacheExpire = 24 * 60 * 60; $POD = $user->POD; $key = $POD->libOptions('twitter_api'); $secret = $POD->libOptions('twitter_secret'); $friends = array(); if ($user->get('twitter_token')) { if ($user->get('twitter_list') != '' && time() - $user->get('twitter_list_generated') < $cacheExpire) { $twoots = json_decode($user->get('twitter_list')); foreach ($twoots as $f) { $friends[] = $f; } } else { try { $oauth = new OAuth($key, $secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->enableDebug(); // This will generate debug output in your error_log $oauth->setToken($user->get('twitter_token'), $user->get('twitter_secret')); $oauth->fetch('https://twitter.com/friends/ids.json?cursor=-1&user_id=' . $user->get('twitter_id')); $json = json_decode($oauth->getLastResponse()); } catch (Exception $e) { } // contains the first 5000 twitter friends foreach ($json->ids as $id) { $friends[] = $id; } $user->addMeta('twitter_list', json_encode($friends)); $user->addMeta('twitter_list_generated', time()); } } return $friends; }
public function REST_Request($callbackUrl, $url, $method, $data = array()) { /** * Example of simple product POST using Admin account via Magento REST API. OAuth authorization is used */ $callbackUrl = $callbackUrl; $temporaryCredentialsRequestUrl = $this->conf['magento_host'] . "/oauth/initiate?oauth_callback=" . urlencode($callbackUrl); $adminAuthorizationUrl = $this->conf['magento_host'] . '/admin/oauth_authorize'; $accessTokenRequestUrl = $this->conf['magento_host'] . '/oauth/token'; $apiUrl = $this->conf['magento_host'] . '/api/rest'; $consumerKey = $this->conf['magentosoap_consumerKey']; $consumerSecret = $this->conf['magentosoap_consumerSecret']; $AccessToken = $this->conf["magentosoap_AccessToken"]; $AccessSecret = $this->conf["magentosoap_AccessSecret"]; try { //$_SESSION['state'] = 2; $authType = 2 == 2 ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI; $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType); $oauthClient->enableDebug(); $oauthClient->disableSSLChecks(); $oauthClient->setToken($AccessToken, $AccessSecret); $resourceUrl = $apiUrl . $url; $oauthClient->fetch($resourceUrl, $data, strtoupper($method), array("Content-Type" => "application/json", "Accept" => "*/*")); //$oauthClient->fetch($resourceUrl); $ret = json_decode($oauthClient->getLastResponse()); $ret = array("error" => 0, "data" => $ret); return $ret; } catch (OAuthException $e) { $ret = array("error" => 1, "message" => "Checking quantity failed"); return $ret; } }
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; }
/** * @return Response */ protected function getResponse() { $responseInfo = $this->oAuthClient->getLastResponseInfo(); $response = Response::createFromRaw($responseInfo['headers_recv']); $response->appendContent($this->oAuthClient->getLastResponse()); return $response; }
/** * @return Response */ protected function getResponse() { $responseHeaders = $this->oAuthClient->getLastResponseHeaders(); $response = Response::createFromRaw($responseHeaders); $response->appendContent($this->oAuthClient->getLastResponse()); return $response; }
function getUserInfo($token, $secret) { $oauth = new OAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->setToken($token, $secret); $oauth->fetch('http://twitter.com/account/verify_credentials.json'); $buf = $oauth->getLastResponse(); return json_decode($buf, true); }
/** * Send a POST request to the specified URL with the specified payload. * @param string $url * @param string $data * @return string Remote data **/ public function sendPOST($url, $data = array()) { $data['_fake_status'] = '200'; // Send the actual request. try { $this->instance->fetch($url, $data, OAUTH_HTTP_METHOD_POST, array('User-Agent' => sprintf(Imgur::$user_agent, Imgur::$key))); } catch (OAuthException $e) { throw new Imgur_Exception("Could not successfully do a sendPOST: " . $e->getMessage(), null, $e); } return $this->instance->getLastResponse(); }
/** * Calls Netflix API methods * * @static * @param $method * @param null $accessToken * @param OAuth $oauth * @param array $params * @return string */ public static function call($method, $accessToken = null, OAuth $oauth, $params = array()) { $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']); $resource = sprintf('%s/%s?output=json', 'http://api.netflix.com', $method); if (count($params)) { $resource = sprintf('%s&%s', $resource, http_build_query($params)); } if ($oauth->fetch($resource)) { return $oauth->getLastResponse(); } }
/** * Calls Vimeo methods: * @see http://vimeo.com/api/docs/methods * * @param String $method = Vimeo method to be called * @param Array $accessToken * @param OAuth $oauth * @param Array $params - additional parameters required for Vimeo method * @return String Json string */ public static function call($method, $accessToken = null, OAuth $oauth, $params = array()) { if ($accessToken) { $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']); } $resource = sprintf('%s?method=%s&format=json', 'http://vimeo.com/api/rest/v2/', $method); if (count($params)) { $resource = sprintf('%s&%s', $resource, http_build_query($params)); } if ($oauth->fetch($resource)) { return $oauth->getLastResponse(); } }
public function linkedin() { $oauth = new OAuth("772ot2tfqntox5", "Y6kUKUlWcWc6yDkd"); $oauth->setToken("94616be2-c292-472d-9f45-dfad9b78f2ef", "cdf34568-ed5f-4a27-a15d-4c8bf276fb4d"); $params = array(); $headers = array(); $method = OAUTH_HTTP_METHOD_GET; $url = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,industry,picture-url,location:(name))?format=json"; $oauth->fetch($url, $params, $method, $headers); $result = json_decode($oauth->getLastResponse(), true); $this->info['nombre'] = $result['firstName']; $this->info['apellido'] = $result['lastName']; $this->info['foto'] = $result['pictureUrl']; $this->info['ubicacion'] = $result['location']['name']; $this->info['industria'] = $result['industry']; }
protected static function fetch_tarball_via_oauth($key, $secret, $uri) { try { $oauth = new OAuth($key, $secret); $oauth->fetch($uri); WP_CLI::debug($oauth->getLastResponseHeaders()); $headers = http_parse_headers($oauth->getLastResponseHeaders()); $mime_type = self::parse_content_type_header($headers['Content-Type']); $content_disposition = self::parse_content_disposition_header($headers['Content-Disposition']); $filename = empty($content_disposition['filename']) ? $filename = tmpfile() : sys_get_temp_dir() . DIRECTORY_SEPARATOR . $content_disposition['filename']; file_put_contents($filename, $oauth->getLastResponse()); return $filename; } catch (OAuthException $e) { WP_CLI::error_multi_line($e->getMessage(), true); } WP_CLI::error('Unknown error', true); }
private function request($method = 'GET', $path, $parameters = array(), $headers = array()) { $url = rtrim($this->host, '/') . '/' . ltrim($path, '/'); try { $result = $this->adapter->fetch($url, $parameters, strtoupper($method), $headers); } catch (\OAuthException $e) { $response = new Response($this->adapter->getLastResponse()); $json = $response->json(); if (empty($json->success)) { throw new \Desk\Exception\ApiCallFailureException('Desk.com request failed', $response); } else { throw $e; } } $body = $this->adapter->getLastResponse(); return new Response($body); }
/** * fetches JSON request on F1, parses and returns response * @param string $url * @param string|array $data * @param const $method * @return void */ public function fetchJson($url, $data = null, $method = OAUTH_HTTP_METHOD_GET) { try { $o = new OAuth($this->settings->key, $this->settings->secret, OAUTH_SIG_METHOD_HMACSHA1); $o->setToken($this->accessToken->oauth_token, $this->accessToken->oauth_token_secret); $headers = array('Content-Type' => 'application/json'); if ($o->fetch($url, $data, $method, $headers)) { if ($this->settings->debug) { return array('headers' => self::http_parse_headers($o->getLastResponseHeaders()), 'response' => json_decode($o->getLastResponse(), true)); } return json_decode($o->getLastResponse(), true); } } catch (OAuthException $e) { $this->error = array('method' => $method, 'url' => $url, 'response' => self::http_parse_headers($o->getLastResponseHeaders())); return $this->error; } }
function oauth_upload($comment, $data) { global $messages, $error; if (!isset($_SESSION['osm_token']) || !isset($_SESSION['osm_secret'])) { $error = _('OAuth token was lost, please relogin.'); oauth_logout(); return false; } try { $stage = 'login'; $oauth = new OAuth(CLIENT_ID, CLIENT_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->setToken($_SESSION['osm_token'], $_SESSION['osm_secret']); $change_data = create_changeset($data, $comment); $xml_content = array('Content-Type' => 'application/xml'); $stage = 'create'; // note: this call works instead of returning 401 because of $xml_content $oauth->fetch(OSM_API_URL . 'changeset/create', $change_data, OAUTH_HTTP_METHOD_PUT, $xml_content); if (!preg_match('/\\d+/', $oauth->getLastResponse(), $m)) { $error = _('Could not aquire changeset id for a new changeset.'); return false; } $changeset = $m[0]; $osc = create_osc($data, $changeset); $stage = 'upload'; $oauth->fetch(OSM_API_URL . 'changeset/' . $changeset . '/upload', $osc, OAUTH_HTTP_METHOD_POST, $xml_content); // todo: parse response and renumber created objects? $stage = 'close'; $oauth->fetch(OSM_API_URL . 'changeset/' . $changeset . '/close', array(), OAUTH_HTTP_METHOD_PUT); $chlink = '<a href="https://www.openstreetmap.org/changeset/' . $changeset . '" target="_blank">' . $changeset . '</a>'; // todo: replace %d with %s and $chlink, removing str_replace $messages[] = '!' . str_replace($changeset, $chlink, sprintf(_('Changeset %d was uploaded successfully.'), $changeset)); return true; } catch (OAuthException $E) { if ($stage == 'upload' && $E->getCode() == 409) { $error = sprintf(_('Conflict while uploading changeset %d: %s.'), $changeset, $oauth->getLastResponse()); // todo: process conflict // http://wiki.openstreetmap.org/wiki/API_0.6#Error_codes_9 } else { print_r($E); $msg = $oauth->getLastResponse(); $error = sprintf(_('OAuth error %d at stage "%s": %s.'), $E->getCode(), $stage, $msg ? $msg : $E->getMessage()); } } return false; }
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()); } }
/** * Retrive Linkedin auth data in Cookie set by Linkedin JSSDK. * * @param CakeRequest $request Request object. * @return mixed Either false or an object of user information of Linkedin */ public function getUser(CakeRequest $request) { $cookie_name = 'linkedin_oauth_' . $this->settings['api_key']; if (isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name]) { $linkedin = json_decode($_COOKIE[$cookie_name]); if (isset($linkedin) && isset($linkedin->access_token) && $this->__verifyToken($linkedin)) { $oauth = new OAuth($this->settings['api_key'], $this->settings['secret_key']); $oauth->fetch('https://api.linkedin.com/uas/oauth/accessToken', array('xoauth_oauth2_access_token' => $linkedin->access_token), OAUTH_HTTP_METHOD_POST); parse_str($oauth->getLastResponse(), $response); $oauth->setToken($response['oauth_token'], $response['oauth_token_secret']); $url = 'http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,public-profile-url,summary,positions)'; // $url = 'http://api.linkedin.com/v1/people/~'; $oauth->fetch($url, array(), OAUTH_HTTP_METHOD_GET, array('x-li-format' => 'json')); $profile = json_decode($oauth->getLastResponse()); $linkedin->profile = $profile; return $linkedin; } } return false; }
private static function makeRequestAndPrintResponse($method, $params, $signature_method = OAUTH_SIG_METHOD_HMACSHA1) { $oauth = new OAuth(Settings::$USOSAPI_CONSUMER_KEY, Settings::$USOSAPI_CONSUMER_SECRET, $signature_method, OAUTH_AUTH_TYPE_URI); if ($signature_method == OAUTH_SIG_METHOD_PLAINTEXT) { $oauth->setRequestEngine(OAUTH_REQENGINE_CURL); } if (Settings::$DEBUG) { $oauth->enableDebug(); } $url = Settings::$USOSAPI_BASE_URL . $method; try { $oauth->fetch($url, $params, OAUTH_HTTP_METHOD_POST); } catch (OAuthException $E) { /* Ignored on purpose. $response_info will be filled either way. */ } $response_info = $oauth->getLastResponseInfo(); header("HTTP/1.0 {$response_info["http_code"]}"); header("Content-Type: {$response_info["content_type"]}"); print $oauth->getLastResponse(); }
private function getCategories() { $brands = Brands::all(); return $brands; $consumer_key = 'b64350b6b45c8fed49aa9983bf197844'; $consumer_secret = '85b3ce2964a63c8fb07d868a58f13b69'; $oauth_token = 'd5608ad8dbd007c0d5cd10688e7d428d'; $oauth_secret = '9f11ac72c96ffd96a00ee58cf67b2d2a'; $client = new \OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION); $client->enableDebug(); $client->setToken($oauth_token, $oauth_secret); try { $client->fetch('http://local.giftbig.com/rest/catalog', '', OAUTH_HTTP_METHOD_GET, ['Content-Type' => 'application/json', 'Accept' => '*/*']); $result = $client->getLastResponse(); $result = json_decode($result); return $result->_embedded->products; } catch (\Exception $e) { return []; } }
function SendTweet($msg) { if ($msg == '') { return false; } DebugMessage('Sending tweet of ' . strlen($msg) . " chars:\n" . $msg); global $twitterCredentials; if ($twitterCredentials === false) { return true; } $params = array(); $params['status'] = $msg; $oauth = new OAuth($twitterCredentials['consumerKey'], $twitterCredentials['consumerSecret']); $oauth->setToken($twitterCredentials['WoWTokens']['accessToken'], $twitterCredentials['WoWTokens']['accessTokenSecret']); $url = 'https://api.twitter.com/1.1/statuses/update.json'; try { $didWork = $oauth->fetch($url, $params, 'POST', array('Connection' => 'close')); } catch (OAuthException $e) { $didWork = false; } $ri = $oauth->getLastResponseInfo(); $r = $oauth->getLastResponse(); if ($didWork && $ri['http_code'] == '200') { $json = json_decode($r, true); if (json_last_error() == JSON_ERROR_NONE) { if (isset($json['id_str'])) { return $json['id_str']; } } return true; } if (isset($ri['http_code'])) { DebugMessage('Twitter returned HTTP code ' . $ri['http_code'], E_USER_WARNING); } else { DebugMessage('Twitter returned unknown HTTP code', E_USER_WARNING); } DebugMessage('Twitter returned: ' . print_r($ri, true), E_USER_WARNING); DebugMessage('Twitter returned: ' . print_r($r, true), E_USER_WARNING); return false; }
public function process($args) { $this->output = ""; $args = trim($args); if (strlen($args) > 0) { try { $oauth = new OAuth($this->config["consumer_key"], $this->config["consumer_secret"], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->setToken($this->config["access_token"], $this->config["access_secret"]); $hashtag = false; if (preg_match("/^#/", $args)) { $hashtag = true; $oauth->fetch("https://api.twitter.com/1.1/search/tweets.json?q=" . urlencode($args) . "&count=3"); } else { $args = str_replace("@", "", $args); $oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={$args}&count=1"); } $twitter_data = json_decode($oauth->getLastResponse()); if ($hashtag == false && count($twitter_data) > 0) { $date = date('d/m/y H:i', strtotime($twitter_data[0]->created_at)); $this->output = "@{$args} : " . $twitter_data[0]->text . " -- {$date}"; } elseif ($hashtag && isset($twitter_data->statuses)) { $twits = array(); foreach ($twitter_data->statuses as $twit) { array_push($twits, $twit->text); } $this->output = "{$args}: " . join("\n", $twits); } else { if (is_array($twitter_data)) { $this->output = "Ups! el usuario @{$args} no existe."; } else { $this->output = "El usuario @{$args} tiene sus twitts como privados."; } } } catch (Exception $e) { $this->output = "No fue posible obtener twitts de {$args}. Ha ocurrido un error."; } } else { $this->output = "Ingresa un usuario."; } }
private function _oauthReq($url, $content = null, $reqType = null, $nonce = null, $timestamp = null) { try { $oauth = new OAuth($this->clientKey, $this->clientSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI); $oauth->enableDebug(); $oauth->setToken($this->tokenKey, $this->tokenSecret); if (!is_null($nonce)) { $oauth->setNonce($nonce); } if (!is_null($timestamp)) { $oauth->setTimestamp($timestamp); } if (is_null($reqType)) { $reqType = OAUTH_HTTP_METHOD_GET; } $oauth->fetch("{$url}", $content, $reqType); $ret = $oauth->getLastResponse(); return $ret; } catch (OAuthException $e) { //return $e->lastResponse; return $e; } }
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()); } }
} 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); }
/** * Action that displays a single TwitterFeed */ public function showAction() { //die(print_r($this->twitterFeedRepository->findByAccountName('remco'),true)); $ffdata = $this->request->getContentObjectData(); $options = t3lib_div::xml2array($ffdata['pi_flexform']); $displayFeed = $options['data']['sDEF']['lDEF']['displayFeed']['vDEF']; $twitterFeed = $this->twitterFeedRepository->findByUid($displayFeed); $account = $twitterFeed->getAccount(); if ($account->getUserToken() == null || $account->getUserSecret == null) { die('You need to add a twitter authorization token/secret to the database manually for now.'); } /* $feed = curl_init("http://twitter.com/statuses/user_timeline/19768085.json?count=20"); curl_setopt($feed,CURLOPT_RETURNTRANSFER,true); $data = curl_exec($feed); $data = json_decode($data,true); //var_dump($data); curl_close($feed); */ $req_url = 'http://api.twitter.com/oauth/request_token'; $authurl = 'https://api.twitter.com/oauth/authorize'; $acc_url = 'https://api.twitter.com/oauth/access_token'; $api_url = 'https://api.twitter.com'; $args = $this->request->getArguments(); if (isset($args['feed'])) { switch ($args['feed']) { case 1: $fid = 1; $title = "My"; $getfeed = $api_url . "/1/statuses/user_timeline.json"; break; case 2: $fid = 2; $title = "My Friends"; $getfeed = $api_url . "/1/statuses/home_timeline.json"; break; case 3: $fid = 3; $title = "Other Peoples"; $getfeed = $api_url . "/1/statuses/public_timeline.json"; break; case 4: $fid = 4; $title = "Search for 'remco'"; $getfeed = "http://search.twitter.com/search.json?q=remco"; break; } } else { $title = "My"; $getfeed = $api_url . "/1/statuses/user_timeline.json"; $fid = 1; } $json = apc_fetch("tx_twitterFeed_{$twitterFeed->getFeedName()}_JSON{$fid}"); if ($json === FALSE) { try { $oauth = new OAuth($this->settings['consumerKey'], $this->settings['consumerSecret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION); $oauth->setToken($account->getUserToken(), $account->getUserSecret()); $oauth->fetch($getfeed, null, OAUTH_HTTP_METHOD_GET); $json = json_decode($oauth->getLastResponse(), true); apc_store("tx_twitterFeed_{$twitterFeed->getFeedName()}_JSON{$fid}", $json, 60 * 5); $status = "fetched from Twitter using OAUTH/GET/JSON and put in the APC cache afterwards"; } catch (OAuthException $e) { $this->flashMessages->add($e->getMessage()); $status = "cat /proc/status > /dev/null"; } } else { $status = "from APC cached JSON"; } //if($fid==4) print_r($json); $this->response->addAdditionalHeaderData("<script src=\"http://platform.twitter.com/anywhere.js?id={$this->settings['anywhereAPIKey']}&v=1\" type=\"text/javascript\"></script>"); $this->view->assign('twitterFeed', $twitterFeed); $this->view->assign('data', $json); $this->view->assign('status', $status); $this->view->assign('title', $title); }
$tokenInfo = null; try { $OAuth = new OAuth($consumerKey, $consumerSecret); $OAuth->enableDebug(); // SSL CA Signed if ($self_signed) { $OAuth->disableSSLChecks(); } $tokenInfo = $OAuth->getRequestToken($requestURL, $callbackURL); } catch (Exception $E) { echo '<h1>There was an error getting the Request Token</h1>'; echo '<pre>'; echo "Message:\n"; print_r($E->getMessage()); echo "\n\nLast Response:\n"; print_r($OAuth->getLastResponse()); echo "\n\nLast Response Info:\n"; print_r($OAuth->getLastResponseInfo()); echo "\n\nDebug Info:\n"; print_r($OAuth->debugInfo); // get info about headers echo '</pre>'; } // Check whether Return is empty or not if (empty($tokenInfo['oauth_token_secret']) || empty($tokenInfo['oauth_token'])) { echo "<pre>Token Info:\n"; print_r($tokenInfo); echo '</pre>'; exit; } $_SESSION['oauth_token_secret'] = $tokenInfo['oauth_token_secret'];
<?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"; }