/**
  * Make a Http Request
  * @param       string          $method         The Http verb
  * @param       string          $url            The relative URL after the host name
  * @param       array|null      $apiRequest     Contents of the body
  * @param       array|null      $queryString    Data to add as a queryString to the url
  * @return      mixed
  * @throws      RequiredFieldMissingException
  * @throws      ConnectException
  * @throws      RequestException
  * @throws      \Exception
  */
 public function makeHttpRequest($method, $url, $apiRequest = null, $queryString = null)
 {
     $this->apiConfiguration->validate();
     $urlEndPoint = $this->apiConfiguration->getApiEndPoint() . '/' . $url;
     $data = ['headers' => ['Authorization' => 'Bearer ' . $this->apiConfiguration->getAccessToken()], 'json' => $apiRequest, 'query' => $queryString];
     try {
         switch ($method) {
             case 'post':
                 $response = $this->guzzle->post($urlEndPoint, $data);
                 break;
             case 'put':
                 $response = $this->guzzle->put($urlEndPoint, $data);
                 break;
             case 'delete':
                 $response = $this->guzzle->delete($urlEndPoint, $data);
                 break;
             case 'get':
                 $response = $this->guzzle->get($urlEndPoint, $data);
                 break;
             default:
                 throw new \Exception('Missing request method');
         }
         if (in_array(current($response->getHeader('Content-Type')), ['image/png', 'image/jpg'])) {
             $result = $response->getBody()->getContents();
         } else {
             $result = json_decode($response->getBody(), true);
         }
         return $result;
     } catch (ConnectException $c) {
         throw $c;
     } catch (RequestException $e) {
         throw $e;
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     $email = $request->email;
     $password = $request->password;
     $client = new Client();
     $res = $client->post('https://api.pragyan.org/user/eventauth', array('body' => array('user_email' => $email, 'event_id' => '39', 'user_pass' => $password)));
     $res = json_decode($res->getBody(), true);
     if ($res['status'] > 0) {
         if (User::where('email', $email)->exists()) {
             $user = User::where('email', $email)->first();
             Session::put('user_id', $user->PID);
             return redirect('home');
         }
         $res = $client->post('https://api.pragyan.org/user/getDetails', array('body' => array('user_email' => $email, 'user_pass' => $password)));
         $res = json_decode($res->getBody(), true);
         if ($res['status'] == 2) {
             $user = new User();
             $user->name = $res['data']['user_fullname'];
             $user->prag_pid = $res['data']['user_id'];
             $user->email = $email;
             $user->save();
             $user = User::where('email', $email)->first();
             Session::put('user_id', $user->PID);
             return redirect('home');
         } else {
             return view('login', ['error' => 'Try after sometime']);
         }
     } else {
         return view('login', ['error' => 'Email or password incorrect! If not registered, register at <a href="http://prgy.in/mdecoder">prgy.in/mdecoder</a>']);
     }
 }
Example #3
0
 public function registerWebPayModule($payment = 'capture')
 {
     $I = $this;
     $I->login();
     $I->amOnPage('/admin/load_module_config.php?module_id=' . MDL_WEBPAY_ID);
     $I->fillField('secret_key', WEBPAY_SECRET_KEY);
     $I->fillField('publishable_key', WEBPAY_PUBLISHABLE_KEY);
     $I->selectOption('input[name=payment]', $payment);
     $I->click('この内容で登録する');
     $I->amOnPage('/admin/ownersstore/');
     $uri = 'http://localhost:9999/admin/ownersstore/';
     $transactionId = $I->grabAttributeFrom('input[name=transactionid]', 'value');
     $sessionId = $I->grabCookie('ECSESSID');
     // posting file and handling confirm window are impossible for ghostdriver
     $client = new Client();
     $I->expectTo('install plugin');
     $client->post($uri, ['body' => ['transactionid' => $transactionId, 'mode' => 'install', 'plugin_file' => fopen('WebPayExt.tar.gz', 'r')], 'cookies' => ['ECSESSID' => $sessionId]]);
     $client->post($uri, ['body' => ['transactionid' => $transactionId, 'mode' => 'enable', 'plugin_id' => 1, 'enable' => 1], 'cookies' => ['ECSESSID' => $sessionId]]);
     $I->amOnPage('/admin/ownersstore/');
     $I->see('WebPay決済モジュール拡張プラグイン');
     $I->seeCheckboxIsChecked('input#plugin_enable');
     $I->seeInDatabase('dtb_payment', array('payment_id' => 5, 'memo03' => MDL_WEBPAY_CODE));
     $I->haveInDatabase('dtb_payment_options', array('deliv_id' => 1, 'payment_id' => 5, 'rank' => 5));
     $I->haveInDatabase('dtb_payment_options', array('deliv_id' => 2, 'payment_id' => 5, 'rank' => 2));
 }
Example #4
0
 public function post($resource, $body, $type, $options = [])
 {
     $options['body'] = $this->serializer->serialize($body, 'json');
     $options['headers'] = ['Content-Type' => 'application/json'];
     $content = $this->client->post($resource, $options)->getBody()->getContents();
     return $this->deserialize($content, $type);
 }
Example #5
0
 public function createTeamMembership($teamId = '', $options = array())
 {
     if (sizeOf($options) < 1 || $teamId == '') {
         return ApiException::errorMessage(999);
     }
     $requestParams = array();
     $requestParams["teamId"] = $teamId;
     if (isset($options["personId"])) {
         $requestParams["personId"] = $options["personId"];
     }
     if (isset($options["personEmail"])) {
         $requestParams["personEmail"] = $options["personEmail"];
     }
     if (isset($options["isModerator"])) {
         $requestParams["isModerator"] = $options["isModerator"];
     }
     $mJson = json_encode($requestParams);
     $client = new Client();
     try {
         $response = $client->post(self::TEAMMEMBERSHIPURI, array('headers' => $this->getBaseHeaders(), 'body' => $mJson, 'verify' => false));
     } catch (ClientException $e) {
         $errorResponse = $e->getResponse();
         $statusCode = $errorResponse->getStatusCode();
         if ($statusCode == 401) {
             $response = $client->post(self::TEAMMEMBERSHIPURI, array('headers' => $this->getRefreshHeaders(), 'body' => $mJson, 'verify' => false));
         } else {
             if ($statusCode != 200) {
                 return ApiException::errorMessage($statusCode);
             }
         }
     }
     return $response;
 }
Example #6
0
 /**
  * Send http request to api and return response.
  *
  * @param string $operation the operation type to perform
  * @param array $args
  *
  * @return Response
  */
 public function send($operation_type, array $args)
 {
     $fields = array_merge($this->authParams(), $args, compact('operation_type'));
     $response = new Response($this->client->post($this->apiUrl, ['body' => Xml::arrayToXml($fields)]));
     $response->offsetSet('original_args', $args);
     return $response;
 }
Example #7
0
 /**
  * Makes a request to a URL.
  *
  * @param string $request
  * @param array  $params
  *
  * @return \Psr7\Request
  */
 protected function request($request, array $params = [])
 {
     $endpoint = $this->config->get('centurian.endpoint');
     $uri = sprintf('%s/%s', $endpoint, $request);
     $data = ['form_params' => $params, 'auth' => [$this->config->get('centurian.token'), null]];
     return $this->client->post($uri, $data);
 }
 /**
  * Retrieve a user by the given credentials.
  *
  * @param array $credentials
  *
  * @return \Magister\Services\Database\Elegant\Model|null
  */
 public function retrieveByCredentials(array $credentials)
 {
     $body = ['body' => $credentials];
     $this->client->delete('sessies/huidige');
     $this->client->post('sessies', $body);
     return $this->retrieveByToken();
 }
 /**
  * Execute the command.
  *
  * @param InputInterface $input The input.
  * @param OutputInterface $output The output.
  * @throws InvalidArgumentException If the configuration is not specified.
  * @return integer
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $configFile = $input->getOption('config-file');
     $config = Yaml::parse(file_get_contents($configFile), true);
     if (!isset($config['strava']['auth'])) {
         throw new InvalidArgumentException('There is no configuration specified for tracker "strava". See example config.');
     }
     $secretToken = $config['strava']['auth']['secretToken'];
     $clientID = $config['strava']['auth']['clientID'];
     $username = $config['strava']['auth']['username'];
     $password = $config['strava']['auth']['password'];
     $httpClient = new Client();
     /** @var \GuzzleHttp\Message\ResponseInterface $response */
     // Do normal login.
     $response = $httpClient->get('https://www.strava.com/login', ['cookies' => true]);
     $authenticityToken = $this->getAuthenticityToken($response);
     // Perform the login to strava.com
     $httpClient->post('https://www.strava.com/session', array('cookies' => true, 'body' => array('authenticity_token' => $authenticityToken, 'email' => $username, 'password' => $password)));
     // Get the authorize page.
     $response = $httpClient->get('https://www.strava.com/oauth/authorize?client_id=' . $clientID . '&response_type=code&redirect_uri=http://localhost&scope=view_private,write&approval_prompt=force', ['cookies' => true]);
     $authenticityToken = $this->getAuthenticityToken($response);
     // Accept the application.
     $response = $httpClient->post('https://www.strava.com/oauth/accept_application?client_id=' . $clientID . '&response_type=code&redirect_uri=http://localhost&scope=view_private,write', array('cookies' => true, 'allow_redirects' => false, 'body' => array('authenticity_token' => $authenticityToken)));
     $redirectLocation = $response->getHeader('Location');
     $urlQuery = parse_url($redirectLocation, PHP_URL_QUERY);
     parse_str($urlQuery, $urlQuery);
     $authorizationCode = $urlQuery['code'];
     // Token exchange.
     $response = $httpClient->post('https://www.strava.com/oauth/token', array('body' => array('client_id' => $clientID, 'client_secret' => $secretToken, 'code' => $authorizationCode)));
     $jsonResponse = $response->json();
     $code = $jsonResponse['access_token'];
     $output->writeln('Your access token is: <comment>' . $code . '</comment>');
     return 0;
 }
 public function postMo(array $messageArr)
 {
     try {
         $this->msgCounter++;
         $words = explode(' ', $messageArr['text']);
         $moParams = array_merge($this->config['mo'], $messageArr, array('message_id' => $this->msgCounter, 'keyword' => $words[0] . '@' . $messageArr['short_id']));
         echo "Posting params from MO to client @" . $messageArr['url'] . ': ' . json_encode($moParams) . "\n";
         $response = $this->httpClient->post($messageArr['url'], ['body' => $moParams]);
         if ($response->getStatusCode() != 200) {
             echo 'received MO reply with status code: ' . $response->getStatusCode() . ', and body' . $response->getBody() . "\n";
             return $this->sendError($response->getBody());
         }
         $responseBody = $response->getBody();
         echo 'received MO reply:' . $responseBody . "\n";
         $this->broadcast('mo_reply', array('message' => $this->parseXMLResponse($responseBody)));
     } catch (\GuzzleHttp\Exception\RequestException $requestException) {
         echo 'received MO reply error of class [' . get_class($requestException) . '] and message: ' . $requestException->getMessage() . "\n";
         if ($requestException->hasResponse()) {
             echo "\nbody: " . $requestException->getResponse()->getBody() . "\n";
             echo "\ncode: " . $requestException->getResponse()->getStatusCode() . "\n";
             $this->sendError($requestException->getMessage(), $this->parseXMLResponse($requestException->getResponse()->getBody()));
         }
         $this->sendError($requestException->getMessage());
     } catch (\Exception $exc) {
         echo 'received MO reply error of class [' . get_class($exc) . '] and message: ' . $exc->getMessage() . "\n";
         $this->sendError($exc->getMessage());
     }
 }
 public function post($full_url, array $multi_parts = [], array $headers = [])
 {
     $options = ['debug' => GUZZLE_DEBUG];
     // Grab the client's handler instance.
     $clientHandler = $this->client->getConfig('handler');
     // Create a middleware that echoes parts of the request.
     $tapMiddleware = Middleware::tap(function ($request) {
         echo $request->getHeader('Content-Type');
         // application/json
         echo $request->getBody();
         // {"foo":"bar"}
     });
     //$options['handler'] = $tapMiddleware($clientHandler);
     $multi_part_vars = array();
     foreach ($multi_parts as $name => $data) {
         if (is_array($data)) {
             $data['name'] = $name;
         } else {
             $data = ['name' => $name, 'contents' => $data];
         }
         $multi_part_vars[] = $data;
     }
     $options['multipart'] = $multi_part_vars;
     //$options['headers'] = ['Referer' =>  $full_url];
     if (!empty($headers)) {
         $options['headers'] = $headers;
     }
     $this->response = $this->client->post($full_url, $options);
     return $this;
 }
