예제 #1
0
function webhookCallback()
{
    global $connectHost, $requestHeaders;
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        # Get the JSON body and HMAC-SHA1 signature of the incoming POST request
        $callbackBody = file_get_contents('php://input');
        $callbackSignature = getallheaders()['X-Square-Signature'];
        # Validate the signature
        if (!isValidCallback($callbackBody, $callbackSignature)) {
            # Fail if the signature is invalid
            error_log("Webhook event with invalid signature detected!");
            return;
        }
        # Load the JSON body into an associative array
        $callbackBodyJson = json_decode($callbackBody);
        # If the notification indicates a PAYMENT_UPDATED event...
        if (property_exists($callbackBodyJson, 'event_type') and $callbackBodyJson->event_type == 'PAYMENT_UPDATED') {
            # Get the ID of the updated payment
            $paymentId = $callbackBodyJson->entity_id;
            # Send a request to the Retrieve Payment endpoint to get the updated payment's full details
            $response = Unirest\Request::get($connectHost . '/v1/me/payments/' . $paymentId, $requestHeaders);
            # Perform an action based on the returned payment (in this case, simply log it)
            error_log(json_encode($response->body, JSON_PRETTY_PRINT));
        }
    } else {
        error_log("Received a non-POST request");
    }
}
예제 #2
0
 protected function Request($Method, $Request, $Body = null, array $Headers = array(), array $SuccessHeaders = array(200, 301, 302))
 {
     try {
         $URL = $this->Endpoint;
         if (is_array($Request)) {
             foreach ($Request as $Key => $Value) {
                 if (is_int($Key)) {
                     $URL .= "/{$Value}";
                 } else {
                     $URL .= "/{$Key}/{$Value}";
                 }
             }
         } else {
             $URL .= '/' . $Request;
         }
         if (!empty($this->DefaultGetParameters)) {
             $URL .= '?' . http_build_query($this->DefaultGetParameters);
         }
         $Headers = array_merge($this->DefaultHeaders, $Headers);
         $Response = Unirest\Request::send($Method, $URL, $Body, $Headers);
         if (in_array($Response->code, $SuccessHeaders)) {
             return array('Code' => $Response->code, 'Headers' => $Response->headers, 'Body' => $Response->raw_body, 'Json' => json_decode($Response->raw_body, true));
         }
         $this->Warning("Response code {$Response->code}. Request to {$URL}");
     } catch (Exception $Exception) {
         $this->Warning(get_class($Exception) . ' thrown (' . $Exception->GetMessage() . ')');
     }
     return false;
 }
 /**
  * Возвращает json_decode ответ от метрики
  * @param string $method  Тип_метода ― GET, POST, PUT или DELETE.
  * @param string $path    Имя_метода ― URL ресурса, над которым выполняется действие.
  * @param array  $options Параметры ― Обязательные и необязательные параметры запроса, которые не входят в состав URL ресурса.
  */
 private function QueryYandex($method = "get", $path = "/counters", $options = array())
 {
     $opt = "";
     if ($method === "get") {
         foreach ($options as $key => $value) {
             if ($value != null) {
                 $opt .= "{$key}={$value}&";
             }
         }
         $ret = Unirest\Request::get("http://api-metrika.yandex.ru" . $path . ".json?pretty=1&{$opt}", array("Content-Type" => "application/x-yametrika+json", "Authorization" => "OAuth " . $this->access_token, "Accept" => "application/x-yametrika+json"));
     } else {
         $ret = Unirest\Request::$method("http://api-metrika.yandex.ru" . $path . ".json?pretty=1", array("Content-Type" => "application/x-yametrika+json", "Authorization" => "OAuth " . $this->access_token, "Accept" => "application/x-yametrika+json", json_encode($options)));
     }
     if ($ret->code != 200) {
         if (property_exists(json_decode($ret->raw_body), 'errors')) {
             $errors = $ret->body->errors;
             foreach ($errors as $err) {
                 throw new Exception("Error:: " . "[" . $err->code . "] [" . $this->error_code[$err->code] . "]");
             }
         }
     } elseif (property_exists(json_decode($ret->raw_body), 'errors')) {
         $errors = $ret->body->errors;
         foreach ($errors as $err) {
             throw new Exception("Method error:: " . "[" . $err->code . "] [" . $err->text . "]");
         }
     } else {
         return json_decode($ret->raw_body);
     }
 }
