Since: 2.0
Author: Paul Klimov (klimov.paul@gmail.com)
Inheritance: extends yii\base\Component
Esempio n. 1
0
 public function updateWeather()
 {
     $client = new Client();
     $response = $client->get('http://api.wunderground.com/api/fa62a2e2278b3297/conditions/q/PL/Lublin.json')->send();
     if ($response->isOk) {
         $currentObs = $response->data['current_observation'];
         if (isset($currentObs['temp_c'])) {
             $this->temperature = $currentObs['temp_c'];
         }
         if (isset($currentObs['pressure_mb'])) {
             $this->pressure = $currentObs['pressure_mb'];
         }
         if (isset($currentObs['wind_kph'])) {
             $this->wind_speed = $currentObs['wind_kph'];
         }
         if (isset($currentObs['icon'])) {
             $this->conditions = $currentObs['icon'];
         }
         if (isset($currentObs['pressure_trend'])) {
             $this->pressure_trend = $currentObs['pressure_trend'];
         }
         if (isset($currentObs['observation_epoch'])) {
             $this->update_time = $currentObs['observation_epoch'];
         }
         if (isset($currentObs['feelslike_c'])) {
             $this->feels_like = $currentObs['feelslike_c'];
         }
         $this->save();
         return true;
     } else {
         return false;
     }
 }
Esempio n. 2
0
 /**
  * Initializes a new request.
  * @param string $url relative url to request.
  * @param array $options HTTP request options. Keys: query, data, headers, options
  * @return \yii\httpclient\Request
  */
 protected function initRequest($url, $options = [])
 {
     $client = new Client(['baseUrl' => self::API_BASE_URL . '/v' . $this->version, 'responseConfig' => ['format' => Client::FORMAT_JSON]]);
     $request = $client->createRequest();
     if (isset($options['data'])) {
         $request->setMethod('post');
         $request->setData($options['data']);
     }
     if (!empty($options['headers'])) {
         $request->setHeaders($options['headers']);
     }
     if (!empty($options['options'])) {
         $request->setOptions($options['options']);
     }
     if (isset($options['query'])) {
         $url_parts = parse_url($url);
         if (isset($url_parts['query'])) {
             $query = $url_parts['query'];
             if (strlen($query) > 0) {
                 $query .= '&';
             }
             $query .= http_build_query($options['query']);
             $url = str_replace($url_parts['query'], $query, $url);
         } else {
             $url_parts['query'] = $options['query'];
             $new_query = http_build_query($url_parts['query']);
             $url .= '?' . $new_query;
         }
     }
     $request->setUrl($url);
     return $request;
 }
 /**
  * @inheritDoc
  */
 public function export()
 {
     $response = $this->httpClient->post($this->webhookUrl, Json::encode($this->getPayload()), ['Content-Type: application/json; charset=UTF-8'])->send();
     if (!$response->getIsOk()) {
         throw new InvalidValueException("Unable to send logs to Slack: {$response->getContent()}", (int) $response->getStatusCode());
     }
 }
Esempio n. 4
0
 /**
  * @param array $data
  * @param string $method
  *
  * @return ApiResponseOk|ApiResponseError
  */
 private function _send(array $data, $method = 'post')
 {
     $client = new Client(['requestConfig' => ['format' => Client::FORMAT_JSON]]);
     $response = $client->createRequest()->setMethod($method)->setUrl($this->url)->addHeaders(['Content-type' => 'application/json'])->addHeaders(['user-agent' => 'JSON-RPC PHP Client'])->setData($data)->setOptions(['timeout' => $this->timeout])->send();
     //Нам сказали это всегда json. А... нет, все мы люди, бывает и не json )
     try {
         $dataResponse = (array) Json::decode($response->content);
     } catch (\Exception $e) {
         \Yii::error("Json api response error: " . $e->getMessage() . ". Response: \n{$response->content}", self::className());
         //Лайф хак, вдруг разработчики апи оставили var dump
         if ($pos = strpos($response->content, "{")) {
             $content = StringHelper::substr($response->content, $pos, StringHelper::strlen($response->content));
             try {
                 $dataResponse = (array) Json::decode($content);
             } catch (\Exception $e) {
                 \Yii::error("Api response error: " . $response->content, self::className());
             }
         }
     }
     if (!$response->isOk) {
         \Yii::error($response->content, self::className());
         $responseObject = new ApiResponseError($dataResponse);
     } else {
         $responseObject = new ApiResponseOk($dataResponse);
     }
     $responseObject->statusCode = $response->statusCode;
     return $responseObject;
 }
