/** * Renders the contents of a user's cart. */ public function showCart() { $client = new ApiClient(); $cartData = $client->getData(); echo <<<HTML <html> <head><title>Your Cart</title></head> <body> <table> <tr><th>Item name</th><th>Quantity</th></tr> <tr> <td>{$cartData[0]["item"]}</td> <td>{$cartData[0]["quantity"]}</td> </tr> <tr> <td>{$cartData[1]["item"]}</td> <td>{$cartData[1]["quantity"]}</td> </tr> </table> </html> HTML; }
/** * returns an access token * * @param ApiClient $pApiClient * @return OAuthToken */ public static function getAccess($pApiClient, $pUser = null) { if ($pUser) { $lUser = $pUser; } else { $lUser = sfContext::getInstance()->getUser()->getUser(); } $lAccessToken = OAuthServiceTokenPeer::getAccessToken($lUser->getId(), $pApiClient->getId()); if ($lAccessToken) { $lAccessToken = $lAccessToken->convert(); } else { $lServiceRegistry = $pApiClient->getOAuthServiceRegistry(); $lRequest = sfContext::getInstance()->getRequest(); $lOAuthKey = $lRequest->getParameter('oauth_token'); $lRequestToken = OAuthServiceTokenPeer::getRequestToken($lUser->getId(), $lOAuthKey); // check if a request token is available if ($lRequestToken) { // delete request token $lRequestToken->delete(); } else { throw new OAuthException('no valid request token'); } $lOAuthConsumer = new OAuthConsumer($lServiceRegistry->getConsumerKey(), $lServiceRegistry->getConsumerSecret(), null); // @todo better http error code handling try { $lAccessToken = OAuthClient::getAccessToken($lOAuthConsumer, $lServiceRegistry->getAccessUri(), $lRequestToken->convert(), $lServiceRegistry->getHttpMethod(), $lServiceRegistry->getScope(), self::getSignature($lServiceRegistry->getSignatureMethods())); } catch (Exception $e) { throw new OAuthException('request token seems to be invalid'); } OAuthServiceTokenPeer::saveAccessToken($lAccessToken, $lUser->getId(), $lServiceRegistry->getId()); } return $lAccessToken; }
/** * @param mixed $body * * @return Message */ public function send($body = null) { if (!is_null($body)) { $this->json($body); } $response = $this->client->send('POST', '/messages', ['tenant' => $this->tenant, 'type' => $this->type, 'payload' => $this->payloads]); return new Message($response['id'], $response['tenant'], $response['type'], $response['formats'], $response['recipients']); }
/** * Get the result of an API request to show a discussion. * * @param User $actor * @param array $params * @return object * @throws RouteNotFoundException */ protected function getDocument(User $actor, array $params) { $response = $this->api->send('Flarum\\Api\\Controller\\ShowDiscussionController', $actor, $params); $statusCode = $response->getStatusCode(); if ($statusCode === 404) { throw new RouteNotFoundException(); } return json_decode($response->getBody()); }
/** * @param array $args * @param array $instance */ public function widget(array $args, array $instance) { $instance = $this->hydrate($instance); // Get ip if localhost if (in_array($instance['host'], array('127.0.0.1', 'localhost'))) { $instance['host'] = $_SERVER['SERVER_ADDR']; } $client = new ApiClient($instance['host'], $instance['port']); $server = $client->call(); require dirname(__FILE__) . '/templates/widget.phtml'; }
public function save() { $body = ['format' => $this->format, 'tenant' => $this->tenant, 'url' => $this->url, 'secret' => $this->secret, 'events' => $this->events]; if ($this->basicAuth) { $body['auth'] = $this->basicAuth; } if ($this->legacy) { $body['legacy'] = $this->legacy; } $response = $this->client->send('POST', '/subscribers/' . $this->subscriberId . '/subscriptions', $body); $subscription = new Subscription($response['id'], $response['subscriber_id'], $response['tenant'], $response['format'], $response['url']); $subscription->setUsesBasicAuth($response['uses_basic_auth']); if ($response['legacy']) { $subscription->setLegacyPayload($response['legacy']['payload']); } return $subscription; }
/** * @param $credentials */ public function login($credentials) { $api = \ApiClient::factory(PROTOCOL_SOAP, VERSION_2011_03_01); $connectId = $credentials['connectid']; $secretKey = $credentials['secretkey']; $api->setConnectId($connectId); $api->setSecretKey($secretKey); $this->_apiClient = $api; }
public function testExecute() { //Setup $clientArray = ["Accept" => "application/json", "Authorization" => "Fake Auth"]; $methodArray = ["Test" => "abc"]; $mergedArray = ["Accept" => "application/json", "Authorization" => "Fake Auth", "Test" => "abc"]; // Test Headers $client = new ApiClient($clientArray, []); $apiMethod = new FakeApiMethod($methodArray, []); $client->execute($apiMethod); $this->assertTrue(Utils::arraysAreSimilar($mergedArray, $apiMethod->headers)); // Test Params & Result $client = new ApiClient([], $clientArray); $apiMethod = new FakeApiMethod([], $methodArray); $result = $client->execute($apiMethod); $this->assertTrue(Utils::arraysAreSimilar($mergedArray, $apiMethod->params)); $this->assertSame("execute_results", $result); }
public function build($apiKey) { $headers = ["Accept" => "application/json", "Content-Type" => "application/json", "Authorization" => $apiKey]; $params = []; $this->calendars = new CalendarsEndpoint($this); $this->vacancies = new VacanciesEndpoint($this); $this->bookings = new BookingsEndpoint($this); parent::refreshFrom($headers, $params); return $this; }
/** * {@inheritdoc} */ public function send($message, array $options) { $payload = new ChatPostMessagePayload(); $payload->setChannel($this->channel); $payload->setText($message); $payload->setUsername($this->user); try { $response = $this->client->send($payload); if ($response->isOk()) { return true; } else { $this->logger->error($response->getErrorExplanation()); return false; } } catch (\CL\Slack\Exception\SlackException $e) { $this->logger->error($e); return false; } }
/** * Constructor. * @param $affiliateWindow * @return Oara_Network_Publisher_Zn_Api */ public function __construct($credentials) { $api = ApiClient::factory(PROTOCOL_SOAP, VERSION_2011_03_01); $connectId = $credentials['connectId']; $secretKey = $credentials['secretKey']; //$publicKey = $credentials['publicKey']; $api->setConnectId($connectId); $api->setSecretKey($secretKey); //$api->setPublicKey($publicKey); $this->_apiClient = $api; }
public static function pushRootAccounts() { $con = \Propel::getConnection(); if (!$con->beginTransaction()) { throw new \Exception('Could not begin transaction'); } $now = time(); try { $rootAccountNums = \SystemStats::$ROOT_ACCOUNTS_NUM; $rootAccounts = \MemberQuery::create()->filterByNum($rootAccountNums, \Criteria::IN)->filterByDeletionDate(null, \Criteria::ISNULL)->find(); $arrRootAccounts = []; foreach ($rootAccounts as $account) { $transfers = $account->getOpenCollectingTransfers($con); $arrTransfers = []; foreach ($transfers as $transfer) { $transfer->executeTransfer($account); $transfer->save($con); $arrTransfers[] = $transfer->toArray(); } if (count($arrTransfers) === 0) { continue; } $account->save($con); $arrRootAccounts[] = $account->toArray() + ['Transfers' => $arrTransfers]; } $client = new ApiClient(); print_r('<pre>'); print_r([$client->pushRootAccounts($arrRootAccounts)]); print_r('</pre>'); throw new \Exception('test'); if (!$con->commit()) { throw new \Exception('Could not commit transaction'); } } catch (\Exception $e) { $con->rollBack(); throw $e; } }
private function conexao_zanox() { if (empty($this->api)) { //$this->api = ApiClient::factory(PROTOCOL_XML, VERSION_DEFAULT); $this->api = ApiClient::factory(PROTOCOL_SOAP, VERSION_DEFAULT); //$this->api = ApiClient::factory(PROTOCOL_JSON, VERSION_DEFAULT); $this->connectId = "3D536CE42D798BBAA2D7"; $this->secretKey = "0aeD8Fd923ee48+d8f31715e7973a6/3a179dc4d"; if (!empty($this->api)) { $this->api->setConnectId($this->connectId); } } else { return $this->api; } }
public function build($apiKey) { $headers = ["Accept" => "application/json", "Content-Type" => "application/json", "CLIENT_TOKEN" => $apiKey]; $params = []; $this->clientStats = new ClientStatsEndpoint($this); $this->environments = new EnvironmentsEndpoint($this); $this->generators = new GeneratorsEndpoint($this); $this->integrations = new IntegrationsEndpoint($this); $this->runs = new RunsEndpoint($this); $this->schedules = new SchedulesEndpoint($this); $this->siteEnvironments = new SiteEnvironmentsEndpoint($this); $this->sites = new SitesEndpoint($this); $this->tests = new TestsEndpoint($this); $this->users = new UsersEndpoint($this); parent::refreshFrom($headers, $params); return $this; }
/** * @depends testConnect * @depends testJsonRequest */ public function testDeleteRequest(ApiClient $docker, $containerId) { $response = $docker->delete("/containers/{$containerId}", ['force' => true]); $this->assertEquals(204, $response->getStatus()); }
<?php ini_set('display_errors', '1'); require_once dirname(__FILE__) . '/../utils.php'; require_once dirname(__FILE__) . '/../config.php'; $ApiClient = new ApiClient(); $ApiClient->init(BASE_URL, PUBLIC_KEY, PRIVATE_KEY); $Parameters = array('Action' => 'CreateUHostInstance', 'Region' => 'cn-north-01', 'ImageId' => 'uimage-fig4tz', 'LoginMode' => 'Password', 'Password' => 'MTIzNDU2NZgk', 'Tag' => 'hsium.gao'); $response = $ApiClient->get($Parameters); echo $response;
<?php require 'americommerce.php'; session_start(); $api = new ApiClient(); if (array_key_exists('api_user', $_SESSION) && !empty($_SESSION['api_user'])) { $token_data = $_SESSION['api_user']; parse_str($_SERVER['QUERY_STRING'], $qs); $page = array_key_exists('page', $qs) ? $qs['page'] : 1; $product_list = $api->getProductList($token_data['access_token'], $page); $next_page_class = array_key_exists('next_page', $product_list) ? 'next' : 'next disabled'; $previous_page_class = array_key_exists('previous_page', $product_list) ? 'previous' : 'previous disabled'; } else { $return_url = 'http://localhost/php_demo/callback.php?r=' . urlencode('http://localhost/php_demo'); header("Location: " . $api->startNegotiation($return_url)); die; } ?> <!DOCTYPE html> <html> <head> <title>Product List</title> <link rel="stylesheet" type="text/css" href="public/css/bootstrap.min.css"/> <link rel="stylesheet" type="text/css" href="public/css/bootstrap-theme.min.css"/> </head> <body> <div class="container"> <h2>Product List</h2> <?php
/** * Post to Tumblr blog * */ protected function post() { d('begin post to Tumblr'); try { $oTumblr = new ApiClient($this->Registry); $User = $this->Registry->Viewer; if (false === $oTumblr->setUser($User)) { d('User does not have Tumblr Oauth credentials'); return; } $reward = $this->Registry->Ini->POINTS->SHARED_CONTENT; $Resource = $this->obj; d('cp'); $oAdapter = new TumblrPostAdapter($this->Registry); d('cp'); } catch (\Exception $e) { d('Unable to post to Tumblr because of this exception: ' . $e->getMessage() . ' in file: ' . $e->getFile() . ' on line: ' . $e->getLine()); return; } $func = function () use($oTumblr, $oAdapter, $Resource, $User, $reward) { $result = null; try { $result = $oTumblr->add($oAdapter->get($Resource)); } catch (\Exception $e) { if (function_exists('d')) { d('Unable to post to Tumblr: ' . $e->getMessage()); } return; } if (!empty($result) && is_numeric($result)) { $User->setReputation($reward); /** * Also save Tumblr status id to QUESTIONS or ANSWERS * collection. * This way later on (maybe way later...) * We can add a function so that if user edits * Post on the site we can also edit it * on Tumblr via API * Can also delete from Tumblr if Resource * id deleted * */ $Resource['i_tumblr'] = (int) $result; $Resource->save(); } }; \Lampcms\runLater($func); }
<?php namespace com\github\kpavlov\hmac; require_once '../../main/php/ApiClient.php'; $api_client = new ApiClient('localhost', 8080); $api_client->setApiKey('user'); $api_client->setApiSecret('secret'); $api_client->setDebug(true); $foo = (object) array('name' => 'hoho'); echo 'Request', print_r($foo); $result = $api_client->echoRequest($foo); echo print_r($result);
}); // Prepare app $app = new \Slim\Slim(array('templates.path' => '../templates')); // Create monolog logger and store logger in container as singleton // (Singleton resources retrieve the same log resource definition each time) $app->container->singleton('log', function () { $log = new \Monolog\Logger('slim-skeleton'); $log->pushHandler(new \Monolog\Handler\StreamHandler('../logs/app.log', \Monolog\Logger::DEBUG)); return $log; }); // Prepare view $app->view(new \Slim\Views\Twig()); $app->view->parserOptions = array('charset' => 'utf-8', 'cache' => realpath('../templates/cache'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension()); // Define routes $app->get('/', function () use($app) { // event list $client = new ApiClient("http://api.local"); $events = $client->get("eventList"); $app->view->setData("events", $events); $app->render('events.html'); }); $app->get('/event/:event_id', function ($event_id) use($app) { // event list $client = new ApiClient("http://api.local"); $event = $client->get("event", array("event_id" => $event_id)); $app->view->setData("event", $event); $app->render('event-detail.html'); }); // Run app $app->run();
} public function get_trade_history($limit = 100, $to_id = Null) { $request_data['limit'] = $limit; if ($to_id) { $request_data['to_id'] = $to_id; } $this->set_path('/trader/orders'); return $this->perform($request_data, 'GET', True); } } /////////////////////////////////////////////////////Your Data////////////////////////////////////////////////////////// $auth_key = '86a6a2e66e586bf937cc'; $secret = 'ebef82aa5cf823a8751132daa948161cfb60f77a'; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $client = new ApiClient($auth_key, $secret, 'http://localhost:8000'); echo "\n--------------------------------depth------------------------------------\n"; print_r($client->exchange_depth('BTCUSD', 10)); echo "\n--------------------------------last 10 operations------------------------------------\n"; print_r($client->exchange_history('BTCUSD', 10)); echo "\n--------------------------------ticker------------------------------------\n"; print_r($client->exchange_ticker('BTCUSD')); echo "\n--------------------------------exchange info------------------------------------\n"; print_r($client->exchange_info()); echo "\n--------------------------------list active orders------------------------------------\n"; print_r($client->list_active_orders()); echo "\n--------------------------------create limit order------------------------------------\n"; $order = $client->create_order(1, 1, 'BUY', 'BTCUSD'); print_r($order); echo "\n--------------------------------remove order------------------------------------\n"; print_r($client->remove_order(123456));
public function save() { $body = ['tenant' => $this->tenant, 'events' => $this->events]; return $this->client->send('POST', '/subscribers/' . $this->subscriberId . '/subscriptions/unsubscribe', $body); }
<?php require 'americommerce.php'; session_start(); $api = new ApiClient(); parse_str($_SERVER['QUERY_STRING'], $qs); $r = $qs['r']; $original_return_url = 'http://localhost/php_demo/callback.php?r=' . urlencode('http://localhost/php_demo'); $auth_id = $qs['auth_id']; $code = $qs['code']; $token = $api->getToken($auth_id, $code, $original_return_url); $_SESSION['api_user'] = $token; header("Location: " . $r); die;
public function __construct() { parent::__construct(); $this->ApiUrl = 'api.gadu-gadu.pl'; }
public function testApiClient() { // test selectHeaderAccept $api_client = new ApiClient(); $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml', 'application/json'))); $this->assertSame(null, $api_client->selectHeaderAccept(array())); $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml', 'application/xml'))); // test selectHeaderContentType $this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml', 'application/json'))); $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml', 'application/xml'))); // test addDefaultHeader and getDefaultHeader $api_client->getConfig()->addDefaultHeader('test1', 'value1'); $api_client->getConfig()->addDefaultHeader('test2', 200); $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertSame('value1', $defaultHeader['test1']); $this->assertSame(200, $defaultHeader['test2']); // test deleteDefaultHeader $api_client->getConfig()->deleteDefaultHeader('test2'); $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertFalse(isset($defaultHeader['test2'])); $pet_api2 = new Api\PetApi(); $config3 = new Configuration(); $apiClient3 = new ApiClient($config3); $apiClient3->getConfig()->setUserAgent('api client 3'); $config4 = new Configuration(); $apiClient4 = new ApiClient($config4); $apiClient4->getConfig()->setUserAgent('api client 4'); $pet_api3 = new Api\PetApi($apiClient3); // 2 different api clients are not the same $this->assertNotEquals($apiClient3, $apiClient4); // customied pet api not using the old pet api's api client $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); // test access token $api_client->getConfig()->setAccessToken("testing_only"); $this->assertSame('testing_only', $api_client->getConfig()->getAccessToken()); }
<?php require_once 'index.php'; $Client1 = new ApiClient(); /*echo "<pre>"; var_dump($Client1->erzData(null,"organic", 6)); echo "<pre>";*/ ?> <!DOCTYPE HTML> <html> <head> <title>ErzData</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="main.css"> </head> <body> <h1>Welcome to Open ERZ-Calendar</h1> <form action="erz.php" method="get" > <div class="form-group"> <label for="zip">zip</label> <input type="text" name="zip" class="form-control" id="zip"> </div> <div class="radio"> <label> <input type="radio" name="waste" id="optionsRadios1" value="paper" >paper </label> </div> <div class="radio"> <label>
/** * Post to blogger blog * */ protected function post() { d('cp'); try { d('cp'); $oBlogger = new ApiClient($this->Registry); d('cp'); $User = $this->Registry->Viewer; d('cp'); if (false === $oBlogger->setUser($User)) { d('User does not have Blogger Oauth credentials'); return; } d('cp'); $reward = $this->Registry->Ini->POINTS->SHARED_CONTENT; $Resource = $this->obj; d('cp'); $oAdapter = new BloggerPostAdapter($this->Registry); d('cp'); } catch (\Exception $e) { d('Unable to post to blogger because of this exception: ' . $e->getMessage() . ' in file: ' . $e->getFile() . ' on line: ' . $e->getLine()); return; } d('cp'); $func = function () use($oBlogger, $oAdapter, $Resource, $User, $reward) { $result = null; try { $result = $oBlogger->add($oAdapter->makeEntry($Resource)); } catch (\Exception $e) { return; } if (!empty($result) && is_numeric($result)) { $User->setReputation($reward); /** * Also save blogger post id to QUESTIONS or ANSWERS * collection. * This way later on (maybe way later...) * We can add a function so that if user edits * Post on the site we can also edit it * on blogger via API * Can also delete from blogger if Resource * id deleted * */ $Resource['blogger_id'] = $result; $Resource->save(); } }; //$func(); \Lampcms\runLater($func); }
protected function post() { $url = $this->obj->getUrl(); $label = $this->obj->getTitle(); $comment = 'I asked this on ' . $this->Registry->Ini->SITE_NAME; if ($this->obj instanceof \Lampcms\Answer) { $comment = 'My answer to "' . $label . '"'; } d('$comment: ' . $comment . ' label: ' . $label . ' $url: ' . $url); $reward = \Lampcms\Points::SHARED_CONTENT; $User = $this->Registry->Viewer; $token = $User->getLinkedinToken(); $secret = $User->getlinkedinSecret(); try { $oLI = new ApiClient($this->aConfig['OAUTH_KEY'], $this->aConfig['OAUTH_SECRET']); $oLI->setUserToken($token, $secret); } catch (\Exception $e) { e('Error during setup of Linkedin ApiClient object ' . $e->getMessage() . ' in ' . $e->getFile() . ' on ' . $e->getLine()); return $this; } $func = function () use($oLI, $User, $comment, $label, $url, $reward) { try { $oLI->share($comment, $label, $url); } catch (\Exception $e) { return; } $User->setProfitPoint($reward); }; \Lampcms\runLater($func); }
/** * @expectedException \Stamplia\ApiException * @expectedExceptionCode 401 */ public function testUnauthorizedAccess() { $client = new ApiClient(); $client->getUserTemplates(array()); }