예제 #4
0
 public function sendRequest($url, $req)
 {
     $headers = array("Content-Type" => "application/xml", 'Authorization' => $this->auth);
     $url = $this->baseUrl . '/' . $url;
     $response = Unirest\Request::post($url, $headers, $req);
     //var_dump($response->body);
     //exit;
     return $response->body;
 }
예제 #5
0
function getChapter($siteId, $mangaId, $chapterId)
{
    $url = "https://doodle-manga-scraper.p.mashape.com/" . $siteId . "/manga/" . $mangaId . "/" . $chapterId;
    $response = Unirest\Request::get($url, array("X-Mashape-Key" => "S4X6YXGRxxmshLDxygnESvTmQ3kAp1DSsDDjsnx14NHnev0ocV", "Accept" => "text/plain"));
    $responseBody = $response->body;
    $chapter[0] = $responseBody->name;
    foreach ($responseBody->pages as $page) {
        $chapter[$page->pageId] = $page->url;
    }
    return $chapter;
}
function deleteItem($itemId)
{
    global $accessToken, $connectHost, $requestHeaders;
    $response = Unirest\Request::delete($connectHost . '/v1/me/items/' . $itemId, $requestHeaders);
    if ($response->code == 200) {
        error_log('Successfully deleted item');
        return $response->body;
    } else {
        error_log('Item deletion failed');
        return NULL;
    }
}
 function addCustomGame($postName, $postGenre = "", $postMetacritic = "", $postTimetobeat = "")
 {
     $servername = "localhost:3306";
     $username = "******";
     $password = "";
     $dbname = "steamgames";
     $nameString = $postName;
     $type = "game";
     $genreString = $postGenre;
     $header_image = "";
     $metacritic = $postMetacritic;
     $recommendations = "manually added";
     $timetobeat = $this->getDataFromHowlongtobeat($nameString);
     if (strcmp($timetobeat, "no info")) {
         $timetobeat = $postTimetobeat;
     }
     if (!$this->checkDatabaseByName($nameString)) {
         $response = Unirest\Request::get("https://ahmedakhan-game-review-information-v1.p.mashape.com/api/v1/information?game_name=" . $nameString, array("X-Mashape-Key" => "QyibUbgQ9zmshV0vBfcODcQk9x8yp1L7QdkjsnDlchW0tBoziv", "Accept" => "application/json"));
         print_r($response);
         if ($response->code == "200") {
             $json = $response->raw_body;
             $obj = json_decode($json, true);
             if (array_key_exists('result', $obj)) {
                 $obj = $obj['result'];
                 $genreString = "";
                 foreach ($obj['genre'] as $genre) {
                     $genreString .= $genre . ", ";
                 }
                 $genreString = substr($genreString, 0, strlen($genreString) - 2);
                 $header_image = $obj['thumbnail'];
                 $metacritic = $obj['metacritic']['criticScore'];
             }
         }
         $conn = new mysqli($servername, $username, $password, $dbname);
         // Check connection
         if ($conn->connect_error) {
             die("Connection failed: " . $conn->connect_error);
         }
         $sql = "INSERT INTO games (name, type, header_image, genres, recommendations, timetobeat, metacritic, played, appid)\n                VALUES ('" . $nameString . "', '" . $type . "', '" . $header_image . "', '" . $genreString . "', '" . $recommendations . "', '" . $timetobeat . "', '" . $metacritic . "', 'no'," . rand(1000000, 10000000) . ")";
         if ($conn->query($sql) === TRUE) {
             echo "Record updated successfully";
         } else {
             echo "Error updating record: " . $conn->error;
         }
         $conn->close();
     } else {
         echo "already in database";
     }
 }
