예제 #1
0
 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();
     }
 }
예제 #2
0
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());
    }
}
예제 #3
0
 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;
 }
예제 #4
0
파일: Twitter.php 프로젝트: hubgit/libapi
 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;
 }
예제 #5
0
 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;
     }
 }
예제 #6
0
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 GetReportsResponse($requestParameters, $requestBody, $oauthRequestUri)
 {
     $this->context->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Info, "Called PrepareRequest method");
     // This step is required since the configuration settings might have been changed.
     $this->RequestCompressor = CoreHelper::GetCompressor($this->context, true);
     $this->ResponseCompressor = CoreHelper::GetCompressor($this->context, false);
     $this->RequestSerializer = CoreHelper::GetSerializer($this->context, true);
     $this->ResponseSerializer = CoreHelper::GetSerializer($this->context, false);
     // Determine dest URI
     $requestUri = '';
     if ($requestParameters->ApiName) {
         // Example: "https://appcenter.intuit.com/api/v1/Account/AppMenu"
         $requestUri = $this->context->baseserviceURL . $requestParameters->ApiName;
     } else {
         if ($oauthRequestUri) {
             // Prepare the request Uri from base Uri and resource Uri.
             $requestUri = $oauthRequestUri;
         } else {
             if ($requestParameters->ResourceUri) {
                 $requestUri = $this->context->baseserviceURL . $requestParameters->ResourceUri;
             } else {
             }
         }
     }
     $oauth = new OAuth($this->context->requestValidator->ConsumerKey, $this->context->requestValidator->ConsumerSecret);
     $oauth->setToken($this->context->requestValidator->AccessToken, $this->context->requestValidator->AccessTokenSecret);
     $oauth->enableDebug();
     $oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
     $oauth->disableSSLChecks();
     $httpHeaders = array();
     if ('QBO' == $this->context->serviceType || 'QBD' == $this->context->serviceType) {
         // IDS call
         $httpHeaders = array('accept' => 'application/json');
         // Log Request Body to a file
         $this->RequestLogging->LogPlatformRequests($requestBody, $requestUri, $httpHeaders, TRUE);
         if ($this->ResponseCompressor) {
             $this->ResponseCompressor->PrepareDecompress($httpHeaders);
         }
     } else {
         // IPP call
         $httpHeaders = array('accept' => 'application/json');
     }
     try {
         $OauthMethod = OAUTH_HTTP_METHOD_GET;
         $oauth->fetch($requestUri, $requestBody, $OauthMethod, $httpHeaders);
     } catch (OAuthException $e) {
         //echo "ERROR:\n";
         //print_r($e->getMessage()) . "\n";
         list($response_code, $response_xml, $response_headers) = $this->GetOAuthResponseHeaders($oauth);
         $this->RequestLogging->LogPlatformRequests($response_xml, $requestUri, $response_headers, FALSE);
         return FALSE;
     }
     list($response_code, $response_xml, $response_headers) = $this->GetOAuthResponseHeaders($oauth);
     // Log Request Body to a file
     $this->RequestLogging->LogPlatformRequests($response_xml, $requestUri, $response_headers, FALSE);
     return array($response_code, $response_xml);
 }
예제 #8
0
 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 [];
     }
 }
예제 #9
0
 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();
 }
예제 #10
0
 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;
     }
 }
 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;
 }