Example #12
0
 /**
  * get access token
  * @param $code
  * @return mixed
  * @throws \App\Exception\OAuthErrorException
  */
 public function getToken($code)
 {
     $result = $this->client->post($this->accessToken, ['headers' => ["Content-Type" => "application/x-www-form-urlencodedrn", "Accept" => "application/json"], 'body' => ['client_id' => \Config::get('github.client_id'), 'client_secret' => \Config::get('github.client_secret'), 'code' => $code, 'redirect_uri' => action('auth.callback')]])->json();
     if (isset($result['error'])) {
         throw new OAuthErrorException($result['error_description']);
     }
     return $result;
 }
 /**
  * Triggers a simulated Stripe web hook event
  *
  * @param null|string $event
  * @return \GuzzleHttp\Message\FutureResponse|\GuzzleHttp\Message\ResponseInterface|\GuzzleHttp\Ring\Future\FutureInterface|null
  * @throws InvalidEventException
  */
 public function triggerEvent($event = null)
 {
     if (is_null($event)) {
         throw new InvalidEventException("Event name required");
     }
     $response = $this->client->post($this->endpoint, ['headers' => ['content-type' => 'application/json'], 'body' => $this->loadEventData($event)]);
     return $response;
 }
Example #14
0
 /**
  * {@inheritdoc}
  */
 public function validate($uri, $secret, $response, $remoteIp = NULL)
 {
     $params = ['secret' => $secret, 'response' => $response];
     if ($remoteIp !== NULL) {
         $params['remoteip'] = $remoteIp;
     }
     return $this->client->post($uri, ['query' => $params]);
 }
 /**
  * Send the given notification.
  *
  * @param  mixed  $notifiable
  * @param  \Illuminate\Notifications\Notification  $notification
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function send($notifiable, Notification $notification)
 {
     if (!($url = $notifiable->routeNotificationFor('slack'))) {
         return;
     }
     $message = $notification->toSlack($notifiable);
     $this->http->post($url, $this->buildJsonPayload($message));
 }
 public function testGetAccessToken()
 {
     $response = self::$client->post('/');
     $token = $response->json();
     $this->assertEquals("v6574b42-a5bc-4574-a87f-5c9d1202e316", $token['access_token']);
     $this->assertEquals("308874923", $token['expires_in']);
     $this->assertEquals("Bearer", $token['token_type']);
 }
 /**
  * {@inheritdoc}
  */
 public function publish(Event $event)
 {
     try {
         $this->client->post(self::PUBLISH_URL, ['body' => $this->serializer->serialize($event, 'json')]);
     } catch (BadResponseException $exception) {
         throw new PublishException($exception->getMessage());
     }
 }