예제 #8
0
 public function identify($params)
 {
     $headers = array("Content-Type" => "application/json", "lifecycle-api-key" => $this->lifecycle_api_key);
     $body = json_encode(array("params" => $params));
     $response = Unirest\Request::post("http://localhost:3400/v1/identify", $headers, $body);
     $response->code;
     // HTTP Status code
     $response->headers;
     // Headers
     $response->body;
     // Parsed body
     $response->raw_body;
     // Unparsed body
     return $response;
 }
예제 #9
0
파일: rest.php 프로젝트: pdelbar/onethree
 /**
  * Use the selectors to retrieve a number of objects.
  *
  * @param One_Scheme $scheme
  * @param array $selectors
  * @return array
  */
 public function select(&$scheme, $selectors)
 {
     //    if (count($selectors)) {
     //      foreach ($selectors as $sel) {
     //        list($path, $val, $op) = $sel;
     //        $query->where($path, $op, $val);
     //      }
     //    }
     $this->init($scheme);
     $route = $this->map->selectRoute;
     $response = Unirest\Request::get($route);
     print_r($response);
     //    $selection = $this->executeSchemeQuery($query);
     //    return (count($selection) > 0) ? $selection : NULL;
 }
function get2014Payments()
{
    global $accessToken, $connectHost;
    # Restrict the request to the 2014 calendar year, eight hours behind UTC
    # Make sure to URL-encode all parameters
    $parameters = http_build_query(array('begin_time' => '2014-01-01T00:00:00-08:00', 'end_time' => '2015-01-01T00:00:00-08:00'));
    # Standard HTTP headers for every Connect API request
    $requestHeaders = array('Authorization' => 'Bearer ' . $accessToken, 'Accept' => 'application/json', 'Content-Type' => 'application/json');
    $payments = array();
    $requestPath = $connectHost . '/v1/me/payments?' . $parameters;
    $moreResults = true;
    while ($moreResults) {
        # Send a GET request to the List Payments endpoint
        $response = Unirest\Request::get($requestPath, $requestHeaders);
        # Read the converted JSON body into the cumulative array of results
        $payments = array_merge($payments, $response->body);
        # Check whether pagination information is included in a response header, indicating more results
        if (array_key_exists('Link', $response->headers)) {
            $paginationHeader = $response->headers['Link'];
            if (strpos($paginationHeader, "rel='next'") !== false) {
                # Extract the next batch URL from the header.
                #
                # Pagination headers have the following format:
                # <https://connect.squareup.com/v1/MERCHANT_ID/payments?batch_token=BATCH_TOKEN>;rel='next'
                # This line extracts the URL from the angle brackets surrounding it.
                $requestPath = explode('>', explode('<', $paginationHeader)[1])[0];
            } else {
                $moreResults = false;
            }
        } else {
            $moreResults = false;
        }
    }
    # Remove potential duplicate values from the list of payments
    $seenPaymentIds = array();
    $uniquePayments = array();
    foreach ($payments as $payment) {
        if (array_key_exists($payment->id, $seenPaymentIds)) {
            continue;
        }
        $seenPaymentIds[$payment->id] = true;
        array_push($uniquePayments, $payment);
    }
    return $uniquePayments;
}
예제 #11
0
function getTrends($index, $section)
{
    global $host;
    global $apiKey;
    global $all_sections;
    //
    $request = "http://api.chartbeat.com/live/toppages/v3/?apikey={$apiKey}&host={$host}&section={$section}&limit=100";
    //
    $response = Unirest\Request::get($request, array("Accept" => "application/json"));
    //
    $json = $response->raw_body;
    //
    $arr = json_decode($json);
    //
    $data = $arr->pages;
    //echo var_dump($data);
    foreach ($data as $key => $value) {
        if ($value->authors != NULL) {
            //
            array_push($all_sections[$index], getSlug($value->path));
        }
    }
}
예제 #12
0
 public function Countries()
 {
     // get data from
     $headers = array();
     $body = array('username' => Public_Api_Username, 'password' => Public_Api_Password, 'action' => 'get_country', 'gzip' => 'no');
     $response = Unirest\Request::get(Public_Api_URl, $headers, $body);
     $items = json_decode($response->raw_body);
     $country = array();
     $temp = array();
     for ($k = 0; $k <= 500; $k++) {
         $j = $k + 1;
         if (isset($items->{$j})) {
             $temp['index'] = $k;
             $temp['Code'] = $items->{$k}->Code;
             $temp['Name'] = $items->{$k}->Name;
             array_push($country, $temp);
         } else {
             //end for
             break;
         }
     }
     return $country;
 }
