public function connect($appKey, $appSecret, $accessToken, $tokenSecret)
 {
     try {
         $client = new Client(self::BASE_URL . '/{version}', ['version' => '1.1']);
         $oauth = new OauthPlugin(['consumer_key' => $appKey, 'consumer_secret' => $appSecret, 'token' => $accessToken, 'token_secret' => $tokenSecret]);
         return $client->addSubscriber($oauth);
     } catch (ClientErrorResponseException $e) {
         $req = $e->getRequest();
         $resp = $e->getResponse();
         print_r($resp);
         die('1');
     } catch (ServerErrorResponseException $e) {
         $req = $e->getRequest();
         $resp = $e->getResponse();
         die('2');
     } catch (BadResponseException $e) {
         $req = $e->getRequest();
         $resp = $e->getResponse();
         print_r($resp);
         die('3');
     } catch (Exception $e) {
         echo 'AGH!';
         die('4');
     }
 }
Exemple #2
0
 public function setLaundryState(&$laundryPlace)
 {
     $user = '******';
     $pass = '******';
     try {
         $client = new Client($laundryPlace['url']);
         $request = $client->get('/LaundryState', [], ['auth' => [$user, $pass, 'Digest'], 'timeout' => 1.5, 'connect_timeout' => 1.5]);
         $response = $request->send();
         $body = $response->getBody();
         libxml_use_internal_errors(true);
         $crawler = new Crawler();
         $crawler->addContent($body);
         foreach ($crawler->filter('img') as $img) {
             $resource = $img->getAttribute('src');
             $img->setAttribute('src', 'http://129.241.126.11/' . trim($resource, '/'));
         }
         $crawler->addHtmlContent('<h1>foobar</h1>');
         //'<link href="http://129.241.126.11/pic/public_n.css" type="text/css">');
         $laundryPlace['html'] = $crawler->html();
         libxml_use_internal_errors(false);
         preg_match_all('/bgColor=Green/', $body, $greenMatches);
         preg_match_all('/bgColor=Red/', $body, $redMatches);
         $laundryPlace['busy'] = count($redMatches[0]);
         $laundryPlace['available'] = count($greenMatches[0]);
     } catch (\Exception $e) {
         $laundryPlace['available'] = self::NETWORK_ERROR;
         $laundryPlace['busy'] = self::NETWORK_ERROR;
         $laundryPlace['html'] = self::NETWORK_ERROR;
     }
 }
 /**
  * Injects the livereload script.
  *
  * @param Response $response A Response instance
  */
 protected function injectScript(Response $response)
 {
     if (function_exists('mb_stripos')) {
         $posrFunction = 'mb_strripos';
         $substrFunction = 'mb_substr';
     } else {
         $posrFunction = 'strripos';
         $substrFunction = 'substr';
     }
     $content = $response->getContent();
     $pos = $posrFunction($content, '</body>');
     if (false !== $pos) {
         $script = "livereload.js";
         if ($this->checkServerPresence) {
             // GET is required, as livereload apparently does not support HEAD requests ...
             $request = $this->httpClient->get($script);
             try {
                 $checkResponse = $this->httpClient->send($request);
                 if ($checkResponse->getStatusCode() !== 200) {
                     return;
                 }
             } catch (CurlException $e) {
                 // If error is connection failed, we assume the server is not running
                 if ($e->getCurlHandle()->getErrorNo() === 7) {
                     return;
                 }
                 throw $e;
             }
         }
         $content = $substrFunction($content, 0, $pos) . "\n" . '<script src="' . $this->httpClient->getBaseUrl() . $script . '"></script>' . "\n" . $substrFunction($content, $pos);
         $response->setContent($content);
     }
 }
 /**
  * Guzzle3 Request implementation
  *
  * @param string $httpMethod
  * @param string $path
  * @param array $params
  * @param null $version
  * @param bool $isAuthorization
  *
  * @return Response|mixed
  * @throws ClientException
  * @throws AuthorizeException
  * @throws ServerException
  * @throws Error
  */
 public function request($httpMethod = 'GET', $path = '', $params = array(), $version = null, $isAuthorization = false)
 {
     //TODO: Implement Guzzle 3 here
     $guzzleClient = new GuzzleClient();
     switch ($httpMethod) {
         case 'GET':
             //TODO: array liked param need manual parser
             $request = $guzzleClient->get($path, array(), array('query' => $params));
             break;
         default:
             //default:'Content-Type'=>'application/json' for "*.json" URI
             $json_body = json_encode($params);
             $request = $guzzleClient->createRequest($httpMethod, $path, array(), $json_body);
             $request->setHeader('Content-Type', 'application/json');
     }
     try {
         $res = $request->send();
     } catch (GuzzleException\ClientErrorResponseException $e) {
         //catch error 404
         $error_message = $e->getResponse();
         if ($isAuthorization) {
             throw new AuthorizeException($error_message, $error_message->getStatusCode(), $e->getPrevious());
         } else {
             throw new ClientException($error_message, $e->getResponse()->getStatusCode(), $e->getPrevious());
         }
     } catch (GuzzleException\ServerErrorResponseException $e) {
         throw new ServerException($e, '$e->getResponse()->getStatusCode()', $e->getPrevious());
     } catch (GuzzleException\BadResponseException $e) {
         throw new Error($e->getResponse(), $e->getResponse()->getStatusCode(), $e->getPrevious());
     }
     $response = new Response($res->json(), $res->getStatusCode());
     return $response;
 }
 /**
  * @param string $postalCode
  * @param string $houseNumber
  * @return array
  */
 public function lookupAddress($postalCode, $houseNumber)
 {
     $this->client->setConfig(['curl.options' => ['CURLOPT_CONNECTTIMEOUT_MS' => '2000', 'CURLOPT_RETURNTRANSFER' => true]]);
     $url = sprintf($this->baseUrl . '/%s/%s', $postalCode, $houseNumber);
     $request = $this->client->get($url)->setAuth($this->apiKey, $this->apiSecret);
     return $request->send()->json();
 }
 public static function getFileCache($location, $expire = false)
 {
     if (is_bool($expire)) {
         $expire = 60 * 30;
     }
     $hash = sha1($location);
     $cacheDir = self::$cache_url;
     $file = "{$cacheDir}{$hash}";
     if (file_exists($file)) {
         $file_content = file_get_contents($file);
         $unserialize_file = unserialize($file_content);
         $file_expire = $unserialize_file['expire'];
         if ($file_expire > time()) {
             return base64_decode($unserialize_file['content']);
         }
     }
     mt_srand();
     $randomize_user_agent = self::$user_agents[mt_rand(0, count(self::$user_agents) - 1)];
     $location = parse_url($location);
     $http = "http://{$location['host']}";
     $path = "{$location['path']}?{$location['query']}";
     $client = new Client($http);
     $request = $client->get($path);
     $request->setHeader('User-Agent', $randomize_user_agent);
     $response = $request->send();
     if (!$response->isSuccessful()) {
         return false;
     }
     $content = $response->getBody(true);
     $store = array('date' => time(), 'expire' => time() + $expire, 'content' => base64_encode($content));
     $serialize = serialize($store);
     file_put_contents($file, $serialize);
     return $content;
 }
 /**
  * Makes the request to the server.
  * 
  * @param string $server	
  * @param string $service		The rest service to access e.g. /connections/communities/all
  * @param string $method		GET, POST or PUT
  * @param string $body
  * @param string $headers
  */
 public function makeRequest($server, $service, $method, $options, $body = null, $headers = null, $endpointName = "connections")
 {
     $store = SBTCredentialStore::getInstance();
     $settings = new SBTSettings();
     $token = $store->getToken($endpointName);
     $response = null;
     $client = new Client($server);
     $client->setDefaultOption('verify', false);
     // If global username and password is set, then use it; otherwise use user-specific credentials
     if ($settings->getBasicAuthMethod($endpointName) == 'global') {
         $user = $settings->getBasicAuthUsername($endpointName);
         $password = $settings->getBasicAuthPassword($endpointName);
     } else {
         $user = $store->getBasicAuthUsername($endpointName);
         $password = $store->getBasicAuthPassword($endpointName);
     }
     try {
         $request = $client->createRequest($method, $service, $headers, $body, $options);
         if ($settings->forceSSLTrust($endpointName)) {
             $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
             $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
         }
         if ($method == 'POST' && isset($_FILES['file']['tmp_name'])) {
             $request->addPostFile('file', $_FILES['file']['tmp_name']);
         }
         $request->setAuth($user, $password);
         $response = $request->send();
     } catch (Guzzle\Http\Exception\BadResponseException $e) {
         $response = $e->getResponse();
     }
     return $response;
 }
 public function authenticate(array $credentials)
 {
     $mcrypt = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($mcrypt), MCRYPT_DEV_RANDOM);
     mcrypt_generic_init($mcrypt, $this->cryptPassword, $iv);
     $url = $this->getUrl($credentials[self::USERNAME], $credentials[self::PASSWORD], $mcrypt, $iv);
     try {
         $res = $this->httpClient->get($url)->send();
     } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
         if ($e->getResponse()->getStatusCode() === 403) {
             throw new \Nette\Security\AuthenticationException("User '{$credentials[self::USERNAME]}' not found.", self::INVALID_CREDENTIAL);
         } elseif ($e->getResponse()->getStatusCode() === 404) {
             throw new \Nette\Security\AuthenticationException("Invalid password.", self::IDENTITY_NOT_FOUND);
         } else {
             throw $e;
         }
     }
     $responseBody = trim(mdecrypt_generic($mcrypt, $res->getBody(TRUE)));
     $apiData = Json::decode($responseBody);
     $user = $this->db->table('users')->where('id = ?', $apiData->id)->fetch();
     $registered = new \DateTimeImmutable($apiData->registered->date, new \DateTimeZone($apiData->registered->timezone));
     $userData = array('username' => $credentials[self::USERNAME], 'password' => $this->calculateAddonsPortalPasswordHash($credentials[self::PASSWORD]), 'email' => $apiData->email, 'realname' => $apiData->realname, 'url' => $apiData->url, 'signature' => $apiData->signature, 'language' => $apiData->language, 'num_posts' => $apiData->num_posts, 'apiToken' => $apiData->apiToken, 'registered' => $registered->getTimestamp());
     if (!$user) {
         $userData['id'] = $apiData->id;
         $userData['group_id'] = 4;
         $this->db->table('users')->insert($userData);
         $user = $this->db->table('users')->where('username = ?', $credentials[self::USERNAME])->fetch();
     } else {
         $user->update($userData);
     }
     return $this->createIdentity($user);
 }
 /**
  * Build a new FactoryDriver
  *
  * @param Container $app
  */
 public function __construct(Container $app)
 {
     $this->app = $app;
     $this->client = new \Guzzle\Http\Client();
     $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
     $this->client->addSubscriber($cookiePlugin);
 }