Example #18
0
 /**
  * Obtain a request token which can be used to obtain an request token.
  *
  * @param string $callback A URL on your website where the users are redirected to after accepting the permissions
  *
  * @return array An array containing the request_token, the request_token_secret and the authorize_url
  */
 public function getRequestToken($callback_url)
 {
     $response = $this->client->post('request_token', ['query' => ['oauth_callback' => $callback_url]]);
     $tokens = self::decodeUrlEncodedResponse($response->getBody());
     $request_token = $tokens['oauth_token'];
     $request_token_secret = $tokens['oauth_token_secret'];
     return ['request_token' => $request_token, 'request_token_secret' => $request_token_secret, 'authorize_url' => 'https://api.xing.com/v1/authorize?oauth_token=' . $request_token];
 }
 /**
  * Send the given notification.
  *
  * @param  mixed  $notifiable
  * @param  \Illuminate\Notifications\Notification  $notification
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function send($notifiable, Notification $notification)
 {
     if (!($url = $notifiable->routeNotificationFor('slack'))) {
         return;
     }
     $message = $notification->toSlack($notifiable);
     return $this->http->post($url, ['json' => ['text' => $message->content, 'attachments' => $this->attachments($message)]]);
 }
Example #20
0
 /**
  * @param \Lunchbot\Menu\LunchMenuResult[] $results
  */
 public function publishResults(array $results)
 {
     $this->httpClient->post($this->url, ['body' => json_encode(['channel' => $this->channel, 'username' => 'Lunchbot', 'icon_url' => 'https://cdn2.iconfinder.com/data/icons/life-concepts-lifestyles/128/eating-512.png', 'text' => implode("\n\n", array_map(function (LunchMenuResult $result) {
         return sprintf("*<%s|%s>*\n%s", $result->getRestaurantWebAddress(), $result->getRestaurantName(), implode("\n", array_map(function (LunchMenuItem $item) {
             return $item->getDescription();
         }, $result->getTodayLunchMenu())));
     }, $results))])]);
 }
