/** * Performs a POST request. * * @param string $endpoint * Endpoint to make request to. * * @param array $headers * An array of parameters to send in the request. * * @param array $params * An array of parameters to send in the request. * * @param boolean $post * true to make a POST request, else a GET request will be made. * * @return array * The JSON data returned from the API. * * @throws CasperException * An exception is thrown if an error occurs. */ public function request($endpoint, $headers = array(), $params = array(), $post = false) { $ch = curl_init(); if ($headers == null) { $headers = array(); } if ($params == null) { $params = array(); } $headers = array_merge(self::$CURL_HEADERS, $headers); $headers[] = "X-Casper-API-Key: " . $this->apiKey; curl_setopt_array($ch, self::$CURL_OPTIONS); curl_setopt($ch, CURLOPT_URL, self::URL . $endpoint); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verifyPeer); if ($this->proxy != null) { curl_setopt($ch, CURLOPT_PROXY, $this->proxy); } $jwt_params = array("iat" => time()); $jwt = JWT::encode(array_merge($jwt_params, $params), $this->apiSecret, "HS256"); if ($post) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array("jwt" => $jwt))); } $response = curl_exec($ch); if (curl_errno($ch) == 60) { curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . "/ca_bundle.crt"); $response = curl_exec($ch); } if ($response === FALSE) { $error = curl_error($ch); curl_close($ch); throw new CasperException($error); } $json = json_decode($response, true); if ($json == null) { curl_close($ch); throw new CasperException(sprintf("[%s] Failed to decode response!\nResponse: %s", $endpoint, $response)); } $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($code != 200) { curl_close($ch); $json_code = $json["code"]; $json_message = $json["message"]; if (isset($json_code) && isset($json_message)) { throw new CasperException(sprintf("Casper API Response: [%s] [%s] %s", $endpoint, $json_code, $json_message)); } else { throw new CasperException(sprintf("Casper API Response: [%s] [%s] Unknown Error\nResponse: %s", $endpoint, $code, $response)); } } curl_close($ch); return $json; }
/** * Encode a PHP object into a JSON string. * * @param object|array $input A PHP object or array * * @return string JSON representation of the PHP object or array * @throws DomainException Provided object could not be encoded to valid JSON */ public static function jsonEncode($input) { $json = json_encode($input); if (function_exists('json_last_error') && ($errno = json_last_error())) { JWT::_handleJsonError($errno); } else { if ($json === 'null' && $input !== null) { throw new DomainException('Null result with non-null input'); } } return $json; }