Exemple #10
0
 public static function create($host, $ssl, $clientID, $apiKey)
 {
     $guzzle = new GuzzleHttpClient(($ssl ? 'https' : 'http') . '://' . $host . '/');
     $signer = new RequestSigner($clientID, $apiKey);
     $guzzle->addSubscriber($signer);
     return new static($guzzle);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('Updating the WSDL file');
     $client = $this->getContainer()->get('phpforce.soap_client');
     // Get current session id
     $loginResult = $client->getLoginResult();
     $sessionId = $loginResult->getSessionId();
     $instance = $loginResult->getServerInstance();
     $url = sprintf('https://%s.salesforce.com', $instance);
     $guzzle = new Client($url, array('curl.CURLOPT_SSL_VERIFYHOST' => false, 'curl.CURLOPT_SSL_VERIFYPEER' => false));
     // type=* for enterprise WSDL
     $request = $guzzle->get('/soap/wsdl.jsp?type=*');
     $request->addCookie('sid', $sessionId);
     $response = $request->send();
     $wsdl = $response->getBody();
     $wsdlFile = $this->getContainer()->getParameter('phpforce.soap_client.wsdl');
     // Write WSDL
     file_put_contents($wsdlFile, $wsdl);
     // Run clear cache command
     if (!$input->getOption('no-cache-clear')) {
         $command = $this->getApplication()->find('cache:clear');
         $arguments = array('command' => 'cache:clear');
         $input = new ArrayInput($arguments);
         $command->run($input, $output);
     }
 }
 /**
  * @see http://explorer.nuxeo.com/nuxeo/site/distribution/current/listOperations List of available operations
  * @param string $operation
  * @return NuxeoRequest
  */
 public function newRequest($operation)
 {
     $request = $this->client->createRequest(Request::POST, $operation, $this->headers);
     $request->setAuth($this->auth->getUsername(), $this->auth->getPassword());
     $newRequest = new NuxeoRequest($request);
     return $newRequest;
 }
 protected function setUp()
 {
     $this->httpClient = new HttpClient('http://localhost');
     $this->clientMocker = new MockPlugin();
     $this->httpClient->addSubscriber($this->clientMocker);
     $this->engineClient = new EngineClient($this->httpClient, array('collection_name' => 'widgets'));
 }
 public function connect($errors = 0)
 {
     $client = new Client(null);
     if (!file_exists($this->_cookieFile)) {
         file_put_contents($this->_cookieFile, "");
     }
     $cookiePlugin = new CookiePlugin(new FileCookieJar($this->_cookieFile));
     $client->addSubscriber($cookiePlugin);
     $client->setUserAgent('User-Agent', 'Mozilla/5.0 (Linux; U; Android 4.2.2; de-de; GT-I9195 Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30');
     $this->_client = $client;
     try {
         $url = $this->getLoginUrl();
         $this->loginAndGetCode($url);
         $this->enterAnswer();
         $this->gatewayMe();
         $this->auth();
         $this->getSid();
         $this->utasRefreshNucId();
         $this->auth();
         $this->utasAuth();
         $this->utasQuestion();
     } catch (\Exception $e) {
         throw $e;
         // server down, gotta retry
         if ($errors < static::RETRY_ON_SERVER_DOWN && preg_match("/service unavailable/mi", $e->getMessage())) {
             $this->connect(++$errors);
         } else {
             throw new \Exception('Could not connect to the mobile endpoint.');
         }
     }
     return array("nucleusId" => $this->nucId, "userAccounts" => $this->accounts, "sessionId" => $this->sid, "phishingToken" => $this->phishingToken, "platform" => $this->_loginDetails['platform']);
 }
