示例#1
0
/**
 * Returns the atom feed only requires oauth3/OAuthRequester.php
 * TODO: will need to throw execptions for if user has no token, or if token no longer works... :/
 */
function oauth3_obtain_feed($user_id, $request_uri = 'https://mail.google.com/mail/feed/atom')
{
    // Do we have a token for this user???
    // if not return error print "no token found for" exit();
    // if this is a curl call you can't use global user here
    //$user_id= 5;
    //$request_uri = 'https://mail.google.com/mail/feed/atom';
    try {
        $req = new OAuthRequester($request_uri, 'GET', $params = null);
        $result = $req->doRequest($user_id);
        //throws OAuthException exception on an error
        // $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
        $feed = $result['body'];
    } catch (OAuthException $e) {
        //print "Error: $e";
    }
    // TODO: how to return whatever error it says
    // should return feed body Output while still testing
    if (empty($feed) or !empty($e)) {
        return "FALSE Error Message: {$e}";
        // print "reasons for false or error info"; // or just log the error info
    } else {
        return $feed;
    }
}
示例#2
0
function douban_callback()
{
    OAuthRequester::requestAccessToken(DOUBAN_KEY, $_SESSION['oauth_token'], 0, 'POST', $options = array('oauth_verifier' => $_SESSION['oauth_token']));
    $req = new OAuthRequester('http://api.douban.com/people/' . urlencode('@me'), 'get');
    $res = $req->doRequest();
    $user_data = new SimpleXMLElement($res['body']);
    $uid = array_pop(explode('/', $user_data->id));
    $auth_type = 'douban';
    $auth = R::findOne('oauth', "uid=? AND type=?", array($uid, $auth_type));
    if (!$auth) {
        $auth = R::dispense('oauth');
        $auth->uid = $uid;
        $auth->type = $auth_type;
        $encrypt_key = rand(100000, 999999);
        $auth->secret = $encrypt_key;
    } else {
        $encrypt_key = $auth->secret;
    }
    $cookie_str = sha1(implode('', array($uid, $auth_type, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], $encrypt_key)));
    $expire = time() + 3600 * 24 * 365;
    setcookie('s', $cookie_str, $expire);
    setcookie('auth_type', $auth_type, $expire);
    setcookie('uid', $uid, $expire);
    $auth->setMeta('buildcommand.unique', array(array('uid', 'type')));
    $auth->setMeta('buildcommand.indexes', array('uid' => 'uid'));
    R::store($auth);
}
示例#3
0
 /**
  * Request a request token from the site belonging to consumer_key
  * 
  * @param string consumer_key
  * @param int usr_id
  * @exception OAuthException when no key could be fetched
  * @exception OAuthException when no server with consumer_key registered
  * @return array (authorize_uri, token)
  */
 static function requestRequestToken($consumer_key, $usr_id)
 {
     OAuthRequestLogger::start();
     $store = OAuthStore::instance();
     $r = $store->getServer($consumer_key);
     $uri = $r['request_token_uri'];
     $oauth = new OAuthRequester($uri, 'POST');
     $oauth->sign($usr_id, $r);
     $text = $oauth->curl_raw();
     if (empty($text)) {
         throw new OAuthException('No answer from the server "' . $uri . '" while requesting a request token');
     }
     $data = $oauth->curl_parse($text);
     if ($data['code'] != 200) {
         throw new OAuthException('Unexpected result from the server "' . $uri . '" (' . $data['code'] . ') while requesting a request token');
     }
     $token = array();
     $params = explode('&', $data['body']);
     foreach ($params as $p) {
         @(list($name, $value) = explode('=', $p, 2));
         $token[$name] = $oauth->urldecode($value);
     }
     if (!empty($token['oauth_token']) && !empty($token['oauth_token_secret'])) {
         $store->addServerToken($consumer_key, 'request', $token['oauth_token'], $token['oauth_token_secret'], $usr_id);
     } else {
         throw new OAuthException('The server "' . $uri . '" did not return the oauth_token or the oauth_token_secret');
     }
     OAuthRequestLogger::flush();
     // Now we can direct a browser to the authorize_uri
     return array('authorize_uri' => $r['authorize_uri'], 'token' => $token['oauth_token']);
 }
