getHttpClient()->setOptions([ 'maxredirects' => 0, 'timeout' => 180, 'keepalive' => false, 'adapter' => 'Zend\Http\Client\Adapter\Curl', ]); } public function pay(array $packet) { $response = $this->purchase($packet); if ($response->getApprovalCode() == Response::APPROVED) { return $response->getItemId(); } throw new Exception($response->getDetailedMessage()); } public function purchase(array $packet) { $packetEntity = new Packet\Purchase($packet); $packetEntity->setTid($this->getMerchantId()); $response = $this->request($packetEntity); return $response; } private function request(Packet $packet) { $this->getHttpClient()->setUri(self::GATEWAY)->setMethod(HttpRequest::METHOD_POST); $this->getHttpClient()->setParameterPost(['packet' => $packet->toBinary()]); try { $httpResponse = $this->getHttpClient()->send(); if ($httpResponse->getStatusCode() != HttpResponse::STATUS_CODE_200) { $message = 'Invalid response payment gateway: code ' . $httpResponse->getStatusCode() . '; message: ' . $httpResponse->getReasonPhrase(); throw new Exception($message); } $body = $httpResponse->getBody(); $response = Response::fromBinary($body); if (in_array($response->getModifierCode(), [2090, 2091])) { throw new Exception($response->getMessage()); } } catch (PhpException $e) { $this->emergency($e->getMessage()); $this->info('Request: ' . $packet->__toString()); $this->info($this->httpDump($packet)); throw new Exception($e->getMessage()); } return $response; } public function getLogFilePattern() { return $this->logFilePattern; } public function setLogFilePattern($logFilePattern) { $this->logFilePattern = $logFilePattern; return $this; } public function log($level, $message, array $context = []) { $file = Qs_String::fill($this->getLogFilePattern(), [ 'year' => idate('Y'), 'month' => date('m'), 'date' => date('Y-m-d'), ]); $dir = dirname($file); if (!file_exists($dir) && false === mkdir($dir, 0755, true)) { trigger_error('Failed to create directory: ' . $dir); return; } $handle = fopen($file, 'a+'); $indent = "\t"; $text = date('Y-m-d H:i:s') . $indent . strtoupper($level) . $indent . Qs_String::fill($message, $context) . PHP_EOL; fwrite($handle, $text); fclose($handle); } private function httpDump(Packet $packet) { if (!($request = $this->getHttpClient()->getLastRawRequest())) { return null; } $line = str_repeat('-', 120) . PHP_EOL; $doubleLine = str_repeat('=', 120) . PHP_EOL; return 'HTTP INFO' . PHP_EOL . $doubleLine . "Request\n{$line}" . $packet->__toString() . PHP_EOL . "{$line}Response\n{$line}" . $this->getHttpClient()->getLastRawResponse() . PHP_EOL . $doubleLine; } public function getMerchantId() { return $this->merchantId; } public function setMerchantId($merchantId) { $this->merchantId = $merchantId; return $this; } }