Esempio n. 5
0
 private function _getXML()
 {
     $client = new Client();
     $response = $client->get($this->url)->send();
     if ($response->isOk) {
         return $response->data['channel'];
     } else {
         return false;
     }
 }
 /**
  * @return \yii\httpclient\Client
  */
 public function getHttpClient()
 {
     if (!is_object($this->_httpClient)) {
         $this->_httpClient = Instance::ensure($this->_httpClient, Client::className());
     }
     return $this->_httpClient;
 }
 private function getRemoteRates()
 {
     /**
      * uploading rates from European Central Bank
      */
     $client = new Client();
     $response = $client->createRequest()->setMethod('get')->setFormat(Client::FORMAT_XML)->setUrl(self::RATES_XML_URL)->send();
     $this->xml = $response;
     $currency = new Currency(['code' => 'EUR', 'rateToEur' => 1]);
     $this->rates[$currency->code] = $currency;
     foreach ($response->data['Cube']['Cube']['Cube'] as $k => $v) {
         $currency = new Currency();
         $currency->code = (string) $v['currency'];
         $currency->rateToEur = (double) $v['rate'];
         $this->rates[$currency->code] = $currency;
     }
     //foreach
 }
Esempio n. 8
0
 /**
  * Sends the specified message.
  * This method should be implemented by child classes with the actual email sending logic.
  * @param Message $message the message to be sent
  * @return boolean whether the message is sent successfully
  */
 protected function sendMessage($message)
 {
     $request = $this->httpclient->post($this->getUrl(), ['from' => $this->normalizeAddress($message->getFrom()), 'to' => $this->normalizeAddress($message->getTo()), 'cc' => $this->normalizeAddress($message->getCc()), 'bcc' => $this->normalizeAddress($message->getBcc()), 'subject' => $message->getSubject(), 'text' => $message->getTextBody(), 'html' => $message->getHtmlBody()], ['Authorization' => 'Basic ' . base64_encode('api:' . $this->apiKey)]);
     $response = $request->send();
     if ($response->getIsOk()) {
         return true;
     } else {
         try {
             $data = Json::decode($response->content);
             if (!isset($data['message'])) {
                 throw new InvalidParamException("'message' field in response data is not set");
             }
         } catch (InvalidParamException $e) {
             throw new MailerException("Invalid response from Mailgun API", 0, $e);
         }
         throw new MailerException("Mailgun sending error: {$data['message']}");
     }
 }
Esempio n. 9
0
    /**
     * 拼装申报数据并返回响应结果
     * $data 原生数据
    */
    private function response($data, $url){
    	//echo $url;
        $basic = $this->basicData();

        $array = array_merge($basic, $data);
        $EData = json_encode($array); // 原生数据
        $client = new Client();
        $response = $client->createRequest()
            ->setMethod('post')
            ->setUrl($url)
            ->setData(['EData' => $EData])
            ->send();

        if ($response->isOk) {
            $res = json_decode($response->content);
            return $res;
        }
    }