示例#4
0
 public function getIdentity($oauth_user_id)
 {
     // get twitter handle
     #$request = new OAuthRequester('http://api.twitter.com/1/account/verify_credentials.xml', 'GET');
     $request = new OAuthRequester('http://api.twitter.com/1/account/verify_credentials.json', 'GET');
     $result = $request->doRequest($oauth_user_id);
     if ($result['code'] == 200) {
         $data = json_decode($result['body'], true);
         if (is_null($data)) {
             switch (json_last_error()) {
                 case JSON_ERROR_DEPTH:
                     error_log('JSON Error: Maximum stack depth exceeded');
                     break;
                 case JSON_ERROR_CTRL_CHAR:
                     error_log('JSON Error: Unexpected control character found');
                     break;
                 case JSON_ERROR_SYNTAX:
                     error_log('JSON Error: Syntax error, malformed JSON');
                     break;
                 case JSON_ERROR_NONE:
                     error_log('JSON Error: No errors');
                     break;
             }
             return null;
         }
         if (!is_null($data) && array_key_exists('id', $data) && array_key_exists('name', $data)) {
             return $data;
         }
     }
     return null;
 }
function getResponseAPI($userIdZyncro, $sessionid, $serviceAPI)
{
    // Init the OAuthStore
    $options = array('consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET, 'server_uri' => OAUTH_HOST, 'request_token_uri' => REQUEST_TOKEN_URL, 'signature_methods' => array('HMAC-SHA1'), 'authorize_uri' => AUTHORIZE_URL, 'access_token_uri' => ACCESS_TOKEN_URL);
    // Note: do not use "Session" storage in production. Prefer a database
    // storage, such as MySQL.
    OAuthStore::instance("Session", $options);
    try {
        // get a request token
        $getRequestTokenParams = array();
        $tokenResultParams = OAuthRequester::requestRequestToken(CONSUMER_KEY, 0, $getRequestTokenParams, 'GET');
        // get an access token
        $oauthToken = $tokenResultParams['token'];
        $getAccessTokenParams = array('oauth_verifier' => $sessionid);
        OAuthRequester::requestAccessToken(CONSUMER_KEY, $oauthToken, 0, 'POST', $getAccessTokenParams);
        // make the request.
        $urlRequest = OAUTH_HOST . $serviceAPI;
        $request = new OAuthRequester($urlRequest, 'GET');
        $result = $request->doRequest(0);
        if ($result['code'] == 200) {
            return $result['body'];
        }
    } catch (OAuthException2 $e) {
    }
}
示例#6
0
 public function getIdentity($oauth_user_id)
 {
     // get meetup user id
     $request = new OAuthRequester('https://www.google.com/m8/feeds/groups/default/full', 'GET');
     $result = $request->doRequest($oauth_user_id);
     $self_url = null;
     if ($result['code'] == 200) {
         $raw_xml = $result['body'];
         $xml = new SimpleXMLElement($raw_xml);
         return array('id' => (string) $xml->id, 'name' => (string) $xml->author->name, 'email' => (string) $xml->author->email);
     }
     return null;
 }
示例#7
0
 public function getIdentity($oauth_user_id)
 {
     // get twitter handle
     $request = new OAuthRequester('http://www.ohloh.net/accounts/me.xml', 'GET');
     $result = $request->doRequest($oauth_user_id);
     if ($result['code'] == 200) {
         $raw_xml = $result['body'];
         $xml = new SimpleXMLElement($raw_xml);
         // todo add more fields
         return array('id' => (string) $xml->id, 'name' => (string) $xml->name);
     }
     return null;
 }
示例#8
0
 /**
  * Given a URL return an OAuth signed URL.  This will handle creating a timestamp and nonce
  *
  * @param string $url the unsigned url
  * @param string $method request method GET, POST, PUT, DELETE
  * @param string $key oauth key
  * @param string $secret oauth secret
  * @param array $params querystring or post parameters
  * @param string $body the body contents of the request
  * @param string $signature_method method used for signature (default = 'HMAC_SHA1')
  */
 public static function SignUrl($url, $method, $key, $secret, $params = null, $body = null, $signature_method = 'HMAC_SHA1')
 {
     $options = array('consumer_key' => $key, 'consumer_secret' => $secret);
     $params = $params ? $params : array();
     OAuthStore::instance("2Leg", $options);
     // Obtain a request object for the request we want to make
     $request = new OAuthRequester($url, $method, $params, $body);
     $sig = $request->sign($key, null, '');
     $data = $request->signatureBaseString();
     $url = substr(urldecode($data . '&oauth_signature=' . $request->calculateDataSignature($data, $secret, '', $signature_method)), strlen($method) + 1);
     $url = VerySimpleStringUtil::ReplaceFirst('&', '?', $url);
     return $url;
 }
示例#9
0
 public function getIdentity($oauth_user_id)
 {
     // get meetup user id
     $request = new OAuthRequester('https://api.meetup.com/members.json/?relation=self', 'GET');
     $result = $request->doRequest($oauth_user_id);
     if ($result['code'] == 200) {
         $userdata = json_decode($result['body'], true);
         // array includes 'id' parameter which uniquely identifies a user
         if (array_key_exists('id', $userdata['results'][0]) && array_key_exists('name', $userdata['results'][0])) {
             return $userdata['results'][0];
         }
     }
     return null;
 }
示例#10
0
 function query($query)
 {
     if (preg_match("/^SELECT|^SHOW|^DESCRIBE/i", $query)) {
         $request = new OAuthRequester(URL . "?sql=" . rawurlencode($query), 'GET');
     } else {
         $request = new OAuthRequester(URL, 'POST', "sql=" . rawurlencode($query));
     }
     $result = $request->doRequest($this->user_id);
     if ($result['code'] == 200) {
         return $result['body'];
     } else {
         return null;
     }
 }
 function query($query)
 {
     if (preg_match("/^SELECT|^SHOW|^DESCRIBE/i", $query)) {
         $request = new OAuthRequester("https://www.googleapis.com/fusiontables/v1/query?sql=" . rawurlencode($query), 'GET');
     } else {
         $request = new OAuthRequester("https://www.googleapis.com/fusiontables/v1/query", 'POST', "sql=" . rawurlencode($query));
     }
     $result = $request->doRequest($this->user_id);
     if ($result['code'] == 200) {
         return $result['body'];
     } else {
         return null;
     }
 }
示例#12
0
  public function run_query($endpoint, $params, $method="GET")
  {
    if (!$this->apiKey)
      throw new Semantics3_AuthenticationError('No API key provided.');

    if (!$this->apiSecret)
      throw new Semantics3_AuthenticationError('No API secret provided.');

    $options = array( 'consumer_key' => $this->apiKey, 'consumer_secret' => $this->apiSecret );
    OAuthStore::instance("2Leg", $options );
    $url = $this->apiBase.$endpoint;
    if ($method == "GET") {
      $url = $url."?q=".urlencode(json_encode($params));
      $params = null;
    }
    else {
      $params = json_encode($params);
    }

    try
    {
      switch ($method) {
        case "GET":
          $request = new OAuthRequester($url, $method, $params);
          break;
        case "POST":
          $request = new OAuthRequester($url, $method, '', $params);
          break;
        case "DELETE":
          $request = new OAuthRequester($url, $method);
          break;
        default:
          $request = new OAuthRequester($url, $method);
      }

      $result = $request->doRequest();
      return $result['body'];
    }
    catch(OAuthException2 $e)
    {
      print "\n";
      $error = $e->getMessage();
      print $error."\n";
    }

  }
示例#13
0
function fGetTweets($user, $limit)
{
    $options = array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET);
    OAuthStore::instance("2Leg", $options);
    try {
        // Obtain a request object for the request we want to make
        $request = new OAuthRequester(TWITTER_REQUEST_TOKEN_URL, "POST");
        $result = $request->doRequest(0);
        parse_str($result['body'], $params);
        // now make the request.
        $request = new OAuthRequester(TWITTER_PUBLIC_TIMELINE_API, 'GET', $params);
        $result = $request->doRequest();
        $response = $result['body'];
    } catch (OAuthException2 $e) {
        $response = "Exception" . $e->getMessage();
    }
    return $response;
}
示例#14
0
 protected function getOAuthRequester($method, $url, $params)
 {
     switch ($method) {
         case "GET":
             $request = new OAuthRequester($url, $method, $params);
             break;
         case "POST":
             $request = new OAuthRequester($url, $method, '', $params);
             break;
         case "DELETE":
             $request = new OAuthRequester($url, $method);
             break;
         default:
             $request = new OAuthRequester($url, $method);
     }
     $result = $request->doRequest();
     return $result['body'];
 }