예제 #13
0
 /**
  * Fetches a json containing a randomly generated word from the API, based on the difficulty
  * setting. Returns the json.
  * @param unknown $url
  */
 private function retrieveRandomWord($url)
 {
     $response = Unirest\Request::get($url, array("X-Mashape-Key" => "xJkqXGguDTmshoNIaGVnrMZlFPmUp1WrnZLjsn8DDx3DFQhNq5", "Accept" => "application/json"));
     $wordJSON = json_decode($response->raw_body);
     $word = $wordJSON->{"word"};
     /*
      * The API provides some weird words (if you can even call them that) like "dr. j" which I don't think should be included.
      * If such a word is provided, the function instead calls itself recursively to get a new word.
      */
     if (strpos($word, '.') !== false || strpos($word, ' ') !== false) {
         return retrieveRandomWord($url);
     } else {
         return strtoupper($word);
     }
     /*Loose idea for discarding words with too low frequency. API seems to be broken however,
      * sometimes the frequency parameter doesn't exist, unsure of the cause (nothing stated in docs).
      *
      *
      * $freq = $wordJSON->{"frequency"};
      * if ($freq > 3.5) return $wordJSON->{"word"};
      * else return retrieveRandomWord($url);
      */
 }
예제 #14
0
function callback()
{
    global $connectHost, $oauthRequestHeaders;
    # Extract the returned authorization code from the URL
    $authorizationCode = $_GET['code'];
    if ($authorizationCode) {
        # Provide the code in a request to the Obtain Token endpoint
        $oauthRequestBody = array('client_id' => $applicationId, 'client_secret' => $applicationSecret, 'code' => $authorizationCode);
        $response = Unirest\Request::post($connectHost . '/oauth2/token', $oauthRequestBody, $requestHeaders);
        # Extract the returned access token from the response body
        if (property_exists($response, 'access_token')) {
            # Here, instead of printing the access token, your application server should store it securely
            # and use it in subsequent requests to the Connect API on behalf of the merchant.
            error_log('Access token: ' . $response->access_token);
            error_log('Authorization succeeded!');
            # The response from the Obtain Token endpoint did not include an access token. Something went wrong.
        } else {
            error_log('Code exchange failed!');
        }
        # The request to the Redirect URL did not include an authorization code. Something went wrong.
    } else {
        error_log('Authorization failed!');
    }
}
예제 #15
0
 public function ReadHotels($params)
 {
     $headers = array();
     $params['action'] = 'hotel_search';
     $params['username'] = Public_Api_Username;
     $params['password'] = Public_Api_Password;
     try {
         $response = Unirest\Request::get(Public_Api_URl, $headers, $params);
         $items = json_decode($response->raw_body);
     } catch (Exception $ex) {
         $items = array();
     }
     //save items as array
     if ($items->TotalCount) {
         $hotels = array();
         foreach ($items->TotalCount as $h) {
             array_push($hotels, $h);
         }
         //svae items in dbase
         return $hotels;
     } else {
         return array();
     }
 }