Esempio n. 10
0
 public function query($url, $data)
 {
     $client = new Client(['baseUrl' => $this->baseUrl]);
     $response = $client->post($url, $data, ['Authorization' => 'Token ' . $this->token, 'X-Secret' => $this->secret])->setFormat(Client::FORMAT_JSON)->send();
     if ($response->isOk) {
         return $response->data;
     } else {
         print_r($response);
     }
     return false;
 }
 /**
  * Private method to send request for all methods
  * @param $url
  * @param $params
  * @param string $format
  * @return Response
  */
 private function _send($url, $params, $format = 'post')
 {
     $data = ArrayHelper::merge(['login' => $this->login, 'pass' => $this->pass], $params);
     return $this->_client->createRequest()->setUrl($url)->setMethod($format)->setData($data)->send();
 }
Esempio n. 12
0
 /**
  * @return Client
  */
 public function getServiceHttpClient()
 {
     $this->preProcessConfigurableItem('serviceHttpClient', Client::className());
     return $this->serviceHttpClient;
 }
Esempio n. 13
0
 public function send($text = null, $icon = null, $attachments = [])
 {
     $this->httpclient->post($this->url, ['payload' => Json::encode($this->getPayload($text, $icon, $attachments))]);
 }
Esempio n. 14
0
 /**
  * Send a message to slack
  * @param string $text message text
  * @param string $emoji emoji icon
  * @param array $attachments attachments (@see https://api.slack.com/incoming-webhooks)
  * @param string $channel channel to send to
  */
 public function send($text = null, $emoji = null, $attachments = [], $channel = null)
 {
     $this->httpclient->post($this->url, ['payload' => Json::encode($this->getPayload($text, $emoji, $attachments, $channel))])->send();
 }
Esempio n. 15
0
 private function send($url, $data)
 {
     $params = ArrayHelper::merge(['login' => $this->login, 'pass' => $this->pass], $data);
     return $this->_client->get($url, $params)->send();
 }
Esempio n. 16
0
 public function query($url, $data)
 {
     $client = new Client(['baseUrl' => self::$baseUrl]);
     $response = $client->post($url, $data, ['Authorization' => 'Token 1d06237cf740861ef28bcfd9fa3994097c1b50b5', 'X-Secret' => self::$token])->setFormat(Client::FORMAT_JSON)->send();
     if ($response->isOk) {
         return $response->data;
     }
     return false;
 }
Esempio n. 17
0
 /**
  * Creates HTTP client instance from reference or configuration.
  * @param string|array $reference component name or array configuration.
  * @return Client HTTP client instance.
  * @since 2.1
  */
 protected function createHttpClient($reference)
 {
     return Instance::ensure($reference, Client::className());
 }
Esempio n. 18
0
 public static function request($url, $params = array(), $requestMethod = 'get')
 {
     $client = new Client();
     $response = $client->createRequest()->setMethod($requestMethod)->setUrl($url)->setData($params)->send();
     if ($response->isOk) {
         return $response->content;
     } else {
         return null;
     }
 }
Esempio n. 19
0
 /**
  * Initializes a new request.
  * @param array $options HTTP post data
  * @return \yii\httpclient\Request
  */
 protected function initRequest($options = [])
 {
     $client = new Client(['requestConfig' => ['format' => Client::FORMAT_JSON]]);
     $request = $client->createRequest()->setMethod('post')->setUrl(self::BASE_URL)->setData($options)->setHeaders(['Authorization' => 'key=' . $this->_apiKey]);
     return $request;
 }