示例#15
0
function readTimeline($user, $count)
{
    try {
        // Obtain a request object for the request we want to make
        $request = new OAuthRequester(TWITTER_REQUEST_TOKEN_URL, "POST");
        $result = $request->doRequest(0);
        parse_str($result['body'], $params);
        // now make the request.
        if ($user === false) {
            $url = TWITTER_PUBLIC_TIMELINE_API;
        } else {
            $url = TWITTER_USER_TIMELINE_API . '?screen_name=' . $user . '&count=' . $count;
        }
        $request = new OAuthRequester($url, 'GET', $params);
        $result = $request->doRequest();
        $response = $result['body'];
    } catch (OAuthException2 $e) {
        $response = "Exception" . $e->getMessage();
    }
    return $response;
}
示例#16
0
 function index()
 {
     $options = array('consumer_key' => $this->key, 'consumer_secret' => $this->secret);
     OAuthStore::instance("2Leg", $options);
     $url = "http://api.twitter.com/1/statuses/home_timeline.format?include_entities=true";
     // this is the URL of the request
     $method = "GET";
     // you can also use POST instead
     $params = null;
     try {
         // Obtain a request object for the request we want to make
         $request = new OAuthRequester($url, $method, $params);
         // Sign the request, perform a curl request and return the results,
         // throws OAuthException2 exception on an error
         // $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
         $result = $request->doRequest();
         $response = $result['body'];
         echo $response;
     } catch (OAuthException2 $e) {
     }
 }