Example #21
0
 /**
  * 登入 Ecourse.
  *
  * @return void
  * @throws AuthorizationException
  */
 private function signIn()
 {
     $response = $this->client->post(self::SIGN_IN, ['allow_redirects' => false, 'cookies' => $this->jar, 'form_params' => ['id' => decrypt(Session::get('ccu.sso.username')), 'pass' => decrypt(Session::get('ccu.sso.password')), 'ver' => 'C']]);
     if (!str_contains($response->getHeaderLine('location'), 'Courses_Admin')) {
         throw new AuthorizationException();
     }
     Session::put('ccu.ecourse.jar', encrypt(serialize($this->jar)));
 }
 protected function push($title, $body, $deviceIden = null)
 {
     $payload = array('type' => 'note', 'title' => $title, 'body' => $body);
     if ($deviceIden !== null) {
         $payload['device_iden'] = $deviceIden;
     }
     $this->guzzle->post('pushes', array('headers' => $this->headers, 'json' => $payload));
 }
 protected function enableNewConfiguration($project)
 {
     $response = $this->client->post(sprintf('projects/%s/features', $project['id']), array('json' => array("feature" => "orchestrator-kbc-config")));
     $response = json_decode($response->getBody()->getContents(), true);
     if (!in_array('orchestrator-kbc-config', $response['features'])) {
         throw new StorageApi\InvalidStateException('Feature was not enabled');
     }
 }