예제 #16
0
    exit;
});
$app->get('/api/v1/zip/:zip', function ($zip) {
    $headers = array("Accept" => "application/json");
    $key = '2f4d666f6f04dbad2164175736a5a2dc';
    $url = "http://api.openweathermap.org/data/2.5/weather?zip={$zip}&APPID={$key}&units=imperial";
    $response = Unirest\Request::get($url, $headers);
    header("Content-Type: application/json");
    echo json_encode($response->body);
    exit;
});
$app->get('/api/v1/forecast/:lat/:lon', function ($lat, $lon) {
    $headers = array("Accept" => "application/json");
    $key = '2f4d666f6f04dbad2164175736a5a2dc';
    $url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat={$lat}&lon={$lon}&appid={$key}&units=imperial";
    $response = Unirest\Request::get($url, $headers);
    header("Content-Type: application/json");
    echo json_encode($response->body);
    exit;
});
$app->get('/api/v1/loc/:zip', function ($zip) {
    $headers = array("Accept" => "application/json");
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address={$zip}";
    $response = Unirest\Request::get($url, $headers);
    $resp = $response->body->results[0]->geometry->location;
    $res = array('lat' => $resp->lat, 'lon' => $resp->lng);
    header("Content-Type: application/json");
    echo json_encode($res);
    exit;
});
$app->run();
예제 #17
0
        echo "<i class=\"fa fa-star evo-green\"></i>";
    }
    ?>
				</div>
				<div>
					<?php 
    echo "<a href=\"mailto:" . $obj['TaskOwnerEmailAddress'] . "?subject=" . $campaignName . " - " . $obj['TaskName'] . "&body=http://unilever.humanig.com/campaign/" . $project_id . "/" . $task_id . "\">";
    ?>
					<div class="circle_container"><div class="email_address"><i class="fa fa-envelope-o"></i></div></div></a>
				</div>
				<?php 
    $user_id = $obj['TaskOwnerUserID'];
    $url = $this->container->getParameter('apiUrl') . "users/" . $user_id . "/profile.json";
    $api_key = $_COOKIE['api'];
    $api_header = array('x-wsse' => 'ApiKey="' . $api_key . '"');
    $response = Unirest\Request::get($url, $api_header);
    $user_profile = json_decode($response->raw_body, true)[0];
    $honey_id = $user_profile['honey_id'];
    $honey_link = "https://honey.is/home/#user/{$honey_id}/profile";
    if ($honey_id) {
        echo '<div><a href="' . $honey_link . '"><div class="circle_container circle-honey"><div class="email_address"><i class="honey-link"></i></div></div></a><div>';
    }
    ?>
			</th>
		</tr>
	</thead>
	<?php 
}
?>
	<tbody>
		<tr class="data_row">
 public function getItems($options)
 {
     $headers = array('Cookie' => $this->webCookies, 'Timeout' => Unirest\Request::timeout(5));
     $response = Unirest\Request::get('https://steamcommunity.com/trade/' . $options['tradeId'] . '/receipt/', $headers);
     if ($response->code != 200) {
         die('Error get items. Server response code: ' . $response->code);
     }
     $body = $response->body;
     preg_match('/(var oItem;[\\s\\S]*)<\\/script>/', $body, $matches);
     if (!$matches) {
         die('Error get items: no session');
     }
     $temp = str_replace(array("\r", "\n"), "", $matches[1]);
     $items = array();
     preg_match_all('/oItem = {(.*?)};/', $temp, $matches);
     foreach ($matches[0] as $key => $value) {
         $value = rtrim(str_replace('oItem = ', '', $value), ';');
         $items[] = json_decode($value, 1);
     }
     return $items;
 }
예제 #19
0
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    </head>
<body>
<form name="input" action="index.php" method="POST">
 <div class="input-group">
   <span class="input-group-btn">
    <input type="submit" type="button">IR!</button>
    </span>
    <input type="text" name="word" class="form-control" placeholder="search for...">
   </div>