示例#17
0
 /**
  * send an api call to yotpo to authenticate and get an access token
  * @return access token
  */
 public function oauthAuthentication()
 {
     if ($this->app_key == null or $this->secret == null) {
         Mage::log('Missing app key or secret');
         return null;
     }
     $yotpo_options = array('consumer_key' => $this->app_key, 'consumer_secret' => $this->secret, 'client_id' => $this->app_key, 'client_secret' => $this->secret, 'grant_type' => 'client_credentials');
     OAuthStore::instance("2Leg", $yotpo_options);
     try {
         $request = new OAuthRequester(self::YOTPO_OAUTH_TOKEN_URL, "POST", $yotpo_options);
         if (!$request) {
             Mage::log('Failed to get token access from yotpo api');
             return null;
         }
         $result = $request->doRequest(0);
         $tokenParams = json_decode($result['body'], true);
         return $tokenParams['access_token'];
     } catch (OAuthException2 $e) {
         Mage::log('error: ' . $e);
         return null;
     }
 }
示例#18
0
 public function run_query($endpoint, $query_arr)
 {
     if (!$this->apiKey) {
         throw new Semantics3_AuthenticationError('No API key provided.');
     }
     if (!$this->apiSecret) {
         throw new Semantics3_AuthenticationError('No API secret provided.');
     }
     $options = array('consumer_key' => $this->apiKey, 'consumer_secret' => $this->apiSecret);
     OAuthStore::instance("2Leg", $options);
     $url = "https://api.semantics3.com/v1/{$endpoint}?q=" . $query_arr;
     $method = "GET";
     $params = null;
     try {
         $request = new OAuthRequester($url, $method, $params);
         $result = $request->doRequest();
         return $result['body'];
     } catch (OAuthException2 $e) {
         print "\n";
         $error = $e->getMessage();
         print $error . "\n";
     }
 }
示例#19
0
<?php