Exemple #15
0
 /**
  * {@InheritDoc}
  */
 public function send(Request $request)
 {
     $guzzleRequest = $this->client->createRequest($request->getMethod(), $request->getUri(), $request->getHeaders(), $request->getBody());
     $guzzleResponse = $guzzleRequest->send();
     $response = new Response($guzzleResponse->getStatusCode(), $guzzleResponse->getHeaders()->toArray(), $guzzleResponse->getBody(true));
     return $response;
 }
 /**
  * Get RealFaviconGenerator response
  *
  * @param QueryData $queryData RealFaviconGenerator query
  * @return mixed RealFaviconGenerator response
  */
 protected function getResponse(QueryData $queryData)
 {
     $client = new Client($this->generator->getBaseurl());
     $request = $client->post($this->generator->getUri(), null, $queryData->__toString());
     $response = $client->send($request);
     return $response;
 }
Exemple #17
0
 /**
  * @dataProvider cbProvider
  */
 public function testResponse($expectedStatusCode, $expectedResponseContent, $request, $testCase, $testHeaders)
 {
     $process = new Process('php -S [::1]:8999', __DIR__ . '/../../resources');
     $process->start();
     sleep(1);
     $signature = sha1($request . ServerMock::PROJECT_SECRET_KEY);
     $headers = null;
     if ($testHeaders) {
         $headers = $testHeaders;
     } else {
         $headers = array('Authorization' => 'Signature ' . $signature);
     }
     $request = $this->guzzleClient->post('/webhook_server.php?test_case=' . $testCase, $headers, $request);
     try {
         $response = $request->send();
     } catch (BadResponseException $e) {
         $process->stop();
         $response = $e->getResponse();
     }
     static::assertSame($expectedResponseContent, $response->getBody(true));
     static::assertSame($expectedStatusCode, $response->getStatusCode());
     static::assertArrayHasKey('x-xsolla-sdk', $response->getHeaders());
     static::assertSame(Version::getVersion(), (string) $response->getHeader('x-xsolla-sdk'));
     static::assertArrayHasKey('content-type', $response->getHeaders());
     if (204 === $response->getStatusCode()) {
         static::assertStringStartsWith('text/plain', (string) $response->getHeader('content-type'));
     } else {
         static::assertStringStartsWith('application/json', (string) $response->getHeader('content-type'));
     }
 }
 /**
  * Test is beberlei collaborator of doctrine/cache
  */
 public function testCollaboratorExists()
 {
     $client = new Client('https://api.github.com');
     $request = $client->get('/repos/doctrine/cache/collaborators/beberlei');
     $response = $request->send();
     $this->assertEquals($response->getStatusCode(), 204);
 }
 /**
  * @param Application $app An Application instance
  * @return ControllerCollection A ControllerCollection instance
  */
 public function connect(Application $app)
 {
     $this->initTwig(__DIR__ . '/views');
     $controllers = $app['controllers_factory'];
     $controllers->get('/', function (Application $app) {
         $herokuStatus = self::STATUS_ERROR;
         try {
             $client = new Client('https://status.heroku.com');
             $httpResponse = $client->get('/api/v3/current-status')->send();
             if ($httpResponse->getStatusCode() === 200) {
                 $jsonArray = $httpResponse->json();
                 if ($jsonArray['status']['Production'] == 'green') {
                     $herokuStatus = self::STATUS_OK;
                     if ($jsonArray['status']['Development'] != 'green') {
                         $herokuStatus = self::STATUS_WARNING;
                     }
                 }
             }
         } catch (\Exception $e) {
             return $this->twig->render('error.html.twig');
         }
         return $this->twig->render('index.html.twig', ['status' => $herokuStatus]);
     });
     return $controllers;
 }
 /**
  * Constructor requires final url endpoint to send request to as
  * first parameter. Optional second argument is a client object of type
  * Guzzle\Http\Client.
  *
  *
  * @param string $baseUrl Host to make requests to e.g. https://www.lush.co.uk
  * @param \Guzzle\Http\Client $client Instance of Guzzle client object to use.
  * @param bool $debug If set to true then debug messages will be emitted by the underlying Guzzle client
  */
 public function __construct($baseUrl, \Guzzle\Http\Client $client, $debug = false)
 {
     $this->baseUrl = $baseUrl;
     $client->setBaseUrl($this->baseUrl);
     $this->client = $client;
     $this->debug = (bool) $debug;
 }
