post() публичный статический Метод

Send POST request to a URL
public static post ( string $url, array $headers = [], mixed $body = null, string $username = null, string $password = null ) : unirest\Response
$url string URL to send the POST request to
$headers array additional headers to send
$body mixed POST body data
$username string Basic Authentication username (deprecated)
$password string Basic Authentication password (deprecated)
Результат unirest\Response response
 public function sendContent($from, $to, $subject, $type, $content)
 {
     if (is_string($to)) {
         $to = [$to];
     }
     $recipients = Mailjet::parse_recipient_type($to);
     // Build the HTTP POST body text
     if ($type == 'html') {
         $body = http_build_query(array('from' => $from, 'to' => implode(', ', $recipients['to']), 'cc' => implode(', ', $recipients['cc']), 'bcc' => implode(', ', $recipients['bcc']), 'subject' => $subject, 'html' => $content));
     } else {
         if ($type == 'text') {
             $body = http_build_query(array('from' => $from, 'to' => implode(', ', $recipients['to']), 'cc' => implode(', ', $recipients['cc']), 'bcc' => implode(', ', $recipients['bcc']), 'subject' => $subject, 'text' => $content));
         } else {
             throw new Exception('Wrong email type');
         }
     }
     utils::log($body);
     $options = array('scheme' => 'http', 'host' => 'api.mailjet.com', 'path' => '/v3/send/');
     $endpoint = Mailjet::unparse_url($options);
     $headers = array('Authorization' => 'Basic ' . $this->_authentificate, 'Content-Type' => 'application/x-www-form-urlencoded', 'Content-Length' => strlen($body));
     // API request
     Unirest\Request::verifyPeer(false);
     $response = Unirest\Request::post($endpoint, $headers, $body);
     utils::log('STATUS: ' . $response->code);
     utils::log('HEADERS: ' . json_encode($response->headers));
     utils::log('BODY: ' . $response->raw_body);
     return $response->code == 200;
 }
Пример #2
0
 /**
  * [performTransaction description].
  *
  * @return [type] [description]
  */
 protected function performTransaction()
 {
     $this->prepareRequest();
     $unirestResponse = Unirest::post($this->endpoint, array(), $this->requestBody);
     $this->responseXMLString = $unirestResponse->body;
     $this->responseXML = simplexml_load_string($this->responseXMLString);
 }
Пример #3
0
 public static function post($body = null, $headers = null)
 {
     if (!$headers) {
         $headers = Rapid::getAuthHeader();
     }
     $response = Request::post(Rapid::getUrl(self::$route), $headers, http_build_query($body));
     return Response::make($response);
 }
Пример #4
0
 public function postInfo($url, $inputs = null, $param = null)
 {
     $url = setApiUrl($url, $param);
     //Log::info($url);
     $response = Unirest\Request::post($url, $this->_headers, json_encode($inputs));
     //Log::info(json_encode($response));
     return dealResponse($response);
 }