// Load: http://code.google.com/p/oauth-php/
require_once 'oauth-php-r50/library/OAuthStore.php';
require_once 'oauth-php-r50/library/OAuthRequester.php';
require_once 'config.inc.php';
// Request parameters are oauth_token, consumer_key and usr_id.
$oauth_token = $_GET['oauth_token'];
try {
    OAuthRequester::requestAccessToken($consumer_key, $oauth_token, $user_id);
} catch (OAuthException $e) {
    // Something wrong with the oauth_token.
    // Could be:
    // 1. Was already ok
    // 2. We were not authorized
    print 'error!';
    print_r($e);
}
header('Location: index.php');
exit;
示例#20
0
 /**
  * Request an access token from the site belonging to consumer_key.
  * Before this we got an request token, now we want to exchange it for
  * an access token.
  * 
  * @param string consumer_key
  * @param string token
  * @param int usr_id		user requesting the access token
  * @param string method (optional) change the method of the request, defaults to POST (as it should be)
  * @param array options (optional) extra options for request, eg token_ttl
  * @param array curl_options	optional extra options for curl request
  *  
  * @exception OAuthException2 when no key could be fetched
  * @exception OAuthException2 when no server with consumer_key registered
  */
 static function requestAccessToken($consumer_key, $token, $usr_id, $method = 'POST', $options = array(), $curl_options = array())
 {
     OAuthRequestLogger::start();
     $store = OAuthStore::instance();
     $r = $store->getServerTokenSecrets($consumer_key, $token, 'request', $usr_id);
     $uri = $r['access_token_uri'];
     $token_name = $r['token_name'];
     // Delete the server request token, this one was for one use only
     $store->deleteServerToken($consumer_key, $r['token'], 0, true);
     // Try to exchange our request token for an access token
     $oauth = new OAuthRequester($uri, $method);
     if (isset($options['oauth_verifier'])) {
         $oauth->setParam('oauth_verifier', $options['oauth_verifier']);
     }
     if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) {
         $oauth->setParam('xoauth_token_ttl', intval($options['token_ttl']));
     }
     OAuthRequestLogger::setRequestObject($oauth);
     $oauth->sign($usr_id, $r);
     $text = $oauth->curl_raw($curl_options);
     if (empty($text)) {
         throw new OAuthException2('No answer from the server "' . $uri . '" while requesting a request token');
     }
     $data = $oauth->curl_parse($text);
     if ($data['code'] != 200) {
         throw new OAuthException2('Unexpected result from the server "' . $uri . '" (' . $data['code'] . ') while requesting a request token');
     }
     $token = array();
     $params = explode('&', $data['body']);
     foreach ($params as $p) {
         @(list($name, $value) = explode('=', $p, 2));
         $token[$oauth->urldecode($name)] = $oauth->urldecode($value);
     }
     if (!empty($token['oauth_token']) && !empty($token['oauth_token_secret'])) {
         $opts = array();
         $opts['name'] = $token_name;
         if (isset($token['xoauth_token_ttl'])) {
             $opts['token_ttl'] = $token['xoauth_token_ttl'];
         }
         $store->addServerToken($consumer_key, 'access', $token['oauth_token'], $token['oauth_token_secret'], $usr_id, $opts);
     } else {
         throw new OAuthException2('The server "' . $uri . '" did not return the oauth_token or the oauth_token_secret');
     }
     OAuthRequestLogger::flush();
 }
示例#21
0
<?php