예제 #12
0
파일: API.php 프로젝트: hubgit/libapi
 function get_data($url, $params = array(), $format = 'json', $http = array(), $cache = TRUE)
 {
     unset($this->response, $this->data, $this->xpath);
     if (!isset($http['method'])) {
         $http['method'] = 'GET';
     }
     if ($cache && $this->cache) {
         // can set either of these to FALSE to disable the cache
         if ($http['method'] === 'GET') {
             // only use the cache for GET requests (TODO: allow caching of some POST requests?)
             return $this->get_cached_data($url, $params, $format, $http);
         }
     }
     // FIXME: is this a good idea?
     if ($http['method'] === 'POST' && empty($http['content']) && !empty($params)) {
         $http['content'] = http_build_query($params);
         $params = array();
     }
     if (!empty($params)) {
         ksort($params);
         $url .= '?' . http_build_query($params);
     }
     if (isset($http['file'])) {
         $http['content'] = file_get_contents($http['file']);
     }
     // TODO: allow setting default HTTP headers in Config.php
     if (!isset($http['header']) || !preg_match('/Accept: /', $http['header'])) {
         $http['header'] .= (empty($http['header']) ? '' : "\n") . $this->accept_header($format);
     }
     $http['header'] .= (empty($http['header']) ? '' : "\n") . "Connection: close";
     //debug($http);
     //$http['header'] = '';
     $context = empty($http) ? NULL : stream_context_create(array('http' => $http));
     if (!empty($this->oauth)) {
         $oauth = new OAuth($this->oauth['consumer_key'], $this->oauth['consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
         $oauth->enableDebug();
         $oauth->setToken($this->oauth['token'], $this->oauth['secret']);
         try {
             $headers = explode("\n", $http['header']);
             $http['header'] = array();
             foreach ($headers as $value) {
                 if (preg_match('/^\\s*(.+?):\\s*(.+)/', $value, $matches)) {
                     $http['header'][$matches[1]] = trim($matches[2]);
                 }
             }
             $oauth->fetch($url, $http['content'], constant('OAUTH_HTTP_METHOD_' . $http['method']), $http['header']);
             $this->response = $oauth->getLastResponse();
             //debug($this->response);
             $info = $oauth->getLastResponseInfo();
             //debug($info);
             $this->http_response_header = explode("\n", $info['headers_recv']);
             //debug($this->http_response_header);
         } catch (OAuthException $e) {
             debug($oauth->debugInfo);
         }
     } else {
         debug_log('Sending request to ' . $url);
         debug('Sending request to ' . $url);
         //debug(array($url, $http));
         $this->response = file_get_contents($url, false, $context);
         $this->http_response_header = $http_response_header;
     }
     //debug($this->http_response_header);
     $this->parse_http_response_header();
     $this->parse_effective_url($url);
     debug('Received response from ' . $this->http_effective_url);
     debug_log('Received response from ' . $this->http_effective_url);
     //debug_log($this->response);
     if ($this->response !== false) {
         try {
             $this->data = $this->format_data($format);
             $this->validate_data($format);
         } catch (DataException $e) {
             $e->errorMessage();
         } catch (Exception $e) {
             debug($e->getMessage());
         }
     }
     return $this->data;
 }
예제 #13
0
            print " Secret: {$access_secret}\n";
            print " Session Handle: {$access_session}\n\n";
        } else {
            $access_token = NULL;
            $access_secret = NULL;
            $access_session = NULL;
            print "Unable to refresh access token, will need to request a new one.\n";
        }
    }
}
// 3. If none of that worked, send the user to get a new token
if (!$access_token) {
    print 'no access token ******************';
    print "Better try to get a new access token.\n";
    $o = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
    $o->enableDebug();
    $request_token = NULL;
    try {
        $response = $o->getRequestToken("https://api.login.yahoo.com/oauth/v2/get_request_token", 'oob');
        print '<br />';
        print 'response<br /><br />';
        var_dump($response);
        print '<br /><br />';
        print '<br />';
        $request_token = $response['oauth_token'];
        $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";
    }
예제 #14
0
 function oauth()
 {
     $oauth = new OAuth($this->config['consumer_key'], $this->config['consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
     $oauth->enableDebug();
     return $oauth;
 }
예제 #15
0
    /**
     * 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>";
    }
예제 #16
0
    unset($_SESSION['oaccess_oauth_token']);
    unset($_SESSION['oaccess_oauth_token_secret']);
}
$err = "Error [OAuth]: ";
try {
    if (!isset($oauth['opera']['consumerkey'])) {
        error_log($err . "You must set the OAuth consumer key in the configuration file");
        exit;
    }
    if (!isset($oauth['opera']['consumersecret'])) {
        error_log($err . "You must set the OAuth consumer secret in the configuration file");
        exit;
    }
    $oauthc = new OAuth($oauth['opera']['consumerkey'], $oauth['opera']['consumersecret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
    //initiate
    $oauthc->enableDebug();
    if (empty($_SESSION['orequest_token_secret'])) {
        // first stage is to get and keep the request token and secret
        // and then re-direct the user to page where they enter their
        // credentials for this request, we need to use POST method
        $request_token_url = $oauth['opera']['requesttokenurl'];
        $request_token_info = $oauthc->getRequestToken($request_token_url, OAUTH_HTTP_METHOD_POST);
        // check for errors
        if ($request_token_info == FALSE) {
            error_log($err . "The OAuth server did not provide the request token and secret");
            exit;
        }
        // store the request token & secret for the access token stage
        $_SESSION['orequest_token_secret'] = $request_token_info['oauth_token_secret'];
        $_SESSION['orequest_token'] = $request_token_info['oauth_token'];
        // redirect user to the authorization (login) page
예제 #17
0
파일: functions.php 프로젝트: hubgit/libapi
function oauth_authorize($prefix, $urls){
  $oauth = new OAuth(Config::get($prefix . '_CONSUMER_KEY'), Config::get($prefix . '_CONSUMER_SECRET'), OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
  $oauth->enableDebug();

  try {
    $request_token = $oauth->getRequestToken($urls['request_token']);
  } catch (OAuthException $e){ debug($oauth->debugInfo); };

  //debug($request_token);

  $url = $urls['authorize'] . '?' . http_build_query(array('oauth_token' => $request_token['oauth_token'], 'callback_url' => 'oob'));
  print 'Authorize: ' . $url  . "\n";
  system(sprintf('open %s', escapeshellarg($url)));
  fwrite(STDOUT, "Enter the PIN: ");
  $verifier = trim(fgets(STDIN));

  $oauth->setToken($request_token['oauth_token'], $request_token['oauth_token_secret']);
  try {
    $access_token = $oauth->getAccessToken($urls['access_token'], NULL, $verifier);
  } catch (OAuthException $e){ debug($oauth->debugInfo); };

  printf("'%s_TOKEN' => '%s',\n'%s_TOKEN_SECRET' => '%s',\n", $prefix, $access_token['oauth_token'], $prefix, $access_token['oauth_token_secret']);
  exit();
}
예제 #18
0
 public function index()
 {
     $my_desk_url = 'https://aritzia.desk.com';
     //Application key and secret found here:
     // https://[yoursite].desk.com/admin/settings/api-applications
     $consumer_key = 'gdCcZ8awl9Z0NLcZGLS7';
     $consumer_secret = 'rWxfb6PEJ0b5h6EgyeZVgjefTJnXBNx772GortFj';
     //Access token & secret (Click [Your Access Token] on App Listing)
     // https://[yoursite].desk.com/admin/settings/api-applications)
     $access_token = 'rFI1WU7kKbaUDZ1SJOXv';
     $access_secret = '3LQfUUzeheXHCkaglKJdJl0D8ATy4XlEFt5rMIeV';
     try {
         //Create a new Oauth request.
         $oauth = new OAuth($consumer_key, $consumer_secret);
         $oauth->enableDebug();
         $oauth->setToken($access_token, $access_secret);
         $action = 'list';
         if (isset($_GET['action'])) {
             $action = $_GET['action'];
         }
         switch ($action) {
             case 'resolve':
                 $id = $_GET['id'];
                 //Example of a PUT API action - resolve a case
                 $oauth->fetch($my_desk_url . "/api/v1/cases/" . $id . ".json", array('case_status_type_id' => 70), OAUTH_HTTP_METHOD_PUT);
                 header('Location: /desk-oauth-example-single.php');
                 break;
             case 'show':
                 $id = $_GET['id'];
                 //Example of GET Show action
                 $oauth->fetch($my_desk_url . "/api/v1/cases/" . $id . ".json", array(), OAUTH_HTTP_METHOD_GET);
                 //Get Response
                 $json = json_decode($oauth->getLastResponse());
                 echo "<a href='/desk-oauth-example-single.php'>BACK</a>";
                 print_obj($json->case);
                 break;
             default:
                 //Example of a List action
                 //Parse query parameters
                 $query = '';
                 if (isset($_GET['email'])) {
                     $query = '?email=' . $_GET['email'];
                 }
                 //Sample GET Request
                 $oauth->fetch($my_desk_url . "/api/v1/cases.json" . $query, array(), OAUTH_HTTP_METHOD_GET);
                 //Get Response
                 $json = json_decode($oauth->getLastResponse());
                 echo "<h3>Total Cases: " . $json->total . "</h3>";
                 echo "<ul>";
                 foreach ($json->results as $key => $value) {
                     $case = $value->case;
                     echo "<li>";
                     echo "<b>Case #" . $case->id . ": " . $case->subject . "</b>";
                     if (!in_array($case->case_status_type, array("resolved", "closed"))) {
                         echo "&nbsp;(<a href='/desk-oauth-example-single.php?action=resolve&id=" . $case->id . "'>resolve</a>)";
                     } else {
                         echo "&nbsp;(" . $case->case_status_type . ")";
                     }
                     echo "&nbsp;(<a href='/desk-oauth-example-single.php?action=show&id=" . $case->id . "'>details</a>)";
                     //echo "<br/>".($case->preview);
                     echo "</li>";
                 }
                 echo "</ul>";
                 //print_r($json);
                 break;
         }
     } catch (OAuthException $E) {
         print_r($E);
     }
     function print_obj($obj)
     {
         echo "<ul>";
         foreach ($obj as $key => $value) {
             echo "<li>";
             echo "<b>" . $key . "</b> ";
             if (is_object($value)) {
                 print_obj($value);
             } else {
                 if (is_array($value)) {
                     echo implode(",", $value);
                 } else {
                     echo $value;
                 }
             }
             echo "</li>";
         }
         echo "</ul>";
     }
 }
예제 #19
0
    /**
     * Create the login popup
     */
    function meetup_login_popup()
    {
        $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 login" style="padding:15px;">';
        if (empty($this->key) || empty($this->secret)) {
            echo $header;
            echo '<p><a href="' . admin_url('options-general.php') . '">Please enter your OAuth key & secret.</a></p>';
            exit;
        }
        session_start();
        if (!array_key_exists('state', $_SESSION)) {
            $_SESSION['state'] = 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);
                //,plugins_url('vs-oauth.php',__FILE__));
                $_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']);
            echo $header;
            $oauth->fetch($this->api_url . "/members?relation=self");
            $response = json_decode($oauth->getLastResponse());
            $meetup = $response->results[0];
            unset($meetup->topics);
            $id = $this->get_user_by_meetup($meetup->id);
            $id = apply_filters('meetup_wp_user_id', $id, $meetup);
            //if the user wasn't found, $id is null, and get_user_by returns false.
            if (false === ($user = get_user_by('id', $id))) {
                //there is no user, so create, and log in.
                $user_info = array('user_login' => sanitize_title($meetup->name), 'user_nicename' => $meetup->name, 'display_name' => $meetup->name, 'nickname' => $meetup->name, 'user_url' => $meetup->link, 'description' => $meetup->bio);
                $new_user = wp_insert_user($user_info);
                if (is_wp_error($new_user)) {
                    wp_die($new_user);
                }
                wp_set_auth_cookie($new_user);
                $user = get_user_by('id', $new_user);
                do_action('meetup_user_create', $user, $meetup);
                $new_user_redirect = apply_filters('meetup_login_new_user_redirect', admin_url('profile.php'), $user);
                echo "<script>window.opener.location.href = '" . $new_user_redirect . "'; window.close();</script>";
            } else {
                wp_set_auth_cookie($user->ID);
                wp_set_current_user($user->ID);
                do_action('meetup_user_update', $user, $meetup);
                $existing_user_redirect = apply_filters('meetup_login_existing_user_redirect', get_bloginfo('url'), $user);
                echo "<script>window.opener.location.href = '" . $existing_user_redirect . "'; window.close();</script>";
            }
        } 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>";
            }
            if (WP_DEBUG) {
                echo "<pre>" . print_r($_SESSION, true) . "</pre>";
            }
            if (WP_DEBUG) {
                echo "<pre>" . print_r($_GET, true) . "</pre>";
            }
        }
        unset($_SESSION['state']);
    }