Exemple #21
0
 /**
  * @return Client
  */
 private function buildClient()
 {
     $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
     $client = new Client();
     $client->addSubscriber($cookiePlugin);
     return $client;
 }
Exemple #22
0
 /**
  * Scrape URL and collect output
  * @param string $url
  * @param OutputInterface $output
  */
 public function scrape($url, OutputInterface $output)
 {
     $this->collection->exchangeArray([]);
     try {
         $initialPage = $this->client->get($url)->send();
     } catch (BadResponseException $e) {
         $output->writeln('<error>' . $e->getMessage() . '</error>');
         throw new \RuntimeException('Unable to load initial page');
     }
     $xml = $this->getSimpleXml($initialPage->getBody());
     $items = $xml->xpath($this->config['collection']);
     foreach ($items as $item) {
         $title = $item->xpath($this->config['title']);
         $unitPrice = $item->xpath($this->config['unitPrice']);
         $itemUrl = $item->xpath($this->config['itemUrl']);
         $itemSize = 0;
         $itemDesc = null;
         if (isset($itemUrl[0]->attributes()['href'])) {
             try {
                 $itemPage = $this->client->get((string) $itemUrl[0]->attributes()['href'])->send();
                 $itemPageBody = $this->getSimpleXml($itemPage->getBody());
                 $itemSize = $itemPage->getContentLength();
                 $itemDesc = $itemPageBody->xpath($this->config['desc']);
             } catch (BadResponseException $e) {
                 $output->writeln('<error>' . $e->getMessage() . '</error>');
             }
         }
         if ($title && $unitPrice) {
             $parsedPrice = (double) \trim(\str_replace('&pound', null, $unitPrice[0]));
             $this->collection->append(['title' => \trim($title[0]), 'unit_price' => $parsedPrice, 'description' => \trim($itemDesc[0]), 'size' => \round($itemSize / 1024) . 'kb']);
         }
     }
     return $this->collection;
 }
