/** * check login * 检查登录合法性及返回sdk返回的用户id或部分用户信息 */ public function check() { //http请求中所有请求参数数组 $params = $_REQUEST; //检测必要参数 if (!$this->parametersIsset($params)) { echo 'parameter not complete'; exit; } //模拟http请求 include_once './classes/HttpHelper.php'; $http = new HttpHelper(); //这里建议使用post方式提交请求,避免客户端提交的参数再次被urlencode导致部分渠道token带有特殊符号验证失败 $result = $http->post($this->_loginCheckUrl, $params); //@todo在这里处理游戏逻辑,在服务器注册用户信息等 $json_array = json_decode($result, true); $json_array['ext']['accountID'] = $json_array['common']['uid']; echo json_encode($json_array); //$result如: {"status":"ok","data":{--渠道服务器返回的信息--},"common":{"channel":"渠道标识","uid":"用户标识"}} //输出anysdk统一登录返回 if (self::DEBUG_MODE) { $logFile = '/tmp/game.server.login.check.log'; file_put_contents($logFile, "#" . date('Y-m-d H:i:s') . "\n", FILE_APPEND); file_put_contents($logFile, "#URL:\n" . print_r($http->getUrl(), TRUE) . "\n", FILE_APPEND); file_put_contents($logFile, "#RESULT:\n" . print_r($result, TRUE) . "\n", FILE_APPEND); file_put_contents($logFile, "#DECODE:\n" . print_r(json_decode($result, true), TRUE) . "\n", FILE_APPEND); } }
/** * 查询订单接口 * @param type $userId * @param type $cpOrderId */ function queryOrder($userId, $cpOrderId) { $params = array('appId' => Configuration::APP_ID, 'uid' => $userId, 'cpOrderId' => $cpOrderId); $signObj = new SignatureHelper(); $signature = $signObj->sign($params, Configuration::SECRET_KEY); $params['signature'] = $signature; $request = new HttpHelper(); $response = $request->get(Configuration::QUERY_ORDER_URL, $params); //TODO: 后续业务逻辑处理 echo $response; }
public static function queryGeoCoder($address) { $contents = ''; // query use fsockopen $http = new HttpHelper(); $response = $http->get(sprintf('http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false', urlencode($address))); if (isset($response['body'])) { return json_decode($response['body']); } return null; }
public function doAction($request, $iSigner = null, $credential = null, $autoRetry = true, $maxRetryNumber = 3) { if (null == $this->iClientProfile && (null == $iSigner || null == $credential || null == $request->getRegionId() || null == $request->getAcceptFormat())) { throw new ClientException("No active profile found.", "SDK.InvalidProfile"); } if (null == $iSigner) { $iSigner = $this->iClientProfile->getSigner(); } if (null == $credential) { $credential = $this->iClientProfile->getCredential(); } $request = $this->prepareRequest($request); $domain = EndpointProvider::findProductDomain($request->getRegionId(), $request->getProduct()); if (null == $domain) { throw new ClientException("Can not find endpoint to access.", "SDK.InvalidRegionId"); } $requestUrl = $request->composeUrl($iSigner, $credential, $domain); if (count($request->getDomainParameter()) > 0) { $httpResponse = HttpHelper::curl($requestUrl, $request->getMethod(), $request->getDomainParameter(), $request->getHeaders()); } else { $httpResponse = HttpHelper::curl($requestUrl, $request->getMethod(), $request->getContent(), $request->getHeaders()); } $retryTimes = 1; while (500 <= $httpResponse->getStatus() && $autoRetry && $retryTimes < $maxRetryNumber) { $requestUrl = $request->composeUrl($iSigner, $credential, $domain); if (count($request->getDomainParameter()) > 0) { $httpResponse = HttpHelper::curl($requestUrl, $request->getDomainParameter(), $request->getHeaders()); } else { $httpResponse = HttpHelper::curl($requestUrl, $request->getMethod(), $request->getContent(), $request->getHeaders()); } $retryTimes++; } return $httpResponse; }
public function onRequest($request, $response) { //SysLog::debug(__METHOD__ . print_r($request,true), __CLASS__); //统一进行路由和数据的预处理 $req = HttpHelper::httpReqHandle($request); // SysLog::info(__METHOD__.print_r($req,true),__CLASS__); if ($req['r'] === HttpHelper::HTTP_ERROR_URI) { $response->status(404); //todo:log $response->end("not found"); return; } //SysLog::info(__METHOD__.' '.__LINE__ . " REQUEST IS ".print_r($req,true),__CLASS__); $class = $req['route']['controller'] . 'Controller'; $fun = 'action' . $req['route']['action']; //判断类是否存在 if (!class_exists($class) || !method_exists($class, $fun)) { $response->status(404); SysLog::error(__METHOD__ . " class or fun not found class == {$class} fun == {$fun}", __CLASS__); $response->end("uri not found"); return; } $obj = new $class($this->server, array('request' => $req['request'], 'response' => $response), $request->fd); //代入参数 $request->scheduler->newTask($obj->{$fun}()); $request->scheduler->run(); }
public static function httpBuildMultiQuery($data, $key = null) { $query = array(); if (empty($data)) { return $key . '='; } $isAssocArray = ArrayHelper::isAssociativeArray($data); foreach ($data as $k => $value) { if (is_string($value) || is_numeric($value)) { $brackets = $isAssocArray ? '[' . $k . ']' : '[]'; $query[] = urlencode(is_null($key) ? $k : $key . $brackets) . '=' . rawurlencode($value); } elseif (is_array($value)) { $nested = is_null($key) ? $k : $key . '[' . $k . ']'; $query[] = HttpHelper::httpBuildMultiQuery($value, $nested); } } return implode('&', $query); }
/** * Makes an HTTP request using CURL. * * @param $url string the URL to request * @param string $method The request method ('GET', 'POST', 'PUT', 'DELETE', etc) * @param null $data Any additional data to include in the payload. * @param null $headers Additional headers to send. * @param int $timeout The request timeout in milliseconds * @return bool|string The response string, or false if there was an error. */ public static function request_curl($url, $method = 'GET', $data = null, $headers = null, $timeout = 300) { $cn = curl_init(); if (!empty($data)) { if (strtolower($method) == 'post' || strtolower($method) == 'put') { curl_setopt($cn, CURLOPT_POSTFIELDS, http_build_query($data)); } else { $url = HttpHelper::appendToUrl($url, $data); } } curl_setopt($cn, CURLOPT_URL, $url); curl_setopt($cn, CURLOPT_TIMEOUT, $timeout); curl_setopt($cn, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($cn, CURLOPT_FORBID_REUSE, 0); curl_setopt($cn, CURLOPT_ENCODING, 'gzip,deflate'); if (!self::$verifySsl) { curl_setopt($cn, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($cn, CURLOPT_SSL_VERIFYPEER, 0); } if (!empty($headers)) { $h = array(); while (list($header, $headerValue) = each($headers)) { array_push($h, $header . ': ' . $headerValue); } curl_setopt($cn, CURLOPT_HTTPHEADER, $h); } try { ob_start(); if (curl_exec($cn)) { return ob_get_clean(); } else { ob_end_clean(); return false; } } catch (\Exception $e) { ob_end_clean(); throw $e; } }
public function testCurl() { $httpResponse = HttpHelper::curl("ecs.aliyuncs.com"); $this->assertEquals(400, $httpResponse->getStatus()); $this->assertNotNull($httpResponse->getBody()); }
public function getProfile($fb_uid) { if (empty($fb_uid)) { throw new FacebookException('Facebook unique id missing.'); } $url = $this->graphURL() . '/' . $fb_uid . '?fields=picture'; try { $http = new HttpHelper(); $result = $http->get($url, array('ssl_verifypeer' => false)); } catch (YException $e) { return; } $result = json_decode($result['body']); return $result; }
/** * Execute an HTTP request and return the results * * This function will throw if no connection to the server can be established or if * there is a problem during data exchange with the server. * * will restore it. * * @throws Exception * * @param string $method - HTTP request method * @param string $url - HTTP URL * @param string $data - data to post in body * @param array $customHeader - any array containing header elements * * @return HttpResponse */ private function executeRequest($method, $url, $data, $customHeader = array()) { HttpHelper::validateMethod($method); $database = $this->getDatabase(); if ($database === '') { $url = '/_db/' . '_system' . $url; } else { $url = '/_db/' . $database . $url; } // create request data if ($this->_batchRequest === false) { if ($this->_captureBatch === true) { $this->_options->offsetSet(ConnectionOptions::OPTION_BATCHPART, true); $request = HttpHelper::buildRequest($this->_options, $method, $url, $data, $customHeader); $this->_options->offsetSet(ConnectionOptions::OPTION_BATCHPART, false); } else { $request = HttpHelper::buildRequest($this->_options, $method, $url, $data, $customHeader); } if ($this->_captureBatch === true) { $batchPart = $this->doBatch($method, $request); if (!is_null($batchPart)) { return $batchPart; } } } else { $this->_batchRequest = false; $this->_options->offsetSet(ConnectionOptions::OPTION_BATCH, true); $request = HttpHelper::buildRequest($this->_options, $method, $url, $data, $customHeader); $this->_options->offsetSet(ConnectionOptions::OPTION_BATCH, false); } $traceFunc = $this->_options[ConnectionOptions::OPTION_TRACE]; if ($traceFunc) { // call tracer func if ($this->_options[ConnectionOptions::OPTION_ENHANCED_TRACE]) { list($header) = HttpHelper::parseHttpMessage($request, $url, $method); $headers = HttpHelper::parseHeaders($header); $traceFunc(new TraceRequest($headers[2], $method, $url, $data)); } else { $traceFunc('send', $request); } } // open the socket. note: this might throw if the connection cannot be established $handle = $this->getHandle(); if ($handle) { // send data and get response back if ($traceFunc) { // only issue syscall if we need it $startTime = microtime(true); } $result = HttpHelper::transfer($handle, $request); if ($traceFunc) { // only issue syscall if we need it $timeTaken = microtime(true) - $startTime; } $status = socket_get_status($handle); if ($status['timed_out']) { throw new ClientException('Got a timeout while waiting for the server\'s response', 408); } if (!$this->_useKeepAlive) { // must close the connection fclose($handle); } $response = new HttpResponse($result, $url, $method); if ($traceFunc) { // call tracer func if ($this->_options[ConnectionOptions::OPTION_ENHANCED_TRACE]) { $traceFunc(new TraceResponse($response->getHeaders(), $response->getHttpCode(), $response->getBody(), $timeTaken)); } else { $traceFunc('receive', $result); } } return $response; } throw new ClientException('Whoops, this should never happen'); }
protected function doVerifyCookies() { $cookies = HttpHelper::getCookies(); $user = NULL; try { $user = new User($cookies['username'], $cookies['passhash']); } catch (Exception $e) { } if (!$user || !$this->checkUserValidity($user)) { $this->status = self::REDIRECTING; HttpHelper::unsetCookies(); HttpHelper::redirect('/'); // exits script return false; } $this->user = $user; $this->status = self::LOGGED_IN; return true; }
} if (!empty($_SERVER['HTTP_CLOUDFRONT_FORWARDED_PROTO']) && $_SERVER['HTTP_CLOUDFRONT_FORWARDED_PROTO'] === 'https') { return true; } return false; } public static function getProtocol() { return self::isHttps() ? 'https:' : 'http:'; } public static function getBasePath() { return self::getProtocol() . '//' . $_SERVER['HTTP_HOST'] . substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/')) . '/'; } } $basepath = HttpHelper::getBasePath(); ?> <!doctype html> <!--[if IE 8]> <html class="no-js lt-ie10 lt-ie9"> <![endif]--> <!--[if IE 9]><html class="no-js lt-ie10"><![endif]--> <!--[if gt IE 9]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no" /> <title>Pay it</title> <!-- this is used for history, absolute uri to your 'index' --> <meta name="document-base" content="<?php echo $basepath;
/** * Set up the response * * @throws ClientException * * @param string $responseString - the complete HTTP response as supplied by the server * @param string $originUrl The original URL the response is coming from * @param string $originMethod The HTTP method that was used when sending data to the origin URL */ public function __construct($responseString, $originUrl = null, $originMethod = null) { list($this->_header, $this->_body) = HttpHelper::parseHttpMessage($responseString, $originUrl, $originMethod); list($this->_httpCode, $this->_result, $this->_headers) = HttpHelper::parseHeaders($this->_header); }
/** * Deprecated. */ public static function httpRequest($url, array $options = array()) { return HttpHelper::cachedRequest($url, $options); }
/** * @test */ public function exchangeIndexNumericalByTextual() { $this->assertCount(0, HttpHelper::exchangeIndexNumericalByTextual(['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e'])); $this->assertCount(1, HttpHelper::exchangeIndexNumericalByTextual([0 => ['a', 'b', 'c', 'd', 'e']], ['a', 'b', 'c', 'd', 'e'])); }
/** * Splits a http message into its header and body. * * @param string $httpMessage The http message string. * @param string $originUrl The original URL the response is coming from * @param string $originMethod The HTTP method that was used when sending data to the origin URL * * @throws ClientException * @return array */ public static function parseHttpMessage($httpMessage, $originUrl = null, $originMethod = null) { assert(is_string($httpMessage)); $barrier = HttpHelper::EOL . HttpHelper::EOL; $parts = explode($barrier, $httpMessage, 2); $parsed = HttpHelper::parseHeaders($parts[0]); if ($parsed[0] == 304 || $parsed[0] == 204) { return $parts; } if (!isset($parts[1]) or $parts[1] === null) { if ($originUrl !== null && $originMethod !== null) { throw new ClientException('Got an invalid response from the server after request to ' . $originMethod . ' ' . $originUrl); } throw new ClientException('Got an invalid response from the server'); } return $parts; }
/** * Makes a generic API request. * * @param string $cmd The name of the command * @param array $params Additional parameters to send with the request. * @return Result The result of the request. */ protected function request($cmd, $params = array()) { return new Result(HttpHelper::request($this->baseUrl, $this->requestMethod, array_merge(array('cmd' => $cmd, 'key' => $this->apiKey, 'format' => 'php', 'unique_id' => uniqid($this->uniquePrefix, true)), $params))); }
public function facebookAuthenticate() { // init vars $item_id = YRequest::getInt('item_id', 0); $item = YTable::getInstance('item')->get($item_id); // get facebook client $connection = CommentHelper::getFacebookClient(); if ($connection) { $code = YRequest::getString('code', ''); $uri = new JURI(); $redirect = $uri->root() . $this->link_base . '&controller=comment&task=facebookauthenticate&item_id=' . $item_id; $url = $connection->getAccessTokenURL($code, $redirect); $http = new HttpHelper(); $result = $http->get($url, array('ssl_verifypeer' => false)); $token = str_replace('access_token=', '', $result['body']); $_SESSION['facebook_access_token'] = $token; } $redirect = JRoute::_(RouteHelper::getItemRoute($item)); $this->setRedirect($redirect); }