예제 #20
0
파일: OAuth1.php 프로젝트: odesk/php-odesk
 /**
  * Get OAuth instance
  *
  * @param   integer $authType Auth type
  * @access  protected
  * @return  object
  */
 protected function _getOAuthInstance($authType)
 {
     ApiDebug::p('get OAuth instance');
     $oauth = new \OAuth(self::$_apiKey, self::$_secret, self::$_sigMethod, $authType);
     if (ApiConfig::get('debug')) {
         $oauth->enableDebug();
     }
     if (!self::$_verifySsl) {
         $oauth->disableSSLChecks();
     }
     return $oauth;
 }
예제 #21
0
 /**
  * Run the request
  * 
  * @param \Raml\SecurityScheme $securityscheme_obj The security scheme to process the call data for
  * @param \V1\APICall $apicall_obj					The APICall object
  * 
  * @return mixed The object we just completed or an array describing the next step in the security process
  */
 public function run(\Raml\SecurityScheme $securityscheme_obj, \V1\APICall $apicall_obj)
 {
     $settings = $securityscheme_obj->getSettings()->asArray();
     $credentials = $apicall_obj->get_credentials();
     $settings['authorization'] = empty($settings['authorization']) ? 'header' : \Str::lower($settings['authorization']);
     // Verify that we have the required credentials for the request.
     if (empty($credentials['OAUTH_CONSUMER_KEY']) || empty($credentials['OAUTH_CONSUMER_SECRET']) || empty($credentials['OAUTH_USER_ID'])) {
         $this->error = true;
         return $this;
     }
     // Store the proper credentials in the DB.
     $this->store_credentials($credentials);
     // Pull data from the cache for the current request, allowing for multiple authentications for the customer.
     $this->cache_id = hash('sha256', $credentials['OAUTH_CONSUMER_KEY'] . $credentials['OAUTH_CONSUMER_SECRET'] . $credentials['OAUTH_USER_ID']);
     $credentials = array_replace($this->get_cache(), $credentials);
     // Where should we set the authorization data?
     switch ($settings['authorizeLocation']) {
         case 'header':
             $authorize_location = OAUTH_AUTH_TYPE_AUTHORIZATION;
             break;
         case 'query':
             $authorize_location = OAUTH_AUTH_TYPE_URI;
             break;
         case 'body':
             $authorize_location = OAUTH_AUTH_TYPE_FORM;
             break;
         case 'none':
             $authorize_location = OAUTH_AUTH_TYPE_NONE;
             break;
     }
     try {
         // Create the PECL installed OAuth object.
         $oauth = new \OAuth($credentials['OAUTH_CONSUMER_KEY'], $credentials['OAUTH_CONSUMER_SECRET'], $settings['signatureMethod'], $authorize_location);
         if (\Fuel::$env !== 'production') {
             $oauth->enableDebug();
         }
         if (empty($credentials['OAUTH_ACCESS_TOKEN']) || empty($credentials['OAUTH_ACCESS_TOKEN_SECRET'])) {
             // Get our access token and secret.
             if (($credentials = $this->get_access_tokens($oauth, $settings, $credentials)) === false) {
                 $this->error = true;
                 return $this;
             }
             // Authentication of my second leg (Yup. It's hairy, so it must be mine.)
             if (!empty($credentials['errors'])) {
                 return $credentials;
             }
         }
         $oauth->setToken($credentials['OAUTH_ACCESS_TOKEN'], $credentials['OAUTH_ACCESS_TOKEN_SECRET']);
         // Collect parameters to build our signature
         $params = null;
         if ($apicall_obj->get_body_type() === 'application/x-www-form-urlencoded') {
             // If we need to handle string bodies later, we will.
             if (is_array($apicall_obj->get_method_params())) {
                 $params = http_build_query($apicall_obj->get_method_params(), null, '&', PHP_QUERY_RFC3986) . '&';
             }
         }
         $params .= http_build_query($apicall_obj->get_query_params(), null, '&') . '&' . ($params .= http_build_query($apicall_obj->get_headers(), null, '&'));
         $header = $oauth->getRequestHeader($apicall_obj->get_method(), $apicall_obj->get_url(), $params);
         $apicall_obj->set_header('Authorization', $header);
         return true;
     } catch (\OAuthException $e) {
         // Something went wrong, so destroy the cache so it can get fixed.
         $this->delete_cache();
         // Let the script automatically continue searching for security methods.
         $this->error = true;
         return $this;
     }
 }