Exemple #23
0
 private function request($method, $path, $params = array())
 {
     $url = $this->api . rtrim($path, '/') . '/';
     // Using Guzzle library ---------------------------------
     $client = new Client($url, array('ssl.certificate_authority' => false, 'curl.options' => array('CURLOPT_CONNECTTIMEOUT' => 30)));
     // headers
     $headers = array('Connection' => 'close', 'User-Agent' => 'PHPPlivo');
     if (!strcmp($method, "POST")) {
         $request = $client->post('', $headers, json_encode($params));
         $request->setHeader('Content-type', 'application/json');
     } else {
         if (!strcmp($method, "GET")) {
             $request = $client->get('', $headers, $params);
             $request->getQuery()->merge($params);
         } else {
             if (!strcmp($method, "DELETE")) {
                 $request = $client->delete('', $headers, $params);
                 $request->getQuery()->merge($params);
             }
         }
     }
     $request->setAuth($this->auth_id, $this->auth_token);
     $response = $request->send();
     $responseData = $response->json();
     $status = $response->getStatusCode();
     return array("status" => $status, "response" => $responseData);
 }
Exemple #24
0
 public function getStatusFromWoeid($woeid)
 {
     $request = $this->guzzle->createRequest(self::WEBSERVICE_METHOD, self::WEBSERVICE_URI . $woeid);
     $response = $this->guzzle->send($request);
     $status = $this->parseWeatherResponse($response->xml());
     return $status;
 }
 function it_set_up_a_client_oauth_plugin_subscriber(Client $client, RequestBuilder $builder, $factory, $plugin)
 {
     $builder->getCredentials()->willReturn(['some builder credentials']);
     $factory->create(['some builder credentials'])->shouldBeCalled()->willReturn($plugin);
     $client->addSubscriber($plugin)->shouldBeCalled();
     $this->secureClient($client, $builder);
 }