Example #24
0
 /**
  * Display the specified resource.
  *
  * @param $link
  * @return \Illuminate\Http\Response
  * @internal param int $id
  */
 public function show($link)
 {
     $client = new Client();
     $baseUrl = 'https://www.youmagine.com/';
     $response = $client->get($baseUrl . 'designs/' . $link);
     $code = $response->getBody();
     $xs = Selector::loadHTML($code);
     // Scrape Youmagine thing information from DOM
     try {
         $name = $xs->find('/html/body/div[2]/div/h1')->extract();
         $description = $xs->find('//*[@id="information"]/div[2]')->extract();
         $files = $xs->findAll('//*[@id="documents"]/div/ul/li[*]/div[3]/div[1]/a')->map(function ($node) {
             return $node->find('@href')->extract();
         });
     } catch (NodeNotFoundException $e) {
         return response()->view('thing.none');
     }
     // Get files
     $downloadLinks = [];
     foreach ($files as $file) {
         $response = $client->get($baseUrl . $file, ['allow_redirects' => false]);
         $code = $response->getBody();
         preg_match('/"(.*?)"/', $code, $downloadLinkMatch);
         $downloadLinks[] = $downloadLinkMatch[1];
     }
     // Get access token
     $response = $client->request('POST', 'https://developer.api.autodesk.com/authentication/v1/authenticate', ['form_params' => ['client_id' => env('AUTODESK_CLIENT_ID', ''), 'client_secret' => env('AUTODESK_CLIENT_SECRET', ''), 'grant_type' => 'client_credentials']]);
     $authToken = json_decode($response->getBody())->access_token;
     // Create a bucket
     $bucketKey = Str::lower(Str::random(16));
     $response = $client->request('POST', 'https://developer.api.autodesk.com/oss/v2/buckets', ['json' => ['bucketKey' => $bucketKey, 'policyKey' => 'transient'], 'headers' => ['Authorization' => 'Bearer ' . $authToken]]);
     $bucketKey = json_decode($response->getBody())->bucketKey;
     // Upload to bucket
     $bucket = [];
     foreach ($downloadLinks as $downloadLink) {
         $fileName = pathinfo($downloadLink)['basename'];
         $file = fopen(base_path('public/cache/' . $fileName), 'w');
         /** @noinspection PhpUnusedLocalVariableInspection */
         $response = $client->get($downloadLink, ['sink' => $file]);
         $file = fopen(base_path('public/cache/' . $fileName), 'r');
         $response = $client->request('PUT', 'https://developer.api.autodesk.com/oss/v2/buckets/' . $bucketKey . '/objects/' . $fileName, ['body' => $file, 'headers' => ['Authorization' => 'Bearer ' . $authToken]]);
         $body = json_decode($response->getBody());
         $bucket[] = ['filename' => $body->objectKey, 'urn' => $body->objectId];
     }
     // Set up references
     $references = ['master' => $bucket[0]['urn'], 'dependencies' => []];
     foreach ($bucket as $file) {
         if ($file['filename'] === $bucket[0]['filename']) {
             continue;
         }
         $references['dependencies'][] = ['file' => $file['urn'], 'metadata' => ['childPath' => $file['filename'], 'parentPath' => $bucket[0]['filename']]];
     }
     $response = $client->post('https://developer.api.autodesk.com/references/v1/setreference', ['json' => $references, 'headers' => ['Authorization' => 'Bearer ' . $authToken]]);
     // Register data with the viewing services
     $urn = base64_encode($bucket[0]['urn']);
     $response = $client->post('https://developer.api.autodesk.com/viewingservice/v1/register', ['json' => ['urn' => $urn], 'headers' => ['Authorization' => 'Bearer ' . $authToken]]);
     return response()->view('thing.show', compact('name', 'description', 'urn', 'authToken') + ['pollUrl' => 'https://developer.api.autodesk.com/viewingservice/v1/' . $urn, 'dl' => $downloadLinks[0]]);
 }
 public function testSendTest()
 {
     $response = self::$client->post('/');
     $testSend = TestSend::create($response->json());
     $this->assertInstanceOf('Ctct\\Components\\EmailMarketing\\TestSend', $testSend);
     $this->assertEquals("HTML", $testSend->format);
     $this->assertEquals("oh hai there", $testSend->personal_message);
     $this->assertEquals("*****@*****.**", $testSend->email_addresses[0]);
 }