예제 #22
0
            unset($scope['links']);
            $scope['filesystem']['write'] = false;
        } else {
            if ($_GET['scope'] == 'none') {
                $scope = array();
            }
        }
    }
    $scope = json_encode($scope);
    $requestURL .= '?scope=' . urlencode($scope);
}
session_start();
$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";
예제 #23
0
 private function getServiceObject($bClearStorage = true)
 {
     if ($bClearStorage) {
         $this->unsetAuthorizedUser();
     }
     $oConsumer = new OAuth($this->sKey, $this->sSecret);
     $oConsumer->setAuthType(OAUTH_AUTH_TYPE_URI);
     $oConsumer->enableDebug();
     return $oConsumer;
 }
예제 #24
0
 protected function fetch($sKey, $sSecret, $aParams = array())
 {
     if (!$this->isAuthorized()) {
         return array();
     }
     try {
         $oConsumer = new OAuth($sKey, $sSecret);
         $oConsumer->setAuthType(OAUTH_AUTH_TYPE_URI);
         $oConsumer->enableDebug();
         $oConsumer->setToken($this->oSession->getValue('sys_oauth_token'), $this->oSession->getValue('sys_oauth_secret'));
         $oConsumer->fetch(BX_DOL_OAUTH_URL_FETCH_DATA, $aParams, OAUTH_HTTP_METHOD_POST);
         //echo $oConsumer->getLastResponse(); exit;	//--- Uncomment to debug
         return json_decode($oConsumer->getLastResponse(), true);
     } catch (OAuthException $e) {
         return array();
     }
 }