Exemple #26
0
 /**
  * @return \DOMDocument
  */
 public function getDocument()
 {
     $request = $this->client->get($this->url);
     $this->response = $request->send();
     $this->setHtml($this->response->getBody(true));
     return parent::getDocument();
 }
 protected function _fetchById($id, $options)
 {
     $settings = craft()->plugins->getPlugin('weather')->getSettings();
     try {
         $client = new Client('http://api.openweathermap.org');
         foreach ($options as $key => $value) {
             $client->setDefaultOption("query/{$key}", $value);
         }
         if (isset($settings->apiKey) && strlen($settings->apiKey) > 0) {
             $client->setDefaultOption('query/APPID', $settings->apiKey);
         }
         $client->setDefaultOption('query/id', $id);
         $request = $client->get('/data/2.5/weather', array('$e'));
         $response = $request->send();
     } catch (CurlException $e) {
         WeatherPlugin::log("Connection error to Open Weather Maps API", LogLevel::Error);
         return false;
     }
     if ($response->isSuccessful()) {
         $data = $response->json();
         if ($data['cod'] == 200) {
             return $data;
         } else {
             WeatherPlugin::log("Error: {$data['message']}", LogLevel::Error);
             return false;
         }
     }
 }
 public function store(Request $request)
 {
     // validate indata
     /*
      * - ClientId
      * - ShipToCompany (semi required)
      * - ShipToFirstname (semi required)
      * - ShipToLastname (semi required)
      * - ShipToAddress (required)
      * - ShipToAddress2
      * - ShipToPostalCode (required)
      * - ShipToCity (required)
      * - ShipToCountry [Lista på svenska]
      * - ShipToEmail
      * - ShipToPhone
      * - ShipToFax
      * - Text1 [Eget fält]
      * - QuantityARTIKELNR1 [ARTIKELNR1 byts ut mot artikelnr?] numeric
      * - ItemIdentifier [Skicka artikelnr som värde]
      */
     $this->validate($request, ['ClientId' => 'required', 'ShipToCompany' => 'required_without:ShipToFirstname,ShipToLastname', 'ShipToFirstname' => 'required_without:ShipToCompany', 'ShipToLastname' => 'required_without:ShipToCompany', 'ShipToAddress' => 'required', 'ShipToAddress2' => '', 'ShipToPostalCode' => 'required', 'ShipToCity' => 'required', 'ShipToCountry' => 'required', 'ShipToEmail' => '', 'ShipToPhone' => '', 'ShipToFax' => '', 'Text1' => '', 'Quantity[*]' => '', 'ItemIdentifier' => '']);
     // posta till http://linabews.lxir.se/order13.asp
     $client = new Client(getenv('NORDICGATEWAY_ENDPOINT'));
     $request = $client->post('order13.asp', null, $request->all())->send();
     return $request->getStatusCode();
 }
 public function onRenderShoppingComplete()
 {
     $app = $this->app;
     $orderId = $app['session']->get('eccube.front.shopping.order.id');
     if (!$orderId) {
         $app->log('onRenderShoppingComplete event orderId not found', array(), Logger::ERROR);
         return;
     }
     $Order = $app['eccube.repository.order']->find($orderId);
     if (!$Order) {
         $app->log('onRenderShoppingComplete event Order not found', array(), Logger::ERROR);
         return;
     }
     $FreeeLight = $app['eccube.plugin.repository.freeelight']->find(1);
     if (!$FreeeLight && !$FreeeLight->getCompanyId()) {
         $app->log('onRenderShoppingComplete event Freee not setup', array(), Logger::ERROR);
         return;
     }
     $OAuth2 = $app['eccube.plugin.repository.freee_oauth2']->find(FreeeOAuth2::DEFAULT_ID);
     if (!$OAuth2) {
         $app->log('onRenderShoppingComplete event Freee OAuth2 unauthorization', array(), Logger::ERROR);
         return;
     }
     $client = new Client('https://api.freee.co.jp');
     if ($OAuth2->isExpire()) {
         $params = array('grant_type' => 'refresh_token', 'client_id' => $FreeeLight->getClientId(), 'client_secret' => $FreeeLight->getClientSecret(), 'refresh_token' => $OAuth2->getRefreshToken());
         $data = $client->post('/oauth/token?grant_type=refresh_token', array(), $params)->send()->json();
         $OAuth2->setPropertiesFromArray($data);
         $app['orm.em']->flush();
     } else {
         $app['session']->set('access_token', 'not expire');
     }
     $AccountItem = $app['eccube.plugin.repository.freee_account_item']->findOneBy(array('name' => '売掛金'));
     $Tax = $app['eccube.plugin.repository.freee_tax']->findOneBy(array('name' => 'sales_with_tax_8'));
     $Wallet = $app['eccube.plugin.repository.freee_wallet']->findOneBy(array('name' => '現金'));
     $client = new Client('https://api.freee.co.jp');
     $detail = new \StdClass();
     $detail->account_item_id = $AccountItem->getId();
     $detail->tax_code = $Tax->getCode();
     $detail->amount = $Order->getPaymentTotal();
     $detail->item_id = null;
     $detail->section_id = null;
     $detail->tag_ids = array();
     $detail->description = "";
     $payment = new \StdClass();
     $payment->date = date('Y-m-d');
     $payment->from_walletable_type = $Wallet->getType();
     $payment->from_walletable_id = $Wallet->getId();
     $payment->amount = $Order->getPaymentTotal();
     $params = array("company_id" => $FreeeLight->getCompanyId(), "issue_date" => date('Y-m-d'), "due_date" => null, "type" => "income", "partner_id" => null, "ref_number" => $Order->getId(), "details" => array($detail), "payments" => array());
     $app['session']->set('complete_params', json_encode($params));
     try {
         $request = $client->post('/api/1/deals.json', array('Authorization' => 'Bearer ' . $OAuth2->getAccessToken(), 'content-type' => 'application/json'), array());
         $request->setBody(json_encode($params));
         $result = $request->send()->json();
         $app['session']->set('complete', $result);
     } catch (\Exception $e) {
         $app->log($e->getMessage(), array(), Logger::ERROR);
     }
 }