</form>
<?php 
require __DIR__ . '/vendor/autoload.php';
$response = Unirest\Request::get("https://montanaflynn-dictionary.p.mashape.com/define?word=" . $_GET["word"], array("X-Mashape-Key" => "ZA8k3CJvxdmshT0XPS3S6WV6vnfwp1hj5F9jsnNujBw5cKjh2Y", "Accept" => "application/json"));
echo "<ul class=\"nav nav-pills\">";
foreach ($response->body->definitions as $definition) {
    echo "<li role=\"presentation\"><a href=\"#\">" . $definition->text . "</a></li>";
}
echo "</ul>";
?>
 </div>
</div>
</body> 
</html>
예제 #20
0
$app->get('/pantryApp', function () use($app) {
    $app->render('pantryApp.twig');
});
$app->get('/recipeApp', function () use($app) {
    $app->render('recipeApp.twig');
    $data = $response->body->hits;
    try {
        foreach ($data as $recipe) {
            echo '<li class="panel">' . "Label: " . $recipe->recipe->label . '<br>' . 'Source: ' . $recipe->recipe->source . '<br>' . $recipe->recipe->uri . '<br>' . $recipe->recipe->url . '</li>';
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    Unirest\Request::verifyPeer(false);
    // These code snippets use an open-source library. http://unirest.io/php
    $response = Unirest\Request::get("https://edamam-recipe-search-and-diet-v1.p.mashape.com/search?_app_id=691b076d&_app_key=3e8c229f325ab89e7d270b29c8294a35&q={$_POST['item_name']}", array("X-Mashape-Key" => "XU83D7WqBomshL1uFNq7KVvGMz8Wp1IGNqzjsnUgU0fQWqPRk1", "Accept" => "application/json"));
});
//DATAENTRY FORM
require "/databaseConnect/databaseConnectionPantry.php";
//DATABASE CONNECTION
//DATABASE POST VARIABLES SET
$app->get('/dataEntryForm', function () use($app) {
    $app->render('dataEntryForm.twig');
    //!FORM DATA VALIDATION NEEDS ADDRESSED; IF () PARAMETERS NOT LOGICAL SOUND!
    try {
        if ($_POST['submit'] = true) {
            $itemName = $_POST['item_name'];
            $itemCount = $_POST['count'];
            $itemDesc = $_POST['description'];
            echo "Form was successfully submitted";
        } else {
예제 #21
0
<?php

require_once 'unirest-php-master/src/Unirest.php';
// These code snippets use an open-source library.
$request = Unirest\Request::get("https://itunes.apple.com/search?term=metallica", array("Accept" => "application/json"));
echo "<pre>";
$output = "<ul>";
foreach ($request->body->results as $data) {
    print_r($data);
    /*	
        $output .= "<h4>".$data['id']."</h4>";
        $output .= "<h5>".$data['title']."</h5>";
        $output .= "<li>Meal: ".$data['imageUrls']."</li>";
        $output .= "<a href=>".$data['image']."</a>";
    */
}
$output .= "</ul>";
echo utf8_decode($output);
?>

예제 #22
0
<?php

require_once 'C:\\xampp\\htdocs\\tb\\unirest-php-master\\src\\Unirest.php';
include 'core/init.php';
include 'includes/overall/header_loggedin.php';
// Unirest\Request::proxy('172.31.1.3', 8080, CURLPROXY_HTTP);
// Unirest\Request::proxyAuth('iec2012075', '');
// $ch = curl_init("http://iiita.ac.in");
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = Unirest\Request::get("https://site2sms.p.mashape.com/index.php?msg=bolyaarsushant&phone=7275065468&pwd=sushant&uid=7275065468", array("X-Mashape-Key" => "2AMQ553BWimshuYmDk9khdX7gKlKp1SUNzujsnbQkwxgQv2FyS", "Accept" => "application/json"));
예제 #23
0
 public function delete($url)
 {
     Unirest\Request::auth($this->login, $this->pass);
     Unirest\Request::defaultHeader('User-Agent', $this->service . " (" . $this->mail . ")");
     $response = Unirest\Request::delete($this->root . $url . '.json');
     if (floor($response->code / 100) >= 4) {
         throw new Error($response->body->errors->error[0]);
     }
     return $response->body;
 }
예제 #24
0
    public function testUploadIfFilePartOfData()
    {
        $response = Unirest\Request::post('http://httpbin.org/post', array(
            'Accept' => 'application/json'
        ), array(
            'name' => 'Mark',
            'files[owl.gif]' => Unirest\File::add(UPLOAD_FIXTURE)
        ));
        $this->assertEquals(200, $response->code);

        //$files = $response->body->files;
        //$this->assertEquals('This is a test', $files->file);

        $form = $response->body->form;
        $this->assertEquals('Mark', $form->name);
    }
예제 #25
0
 public function testUploadIfFilePartOfData()
 {
     $response = Unirest\Request::post('http://mockbin.com/request', array('Accept' => 'application/json'), array('name' => 'Mark', 'files[owl.gif]' => Unirest\File::add(UPLOAD_FIXTURE)));
     $this->assertEquals(200, $response->code);
     $this->assertEquals('POST', $response->body->method);
     $this->assertEquals('Mark', $response->body->postData->params->name);
     $this->assertEquals('This is a test', $response->body->postData->params->{'files[owl.gif]'});
 }
예제 #26
0
 /**
  * Execute POST request to Seats.io RESTful API
  * Full response in $this->response
  * @see Unirest for PHP http://unirest.io/php.html
  *
  * @param string 	$url endpoint URL
  * @return mixed 	Data - body of response
  *
  * @throws exceptionclass Throws exception when HTTP response is not 200
  *
  * @access private
  */
 private function postRequest($url = null)
 {
     if (!empty($url)) {
         $this->request->url = $url;
     }
     $this->response = Unirest\Request::post($this->request->url, $this->request->headers, json_encode($this->request->data));
     if ($this->response->code !== 200) {
         throw new Exception('postRequest - Exception: ' . (!empty($this->response->body) ? $this->response->body->message : $this->response->headers[0]));
     }
     return $this->response->body;
 }
예제 #27
0
 /**
  * Get the Next Collection Date when available
  *
  * @return mixed
  */
 public function NextCollectionDate()
 {
     $this->clearStoredResponse();
     $response = Unirest\Request::get($this->api_url_nextcollectiondate, ["Content-Type" => "application/json", "Accept" => "application/json"]);
     $this->setStoredResponse($response);
     if (isset($response->code) && $response->code === 200 && isset($response->body->status) && $response->body->status === 'ok') {
         return $response->body->details->next_collection_date;
     }
     return false;
 }
예제 #28
0
 public function testJSONOpts()
 {
     $opts = Unirest\Request::jsonOpts(false, 512, JSON_NUMERIC_CHECK);
     $response = new Unirest\Response(200, '{"number": 1234567890}', '', $opts);
     $this->assertSame($response->body->number, 1234567890);
 }
예제 #29
0
<?php

require_once dirname(__FILE__) . '/Unirest/File.php';
require_once dirname(__FILE__) . '/Unirest/Method.php';
require_once dirname(__FILE__) . '/Unirest/Response.php';
require_once dirname(__FILE__) . '/Unirest/Request.php';
Unirest\Request::VerifyPeer(false);
예제 #30
-1
파일: index.php 프로젝트: johnsylvain/spott
 public static function toptrack($artist_id)
 {
     $headers = array("Accept" => "application/json");
     $url = "https://api.spotify.com/v1/artists/{$artist_id}/top-tracks?country=US";
     $artist_top_track = Unirest\Request::get($url, $headers)->body;
     Flight::json($artist_top_track);
 }