예제 #25
0
$client_key = '';
$client_secret = '';
$app_key = '';
if ($client_key == '' || $client_secret == '' || $app_key == '') {
    exit('You must edit this script to fill in the client_key, client_secret, and app_key');
}
#
# Leg 1 of the three-legged OAuth procedure
#
# This requests temporary credentials from mobage that can be sent
# to the client.
# Use HTTPS!
$server = 'https://app-sandbox.mobage.com';
$url = "{$server}/1/{$app_key}/request_temporary_credential";
$oauth = new OAuth($client_key, $client_secret);
$oauth->enableDebug();
$temporary_credentials = $oauth->getRequestToken($url);
echo '$temporary_credentials: ';
print_r($temporary_credentials);
$oauth->setToken($temporary_credentials['oauth_token'], $temporary_credentials['oauth_token_secret']);
#
# Leg 2
#
# 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";
예제 #26
0
파일: callback.php 프로젝트: nobelium/oauth
hi -- this is call back

<?php 
@(require_once './config.inc.php');
//print_r($_REQUEST);
if (isset($_REQUEST['request_token']) && isset($_REQUEST['verifier'])) {
    if (isset($_POST['request_token'])) {
        //echo "into inner if";
        try {
            $oauth_client = new OAuth(CLIENT_KEY, CLIENT_SECRET);
            $oauth_client->enableDebug();
            $oauth_client->setToken($_POST['request_token'], $_POST['request_token_secret']);
            $info = $oauth_client->getAccessToken("http://localhost/oauth/pages/oauthhandler.php?query=access_token", null, $_POST['verifier']);
            echo "<br/><br/>Fetching access token<br/><br/>";
            print_r($info);
        } catch (OAuthException $e) {
            print_r($e);
        }
    } else {
        ?>
	<form method="post" action="callback.php">
		<label>token</label>
		<input type="text" name="request_token" value="<?php 
        echo $_REQUEST['request_token'];
        ?>
" /><br />
		<label>secret</label>
		<input type="text" name="request_token_secret" value="" />
		<label>verifier</label>
		<input type="text" name="verifier" value="<?php 
        echo $_REQUEST['verifier'];
예제 #27
0
 /**
  * Make custom call to any API endpoint, signed with consumer_key only (on behalf of CLIENT)
  *
  * @param string $url Endpoint url after '.../1/'
  * @param array $parameters Request parameters
  * @param string $method (OAUTH_HTTP_METHOD_GET, OAUTH_HTTP_METHOD_POST, OAUTH_HTTP_METHOD_PUT, OAUTH_HTTP_METHOD_DELETE)
  * @param array $userHeaders Additional custom headers
  * @return FitBitResponse
  */
 public function client_customCall($url, $parameters, $method, $userHeaders = array())
 {
     $OAuthConsumer = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
     if ($debug) {
         $OAuthConsumer->enableDebug();
     }
     $headers = $this->getHeaders();
     $headers = array_merge($headers, $userHeaders);
     try {
         $OAuthConsumer->fetch($this->baseApiUrl . $url, $parameters, $method, $headers);
     } catch (Exception $E) {
     }
     $response = $OAuthConsumer->getLastResponse();
     $responseInfo = $OAuthConsumer->getLastResponseInfo();
     $this->clientDebug = print_r($OAuthConsumer->debugInfo, true);
     return new FitBitResponse($response, $responseInfo['http_code']);
 }
예제 #28
0
function oauth_request($url)
{
    $scope = 'test';
    // MODIFY: Insert your own consumer key and secret here!
    $consumer_data = array();
    $consumer_data['test']['key'] = 'dj0yJmk9cnZ0dHdnRjNhRE5XJmQ9WVdrOWJqRk5aM0Z3TjJzbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD04NA--';
    $consumer_data['test']['secret'] = '7b98b892dde1649b5d84db1d397b87ac5c62f92b';
    // **** MAIN PROGRAM START HERE ****
    $consumer_key = $consumer_data[$scope]['key'];
    $consumer_secret = $consumer_data[$scope]['secret'];
    // By default, try to store token information in /tmp folder
    $token_file_name = '/tmp/oauth_data_token_storage_' . $consumer_key . '.out';
    $access_token = NULL;
    $access_secret = NULL;
    $access_session = NULL;
    $access_verifier = NULL;
    $store_access_token_data = false;
    if (file_exists($token_file_name) && ($tok_fh = fopen($token_file_name, 'r'))) {
        $invalid_file = false;
        // Get first line: access token
        $access_token = fgets($tok_fh);
        if ($access_token) {
            // Get next line: access secret
            $access_secret = fgets($tok_fh);
            if ($access_secret) {
                // Get next line: access session handle
                $access_session = fgets($tok_fh);
                if (!$access_session) {
                    $invalid_file = true;
                }
            } else {
                $invalid_file = true;
            }
        } else {
            $invalid_file = true;
        }
        if ($invalid_file) {
            print "File did not seem to be formatted correctly -- needs 3 lines with access token, secret, and session handle.\n";
            $access_token = NULL;
            $access_secret = NULL;
            $access_session = NULL;
        } else {
            print "Got access token information!\n";
            $access_token = rtrim($access_token);
            $access_secret = rtrim($access_secret);
            $access_session = rtrim($access_session);
            print " Token: {$access_token}\n";
            print " Secret: {$access_secret}\n";
            print " Session Handle: {$access_session}\n\n";
        }
        // Done with file, close it up
        fclose($tok_fh);
    } else {
        print "Couldn't open {$token_file_name}, assuming we need to get a new request token.\n";
    }
    // 1. See if we have a stored access token/secret/session. If so, try to use
    //    that token.
    if ($access_token) {
        $o = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
        $o->enableDebug();
        $auth_failure = false;
        // Try to make request using stored token
        try {
            $o->setToken($access_token, $access_secret);
            if ($o->fetch($url)) {
                print "Got data from API:\n\n";
                return $o->getLastResponse();
                // . "\n\n";
                print "Successful!\n";
                exit;
            } else {
                print "Couldn'\t fetch\n";
            }
        } catch (OAuthException $e) {
            print 'Error: ' . $e->getMessage() . "\n";
            print 'Error Code: ' . $e->getCode() . "\n";
            print 'Response: ' . $e->lastResponse . "\n";
            if ($e->getCode() == 401) {
                $auth_failure = true;
            }
        }
        // 2. If we get an auth error, try to refresh the token using the session.
        if ($auth_failure) {
            try {
                $response = $o->getAccessToken('https://api.login.yahoo.com/oauth/v2/get_token', $access_session, $access_verifier);
            } catch (OAuthException $e) {
                print 'Error: ' . $e->getMessage() . "\n";
                print 'Response: ' . $e->lastResponse . "\n";
                $response = NULL;
            }
            print_r($response);
            if ($response) {
                $access_token = $response['oauth_token'];
                $access_secret = $response['oauth_token_secret'];
                $access_session = $response['oauth_session_handle'];
                $store_access_token_data = true;
                print "Was able to refresh access token:\n";
                print " Token: {$access_token}\n";
                print " Secret: {$access_secret}\n";
                print " Session Handle: {$access_session}\n\n";
            } else {
                $access_token = NULL;
                $access_secret = NULL;
                $access_session = NULL;
                print "Unable to refresh access token, will need to request a new one.\n";
            }
        }
    }
    // 3. If none of that worked, send the user to get a new token
    if (!$access_token) {
        print "Better try to get a new access token.\n";
        $o = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
        $o->enableDebug();
        $request_token = NULL;
        try {
            $response = $o->getRequestToken("https://api.login.yahoo.com/oauth/v2/get_request_token", 'oob');
            $request_token = $response['oauth_token'];
            $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 "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 "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() . "\n";
                print 'Response: ' . $e->lastResponse . "\n";
                print "Shoot, couldn't get the access token. :(\n";
            }
        }
    }
    if ($access_token) {
        // Try to make request using stored token
        try {
            $o->setToken($access_token, $access_secret);
            if ($o->fetch($url)) {
                print "Got data from API:\n\n";
                return $o->getLastResponse();
                // . "\n\n";
                print "Successful!\n";
            } else {
                print "Couldn'\t fetch\n";
            }
        } catch (OAuthException $e) {
            print 'Error: ' . $e->getMessage() . "\n";
            print 'Error Code: ' . $e->getCode() . "\n";
            print 'Response: ' . $e->lastResponse . "\n";
        }
    }
    // 4. Rewrite token information if necessary
    if ($store_access_token_data) {
        print "Looks like we need to store access token data! Doing that now.\n";
        $tok_fh = fopen($token_file_name, 'w');
        if ($tok_fh) {
            fwrite($tok_fh, "{$access_token}\n");
            fwrite($tok_fh, "{$access_secret}\n");
            fwrite($tok_fh, "{$access_session}\n");
            fclose($tok_fh);
        } else {
            print "Hm, couldn't open file to write back access token information.\n";
        }
    }
}
예제 #29
0
*/
$callbackUrl = "http://magento-7350-19577-45479.cloudwaysapps.com/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://magento-7350-19577-45479.cloudwaysapps.com/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://magento-7350-19577-45479.cloudwaysapps.com/admin/oAuth_authorize';
$accessTokenRequestUrl = 'http://magento-7350-19577-45479.cloudwaysapps.com/oauth/token';
$apiUrl = 'http://magento-7350-19577-45479.cloudwaysapps.com/api/rest';
$consumerKey = 'eedcf9497ab5d8ac3d0bb36a9a5ec2ff';
$consumerSecret = '5dfa269c5eea1403a309aac0980b7565';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
    $_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;
 /**
  * Returns the response by calling REST service.
  *
  * @param ServiceContext $requestParameters The parameters
  * @param string $requestBody The request body
  * @param string $oauthRequestUri The OAuth request uri
  * @return array elements are 0: HTTP response code; 1: HTTP response body
  */
 public function GetResponse($requestParameters, $requestBody, $oauthRequestUri)
 {
     $this->context->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Info, "Called PrepareRequest method");
     // This step is required since the configuration settings might have been changed.
     $this->RequestCompressor = CoreHelper::GetCompressor($this->context, true);
     $this->ResponseCompressor = CoreHelper::GetCompressor($this->context, false);
     $this->RequestSerializer = CoreHelper::GetSerializer($this->context, true);
     $this->ResponseSerializer = CoreHelper::GetSerializer($this->context, false);
     // Determine dest URI
     $requestUri = '';
     if ($requestParameters->ApiName) {
         // Example: "https://appcenter.intuit.com/api/v1/Account/AppMenu"
         $requestUri = $this->context->baseserviceURL . $requestParameters->ApiName;
     } else {
         if ($oauthRequestUri) {
             // Prepare the request Uri from base Uri and resource Uri.
             $requestUri = $oauthRequestUri;
         } else {
             if ($requestParameters->ResourceUri) {
                 $requestUri = $this->context->baseserviceURL . $requestParameters->ResourceUri;
             } else {
             }
         }
     }
     //minorVersion support
     if ($this->context->minorVersion) {
         if ($this->queryToArray($requestUri) == false) {
             $requestUri .= "?minorversion=" . $this->context->minorVersion;
         } else {
             $requestUri .= "&minorversion=" . $this->context->minorVersion;
         }
     }
     $oauth = new OAuth($this->context->requestValidator->ConsumerKey, $this->context->requestValidator->ConsumerSecret);
     $oauth->setToken($this->context->requestValidator->AccessToken, $this->context->requestValidator->AccessTokenSecret);
     $oauth->enableDebug();
     $oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
     $oauth->disableSSLChecks();
     $httpHeaders = array();
     if ('QBO' == $this->context->serviceType || 'QBD' == $this->context->serviceType) {
         // IDS call
         $httpHeaders = array('host' => parse_url($requestUri, PHP_URL_HOST), 'user-agent' => CoreConstants::USERAGENT, 'accept' => '*/*', 'connection' => 'close', 'content-type' => $requestParameters->ContentType, 'content-length' => strlen($requestBody));
         // Log Request Body to a file
         $this->RequestLogging->LogPlatformRequests($requestBody, $requestUri, $httpHeaders, TRUE);
         if ($requestBody && $this->RequestCompressor) {
             $this->RequestCompressor->Compress($httpHeaders, $requestBody);
         }
         if ($this->ResponseCompressor) {
             $this->ResponseCompressor->PrepareDecompress($httpHeaders);
         }
     } else {
         // IPP call
         $httpHeaders = array('user-agent' => CoreConstants::USERAGENT);
     }
     try {
         if ('POST' == $requestParameters->HttpVerbType) {
             $OauthMethod = OAUTH_HTTP_METHOD_POST;
         } else {
             if ('GET' == $requestParameters->HttpVerbType) {
                 $OauthMethod = OAUTH_HTTP_METHOD_GET;
             }
         }
         $oauth->fetch($requestUri, $requestBody, $OauthMethod, $httpHeaders);
     } catch (OAuthException $e) {
         //echo "ERROR:\n";
         //print_r($e->getMessage()) . "\n";
         list($response_code, $response_xml, $response_headers) = $this->GetOAuthResponseHeaders($oauth);
         $this->RequestLogging->LogPlatformRequests($response_xml, $requestUri, $response_headers, FALSE);
         //echo "Response: {$response_code} - {$response_xml} \n";
         //var_dump($oauth->debugInfo);
         //echo "\n";
         //echo "ERROR MESSAGE: " . $oauth->debugInfo['body_recv'] . "\n"; // Useful info from Intuit
         //echo "\n";
         return FALSE;
     }
     list($response_code, $response_xml, $response_headers) = $this->GetOAuthResponseHeaders($oauth);
     // Log Request Body to a file
     $this->RequestLogging->LogPlatformRequests($response_xml, $requestUri, $response_headers, FALSE);
     return array($response_code, $response_xml);
 }