public function call($method, $arguments) { $params = array("method" => $method, "functionOptions" => $arguments, "type" => "json"); $response = wp_remote_get(add_query_arg($params, 'http://api.e-goi.com/v2/rest.php')); if (is_wp_error($response) || $response['response']['code'] != 200) { $this->logger->error('Response: ' . print_r($response, true)); return; } $json = json_decode($response['body'], true); $map = $json['Egoi_Api'][$method]; $this->logger->debug('Response: ' . print_r($map, true)); $status = $map['status']; unset($map['status']); return $this->setMap($map); }
/** * Do actual HTTP request. * * @param string $method * @param string $url * @param string $body * @param array $headers * @return mixed */ protected function request($method, $url, $body = null, $headers = array()) { // Append URL to URL $url = add_query_arg(array('api_key' => $this->apiKey), $url); // Add authorization token to request headers $headers['Authorization'] = "Bearer " . $this->token; // Log method params $this->logger->info("URL: {$url}\n"); $this->logger->info("Method: {$method}\n"); $this->logger->info("Headers: " . print_r($headers, true) . "\n"); $this->logger->info("Body: " . print_r($body, true) . "\n"); switch ($method) { case 'put': $headers['Content-Type'] = 'application/json'; $response = wp_remote_request($url, array('method' => 'PUT', 'headers' => $headers, 'body' => $body)); break; case 'post': $headers['Content-Type'] = 'application/json'; $response = wp_remote_post($url, array('headers' => $headers, 'body' => $body)); break; default: $response = wp_remote_get($url, array('headers' => $headers, 'body' => $body)); break; } // Log error and throw exception if (is_wp_error($response)) { $this->logger->error("WP ERR: " . print_r($response, true) . "\n"); throw new Exception("Error when trying to connect to ConstantContact API"); } // Check if status 200 was received if (200 !== (int) wp_remote_retrieve_response_code($response)) { $this->logger->info("HTTP status error: " . print_r($response, true) . "\n"); } return $response; }
/** * @param String $url * @param String $requestType * @param Array $postData * @param Array $headers */ public function makeApiRequest($url = null, $requestType = 'GET', $postData = array(), $headers = array()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ($requestType == 'POST') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); } curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $data = curl_exec($ch); $this->logger->debug('Response: ' . print_r($data, true) . "\n"); $validResponseCodes = array(200, 201, 409); $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (curl_errno($ch)) { curl_close($ch); return curl_error($ch); } elseif (!in_array($responseCode, $validResponseCodes)) { if ($this->isJson($data)) { $data = json_decode($data); } } curl_close($ch); return $data; }
/** * @see OptimizePress_Modules_Email_ProviderInterface::register() */ public function register($list, $email, $fname, $lname) { $this->logger->info('Registering user: '******'first_name' => $fname, 'last_name' => $lname)); $this->logger->notice('Registration status: ' . print_r($status, true)); return true; }
/** * @see OptimizePress_Modules_Email_ProviderInterface::getItems() */ public function getItems() { $data = array('lists' => array()); $lists = $this->getLists(); foreach ($lists as $list) { $data['lists'][$list['listnum']] = array('name' => $list['title']); } $this->logger->info('Items: ' . print_r($data, true)); return $data; }
/** * @see OptimizePress_Modules_Email_ProviderInterface::getItems() */ public function getItems() { $data = array('lists' => array()); /* * List parsing */ $lists = $this->getLists(); foreach ($lists as $list) { $data['lists'][$list->id] = array('name' => $list->name); } $this->logger->info('Items: ' . print_r($data, true)); return $data; }
/** * @see OptimizePress_Modules_Email_ProviderInterface::getItems() */ public function getItems() { $data = array('lists' => array()); /* * List parsing */ $lists = $this->getLists(); if ($lists['total'] > 0) { foreach ($lists['data'] as $list) { $data['lists'][$list['id']] = array('name' => $list['name']); } } $this->logger->info('Items: ' . print_r($data, true)); return $data; }
/** * Request * * Make a request to the Office Auto Pilot XML Rest API * * @access private * @param $service (string) main API service URL * @param $reqType (string) which function to use * @param $data_xml (xml) the xml to send * @param $return_id (boolean) 1 returns full record(s) in addtion to the success/fail message. * 2 returns the contact id an date last modified in addtion to the success/fail message. * @param $f_add (boolean) when set, forces a new contact to be added (regardless if a contact with a matching email address is found). * Note: "Add" requests initialize this to true, "update" requests initialize it to false. * @return: object */ private function _request($service, $reqType, $data = FALSE, $return_id = FALSE, $f_add = FALSE) { $postargs = "Appid=" . $this->AppID . "&Key=" . $this->Key . "&reqType=" . $reqType . ($return_id ? '&return_id=2' : '&return_id=1') . ($data ? '&data=' . rawurlencode($data) : '') . ($f_add ? '&f_add=1' : ''); //print_r($postargs); $ch = curl_init($this->host . '/' . $service); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postargs); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $output = curl_exec($ch); curl_close($ch); $this->logger->debug('Response: ' . print_r($output, true) . "\n"); //DEBUG //print_r($output); //exit(); return !empty($output) ? new SimpleXMLElement($output) : FALSE; }
/** * Executes an API call * @param string $request JSON encoded array * @return object * @access private */ private function execute($request) { $handle = curl_init($this->apiURL); curl_setopt($handle, CURLOPT_POST, 1); curl_setopt($handle, CURLOPT_POSTFIELDS, $request); curl_setopt($handle, CURLOPT_HEADER, 'Content-type: application/json'); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); $response = json_decode(curl_exec($handle)); $this->logger->debug('Response: ' . print_r($response, true) . "\n"); if (curl_error($handle)) { trigger_error(curl_error($handle), E_USER_ERROR); } $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); if (!($httpCode == '200' || $httpCode == '204')) { trigger_error('API call failed. Server returned status code ' . $httpCode, E_USER_ERROR); } curl_close($handle); if (!$response->error) { return $response->result; } }
/** * HTTP request wrapped with wp_remote_get * @param string $action [description] * @param array $params [description] * @return mixed */ protected function request($action, array $params) { $this->logger->info("arpReach Request\n"); $this->logger->info("Action: {$action}\n"); $this->logger->info("Params: " . print_r($params, true) . "\n"); // Add API key to params stack $params['api_key'] = $this->apiKey; // Lets create request URL $url = add_query_arg($this->urlEncodeParams($params), trailingslashit($this->apiEndpoint) . 'api/' . $action); $this->logger->info("URL: {$url}\n"); $response = wp_remote_get($url); // Log error and throw exception if (is_wp_error($response)) { $this->logger->error("WP ERR: " . print_r($response, true) . "\n"); throw new Exception("Error when trying to connect to arpReach API"); } // Check if status 200 was received if (200 !== (int) wp_remote_retrieve_response_code($response)) { $this->logger->info("HTTP status error: " . print_r($response, true) . "\n"); } return $response; }
public function methodCaller($service, $callArray) { ###Set up the call### $call = new xmlrpcmsg($service, $callArray); ###Send the call### $result = $this->client->send($call); $this->logger->debug('Response: ' . print_r($result, true)); ###Check the returned value to see if it was successful and return it### if (!$result->faultCode()) { return $result->value(); } else { if ($this->debug == "kill") { die("ERROR: " . $result->faultCode() . " - " . $result->faultString()); } elseif ($this->debug == "on") { return "ERROR: " . $result->faultCode() . " - " . $result->faultString(); } elseif ($this->debug == "throw") { throw new iSDKException($result->faultString(), $result->faultCode()); } elseif ($this->debug == "off") { //ignore! } } }
/** * request * * Implemented for a standard OAuth adapter interface * @param mixed $method * @param mixed $uri * @param array $data * @param array $options * @access public * @return void */ public function request($method, $uri, $data = array(), $options = array()) { $uri = $this->app->removeBaseUri($uri); $url = $this->app->getBaseUri() . $uri; # WARNING: non-primative items in data must be json serialized in GET and POST. if ($method == 'POST' or $method == 'GET') { foreach ($data as $key => $value) { if (is_array($value)) { $data[$key] = json_encode($value); } } } $response = $this->makeRequest($method, $url, $data); $this->logger->debug('Response: ' . print_r($response, true)); if (!empty($options['return'])) { if ($options['return'] == 'status') { return $response->headers['Status-Code']; } if ($options['return'] == 'headers') { return $response->headers; } if ($options['return'] == 'integer') { return intval($response->body); } } $data = json_decode($response->body, true); while ($response->headers['Status-Code'] == 403 && $data['error']['type'] === 'RateLimitError') { sleep(5); $response = $this->makeRequest($method, $url, $data); $data = json_decode($response->body, true); } if (empty($options['allow_empty']) && !isset($data)) { throw new OP_AWeberResponseError($uri); } return $data; }
/** * @see OptimizePress_Modules_Email_ProviderInterface::getItems() */ public function getItems() { $data = $this->getData(); $this->logger->info('Items: ' . print_r($data, true)); return $data; }
/** * Actually connect to the server and call the requested methods, parsing the result * You should never have to call this function manually */ function callServer($method, $params) { $dc = "us1"; if (strstr($this->api_key, "-")) { list($key, $dc) = explode("-", $this->api_key, 2); if (!$dc) { $dc = "us1"; } } $host = $dc . "." . $this->apiUrl["host"]; $params["apikey"] = $this->api_key; $this->errorMessage = ""; $this->errorCode = ""; $sep_changed = false; //sigh, apparently some distribs change this to & by default if (ini_get("arg_separator.output") != "&") { $sep_changed = true; $orig_sep = ini_get("arg_separator.output"); ini_set("arg_separator.output", "&"); } $post_vars = http_build_query($params); if ($sep_changed) { ini_set("arg_separator.output", $orig_sep); } $payload = "POST " . $this->apiUrl["path"] . "?" . $this->apiUrl["query"] . "&method=" . $method . " HTTP/1.0\r\n"; $payload .= "Host: " . $host . "\r\n"; $payload .= "User-Agent: MCAPI/" . $this->version . "\r\n"; $payload .= "Content-type: application/x-www-form-urlencoded\r\n"; $payload .= "Content-length: " . strlen($post_vars) . "\r\n"; $payload .= "Connection: close \r\n\r\n"; $payload .= $post_vars; ob_start(); if ($this->secure) { $sock = fsockopen("ssl://" . $host, 443, $errno, $errstr, 30); } else { $sock = fsockopen($host, 80, $errno, $errstr, 30); } if (!$sock) { $this->errorMessage = "Could not connect (ERR {$errno}: {$errstr})"; $this->errorCode = "-99"; ob_end_clean(); return false; } $response = ""; fwrite($sock, $payload); stream_set_timeout($sock, $this->timeout); $info = stream_get_meta_data($sock); while (!feof($sock) && !$info["timed_out"]) { $response .= fread($sock, $this->chunkSize); $info = stream_get_meta_data($sock); } fclose($sock); ob_end_clean(); $this->logger->debug('Response: ' . print_r($response, true)); if ($info["timed_out"]) { $this->errorMessage = "Could not read response (timed out)"; $this->errorCode = -98; return false; } list($headers, $response) = explode("\r\n\r\n", $response, 2); $headers = explode("\r\n", $headers); $errored = false; foreach ($headers as $h) { if (substr($h, 0, 26) === "X-MailChimp-API-Error-Code") { $errored = true; $error_code = trim(substr($h, 27)); break; } } if (ini_get("magic_quotes_runtime")) { $response = stripslashes($response); } $serial = unserialize($response); if ($response && $serial === false) { $response = array("error" => "Bad Response. Got This: " . $response, "code" => "-99"); } else { $response = $serial; } if ($errored && is_array($response) && isset($response["error"])) { $this->errorMessage = $response["error"]; $this->errorCode = $response["code"]; return false; } elseif ($errored) { $this->errorMessage = "No error message was found"; $this->errorCode = $error_code; return false; } return $response; }
/** * Make a request to the Emma API * * @param string $api_method The API method to be called * @param string $http_method The HTTP method to be used (GET, POST, PUT, DELETE, etc.) * @param array $data Any data to be sent to the API * @return string|array API request results **/ function make_request($api_method, $http_method = NULL, $data = NULL) { // Set query string $get_query_string = ''; if ($this->count) { $get_query_string = '?count=true'; } elseif ($this->start >= 0 && $this->end >= 0) { $get_query_string = sprintf('?start=%d&end=%d', $this->start, $this->end); } if (($http_method == 'GET' || $http_method == 'DELETE') && !empty($data)) { $get_query_string = '?'; $get_query_string .= http_build_query($data); } // Set request $request_url = 'https://' . $this->emma_api_domain . '/' . $this->emma_account_id . '/' . $api_method . $get_query_string; // Debugging output if ($this->debug) { echo 'HTTP Method: ' . $http_method . "\n"; echo 'Request URL: ' . $request_url . "\n"; } // Create a cURL handle $ch = curl_init(); // Set the request curl_setopt($ch, CURLOPT_URL, $request_url); // Use HTTP Basic Authentication curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // Set the public_key and private_key curl_setopt($ch, CURLOPT_USERPWD, $this->emma_public_key . ':' . $this->emma_private_key); // Save the response to a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Send data as PUT request curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method); // This may be necessary, depending on your server's configuration curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // Send data if (!empty($data)) { $postdata = json_encode($data); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($postdata))); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); } // Execute cURL request curl_setopt($ch, CURLOPT_HEADER, true); $curl_response = curl_exec($ch); $curl_info = curl_getinfo($ch); $this->logger->debug('Response: ' . print_r($curl_response, true) . "\n"); // Close cURL handle curl_close($ch); // Parse response list($curl_response_headers, $curl_response) = preg_split("/\\R\\R/", $curl_response, 2); if ($this->count) { $parsed_result = $curl_response; } else { $parsed_result = $this->parse_response($curl_response); } // Save response to class variable for use in debugging $this->last_emma_response = $curl_response; $this->last_emma_response_headers = $curl_response_headers; $this->last_emma_response_info = $curl_info; // Return parsed response return $parsed_result; }
/** * Internal method to make a general API request based on the provided options * @param $call_options * @access private */ function _call($call_options, $method, $route, $data = NULL) { $call_options['route'] = $route; $call_options['method'] = $method; if (!is_null($data)) { $call_options['data'] = $this->_serialiser->serialise($data); } $call_options = array_merge($this->_default_call_options, $call_options); $this->_log->log_message('Making ' . $call_options['method'] . ' call to: ' . $call_options['route'], get_class($this), CS_REST_LOG_WARNING); $call_result = $this->_transport->make_call($call_options); $this->_log->log_message('Call result: <pre>' . var_export($call_result, true) . '</pre>', get_class($this), CS_REST_LOG_VERBOSE); $this->logger->debug('Response: ' . print_r($call_result, true)); if ($call_options['deserialise']) { $call_result['response'] = $this->_serialiser->deserialise($call_result['response']); } return new OP_CS_REST_Wrapper_Result($call_result['response'], $call_result['code']); }
/** * @see OptimizePress_Modules_Email_ProviderInterface::getListFields() */ public function getListFields($listId) { $fields = $this->getFormFields($listId); $this->logger->info("Fields for list {$listId} (CampaignMonitor): " . print_r($fields, true)); return array('fields' => $fields); }
/** * @see OptimizePress_Modules_Email_ProviderInterface::getListFields() */ public function getListFields($listId) { $fields = $this->getCustomFields(); $this->logger->info("Fields for list {$listId}: " . print_r($fields, true)); return array('fields' => $fields); }
/** * This method handles the handshaking between this app and the iContact API * @access public * @param string $sResource * @param string $sMethod * @param string $sReturnKey * @param mixed $mPostData Array, object, or string * @return array|object **/ public function makeCall($sResource, $sMethod = 'GET', $mPostData = null, $sReturnKey = null) { // List of needed constants $aRequiredConfigs = array('apiPassword', 'apiUsername', 'appId'); // First off check for definitions foreach ($aRequiredConfigs as $sKey) { // Is it defined if (empty($this->aConfig[$sKey])) { // Set an error $this->addError("{$sKey} is undefined."); } } // Set the URI that we will be calling $sApiUrl = (string) "{$this->getUrl()}{$sResource}"; // Initialize the cURL handle $rHandle = curl_init(); // Give our handle headers curl_setopt($rHandle, CURLOPT_HTTPHEADER, $this->getHeaders()); // Tell our handle that we // want the data returned curl_setopt($rHandle, CURLOPT_RETURNTRANSFER, true); // Turn SSL verifcation off, so scripts do not get broken curl_setopt($rHandle, CURLOPT_SSL_VERIFYPEER, false); // Determine the request // method we are using switch (strtoupper($sMethod)) { // Deleting data case 'DELETE': // Set the cURL custom header curl_setopt($rHandle, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; // Recieving data // Recieving data case 'GET': // Check for a query string if (!empty($this->aSearchParameters)) { // Add the query string $sApiUrl .= (string) '?' . http_build_query($this->aSearchParameters); } break; // Sending data // Sending data case 'POST': // Check for POST data if (empty($mPostData)) { // Add an error, for there is no // POST data to send to the API $this->addError('No POST data was provided.'); } else { // Tell our handle that // we want to send data curl_setopt($rHandle, CURLOPT_POST, true); // Give our handle the data curl_setopt($rHandle, CURLOPT_POSTFIELDS, json_encode($mPostData)); // Set the request JSON $this->sLastRequest = (string) json_encode($mPostData); } break; // Uploading data // Uploading data case 'PUT': if (empty($mPostData)) { // Is there data? $this->addError('No file or data specified for PUT request'); } elseif (!is_string($mPostData) || !file_exists($mPostData)) { // Not a file, so we assume this is just data curl_setopt($rHandle, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($rHandle, CURLOPT_POSTFIELDS, $mPostData); } else { $rFileContentHandle = fopen($mPostData, 'r'); if ($rFileContentHandle === false) { $this->addError('A non-existant file was specified for POST data, or the file could not be opened.'); } else { // Found a file, so upload its contents curl_setopt($rHandle, CURLOPT_PUT, true); curl_setopt($rHandle, CURLOPT_INFILE, $rFileContentHandle); } } break; } // Store the URL into the instance $this->sRequestUri = (string) $sApiUrl; // Give our handle a URL curl_setopt($rHandle, CURLOPT_URL, $sApiUrl); // Try to execute the handle if (!($sResponse = curl_exec($rHandle))) { // Add an error, for we could // not even execute the handle $this->addError('We were unable to execute the cURL handle.'); } $this->logger->debug('Response: ' . print_r($sResponse, true) . "\n"); // Set the response JSON $this->sLastResponse = (string) $sResponse; // Try to decode the response if (!($aResponse = json_decode($sResponse)) && strtoupper($sMethod) != 'DELETE') { // Add an error, for the API // did not return valid JSON $this->addError('The iContact API did not return valid JSON.'); } // Close the cURL handle curl_close($rHandle); // Check for errors from the API if (!empty($aResponse->errors)) { // Loop through the errors foreach ($aResponse->errors as $sError) { // Add the error $this->addError($sError, 1); } } // Check for warnings from the API if (!empty($aResponse->warnings)) { // Loop through the warnings foreach ($aResponse->warnings as $sWarning) { // Add the warning $this->addWarning($sWarning); } } // Check for set errors if (!empty($this->aErrors)) { // Throw a new exception throw new Exception('Errors have occurred and the system cannot continue. Use getErrors() for details.'); } // Check for a total if (!empty($aResponse->total)) { // Store the total records // into the current instsnce $this->iTotal = (int) $aResponse->total; } // Return the response if (strtoupper($sMethod) == 'DELETE') { // Return success return true; } elseif (empty($sReturnKey)) { // Return the entire // base response return $aResponse; } else { // Return the narrowed resposne return $aResponse->{$sReturnKey}; } }