Example #26
0
 /**
  * @param array $requestSettings
  * @return array
  * @throws \Sellsy\Exception\ServerException
  */
 public function call(array $requestSettings)
 {
     try {
         $response = $this->client->post(TransportInterface::API_ENDPOINT, array('headers' => array('Authorization' => $this->getAuthenticationHeader()), 'form_params' => array('request' => 1, 'io_mode' => 'json', 'do_in' => json_encode($requestSettings))));
     } catch (GuzzleException $e) {
         throw new ServerException($e->getMessage(), $e->getCode(), $e);
     }
     return $this->convertResponseBody($response->getBody()->getContents(), $response->getStatusCode());
 }
Example #27
0
 public function IsVerified($recaptcha)
 {
     $response = $this->client->post('https://www.google.com/recaptcha/api/siteverify', ['form_params' => ['secret' => $this->secret, 'response' => $recaptcha, 'remoteip' => $this->remoteIp]]);
     if ($response->getStatusCode() != 200) {
         return false;
     }
     $result = json_decode($response->getBody(), true);
     return @$result['success'] == true;
 }
 /**
  * @param $url
  *
  * @return string
  * @throws \RuntimeException
  */
 private function getCaptchaId($url)
 {
     $response = $this->browser->post($this->settings->getUploadUrl(), array('body' => array('key' => $this->settings->getApiKey(), 'method' => $this->settings->getBase64MethodName(), 'body' => $this->fileService->getBase64($url))));
     list($code, $captchaId) = explode($this->settings->getDelimiter(), $response->getBody());
     if (!$this->settings->isSuccessResponseCode($code)) {
         throw new \RuntimeException(sprintf('Bad response answer "%s"', $code));
     }
     return $captchaId;
 }
 public function generateApplicationForAccess($username, $password, $applicationName)
 {
     $client = new GuzzleClient(['cookies' => true, 'allow_redirects' => true]);
     // Login into the portal.
     $client->post('https://cloud.estimote.com/v1/login', ['headers' => ['Content-Type' => '	application/json'], 'json' => array('username' => $username, 'password' => $password)]);
     $response = $client->post('https://cloud.estimote.com/v1/applications', ['json' => ['name' => $applicationName, 'description' => $applicationName, 'template' => 'your-own-app']]);
     $json = \GuzzleHttp\json_decode($response->getBody(), true);
     return new ApplicationAuthorization($json['name'], $json['token']);
 }
Example #30
0
 /**
  * @param AuthConfig $config
  *
  * @return TokenConfig
  * @throws AuthenticationException
  */
 public function auth(AuthConfig $config)
 {
     $response = $this->client->post($config->getBaseUrl() . '/auth', array('body' => array('username' => $config->getUsername(), 'password' => $config->getPassword())));
     $data = $response->json();
     if (isset($data['error']) && isset($data['code'])) {
         throw new AuthenticationException($data['error'], $data['code']);
     }
     return new TokenConfig($data['token']);
 }