Пример #5
0
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     HTTPRequest::verifyPeer(env('UNIREST_VERIFYPEER'));
     //Get 10 quotes, from a Mashape API
     for ($i = 0; $i < 10; $i++) {
         $response = HTTPRequest::post("https://andruxnet-random-famous-quotes.p.mashape.com/cat=famous", array("X-Mashape-Key" => env('MASHAPE_KEY'), "Content-Type" => "application/x-www-form-urlencoded", "Accept" => "application/json"));
         Quote::create(["content" => $response->body->quote, "author" => $response->body->author, "source" => "https://andruxnet-random-famous-quotes.p.mashape.com/cat=famous"]);
     }
 }
 /**
  * Create email to sms allowed address
  * @param  string     $emailAddress      Required parameter: Your email address.
  * @param  string     $from              Required parameter: Your phone number in E.164 format.
  * @return string response from the API call*/
 public function createAllowedAddress($emailAddress, $from)
 {
     //check that all required arguments are provided
     if (!isset($emailAddress, $from)) {
         throw new \InvalidArgumentException("One or more required arguments were NULL.");
     }
     //the base uri for api requests
     $_queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $_queryBuilder = $_queryBuilder . '/sms/email-sms';
     //process optional query parameters
     APIHelper::appendUrlWithQueryParameters($_queryBuilder, array('email_address' => $emailAddress, 'from' => $from));
     //validate and preprocess url
     $_queryUrl = APIHelper::cleanUrl($_queryBuilder);
     //prepare headers
     $_headers = array('user-agent' => 'ClickSendSDK');
     //set HTTP basic auth parameters
     Request::auth(Configuration::$username, Configuration::$key);
     //and invoke the API call request to fetch the response
     $response = Request::post($_queryUrl, $_headers);
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('BAD_REQUEST', 400, $response->body);
     } else {
         if ($response->code == 401) {
             throw new APIException('UNAUTHORIZED', 401, $response->body);
         } else {
             if ($response->code == 403) {
                 throw new APIException('FORBIDDEN', 403, $response->body);
             } else {
                 if ($response->code == 404) {
                     throw new APIException('NOT_FOUND', 404, $response->body);
                 } else {
                     if ($response->code == 405) {
                         throw new APIException('METHOD_NOT_FOUND', 405, $response->body);
                     } else {
                         if ($response->code == 429) {
                             throw new APIException('TOO_MANY_REQUESTS', 429, $response->body);
                         } else {
                             if ($response->code == 500) {
                                 throw new APIException('INTERNAL_SERVER_ERROR', 500, $response->body);
                             } else {
                                 if ($response->code < 200 || $response->code > 206) {
                                     //[200,206] = HTTP OK
                                     throw new APIException("HTTP Response Not OK", $response->code, $response->body);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $response->body;
 }
Пример #7
0
 /**
  * @param string $doUrl
  * @param string $method
  * @param string $content
  * @return boolean or object
  */
 protected function UnirestapiRegister($content)
 {
     $apiUrl = $this->_apiUrl;
     $url = $apiUrl . "/register";
     $headers = array("Content-Type" => "application/json", "Accept" => "application/json");
     $response = Unirest\Request::post($url, $headers, json_encode($content));
     if ($response->code == '201') {
         $res['code'] = 200;
         $res['body'] = $response->body;
         return $res;
     } elseif ($response->code == '403') {
         $res['code'] = 403;
         $res['body'] = "This email has exist.";
         return $res;
     }
     return false;
 }
Пример #8
0
 public function comfirmPurchase($inputs)
 {
     $url = setApiUrl("numbers.buyNumbers");
     $response = Unirest\Request::post($url, $this->_headers, json_encode($inputs));
     // 		return json_encode($response);
     $response = dealResponse($response);
     if ($response['flag'] == 'success') {
         $data = $response['data'];
         if ($data->total != $data->succeed) {
             $response['flag'] = 'error';
             $response['msg'] = $data->failed_list;
             unset($response['pagging']);
             return json_encode($response);
         } else {
             $response['msg'] = 'Buy numbers successfully';
         }
     }
     return json_encode($response);
 }
 /**
  * Apply a given configuration to one or more numbers
  * @param  DidConfigurationModel     $body     Required parameter: TODO: type description here
  * @return mixed response from the API call*/
 public function createConfiguration($body)
 {
     //the base uri for api requests
     $queryBuilder = Configuration::BASEURI;
     $queryBuilder = Config::get('voxbone.base_uri');
     //prepare query string for API call
     $queryBuilder = $queryBuilder . '/configuration/configuration';
     //validate and preprocess url
     $queryUrl = APIHelper::cleanUrl($queryBuilder);
     //prepare headers
     $headers = array('User-Agent' => 'APIMATIC 2.0', 'Accept' => 'application/json', 'Content-type' => 'application/json; charset=utf-8');
     //prepare API request
     $response = Request::post($queryUrl, $headers, json_encode($body));
     //and invoke the API call request to fetch the response
     //$response = Unirest::getResponse($request);
     //Error handling using HTTP status codes
     if ($response->code < 200 || $response->code > 206) {
         //[200,206] = HTTP OK
         return $response;
     }
     return $response->body;
 }
Пример #10
0
 public function request($path, $params, $headers = [], $isSecure = false)
 {
     $params['appid'] = $this->options['appid'];
     $params['mch_id'] = $this->options['mch_id'];
     $params['nonce_str'] = $this->getNonce();
     $params['sign'] = $this->sign($params);
     $xml = $this->xmlEncode($params);
     if ($isSecure) {
         Request::curlOpt(CURLOPT_SSLCERTTYPE, 'PEM');
         Request::curlOpt(CURLOPT_SSLCERT, $this->options['cert']);
         Request::curlOpt(CURLOPT_SSLKEYTYPE, 'PEM');
         Request::curlOpt(CURLOPT_SSLKEY, $this->options['private']);
     }
     /**
      * @var $res \Unirest\Response
      */
     $res = Request::post(sprintf('%s%s', $this->options['host'], $path), $headers, $xml);
     if ($isSecure) {
         Request::clearCurlOpts();
     }
     if ($res->code !== 200) {
         throw new \Exception('Invalid response status code', $res->code);
     }
     $body = $this->xmlDecode($res->body);
     if (!is_array($body)) {
         throw new \Exception(sprintf('Invalid response body: %s', $res->body));
     }
     if ($body['return_code'] !== static::SUCCESS) {
         throw new \Exception(sprintf('Invalid return_code: %s', $res->body));
     }
     if ($body['appid'] !== $this->options['appid'] || $body['mch_id'] !== $this->options['mch_id']) {
         throw new \Exception(sprintf('Invalid appid or mch_id: %s', $res->body));
     }
     $sign = $body['sign'];
     if ($sign !== $this->sign($body)) {
         throw new \Exception(sprintf('Invalid sign: %s', $res->body));
     }
     return $body;
 }
Пример #11
0
 /**
  * The underlying call to the Kong Server
  *
  * @throws \Ignittion\Kong\KongException when something goes wrong with the Http request
  *
  * @param string $verb
  * @param string $uri
  * @param array $options
  * @param array $body
  * @return \stdClass
  */
 public function call($verb, $uri, array $params = [], array $body = [], array $headers = [])
 {
     $verb = strtoupper($verb);
     $api = "{$this->url}:{$this->port}/{$uri}";
     $headers = array_merge($headers, ['Content-Type: application/json']);
     try {
         switch ($verb) {
             case 'GET':
                 $request = RestClient::get($api, $headers, $params);
                 break;
             case 'POST':
                 $request = RestClient::post($api, $headers, $body);
                 break;
             case 'PUT':
                 $request = RestClient::put($api, $headers, $body);
                 break;
             case 'PATCH':
                 $request = RestClient::patch($api, $headers, $body);
                 break;
             case 'DELETE':
                 $request = RestClient::delete($api, $headers);
                 break;
             default:
                 throw new Exception('Unknown HTTP Request method.');
         }
     } catch (Exception $e) {
         throw new KongException($e->getMessage());
     }
     // save this request
     $this->body = $request->body;
     $this->headers = $request->headers;
     $this->httpCode = $request->code;
     $this->rawBody = $request->raw_body;
     // return a more simplified response
     $object = new stdClass();
     $object->code = $this->httpCode;
     $object->data = $this->body;
     return $object;
 }
Пример #12
0
 /**
  * Request the generation of a call report for a full month
  * @param  string     $year             Required parameter: The year in YYYY format
  * @param  string     $month            Required parameter: The month in MM format
  * @return mixed response from the API call*/
 public function createCdrsFileRequest($year, $month)
 {
     //the base uri for api requests
     $queryBuilder = Configuration::BASEURI;
     $queryBuilder = Config::get('voxbone.base_uri');
     //prepare query string for API call
     $queryBuilder = $queryBuilder . '/cdrs/cdrsfile/request/{year}/{month}';
     //process optional query parameters
     APIHelper::appendUrlWithTemplateParameters($queryBuilder, array('year' => $year, 'month' => $month));
     //validate and preprocess url
     $queryUrl = APIHelper::cleanUrl($queryBuilder);
     //prepare headers
     $headers = array('User-Agent' => 'APIMATIC 2.0', 'Accept' => 'application/json', 'Content-type' => 'application/json; charset=utf-8');
     //prepare API request
     $response = Request::post($queryUrl, $headers);
     //and invoke the API call request to fetch the response
     //$response = Unirest::getResponse($request);
     //Error handling using HTTP status codes
     if ($response->code < 200 || $response->code > 206) {
         //[200,206] = HTTP OK
         return $response;
     }
     return $response->body;
 }
Пример #13
0
        $response->body($core->twig->render('node/403.html'))->send();
        return;
    }
    if (!$core->auth->XSRF($request->param('xsrf'))) {
        $service->flash('<div class="alert alert-warning"> The XSRF token recieved was not valid. Please make sure cookies are enabled and try your request again.</div>');
        $response->redirect('/node/settings?tab=ftp_sett')->send();
    }
    if (!$core->auth->validatePasswordRequirements($request->param('sftp_pass'))) {
        $service->flash('<div class="alert alert-danger">The password you provided does not meet the requirements. Please use at least 8 characters, include at least one number, and use mixed case.</div>');
        $response->redirect('/node/settings?tab=sftp_sett')->send();
    } else {
        /*
         * Update Server FTP Information
         */
        try {
            $unirest = Unirest\Request::post('https://' . $core->server->nodeData('fqdn') . ':' . $core->server->nodeData('daemon_listen') . '/server/reset-password', array("X-Access-Token" => $core->server->nodeData('daemon_secret'), "X-Access-Server" => $core->server->getData('hash')), array("password" => $request->param('sftp_pass')));
            if ($unirest->code === 204) {
                $service->flash('<div class="alert alert-success">Your SFTP password has been updated.</div>');
                $response->redirect('/node/settings?tab=sftp_sett')->send();
            } else {
                throw new \Exception("Scales did not return a success code while attempting to reset an account password. (code: " . $unirest->code . ")");
            }
        } catch (\Exception $e) {
            Tracy\Debugger::log($e);
            $service->flash('<div class="alert alert-danger">Unable to access the Scales daemon to reset your password. Please try again in a moment.</div>');
            $response->redirect('/node/settings?tab=sftp_sett')->send();
        }
    }
});
$klein->respond('POST', '/node/settings/password', function ($request, $response) use($core) {
    $response->body($core->auth->keygen(rand(6, 10)) . "-" . $core->auth->keygen(rand(6, 14)))->send();
Пример #14
0
    if (empty($command)) {
        $service->flash('<div class="alert alert-warning">You entered an invalid command.</div>');
        $response->redirect('/scs')->send();
        return;
    }
    foreach ($servers as $server) {
        $serverToSendCommand = null;
        foreach ($serversArray as $srv) {
            if ($srv['hash'] === $server) {
                $serverToSendCommand = $srv;
            }
        }
        if ($serverToSendCommand != null) {
            $node = ORM::forTable('nodes')->select('nodes.*')->where('id', $serverToSendCommand['node'])->findArray()[0];
            try {
                Unirest\Request::post("https://" . $node['fqdn'] . ":" . $node['daemon_listen'] . "/server/console", array("X-Access-Token" => $node['daemon_secret'], "X-Access-Server" => $server), array("command" => $command));
            } catch (\Exception $e) {
                \Tracy\Debugger::log($e);
                $service->flash('<div class="alert alert-danger">A problem happened while sending the command to the target servers.</div>');
                $response->redirect('/scs')->send();
                return;
            }
        } else {
            $service->flash('<div class="alert alert-warning">One of the servers you selected was invalid.</div>');
        }
    }
    $service->flash('<div class="alert alert-success">Your command has been sent successfully.</div>');
    $response->redirect('/scs')->send();
});
$klein->respond('GET', '/totp', function ($request, $response, $service) use($core) {
    $response->body($core->twig->render('panel/totp.html', array('totp' => $core->user->getData('use_totp'), 'xsrf' => $core->auth->XSRF(), 'flash' => $service->flashes())))->send();
Пример #15
0
        $storage_variables .= $name . "|" . $value . "\n";
    }
    $server = ORM::forTable('servers')->create();
    $server->set(array('hash' => $server_hash, 'daemon_secret' => $daemon_secret, 'node' => $request->param('node'), 'name' => $request->param('server_name'), 'plugin' => $plugin->id, 'daemon_startup' => $request->param('daemon_startup'), 'daemon_variables' => $storage_variables, 'owner_id' => $user->id, 'max_ram' => $request->param('alloc_mem'), 'disk_space' => 0, 'cpu_limit' => $request->param('cpu_limit'), 'block_io' => $request->param('block_io'), 'date_added' => time(), 'server_ip' => $request->param('server_ip'), 'server_port' => $request->param('server_port'), 'sftp_user' => $sftp_username, 'installed' => 0));
    $server->save();
    $ips[$request->param('server_ip')]['ports_free']--;
    $ports[$request->param('server_ip')][$request->param('server_port')]--;
    $node->ips = json_encode($ips);
    $node->ports = json_encode($ports);
    $node->save();
    /*
     * Build Call
     */
    $data = array("name" => $server_hash, "user" => $sftp_username, "build" => array("disk" => array("hard" => $request->param('alloc_disk') < 32 ? 32 : (int) $request->param('alloc_disk'), "soft" => $request->param('alloc_disk') > 2048 ? (int) $request->param('alloc_disk') - 1024 : 32), "cpu" => (int) $request->param('cpu_limit'), "memory" => (int) $request->param('alloc_mem'), "io" => (int) $request->param('block_io')), "startup" => array("command" => $request->param('daemon_startup'), "variables" => $startup_variables), "keys" => array($daemon_secret => array("s:ftp", "s:get", "s:power", "s:files", "s:files:get", "s:files:delete", "s:files:put", "s:files:zip", "s:query", "s:console", "s:console:send")), "gameport" => (int) $request->param('server_port'), "gamehost" => $request->param('server_ip'), "plugin" => $request->param('plugin'));
    try {
        $unirest = Request::post('https://' . $node->fqdn . ':' . $node->daemon_listen . '/server', array('X-Access-Token' => $node->daemon_secret, 'X-Access-Server' => "hodor"), array('settings' => json_encode($data), 'password' => $core->auth->keygen(16), 'build_params' => $request->param('plugin_variable_build_params') ? $request->param('plugin_variable_build_params') : false));
        if ($unirest->code !== 204) {
            throw new Exception("An error occured trying to add a server. (" . $unirest->raw_body . ") [HTTP 1.1/" . $unirest->code . "]");
        }
        ORM::get_db()->commit();
    } catch (Exception $e) {
        Debugger::log($e);
        ORM::get_db()->rollBack();
        $service->flash('<div class="alert alert-danger">An error occured while trying to connect to the remote node. Please check that Scales is running and try again.</div>');
        $response->redirect('/admin/server/new')->send();
        return;
    }
    $service->flash('<div class="alert alert-success">Server created successfully.</div>');
    $response->redirect('/admin/server/view/' . $server->id() . '?tab=installer')->send();
    return;
});
Пример #16
0
 /**
  * @param string $url
  * @param string $method
  * @param string $body
  * @return string
  * @throws ErrorException
  */
 protected function request($url, $method = Method::GET, $body = null)
 {
     $this->output->writeln(sprintf('<fg=white>%s %s</>', $method, $url));
     /** @var $response Unirest\Response */
     $response = strtoupper($method) === Method::POST ? Request::post($url, [], $body) : Request::get($url);
     $result = (string) $response->body;
     $document = new \DOMDocument();
     $document->loadHTML($result);
     $xpath = new \DomXpath($document);
     $errors = $xpath->query('//div[contains(@class, "errorwrap")]');
     if ($errors->length) {
         throw new \ErrorException($errors->item(0)->getElementsByTagName('p')->item(0)->textContent);
     }
     return $result;
 }
Пример #17
0
 public static function postByOther($otherIdOrSlug, $body = null, $headers = null)
 {
     $response = Request::post(Rapid::getUrl(self::$belongsToRouteOthers . '/' . $otherIdOrSlug . '/' . self::$route), $headers, http_build_query($body));
     return Response::make($response);
 }
Пример #18
0
 /**
  * Método que executa a conversão do PDF para jpg
  * @return boolean Retorna TRUE em caso de sucesso ou FALSE em caso de erro
  * @throws \GGE\Lib\Base\Exception
  */
 public function converter()
 {
     if (is_null($this->pdf)) {
         throw new \GGE\Lib\Base\Exception("O arquivo PDF ainda não foi definido");
     }
     if (is_null($this->destino)) {
         throw new \GGE\Lib\Base\Exception("Ainda não foi definida uma pasta de destino para as imagens");
     }
     if (!\GGE\Lib\Filter\Types\String::validarTipo($this->mashapeKey)) {
         throw new \GGE\Lib\Base\Exception("A chave de acesso a API ainda não foi definida");
     }
     //
     $response = \Unirest\Request::post(self::URL, array("X-Mashape-Key" => "37y9fftqS2msh4qv4qXh4C8bWsg3p1AdUtVjsn9EnxMll5NYse"), array("pdf" => \Unirest\File::add($this->pdf), "resolution" => 150));
     die(var_dump($response));
     //Iniciando a conversão
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, self::URL);
     curl_setopt($ch, CURLOPT_HEADER, "X-Mashape-Key: <{$this->mashapeKey}>");
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, array("pdf" => new \CURLFile($this->pdf, "application/pdf"), "resolution" => 150));
     $resultPost = curl_exec($ch);
     var_dump($resultPost);
     $responsePost = json_decode($resultPost);
     if (!$responsePost) {
         throw new \GGE\Lib\Base\Exception("Falha ao tentar converter o PDF. Erro no servidor remoto");
     }
     //Lendo e baixando as imagens resultantes
     curl_setopt($ch, CURLOPT_POST, false);
     curl_setopt($ch, CURLOPT_POSTFIELDS, array("id" => $responsePost->id, "key" => $responsePost->key));
     $resultGet = curl_exec($ch);
     $responseGet = json_decode($resultGet);
     if (!$responseGet) {
         throw new \GGE\Lib\Base\Exception("Falha ao tentar recuperar as imagens resultantes da conversão");
     }
     curl_close($ch);
     if ($responseGet->status != "done") {
         throw new \GGE\Lib\Base\Exception("Falha ao ler as imagens. O servidor retornou uma falha");
     }
     //Baixando as imagens para o servidor
     if (!file_exists($this->destino)) {
         //Caso a pasta de destino não exista
         if (!mkdir($this->destino, "0777", TRUE)) {
             throw new \GGE\Lib\Base\Exception("Falha ao tentar criar a pasta de destino");
         }
     }
     foreach ($responseGet->pictures as $pic) {
         if (!copy($pic, $this->destino, urldecode($pic))) {
             throw new \GGE\Lib\Base\Exception("Ocorreu um erro ao tentar copiar a imagem");
         }
     }
     return TRUE;
 }
Пример #19
0
 public function acceptOffer($options)
 {
     if (!$options['tradeOfferId']) {
         die('No options');
     }
     $form = array('sessionid' => $this->sessionId, 'serverid' => 1, 'tradeofferid' => $options['tradeOfferId']);
     $referer = 'https://steamcommunity.com/tradeoffer/' . $options['tradeOfferId'] . '/';
     $headers = array('Cookie' => $this->webCookies, 'Timeout' => Unirest\Request::timeout(5));
     $headers['referer'] = $referer;
     $response = Unirest\Request::post('https://steamcommunity.com/tradeoffer/' . $options['tradeOfferId'] . '/accept', $headers, $form);
     if ($response->code != 200) {
         die('Error accepting offer. Server response code: ' . $response->code);
     }
     $body = $response->body;
     if ($body && $body->strError) {
         die('Error accepting offer: ' . $body->strError);
     }
     return $body;
 }
Пример #20
0
 public function register($connections)
 {
     $urn = $this->getURN($connections->uniqueIdentifier);
     $desc = (object) array('urn' => base64_encode($urn));
     $config = lmv::config();
     Unirest\Request::verifyPeer(false);
     $response = Unirest\Request::post($config['postRegisterEndPoint'], array('Accept' => 'application/json', 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . lmv::bearer()), json_encode($desc));
     if ($response->code != lmv::HTTP_OK && $response->code != lmv::HTTP_CREATED) {
         utils::log('register fail ' . $response->code);
         return null;
     }
     return (object) array('status' => 'ok', 'statusCode' => $response->code);
 }
Пример #21
0
 /**
  * Create new contact
  * @param  int             $listId                  Required parameter: Your list_id
  * @param  string|null     $phoneNumber             Optional parameter: Your phone number in E.164 format. Must be provided if no fax number or email.
  * @param  string|null     $email                   Optional parameter: Your email. Must be provided if no phone number or fax number.
  * @param  string|null     $faxNumber               Optional parameter: You fax number. Must be provided if no phone number or email.
  * @param  string|null     $firstName               Optional parameter: Your firstname.
  * @param  string|null     $lastName                Optional parameter: Your lastname.
  * @param  string|null     $addressLine1            Optional parameter: Example: 
  * @param  string|null     $addressLine2            Optional parameter: Example: 
  * @param  string|null     $addressCity             Optional parameter: Example: 
  * @param  string|null     $addressState            Optional parameter: Example: 
  * @param  string|null     $addressPostalCode       Optional parameter: Example: 
  * @param  string|null     $addressCountry          Optional parameter: Example: 
  * @param  string|null     $organizationName        Optional parameter: Example: 
  * @param  string|null     $custom1                 Optional parameter: Example: 
  * @param  string|null     $custom2                 Optional parameter: Example: 
  * @param  string|null     $custom3                 Optional parameter: Example: 
  * @param  string|null     $custom4                 Optional parameter: Example: 
  * @return string response from the API call*/
 public function createContact($listId, $phoneNumber = NULL, $email = NULL, $faxNumber = NULL, $firstName = NULL, $lastName = NULL, $addressLine1 = NULL, $addressLine2 = NULL, $addressCity = NULL, $addressState = NULL, $addressPostalCode = NULL, $addressCountry = NULL, $organizationName = NULL, $custom1 = NULL, $custom2 = NULL, $custom3 = NULL, $custom4 = NULL)
 {
     //check that all required arguments are provided
     if (!isset($listId)) {
         throw new \InvalidArgumentException("One or more required arguments were NULL.");
     }
     //the base uri for api requests
     $_queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $_queryBuilder = $_queryBuilder . '/lists/{list_id}/contacts';
     //process optional query parameters
     APIHelper::appendUrlWithTemplateParameters($_queryBuilder, array('list_id' => $listId));
     //process optional query parameters
     APIHelper::appendUrlWithQueryParameters($_queryBuilder, array('phone_number' => $phoneNumber, 'email' => $email, 'fax_number' => $faxNumber, 'first_name' => $firstName, 'last_name' => $lastName, 'address_line_1' => $addressLine1, 'address_line_2' => $addressLine2, 'address_city' => $addressCity, 'address_state' => $addressState, 'address_postal_code' => $addressPostalCode, 'address_country' => $addressCountry, 'organization_name' => $organizationName, 'custom_1' => $custom1, 'custom_2' => $custom2, 'custom_3' => $custom3, 'custom_4' => $custom4));
     //validate and preprocess url
     $_queryUrl = APIHelper::cleanUrl($_queryBuilder);
     //prepare headers
     $_headers = array('user-agent' => 'ClickSendSDK');
     //set HTTP basic auth parameters
     Request::auth(Configuration::$username, Configuration::$key);
     //and invoke the API call request to fetch the response
     $response = Request::post($_queryUrl, $_headers);
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('BAD_REQUEST', 400, $response->body);
     } else {
         if ($response->code == 401) {
             throw new APIException('UNAUTHORIZED', 401, $response->body);
         } else {
             if ($response->code == 403) {
                 throw new APIException('FORBIDDEN', 403, $response->body);
             } else {
                 if ($response->code == 404) {
                     throw new APIException('NOT_FOUND', 404, $response->body);
                 } else {
                     if ($response->code == 405) {
                         throw new APIException('METHOD_NOT_FOUND', 405, $response->body);
                     } else {
                         if ($response->code == 429) {
                             throw new APIException('TOO_MANY_REQUESTS', 429, $response->body);
                         } else {
                             if ($response->code == 500) {
                                 throw new APIException('INTERNAL_SERVER_ERROR', 500, $response->body);
                             } else {
                                 if ($response->code < 200 || $response->code > 206) {
                                     //[200,206] = HTTP OK
                                     throw new APIException("HTTP Response Not OK", $response->code, $response->body);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $response->body;
 }
Пример #22
0
 public function post($uri, $data = [], $files = [])
 {
     $headers = ['Accept' => 'application/json', 'Content-Type' => empty($files) ? 'application/json' : 'multipart/form-data', 'X-IFSISTEM-TOKEN' => $this->token, 'X-IFSISTEM-DIL-ID' => $this->dilId];
     $body = empty($files) ? Request\Body::Json($data) : Request\Body::multipart($data, $files);
     return Request::post($this->uri . $uri, $headers, $body);
 }
Пример #23
0
 /**
  * Calculate voice price
  * @param  array     $parameters     Required parameter: Example: 
  * @return string response from the API call*/
 public function calculatePrice($parameters)
 {
     //check that all required arguments are provided
     if (!isset($parameters)) {
         throw new \InvalidArgumentException("One or more required arguments were NULL.");
     }
     //the base uri for api requests
     $_queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $_queryBuilder = $_queryBuilder . '/voice/price';
     //validate and preprocess url
     $_queryUrl = APIHelper::cleanUrl($_queryBuilder);
     //prepare headers
     $_headers = array('user-agent' => 'ClickSendSDK', 'content-type' => 'application/json; charset=utf-8');
     //set HTTP basic auth parameters
     Request::auth(Configuration::$username, Configuration::$key);
     //and invoke the API call request to fetch the response
     $response = Request::post($_queryUrl, $_headers, Request\Body::json($parameters));
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('BAD_REQUEST', 400, $response->body);
     } else {
         if ($response->code == 401) {
             throw new APIException('UNAUTHORIZED', 401, $response->body);
         } else {
             if ($response->code == 403) {
                 throw new APIException('FORBIDDEN', 403, $response->body);
             } else {
                 if ($response->code == 404) {
                     throw new APIException('NOT_FOUND', 404, $response->body);
                 } else {
                     if ($response->code == 405) {
                         throw new APIException('METHOD_NOT_FOUND', 405, $response->body);
                     } else {
                         if ($response->code == 429) {
                             throw new APIException('TOO_MANY_REQUESTS', 429, $response->body);
                         } else {
                             if ($response->code == 500) {
                                 throw new APIException('INTERNAL_SERVER_ERROR', 500, $response->body);
                             } else {
                                 if ($response->code < 200 || $response->code > 206) {
                                     //[200,206] = HTTP OK
                                     throw new APIException("HTTP Response Not OK", $response->code, $response->body);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $response->body;
 }
Пример #24
0
 public function post($path, $parameter = [])
 {
     return Request::post($this->base_uri . $path, [], $parameter);
 }
Пример #25
0
 /**
  * TODO: type endpoint description here
  * @param  string  $userID        Required parameter: TODO: type description here
  * @param  string  $contactListID Required parameter: TODO: type description here
  * @param  Contact $body          Required parameter: TODO: type description here
  * @return void    response from the API call*/
 public function addContact($userID, $contactListID, $body)
 {
     //the base uri for api requests
     $queryBuilder = Configuration::baseUri();
     //prepare query string for API call
     $queryBuilder = $queryBuilder . '/v3/users/{User ID}/contact_lists/{Contact List ID}/contacts';
     //process optional query parameters
     APIHelper::appendUrlWithTemplateParameters($queryBuilder, array('User ID' => $userID, 'Contact List ID' => $contactListID));
     //validate and preprocess url
     $queryUrl = APIHelper::cleanUrl($queryBuilder);
     //prepare headers
     $headers = array('User-Agent' => 'APIMATIC 2.0', 'Authorization' => sprintf('Bearer %1$s', Configuration::token()));
     //prepare API request
     $response = Request::post($queryUrl, $headers, json_encode($body));
     //Error handling using HTTP status codes
     if ($response->code < 200 || $response->code > 206) {
         //[200,206] = HTTP OK
         throw new APIException("HTTP Response code: " . $response->code . ". " . $response->body->error_description, $response->code);
     }
 }
Пример #26
0
 /**
  * `Check if booking is possible` method request requires lesser parameters as compared to `Create a booking`.In fact before creating a booking we advise to run this request first:- it will check if booking can be made without writing any data in BMG database- it will provide a correct total amount for selected services- if partner is caching products this should be used just before creating a booking - so any differences in cached prices (on partner side) and current price for total amount can be discovered- if partner discover difference in provided total amount then he can act accordingly in his user/client interface (for example - ask customer to accept final changed price)The main difference is that no booking is created in the system and some fields in response JSON object have NULL values. If the product has timeslots, the `timeslotUUID` of the product is REQUIRED in `Check a Booking` and `Create a new booking` methods. Otherwise, it can be excluded.For `booking check` request you don't have to pass customer's data or `partnerReference`.Example JSON request:        {            "productTypeUuid": "9d4b4d76-5b54-5407-b2d9-e6c021cc472e",            "pax": 2,            "children": 3,            "timeSlotUuid": "b02ae425-421f-5edf-a880-4104c0245dac",            "addons": [                {                    "uuid": "37e0f490-d31d-521b-b1f0-95c6e4e38d4c",                    "quantity": "1"                },                {                    "uuid": "a50090e3-567d-5743-9d87-e9d261aad0a9",                    "quantity": "2"                }                ],            "arrivalDate": "2015-06-07",            "usePromotion": false        }Response example:        {          "data": {              "uuid": null,              "totalAmount": "123.98",              "currencyCode": "SGD",              "currencyUuid": "cd15153e-dfd1-5039-8aa3-115bec58e86e",              "totalAmountRequestCurrency": "369.46",              "requestCurrencyCode": "MYR",              "requestCurrencyUuid": "e98aaf89-ae5a-5c11-859a-b36f2c8e13c7",              "createdAt": null,              "updatedAt": null,              "arrivalDate": "2015-06-07",              "salutation": null,              "firstName": null,              "lastName": null,              "email": null,              "phone": null,              "guests": 2,              "children": 3,              "partnerReference": null,              "confirmationEmailSentAt": null,              "confirmationEmailFiles": [],              "status": null,              "productTypeTitle": null,              "productTypeTitleTranslated": null,              "productTypeUuid": "9d4b4d76-5b54-5407-b2d9-e6c021cc472e"          }        }
  * @param  Models\CheckABookingRequest $body     Required parameter: Example: 
  * @return mixed response from the API call
  * @throws APIException Thrown if API call fails
  */
 public function createCheckABooking($body)
 {
     //the base uri for api requests
     $_queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $_queryBuilder = $_queryBuilder . '/v1/bookings/check';
     //validate and preprocess url
     $_queryUrl = APIHelper::cleanUrl($_queryBuilder);
     //prepare headers
     $_headers = array('user-agent' => 'BeMyGuest.SDK.v1', 'Accept' => 'application/json', 'content-type' => 'application/json; charset=utf-8', 'X-Authorization' => Configuration::$xAuthorization);
     //call on-before Http callback
     $_httpRequest = new HttpRequest(HttpMethod::POST, $_headers, $_queryUrl);
     if ($this->getHttpCallBack() != null) {
         $this->getHttpCallBack()->callOnBeforeRequest($_httpRequest);
     }
     //and invoke the API call request to fetch the response
     $response = Request::post($_queryUrl, $_headers, Request\Body::Json($body));
     //call on-after Http callback
     if ($this->getHttpCallBack() != null) {
         $_httpResponse = new HttpResponse($response->code, $response->headers, $response->raw_body);
         $_httpContext = new HttpContext($_httpRequest, $_httpResponse);
         $this->getHttpCallBack()->callOnAfterRequest($_httpContext);
     }
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('Wrong Arguments', $_httpContext);
     } else {
         if ($response->code == 401) {
             throw new APIException('Unauthorized', $_httpContext);
         } else {
             if ($response->code == 403) {
                 throw new APIException('Forbidden', $_httpContext);
             } else {
                 if ($response->code == 404) {
                     throw new APIException('Resource Not Found', $_httpContext);
                 } else {
                     if ($response->code == 405) {
                         throw new APIException('Method Not Allowed', $_httpContext);
                     } else {
                         if ($response->code == 410) {
                             throw new APIException('Resource No Longer Available', $_httpContext);
                         } else {
                             if ($response->code < 200 || $response->code > 208) {
                                 //[200,208] = HTTP OK
                                 throw new APIException("HTTP Response Not OK", $_httpContext);
                             }
                         }
                     }
                 }
             }
         }
     }
     $mapper = $this->getJsonMapper();
     return $mapper->map($response->body, new Models\CheckABookingResponse());
 }
Пример #27
0
 /**
  * Fire Log With Exception
  * @param string $level
  * @param Exception $x
  */
 public static function FireException($level, \Exception $x)
 {
     $headers = array('Accept' => 'application/json');
     $query = self::_fire($level, $x->getMessage(), $x->__toString());
     return Request::post(self::$_FIRE_ENDPOINT, $headers, $query);
 }
 public function getResultsOverrideAction($data_connector_id, $method = null, $url = null, $parms_in = null, $clean = false)
 {
     if ($url == null) {
         $url = $this->url;
     }
     if ($method == null) {
         $method = $this->method;
     }
     $data_connector = DataConnector::findFirstByid($data_connector_id);
     $storage = (array) json_decode($data_connector->storage, true);
     if (array_key_exists('token_expiry', $storage)) {
         if (time() > $storage['token_expiry']) {
             $authenticatorName = "\\PRIME\\Authenticators\\" . $this->authenticator . "Controller";
             $authenticatorController = new $authenticatorName();
             $authenticatorController->initialize();
             $authenticatorController->RefreshTokenAction($data_connector_id);
             $storage = (array) json_decode($data_connector->storage, true);
         }
     }
     if ($clean) {
         $parameters = array();
     } else {
         $parameters = (array) json_decode($data_connector->parameters, true);
     }
     $parms_in = (array) json_decode($parms_in, true);
     foreach ($parms_in as $key => $value) {
         $parameters[$key] = $value;
     }
     if (array_key_exists('rest', $parameters)) {
         foreach ($parameters['rest'] as $item) {
             $url = $url . "/" . $item;
         }
     }
     $query_parms = array();
     if (array_key_exists('query', $parameters)) {
         $query_parms = $parameters['query'];
     }
     $header_parms = array();
     if (array_key_exists('headers', $parameters)) {
         $header_parms = $parameters['headers'];
     }
     $body_parms = array();
     if (array_key_exists('body', $parameters)) {
         $body_parms = $parameters['body'];
     }
     if (array_key_exists('Authorization', $storage)) {
         $header_parms['Authorization'] = $storage['Authorization'];
     }
     switch ($method) {
         case "POST":
             $response = \Unirest\Request::post($url, $header_parms, $body_parms);
             break;
         case "PUT":
             $response = \Unirest\Request::put($url, $header_parms, $body_parms);
             break;
         default:
             $response = \Unirest\Request::get($url, $header_parms, $query_parms);
     }
     $this->view->disable();
     return $response->raw_body;
 }
 /**
  * Import contacts to list
  * @param  int        $listId      Required parameter: Your contact list id you want to access.
  * @param  string     $file        Required parameter: Example: 
  * @return string response from the API call*/
 public function importContactsToList($listId, $file)
 {
     //check that all required arguments are provided
     if (!isset($listId, $file)) {
         throw new \InvalidArgumentException("One or more required arguments were NULL.");
     }
     //the base uri for api requests
     $_queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $_queryBuilder = $_queryBuilder . '/lists/{list_id}/import';
     //process optional query parameters
     APIHelper::appendUrlWithTemplateParameters($_queryBuilder, array('list_id' => $listId));
     //validate and preprocess url
     $_queryUrl = APIHelper::cleanUrl($_queryBuilder);
     //prepare headers
     $_headers = array('user-agent' => 'ClickSendSDK');
     //prepare parameters
     $_parameters = array("file" => Request\Body::file($file));
     //set HTTP basic auth parameters
     Request::auth(Configuration::$username, Configuration::$key);
     //and invoke the API call request to fetch the response
     $response = Request::post($_queryUrl, $_headers, APIHelper::httpBuildQueryDevelop($_parameters));
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('BAD_REQUEST', 400, $response->body);
     } else {
         if ($response->code == 401) {
             throw new APIException('UNAUTHORIZED', 401, $response->body);
         } else {
             if ($response->code == 403) {
                 throw new APIException('FORBIDDEN', 403, $response->body);
             } else {
                 if ($response->code == 404) {
                     throw new APIException('NOT_FOUND', 404, $response->body);
                 } else {
                     if ($response->code == 405) {
                         throw new APIException('METHOD_NOT_FOUND', 405, $response->body);
                     } else {
                         if ($response->code == 429) {
                             throw new APIException('TOO_MANY_REQUESTS', 429, $response->body);
                         } else {
                             if ($response->code == 500) {
                                 throw new APIException('INTERNAL_SERVER_ERROR', 500, $response->body);
                             } else {
                                 if ($response->code < 200 || $response->code > 206) {
                                     //[200,206] = HTTP OK
                                     throw new APIException("HTTP Response Not OK", $response->code, $response->body);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $response->body;
 }
Пример #30
-1
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $username = $input->getOption('username');
     $password = $input->getOption('password');
     $date = $input->getOption('date');
     if (is_null($username) || is_null($password)) {
         throw new \InvalidArgumentException('Both username and password are required.');
     }
     // Make request to get the access_token
     $body = array("username" => $username, "password" => $password);
     $response = Unirest\Request::post("https://app.mybasis.com/login", "", $body);
     $response_cookie = $response->headers['Set-Cookie'][0];
     $cookieArray = explode(';', $response_cookie);
     $accessToken = explode('=', $cookieArray[0])[1];
     // Make request to get the data
     $metricURL = 'https://app.mybasis.com/api/v1/metricsday/me?day=' . $date . '&padding=0' . '&heartrate=true' . '&steps=true' . '&calories=true' . '&gsr=true' . '&skin_temp=true' . '&air_temp=true';
     $headers = array("Accept" => "application/json");
     Unirest\Request::cookie("access_token=" . $accessToken);
     $response = Unirest\Request::get($metricURL, $headers, $body);
     print_r($response->raw_body);
     //        print_r($response->code);        // HTTP Status code
     //        print_r($response->headers);     // Headers
     //        print_r($response->body);        // Parsed body
     //        print_r($response->raw_body);    // Unparsed body
     //
     //
     //        echo $metricURL;
 }