Esempio n. 20
0
use romkaChev\yandexFotki\models\AlbumPhotosCollection;
use romkaChev\yandexFotki\models\AlbumsCollection;
use romkaChev\yandexFotki\models\Author;
use romkaChev\yandexFotki\models\Image;
use romkaChev\yandexFotki\models\options\album\CreateAlbumOptions;
use romkaChev\yandexFotki\models\options\album\DeleteAlbumOptions;
use romkaChev\yandexFotki\models\options\album\GetAlbumPhotosOptions;
use romkaChev\yandexFotki\models\options\album\GetAlbumsOptions;
use romkaChev\yandexFotki\models\options\album\UpdateAlbumOptions;
use romkaChev\yandexFotki\models\options\photo\CreatePhotoOptions;
use romkaChev\yandexFotki\models\options\photo\DeletePhotoOptions;
use romkaChev\yandexFotki\models\options\photo\UpdatePhotoOptions;
use romkaChev\yandexFotki\models\options\tag\DeleteTagOptions;
use romkaChev\yandexFotki\models\options\tag\GetTagPhotosOptions;
use romkaChev\yandexFotki\models\options\tag\UpdateTagOptions;
use romkaChev\yandexFotki\models\Photo;
use romkaChev\yandexFotki\models\Point;
use romkaChev\yandexFotki\models\Tag;
use romkaChev\yandexFotki\models\TagPhotosCollection;
use romkaChev\yandexFotki\validators\AddressBindingValidator;
use romkaChev\yandexFotki\validators\AlbumValidator;
use romkaChev\yandexFotki\validators\AuthorValidator;
use romkaChev\yandexFotki\validators\ImageValidator;
use romkaChev\yandexFotki\validators\PhotoValidator;
use romkaChev\yandexFotki\validators\PointValidator;
use romkaChev\yandexFotki\validators\TagValidator;
use romkaChev\yandexFotki\YandexFotki;
use yii\httpclient\Client;
use yii\i18n\Formatter;
return ['id' => 'testApp', 'basePath' => __DIR__, 'vendorPath' => __DIR__ . '/../../../vendor', 'aliases' => ['@web' => '/', '@webroot' => __DIR__ . '/../runtime', '@vendor' => __DIR__ . '/../../../vendor'], 'components' => ['yandexFotki' => ['class' => YandexFotki::className(), 'apiBaseUrl' => 'http://api-fotki.yandex.ru/api', 'serviceBaseUrl' => 'http://fotki.yandex.ru', 'login' => null, 'oauthToken' => null, 'apiHttpClient' => Client::className(), 'serviceHttpClient' => Client::className(), 'albums' => AlbumComponent::className(), 'photos' => PhotoComponent::className(), 'tags' => TagComponent::className(), 'formatter' => Formatter::className(), 'factory' => ['class' => Factory::className(), 'addressBindingModel' => AddressBinding::className(), 'albumModel' => Album::className(), 'albumsCollectionModel' => AlbumsCollection::className(), 'albumPhotosCollectionModel' => AlbumPhotosCollection::className(), 'authorModel' => Author::className(), 'photoModel' => Photo::className(), 'tagModel' => Tag::className(), 'tagPhotosCollectionModel' => TagPhotosCollection::className(), 'pointModel' => Point::className(), 'imageModel' => Image::className(), 'getAlbumsOptions' => GetAlbumsOptions::className(), 'getAlbumPhotosOptions' => GetAlbumPhotosOptions::className(), 'createAlbumOptions' => CreateAlbumOptions::className(), 'updateAlbumOptions' => UpdateAlbumOptions::className(), 'deleteAlbumOptions' => DeleteAlbumOptions::className(), 'createPhotoOptions' => CreatePhotoOptions::className(), 'updatePhotoOptions' => UpdatePhotoOptions::className(), 'deletePhotoOptions' => DeletePhotoOptions::className(), 'getTagPhotosOptions' => GetTagPhotosOptions::className(), 'updateTagOptions' => UpdateTagOptions::className(), 'deleteTagOptions' => DeleteTagOptions::className(), 'addressBindingValidator' => AddressBindingValidator::className(), 'albumValidator' => AlbumValidator::className(), 'authorValidator' => AuthorValidator::className(), 'pointValidator' => PointValidator::className(), 'photoValidator' => PhotoValidator::className(), 'imageValidator' => ImageValidator::className(), 'tagValidator' => TagValidator::className()]]]];