Exemple #30
0
 /**
  * @dataProvider cbProvider
  */
 public function testResponse($expectedStatusCode, $expectedResponseContent, $request, $testCase, $testHeaders)
 {
     $signature = sha1($request . self::PROJECT_SECRET_KEY);
     if ($testHeaders) {
         $headers = $testHeaders;
     } else {
         $headers = array('Authorization' => 'Signature ' . $signature);
     }
     $request = self::$httpClient->post('/webhook_server.php?test_case=' . $testCase, $headers, $request);
     try {
         $response = $request->send();
     } catch (BadResponseException $e) {
         $response = $e->getResponse();
     }
     static::assertSame($expectedResponseContent, $response->getBody(true));
     static::assertSame($expectedStatusCode, $response->getStatusCode());
     static::assertArrayHasKey('x-xsolla-sdk', $response->getHeaders());
     static::assertSame(Version::getVersion(), (string) $response->getHeader('x-xsolla-sdk'));
     static::assertArrayHasKey('content-type', $response->getHeaders());
     if (Response::HTTP_NO_CONTENT === $response->getStatusCode()) {
         static::assertStringStartsWith('text/plain', (string) $response->getHeader('content-type'));
     } else {
         static::assertStringStartsWith('application/json', (string) $response->getHeader('content-type'));
     }
 }