//session_destroy();
if (!empty($_SESSION['SFDOCTOR_TOKEN'])) {
    try {
        echo '<pre>GET: ' . $uriProfile . '<br/>';
        print_r('');
        echo '</pre>';
        $tokenResultParams = $_SESSION['SFDOCTOR_TOKEN'];
        $request = new OAuthRequester($uriProfile, 'GET', $tokenResultParams);
        $result = $request->doRequest(0);
        if ($result['code'] == 200) {
            echo '<pre>';
            print_r(json_decode($result['body']));
            echo '</pre>';
            exit;
        } else {
            echo 'Error';
        }
    } catch (OAuthException2 $e) {
        echo '<pre>';
        print_r('Error. Maybe you must login with 65dotor account.');
        echo '</pre>';
        echo '<pre>';
        print_r($e->getMessage());
        echo '</pre>';
        echo '<pre>';
        print_r($e);
        echo '</pre>';
        exit;
    }
示例#22
0
 /**
  * signs and executes the request
  * @return array ('code'=>int, 'headers'=>array(), 'body'=>string)
  */
 protected function execute($method, $resource, $params = array(), $body = null)
 {
     //remove empty entries from the fields
     $params = $this->removeEmptiesFromArray($params);
     $options = array('consumer_key' => $this->settings->account, 'consumer_secret' => $this->settings->secretkey);
     OAuthStore::instance('2Leg', $options);
     try {
         //print_r($params);
         $url = $this->settings->base_url . '/sites/' . $this->settings->account . $resource;
         $request = new OAuthRequester($url, $method, $params);
         $result = $request->doRequest();
         return $result;
     } catch (OAuthException2 $e) {
         error_log($e->getMessage());
         //throw new Exception('Error. ' . $e->getMessage());
         return array();
     }
 }
示例#23
0
 /**
  * 
  * signs and executes the request
  *
  * @param string $method HTTP method, e.g. GET, POST, DELETE
  * @param string $resource e.g. /consumptions.json
  * @param array $params query parameters (GET or DELETE)
  * @param array $fields data fields to be encoded as JSON (POST or PUT)
  * @return array ('code'=>int, 'headers'=>array(), 'body'=>string)
  */
 protected function execute($method, $resource, $params = array(), $data = NULL)
 {
     $options = array('consumer_key' => $this->settings->account, 'consumer_secret' => $this->settings->secretkey);
     OAuthStore::instance('2Leg', $options);
     try {
         //print_r($params);
         $url = $this->settings->base_url . '/sites/' . $this->settings->account . $resource;
         if ($method == 'GET' || $method == 'DELETE') {
             $request = new OAuthRequester($url, $method, $params);
         } else {
             if (is_object($data)) {
                 // data is a single item, user or consumption object
                 $body = json_encode($data->getFields());
             } else {
                 if (is_array($data)) {
                     // data is an array of items, users or consumptions
                     $objects = array();
                     foreach ($data as $object) {
                         $objects[] = $object->getFields();
                     }
                     $body = json_encode($objects);
                 }
             }
             $request = new OAuthRequester($url, $method, null, $body);
         }
         $result = $request->doRequest();
         //print_r($result);
         return $result;
     } catch (OAuthException2 $e) {
         error_log($e->getMessage());
         //throw new Exception('Error. ' . $e->getMessage());
         return array();
     }
 }
//- Prepare the PHP OAuth for consuming our Oxygen service
$options = array('consumer_key' => ConsumerKey, 'consumer_secret' => ConsumerSecret, 'server_uri' => BaseUrl, 'request_token_uri' => BaseUrl . 'OAuth/RequestToken', 'authorize_uri' => BaseUrl . 'OAuth/Authorize', 'access_token_uri' => BaseUrl . 'OAuth/AccessToken');
OAuthStore::instance('Session', $options);
$fname = realpath(dirname(__FILE__)) . '/token.txt';
$token = unserialize(file_get_contents($fname));
unlink($fname);
//- To disable the SSL check to avoid an exception with invalidate certificate on the server,
//- use the cURL CURLOPT_SSL_VERIFYPEER option and set it to false.
//- 3rd leg: Get the 'access token' and session
$access = '';
try {
    //- The following line is for reference only, the call to OAuthRequester::requestRequestToken() included that step. But you may need
    //- to call that line with the correct parameters in you run that 'leg' in a different PHP session.
    OAuthStore::instance()->addServerToken(ConsumerKey, 'request', $token['oauth_token'], $token['oauth_token_secret'], 0, array());
    //- $access will contain the server response in case you modified the Google library like documented above
    $access = OAuthRequester::requestAccessToken(ConsumerKey, $token['oauth_token'], 0, 'POST', $options, array(CURLOPT_SSL_VERIFYPEER => 0));
    //- If you did not modify OAuthRequester::requestAccessToken() function as documented above, do this instead
    // $access =array (
    // 	'oauth_token' => OAuthStore::instance ()->getSecretsForSignature ('', 0) ['token'],
    // 	'oauth_token_secret' => OAuthStore::instance ()->getSecretsForSignature ('', 0) ['token_secret'],
    // ) ;
    /*
    define ('OAUTH_HOST', 'http://' . $_SERVER ['SERVER_NAME']) ;
    $request =new OAuthRequester (OAUTH_HOST . $_SERVER ['PHP_SELF'], 'POST', $token) ;
        $access =$request->doRequest (0) ;
    */
    //- In this sample, we save the token to a file, and use it in the Refresh example
    $fname = realpath(dirname(__FILE__)) . '/access_token.txt';
    file_put_contents($fname, serialize($access));
} catch (Exception $e) {
    echo "OAuth/AccessToken\n", 'Caught exception: ', $e->getMessage(), "\n";
示例#25
0
文件: api.php 项目: JaimeA/SkunkWrx
 function synchronize()
 {
     header("Content-Type: text/event-stream\n\n");
     $ALREADY_SEARCHED_PHONES = array();
     $i = 0;
     $st = $this->db->prepare('SELECT audience_phone FROM audience WHERE sync = 0');
     $st->execute($params);
     while ($audience_phone = $st->fetch(PDO::FETCH_ASSOC)) {
         $phone = $audience_phone['audience_phone'];
         if (!array_search($phone, $ALREADY_SEARCHED_PHONES)) {
             array_push($ALREADY_SEARCHED_PHONES, $phone);
             $CONDUCTTR_REQUEST_URL = "https://api.conducttr.com/v1/project/" . CONDUCTTR_PROJECT_ID . "/code?audience_phone=" . $phone;
             $options = array('consumer_key' => CONDUCTTR_CONSUMER_KEY, 'consumer_secret' => CONDUCTTR_CONSUMER_SECRET);
             OAuthStore::instance("2Leg", $options);
             try {
                 $request = new OAuthRequester(CONDUCTTR_REQUEST_TOKEN_URL, $method);
                 $result = $request->doRequest(0);
                 parse_str($result['body'], $params);
                 $request = new OAuthRequester($CONDUCTTR_REQUEST_URL, "GET", $params);
                 $result = $request->doRequest();
                 $response = json_decode($result['body']);
                 if ($response->results[0]->code == $_REQUEST['code']) {
                     $params = array(':audience_phone' => $phone);
                     $st = $this->db->prepare('UPDATE audience SET sync = 1 WHERE audience_phone = :audience_phone');
                     if ($st->execute($params)) {
                         header("Content-Type: text/event-stream\n\n");
                         header("Cache-Control: no-cache");
                         // recommended to prevent caching of event data.
                         echo "id: {$serverTime}" . PHP_EOL;
                         echo "data: {$phone}" . PHP_EOL;
                         echo "retry: 10000" . PHP_EOL;
                         echo PHP_EOL;
                         ob_flush();
                         flush();
                     }
                 }
             } catch (OAuthException2 $e) {
                 echo "Exception" . $e->getMessage();
             }
         }
     }
     sleep(1);
 }
示例#26
0
        return array();
    }
}
$req_token_link = $CFG->wwwroot . '/blocks/gmail/oauth3/service/request_token.php';
$store = OAuthStore::instance('Google');
$user_id = $USER->id;
// most often the current user
// We must check if this user has a authorized token
// if they do not we need a link that says "grant access to my gmail"
// TODO:invalid old token link
// NOTE: if they need to revoke token or if current token doesn't work this link should
//       show up.
$consumer_key = get_config('blocks/gmail', 'consumer_key');
// the google apps domain
try {
    $token = OAuthRequester::requestRequestToken($consumer_key, $user_id);
} catch (OAuthException $e) {
    if ($e->message == 'User not in token table.') {
        // return the grant access link since user doesn't even have an entry in the tokens table
        print 'User has no token.';
    }
    // If Server Returns a 400 or something is the token useless?
}
// Call back location after getting the first token
$callback_uri = $CFG->wwwroot . '/blocks/gmail/oauth3/service/obtain_auth.php?consumer_key=' . rawurlencode($consumer_key) . '&usr_id=' . intval($user_id);
// Now redirect to the autorization uri and get us authorized
if (!empty($token['authorize_uri'])) {
    // Redirect to the server, add a callback to our server
    if (strpos($token['authorize_uri'], '?')) {
        $uri = $token['authorize_uri'] . '&';
    } else {
示例#27
0
         $tokenResultParams = OAuthRequester::requestRequestToken(SFDOCTOR_CONSUMER_KEY, 0, $getAuthTokenParams);
         //  redirect to the 65doctor authorization page, they will redirect back
         header("Location: " . SFDOCTOR_AUTHORIZE_URL . "?oauth_token=" . $tokenResultParams['token'] . $signature);
     } else {
         echo '<pre>';
         print_r('Missing username or password.');
         echo '</pre>';
         exit;
     }
 } else {
     //  STEP 2:  Get an access token
     $oauthToken = $_GET["oauth_token"];
     // echo "oauth_verifier = '" . $oauthVerifier . "'<br/>";
     $tokenResultParams = $_GET;
     try {
         OAuthRequester::requestAccessToken(SFDOCTOR_CONSUMER_KEY, $oauthToken, 0, 'POST', $_GET);
     } catch (OAuthException2 $e) {
         echo '<pre>';
         print_r($e);
         echo '</pre>';
         // Something wrong with the oauth_token.
         // Could be:
         // 1. Was already ok
         // 2. We were not authorized
         return;
     }
     $_SESSION['SFDOCTOR_TOKEN'] = $tokenResultParams;
     // make the resource owner requestrequest.
     //		$request = new OAuthRequester($uriProfile, 'GET', $tokenResultParams);
     //		$result = $request->doRequest(0);
     //		if ($result['code'] == 200) {
示例#28
0
 /**
  * Sign the request, perform a curl request and return the results
  * @param string urlStr unsigned URL request
  * @return array ex: array ('code'=>int, 'headers'=>array(), 'body'=>string)
  */
 protected function request($urlStr, $requestMethod = "GET", $params = null)
 {
     //custom headers
     $curlOptions[CURLOPT_HTTPHEADER] = array();
     $curlOptions[CURLOPT_HTTPHEADER][] = "X-Factual-Lib: " . $this->config['factual']['driverversion'];
     if ($requestMethod == "POST") {
         $curlOptions[CURLOPT_HTTPHEADER][] = "Content-Type: " . "application/x-www-form-urlencoded";
     }
     //other curl options
     $curlOptions[CURLOPT_CONNECTTIMEOUT] = $this->connectTimeout;
     //connection timeout
     $curlOptions[CURLOPT_TIMEOUT] = $this->curlTimeout;
     //execution timeout
     // Build request with OAuth request params
     $request = new OAuthRequester($urlStr, $requestMethod, $params);
     //check & flag debug
     if ($this->debug) {
         $request->debug = true;
         //set debug on oauth request object for curl output
     }
     //Make request
     try {
         $callStart = microtime(true);
         $result = $request->doRequest(0, $curlOptions);
         $callEnd = microtime(true);
     } catch (Exception $e) {
         //catch client exception
         $info['request']['encoded'] = $urlStr;
         $info['request']['unencoded'] = urldecode($urlStr);
         $info['driver'] = $this->config['factual']['driverversion'];
         $info['method'] = $requestMethod;
         $info['message'] = "Service exception (likely a problem on the server side). Client did not connect and returned '" . $e->getMessage() . "'";
         $factualE = new FactualApiException($info);
         throw $factualE;
     }
     $result['request'] = $urlStr;
     //pass request string onto response
     $result['tablename'] = $this->lastTable;
     //pass table name to result object (not available with rawGet())
     //catch server exception & load up on debug data
     if ($result['code'] >= 400 | $this->debug) {
         $body = json_decode($result['body'], true);
         //get a boatload of debug data
         $info['code'] = $result['code'];
         $info['version'] = $body['version'];
         $info['status'] = $body['status'];
         $info['returnheaders'] = $result['headers'];
         $info['driver'] = $this->config['factual']['driverversion'];
         $info['method'] = $requestMethod;
         if (isset($body['error_type'])) {
             $info['error_type'] = $body['error_type'];
         }
         if (isset($body['message'])) {
             $info['message'] = $body['message'];
         }
         if (isset($result['request'])) {
             $info['request']['encoded'] = $result['request'];
             $info['request']['unencoded'] = urldecode($result['request']);
         }
         if (isset($result['tablename'])) {
             $info['tablename'] = $result['tablename'];
         }
         //add post body to debug
         if ($params) {
             $info['body'] = $params;
         }
         //add execution time
         $info['time'] = $callEnd - $callStart;
         //write debug info to stderr if debug mode on
         if ($this->debug) {
             //add only select curl debug information
             unset($request->curlInfo['url']);
             unset($request->curlInfo['content_type']);
             unset($request->curlInfo['certinfo']);
             unset($request->curlInfo['redirect_time']);
             unset($request->curlInfo['redirect_time']);
             unset($request->curlInfo['filetime']);
             unset($request->curlInfo['ssl_verify_result']);
             $info['curl'] = $request->curlInfo;
             $info = array_filter($info);
             //remove empty elements for readability
             file_put_contents('php://stderr', "Debug " . print_r($info, true));
         }
         //chuck exception
         if ($result['code'] >= 400) {
             $factualE = new FactualApiException($info);
             throw $factualE;
         }
     }
     //check for deprecation, add to stdout
     if ($result['code'] == 301) {
         file_put_contents('php://stderr', "Entity is deprecated");
     }
     return $result;
 }
示例#29
0
 /**
  * Returns the request token.
  *
  * @return string The request token.
  */
 protected function getRequestToken()
 {
     $result = \OAuthRequester::requestRequestToken($this->key, 0, null);
     return $result;
 }
示例#30
0
 public function makeOAuthRequest($request, $method = null, $params = null, $body = null, $files = null)
 {
     $request = new OAuthRequester($request, $method, $params, $body, $files);
     return $request->doRequest($this->oauth_user_id);
 }