diff --git a/.gitignore b/.gitignore index 73c05e5..92e36c8 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,9 @@ composer.phar # Netbeans project files /nbproject/ +# PhpStorm +.idea/ + # Merchant settings for integration tests /tests/integration/MerchantSettings.php /tests/integration/merchant_data/* diff --git a/README.md b/README.md index 3b37bba..9c8dc43 100644 --- a/README.md +++ b/README.md @@ -19,22 +19,4 @@ vendor/bin/phpunit tests/integration ## Примеры использования -### 1. Создание чека - -```php -$client = new PostClient($this->starrysApiUrl, $this->secretKeyPath, $this->certPath); -$line = new Line('Test product', 1, 10.00, Line::TAX_VAT18); -$line->addPayAttribute(Line::PAY_ATTRIBUTE_TYPE_FULL_PAID_WITH_GET_PRODUCT); - -$complexServise = new ComplexRequest(time()); -$complexServise->addDocumentType(ComplexRequest::DOCUMENT_TYPE_BUY) - ->addEmail('test@test.ru') - ->addGroup($this->group) - ->addPhone('79050000000') - ->addPlace('www.test.ru') - ->addTaxMode($this->taxMode) - ->addLine($line) - ->addNonCash(10.00); - -$response = new ComplexResponse($client->sendRequest($complexServise)); -``` +Примеры использования можно найти в интеграционных тестах tests/integration diff --git a/composer.json b/composer.json index 548d8b2..6b4f8aa 100644 --- a/composer.json +++ b/composer.json @@ -2,8 +2,9 @@ "name": "payprocessing/starrys", "description": "Starrys", "require": { - "php": ">=5.3", - "psr/log": "1.0.2" + "php": ">=5.5", + "psr/log": "1.0.2", + "myclabs/php-enum": "^1.6" }, "require-dev": { "php": ">=5.6", diff --git a/src/clients/PostClient.php b/src/clients/PostClient.php index 0d915ab..c275da6 100644 --- a/src/clients/PostClient.php +++ b/src/clients/PostClient.php @@ -2,93 +2,99 @@ namespace Platron\Starrys\clients; -use Platron\Starrys\clients\iClient; use Platron\Starrys\SdkException; use Platron\Starrys\services\BaseServiceRequest; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; -class PostClient implements iClient { +class PostClient implements iClient +{ /** @var string */ protected $url; - /** @var string путь до приватного ключа */ - protected $secretKeyPath; - /** @var string путь до сертификата */ - protected $certPath; - - /** @var LoggerInterface */ - protected $logger; - /** @var int */ - protected $connectionTimeout = 30; - - /** - * Секретный ключ для подписи запросов + /** @var string путь до приватного ключа */ + protected $secretKeyPath; + /** @var string путь до сертификата */ + protected $certPath; + + /** @var LoggerInterface */ + protected $logger; + /** @var int */ + protected $connectionTimeout = 30; + + /** + * Секретный ключ для подписи запросов * @param string $url Путь для запросов https://<адрес, указанный в личном кабинете>:<порт, указанный в личном кабинете> - * @param string $secretKeyPath + * @param string $secretKeyPath * @param string $certPath - */ - public function __construct($url, $secretKeyPath, $certPath){ + */ + public function __construct($url, $secretKeyPath, $certPath) + { $this->url = $url; - $this->secretKeyPath = $secretKeyPath; - $this->certPath = $certPath; - } - - /** - * Установить логер - * @param LoggerInterface $logger - * @return self - */ - public function setLogger(LoggerInterface $logger){ - $this->logger = $logger; - return $this; - } - - /** - * Установка максимального времени ожидания - * @param int $connectionTimeout - * @return self - */ - public function setConnectionTimeout($connectionTimeout){ - $this->connectionTimeout = $connectionTimeout; - return $this; - } - - /** - * @inheritdoc - */ - public function sendRequest(BaseServiceRequest $service) { - $requestParameters = $service->getParameters(); - $requestUrl = $this->url.$service->getUrlPath(); - - $curl = curl_init($requestUrl); - if(!empty($requestParameters)){ - curl_setopt($curl, CURLOPT_POST, 1); - curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($requestParameters)); - } + $this->secretKeyPath = $secretKeyPath; + $this->certPath = $certPath; + } + + /** + * Установить логер + * @param LoggerInterface $logger + * @return self + */ + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; + return $this; + } + + /** + * Установка максимального времени ожидания + * @param int $connectionTimeout + * @return self + */ + public function setConnectionTimeout($connectionTimeout) + { + $this->connectionTimeout = $connectionTimeout; + return $this; + } + + /** + * @param BaseServiceRequest $service + * @return \stdClass + * @throws SdkException + */ + public function sendRequest(BaseServiceRequest $service) + { + $requestParameters = $service->getParameters(); + $requestUrl = $this->url . $service->getUrlPath(); + + $curl = curl_init($requestUrl); + if (!empty($requestParameters)) { + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($requestParameters)); + } curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_SSLKEY, $this->secretKeyPath); - curl_setopt($curl, CURLOPT_SSLCERT, $this->certPath); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->connectionTimeout); - - $response = curl_exec($curl); - - if($this->logger){ - $this->logger->log(LogLevel::INFO, 'Requested url '.$requestUrl.' params '. json_encode($requestParameters)); - $this->logger->log(LogLevel::INFO, 'Response '.$response); - } - - if(curl_errno($curl)){ + curl_setopt($curl, CURLOPT_SSLKEY, $this->secretKeyPath); + curl_setopt($curl, CURLOPT_SSLCERT, $this->certPath); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->connectionTimeout); + + $response = curl_exec($curl); + + if ($this->logger) { + $this->logger->log(LogLevel::INFO, 'Requested url ' . $requestUrl . ' params ' . json_encode($requestParameters)); + $this->logger->log(LogLevel::INFO, 'Response ' . $response); + } + + if (curl_errno($curl)) { throw new SdkException(curl_error($curl), curl_errno($curl)); } - - if(empty(json_decode($response))){ - throw new SdkException('Not json response '.$response); - } + + if (empty(json_decode($response))) { + throw new SdkException('Not json response ' . $response); + } return json_decode($response); - } + } } diff --git a/src/clients/iClient.php b/src/clients/iClient.php index b415b20..35ceff6 100644 --- a/src/clients/iClient.php +++ b/src/clients/iClient.php @@ -4,11 +4,12 @@ use Platron\Starrys\services\BaseServiceRequest; -interface iClient { - - /** - * Послать запрос - * @param \Platron\Starrys\BaseService $service - */ - public function sendRequest(BaseServiceRequest $service); +interface iClient +{ + + /** + * Послать запрос + * @param BaseServiceRequest $service + */ + public function sendRequest(BaseServiceRequest $service); } diff --git a/src/data_objects/AgentData.php b/src/data_objects/AgentData.php new file mode 100644 index 0000000..712e659 --- /dev/null +++ b/src/data_objects/AgentData.php @@ -0,0 +1,22 @@ +Operation = (string)$operation; + $this->Phone = (string)$phone; + } +} \ No newline at end of file diff --git a/src/data_objects/BaseDataObject.php b/src/data_objects/BaseDataObject.php index 8d4580e..1f77a70 100644 --- a/src/data_objects/BaseDataObject.php +++ b/src/data_objects/BaseDataObject.php @@ -2,19 +2,24 @@ namespace Platron\Starrys\data_objects; -abstract class BaseDataObject { - /** +abstract class BaseDataObject +{ + /** * Получить параметры, сгенерированные командой * @return array */ - public function getParameters() { - $filledvars = array(); + public function getParameters() + { + $fieldVars = array(); foreach (get_object_vars($this) as $name => $value) { if ($value) { - $filledvars[$name] = $value; + if ($value instanceof BaseDataObject) { + $fieldVars[$name] = $value->getParameters(); + } else { + $fieldVars[$name] = $value; + } } } - - return $filledvars; + return $fieldVars; } } diff --git a/src/data_objects/GetPaymentOperatorData.php b/src/data_objects/GetPaymentOperatorData.php new file mode 100644 index 0000000..0c7352e --- /dev/null +++ b/src/data_objects/GetPaymentOperatorData.php @@ -0,0 +1,18 @@ +Phone = (string)$phone; + } +} \ No newline at end of file diff --git a/src/data_objects/Line.php b/src/data_objects/Line.php index e1d2dc1..34c1bea 100644 --- a/src/data_objects/Line.php +++ b/src/data_objects/Line.php @@ -2,94 +2,101 @@ namespace Platron\Starrys\data_objects; -use Platron\Starrys\SdkException; +use Platron\Starrys\handbooks\AgentModes; +use Platron\Starrys\handbooks\PayAttributeTypes; +use Platron\Starrys\handbooks\Taxes; class Line extends BaseDataObject{ - - const - TAX_NONE = 4, // Не облагается - TAX_VAT0 = 3, // 0% - TAX_VAT10 = 2, // 10% - TAX_VAT18 = 1, // 18% - TAX_VAT110 = 6, // Ставка 10/110 - TAX_VAT118 = 5; // Ставка 18/118 - - const - PAY_ATTRIBUTE_TYPE_FULL_PRE_PAID_BEFORE_GET_PRODUCT = 1, // Полная предварительная оплата до передачи товара - PAY_ATTRIBUTE_TYPE_PARTIAL_PRE_PAID_BEFORE_GET_PRODUCT = 2, // Частичная предварительная оплата до передачи товара - PAY_ATTRIBUTE_TYPE_PRE_PAID = 3, // Аванс - PAY_ATTRIBUTE_TYPE_FULL_PAID_WITH_GET_PRODUCT = 4, // Полная оплата в том числе с учетом аванса в момент передачи товара - PAY_ATTRIBUTE_TYPE_PRE_PAID_WITH_GET_PRODUCT_AND_CREDIT = 5, // Частичная оплата с передачей товара и оформлением кредита - PAY_ATTRIBUTE_TYPE_NOT_PAID_WITH_GET_PRODUCT_AND_CREDIT = 6, // Передача товара без оплаты и оформление кредита - PAY_ATTRIBUTE_TYPE_PAID_CREDIT = 7; // Оплата кредита. Если это значение присутствует - в чеке может быть только 1 позиция - + /** @var int */ protected $Qty; /** @var float */ protected $Price; /** @var int */ - protected $payAttribute; + protected $PayAttribute; /** @var int */ - protected $taxId; + protected $TaxId; + /** @var string */ + protected $Description; + /** @var float */ + protected $SubTotal; /** @var string */ - protected $description; + protected $AgentModes; + /** @var TransferOperatorData */ + protected $TransferOperatorData; + /** @var GetPaymentOperatorData */ + protected $GetPaymentOperatorData; + /** @var AgentData */ + protected $AgentData; + /** @var ProviderData */ + protected $ProviderData; /** * @param string $description Наименование товарной позиции * @param float $qty Количество. Указывается в штуках. До 3 знаков после запятой * @param int $price Цена указывается в копейках - * @param int $taxId Налоговая ставка из констант - * @throws SdkException + * @param Taxes $taxId Процент налога на позицию */ - public function __construct($description, $qty, $price, $taxId) { - if(!in_array($taxId, $this->getTaxes())){ - throw new SdkException('Wrong tax'); - } - + public function __construct($description, $qty, $price, Taxes $taxId) { $this->Qty = (int)($qty * 1000); - $this->Price = (float)$price; - $this->taxId = $taxId; - $this->description = $description; + $this->Price = (int)$price; + $this->TaxId = $taxId->getValue(); + $this->Description = $description; } /** * Признак способа расчета. Задается из констант. Не обязателен при БСО - * @param int $payAttribute + * @param PayAttributeTypes $payAttributeType */ - public function addPayAttribute($payAttribute){ - if(!in_array($payAttribute, $this->getPayAttributes())){ - throw new SdkException('Wrong pay attribute'); - } - - $this->payAttribute = $payAttribute; + public function addPayAttribute(PayAttributeTypes $payAttributeType){ + $this->PayAttribute = $payAttributeType->getValue(); } - - /** - * Получить все возможные налоговые ставки - */ - protected function getTaxes(){ - return [ - self::TAX_NONE, - self::TAX_VAT0, - self::TAX_VAT10, - self::TAX_VAT110, - self::TAX_VAT118, - self::TAX_VAT18, - ]; - } - + /** - * Получить все возможные налоговые ставки - */ - protected function getPayAttributes(){ - return [ - self::PAY_ATTRIBUTE_TYPE_FULL_PAID_WITH_GET_PRODUCT, - self::PAY_ATTRIBUTE_TYPE_FULL_PRE_PAID_BEFORE_GET_PRODUCT, - self::PAY_ATTRIBUTE_TYPE_NOT_PAID_WITH_GET_PRODUCT_AND_CREDIT, - self::PAY_ATTRIBUTE_TYPE_PAID_CREDIT, - self::PAY_ATTRIBUTE_TYPE_PARTIAL_PRE_PAID_BEFORE_GET_PRODUCT, - self::PAY_ATTRIBUTE_TYPE_PRE_PAID, - self::PAY_ATTRIBUTE_TYPE_PRE_PAID_WITH_GET_PRODUCT_AND_CREDIT, - ]; - } + * @param $subTotal + */ + protected function addSubTotal($subTotal) + { + $this->SubTotal = $subTotal; + } + + /** + * @param AgentModes $agentMode + */ + public function addAgentModes(AgentModes $agentMode) + { + $this->AgentModes = $agentMode->getValue(); + } + + /** + * @param TransferOperatorData $transferOperatorData + */ + public function addTransferOperatorData(TransferOperatorData $transferOperatorData) + { + $this->TransferOperatorData = $transferOperatorData; + } + + /** + * @param GetPaymentOperatorData $getPaymentOperatorData + */ + public function addGetPaymentOperatorData(GetPaymentOperatorData $getPaymentOperatorData) + { + $this->GetPaymentOperatorData = $getPaymentOperatorData; + } + + /** + * @param AgentData $agentData + */ + public function addAgentData(AgentData $agentData) + { + $this->AgentData = $agentData; + } + + /** + * @param ProviderData $providerData + */ + public function addProviderData(ProviderData $providerData) + { + $this->ProviderData = $providerData; + } } diff --git a/src/data_objects/ProviderData.php b/src/data_objects/ProviderData.php new file mode 100644 index 0000000..bd6018a --- /dev/null +++ b/src/data_objects/ProviderData.php @@ -0,0 +1,26 @@ +Name = (string)$name; + $this->INN = (string)$inn; + $this->Phone = (string)$phone; + } +} \ No newline at end of file diff --git a/src/data_objects/TransferOperatorData.php b/src/data_objects/TransferOperatorData.php new file mode 100644 index 0000000..f77534d --- /dev/null +++ b/src/data_objects/TransferOperatorData.php @@ -0,0 +1,31 @@ +Name = (string)$name; + $this->INN = (string)$inn; + $this->Address = (string)$address; + $this->Phone = (string)$phone; + } + +} \ No newline at end of file diff --git a/src/handbooks/AgentModes.php b/src/handbooks/AgentModes.php new file mode 100644 index 0000000..b7494c6 --- /dev/null +++ b/src/handbooks/AgentModes.php @@ -0,0 +1,17 @@ + $value) { - if ($value) { - $filledvars[$name] = (string)$value; - } - } - - return $filledvars; - } } diff --git a/src/services/BaseServiceResponse.php b/src/services/BaseServiceResponse.php index 5d62304..0d73e7a 100644 --- a/src/services/BaseServiceResponse.php +++ b/src/services/BaseServiceResponse.php @@ -4,52 +4,56 @@ use stdClass; -abstract class BaseServiceResponse { - - /** @var int */ - protected $errorCode; - - /** @var string */ - protected $errorMessages = []; - - /** - * @param stdClass $response - */ - public function __construct(stdClass $response) { - foreach (get_object_vars($this) as $name => $value) { +abstract class BaseServiceResponse +{ + + /** @var int */ + protected $errorCode; + + /** @var string */ + protected $errorMessages; + + /** + * @param stdClass $response + */ + public function __construct(stdClass $response) + { + foreach (get_object_vars($this) as $name => $value) { if (isset($response->$name)) { $this->$name = $response->$name; } } - } - - /** - * Проверка на ошибки в ответе - * @param array $response - * @return boolean - */ - public function isValid(){ - if(!empty($this->errorCode)){ - return false; - } - else { - return true; - } - } - - /** - * Получить код ошибки из ответа - * @return int - */ - public function getErrorCode(){ - return $this->errorCode; - } - - /** - * Получить описание ошибки - * @return string - */ - public function getErrorDescription(){ - return implode(',', $this->errorMessages); - } + } + + /** + * Проверка на ошибки в ответе + * @param array $response + * @return boolean + */ + public function isValid() + { + if (!empty($this->errorCode)) { + return false; + } else { + return true; + } + } + + /** + * Получить код ошибки из ответа + * @return int + */ + public function getErrorCode() + { + return $this->errorCode; + } + + /** + * Получить описание ошибки + * @return string + */ + public function getErrorDescription() + { + return implode(',', $this->errorMessages); + } } diff --git a/src/services/ComplexRequest.php b/src/services/ComplexRequest.php index f65f309..4b77887 100644 --- a/src/services/ComplexRequest.php +++ b/src/services/ComplexRequest.php @@ -3,258 +3,219 @@ namespace Platron\Starrys\services; use Platron\Starrys\data_objects\Line; -use Platron\Starrys\SdkException; +use Platron\Starrys\handbooks\DocumentTypes; +use Platron\Starrys\handbooks\TaxModes; + +class ComplexRequest extends BaseServiceRequest +{ -class ComplexRequest extends BaseServiceRequest{ - /** @var string */ - protected $device = 'auto'; + protected $Device = 'auto'; /** @var string */ - protected $fullResponse = false; + protected $ClientId; /** @var string */ - protected $group; + protected $Group; /** @var int */ - protected $requestId; + protected $RequestId; /** @var int */ protected $documentType; /** @var int */ - protected $taxMode; - /** @var int */ - protected $phone; + protected $TaxMode; /** @var string */ - protected $email; + protected $Place; /** @var string */ - protected $place; - /** @var Line[] */ - protected $lines; - /** @var string */ - protected $password; + protected $Password; /** @var float */ - protected $cash; + protected $Cash; /** @var float[] */ - protected $nonCash; + protected $NonCash; /** @var float */ - protected $advancePayment; + protected $AdvancePayment; /** @var float */ - protected $credit; + protected $Credit; /** @var float */ - protected $consideration; - - const - DOCUMENT_TYPE_SELL = 0, // Приход - DOCUMENT_TYPE_SELL_REFUND = 2, // Возврат прихода - DOCUMENT_TYPE_BUY = 1, // Расход - DOCUMENT_TYPE_BUY_REFUND = 3; // Возврат расхода - - const - TAX_MODE_OSN = 1, // общая СН - TAX_MODE_USN_INCOME = 2, // упрощенная СН (доходы) - TAX_MODE_USN_INCOME_OUTCOME = 4, // упрощенная СН (доходы минус расходы) - TAX_MODE_ENDV = 8, // единый налог на вмененный доход - TAX_MODE_ESN = 16, // единый сельскохозяйственный налог - TAX_MODE_PATENT = 32; // патентная СН - - /** - * @inheritdoc - */ - public function getUrlPath() { - return '/fr/api/v2/Complex'; - } - + protected $Consideration; + /** @var string */ + protected $Address; + /** @var string */ + protected $Terminal; + /** @var int */ + private $phone; + /** @var string */ + private $email; + /** @var Line[] */ + private $lines; + + /** + * @inheritdoc + */ + public function getUrlPath() + { + return '/fr/api/v2/Complex'; + } + /** * @param int $requestId id запроса */ - public function __construct($requestId) { - $this->requestId = $requestId; + public function __construct($requestId) + { + $this->RequestId = (string)$requestId; } - + /** * Установить идентификатор предприятия. Передается в случае использования одного сертификата на несколько предприятий * @param string $group - * return $this */ - public function addGroup($group){ - $this->group = $group; - return $this; + public function addGroup($group) + { + $this->Group = (string)$group; } - + /** * Установить тип чека - * @param string $documentType - * @return $this + * @param DocumentTypes $documentType */ - public function addDocumentType($documentType){ - if(!in_array($documentType, $this->getDocumentTypes())){ - throw new SdkException('Wrong payment type'); - } - - $this->documentType = $documentType; - return $this; + public function addDocumentType(DocumentTypes $documentType) + { + $this->documentType = $documentType->getValue(); } /** * Установить режим налогообложения. Нужно если у организации существует более 1 системы налогообложения - * @param int $taxMode - * @return $this + * @param TaxModes $taxMode */ - public function addTaxMode($taxMode){ - if(!in_array($taxMode, $this->getTaxModes())){ - throw new SdkException('Wrong tax mode'); - } - - $this->taxMode = $taxMode; - return $this; + public function addTaxMode(TaxModes $taxMode) + { + $this->TaxMode = $taxMode->getValue(); } - + /** * Установить телефон покупателя * @param int $phone - * @return $this */ - public function addPhone($phone){ - $this->phone = $phone; - return $this; + public function addPhone($phone) + { + $this->phone = (string)$phone; } - + /** * Установить email покупателя * @param string $email - * @return $this */ - public function addEmail($email){ - $this->email = $email; - return $this; + public function addEmail($email) + { + $this->email = (string)$email; } - + /** * Сумма оплаты наличными. Если сумма равна нулю, то это поле можно опустить * @param float $cash - * @return $this */ - public function addCash($cash){ - $this->cash = $cash; - return $this; + public function addCash($cash) + { + $this->Cash = (int)$cash; } - + /** * Массив из 3-ех элеметов с суммами оплат 3 различных типов. Обычно передается только первое значение * @param int $firstAmount Сумма в копейках * @param int $secondAmount Сумма в копейках * @param int $thirdAmount Сумма в копейках - * @return $this */ - public function addNonCash($firstAmount, $secondAmount = 0, $thirdAmount = 0){ - $this->nonCash = [$firstAmount, $secondAmount, $thirdAmount]; - return $this; + public function addNonCash($firstAmount, $secondAmount = 0, $thirdAmount = 0) + { + $this->NonCash = [(int)$firstAmount, (int)$secondAmount, (int)$thirdAmount]; } - + /** * Сумма оплаты предоплатой. Поле не обязательное * @param int $advancePayment Сумма в копейках - * @return $this */ - public function addAdvancePayment($advancePayment){ - $this->advancePayment = $advancePayment; - return $this; + public function addAdvancePayment($advancePayment) + { + $this->AdvancePayment = (int)$advancePayment; } - + /** * Сумма оплаты постоплатой. Не обязательное * @param int $credit Сумма в копейках - * @return $this */ - public function addCredit($credit){ - $this->credit = $credit; - return $this; + public function addCredit($credit) + { + $this->Credit = (int)$credit; } - + /** * Сумма оплаты встречным предоставлением. Не обязательное * @param int $consideration Сумма в копейках - * @return $this */ - public function addConsideration($consideration){ - $this->consideration = $consideration; - return $this; + public function addConsideration($consideration) + { + $this->Consideration = (int)$consideration; } - + /** * Место расчетов. Можно указать адрес сайта * @param string $place - * @return $this */ - public function addPlace($place){ - $this->place = $place; - return $this; + public function addPlace($place) + { + $this->Place = (string)$place; } - + /** * Добавить позицию в чек * @param Line $line - * @return $this */ - public function addLine(Line $line){ + public function addLine(Line $line) + { $this->lines[] = $line; - return $this; } - + /** * Установить пароль. Не обязательно. Подробнее смотри в полной версии документации * @param int $password - * @return $this */ - public function addPassword($password){ - $this->password = $password; - return $this; + public function addPassword($password) + { + $this->Password = (string)$password; } - + /** - * {@inheritdoc} + * @param $clientId */ - public function getParameters() { - $lines = []; - foreach($this->lines as $line){ - $lines[] = $line->getParameters(); - } - - $params = [ - 'Device' => $this->device, - 'Group' => $this->group, - 'Password' => $this->password, - 'RequestId' => (string)$this->requestId, - 'Lines' => $lines, - 'Cash' => $this->cash, - 'NonCash' => $this->nonCash, - 'AdvancePayment' => $this->advancePayment, - 'Credit' => $this->credit, - 'Consideration' => $this->consideration, - 'TaxMode' => $this->taxMode, - 'DocumentType' => $this->documentType, - 'PhoneOrEmail' => $this->email ? $this->email : $this->phone, - 'Place' => $this->place, - 'FullResponse' => $this->fullResponse, - ]; - - return $params; - } - - protected function getDocumentTypes(){ - return [ - self::DOCUMENT_TYPE_BUY, - self::DOCUMENT_TYPE_BUY_REFUND, - self::DOCUMENT_TYPE_SELL, - self::DOCUMENT_TYPE_SELL_REFUND, - ]; - } + public function addClientId($clientId) + { + $this->ClientId = (string)$clientId; + } - protected function getTaxModes(){ - return [ - self::TAX_MODE_ENDV, - self::TAX_MODE_ESN, - self::TAX_MODE_OSN, - self::TAX_MODE_PATENT, - self::TAX_MODE_USN_INCOME, - self::TAX_MODE_USN_INCOME_OUTCOME, - ]; - } + /** + * @param string $address + */ + public function addAddress($address) + { + $this->Address = (string)$address; + } + + /** + * @param $terminal + */ + public function addTerminal($terminal) + { + $this->Terminal = $terminal; + } + + /** + * @return array + */ + public function getParameters() + { + $params = parent::getParameters(); + $params['PhoneOrEmail'] = $this->email ? $this->email : $this->phone; + $params['FullResponse'] = true; + foreach($this->lines as $line){ + $params['Lines'][] = $line->getParameters(); + } + return $params; + } } diff --git a/src/services/ComplexResponse.php b/src/services/ComplexResponse.php index 11455a1..7904f2a 100644 --- a/src/services/ComplexResponse.php +++ b/src/services/ComplexResponse.php @@ -2,30 +2,30 @@ namespace Platron\Starrys\services; -use Platron\Starrys\services\BaseServiceResponse; use stdClass; -class ComplexResponse extends BaseServiceResponse { +class ComplexResponse extends BaseServiceResponse +{ /** @var int День формирования документа */ - public $Day; + public $Day; /** @var int Месяц формирования документа */ - public $Month; + public $Month; /** @var int Год формирования документа */ - public $Year; + public $Year; /** @var int Час формирования документа */ - public $Hour; + public $Hour; /** @var int Минута формирования документа */ - public $Minute; + public $Minute; /** @var int Секунда формирования документа */ - public $Second; + public $Second; /** @var string Регистрационный номер документа */ - public $DeviceRegistrationNumber; + public $DeviceRegistrationNumber; /** @var string Заводской номер устройста */ - public $DeviceSerialNumber; + public $DeviceSerialNumber; /** @var string Номер фискального накопителя, в котором сформирован документ */ public $FNSerialNumber; - /** @var string Номер фискального документа */ + /** @var string Номер фискального документа */ public $FiscalDocNumber; /** @var string Фискальный признак документа */ public $FiscalSign; @@ -33,33 +33,34 @@ class ComplexResponse extends BaseServiceResponse { public $GrandTotal; /** @var string QR-код чека */ public $QR; - + /** @var string Заводской номер устройства */ public $Name; /** @var string Адрес устройства */ public $Address; - - /** - * @inheritdoc - */ - public function __construct(stdClass $response) { - if(!empty($response->FCEError)){ + + /** + * @inheritdoc + */ + public function __construct(stdClass $response) + { + if (!empty($response->FCEError)) { $this->errorCode = $response->FCEError; $this->errorMessages[] = $response->ErrorDescription; return $this; } - - if(!empty($response->Response->Error)){ + + if (!empty($response->Response->Error)) { $this->errorCode = $response->Response->Error; - foreach($response->Response->ErrorMessages as $message){ + foreach ($response->Response->ErrorMessages as $message) { $this->errorMessages .= $message; } return $this; } - + parent::__construct($response); parent::__construct($response->Device); parent::__construct($response->Date->Date); parent::__construct($response->Date->Time); - } + } } diff --git a/tests/integration/ComplexTest.php b/tests/integration/ComplexTest.php index 7c7a14f..34a31fe 100644 --- a/tests/integration/ComplexTest.php +++ b/tests/integration/ComplexTest.php @@ -3,27 +3,72 @@ namespace Platron\Starrys\tests\integration; use Platron\Starrys\clients\PostClient; +use Platron\Starrys\data_objects\AgentData; +use Platron\Starrys\data_objects\GetPaymentOperatorData; use Platron\Starrys\data_objects\Line; +use Platron\Starrys\data_objects\ProviderData; +use Platron\Starrys\data_objects\TransferOperatorData; +use Platron\Starrys\handbooks\AgentModes; +use Platron\Starrys\handbooks\DocumentTypes; +use Platron\Starrys\handbooks\PayAttributeTypes; +use Platron\Starrys\handbooks\Taxes; +use Platron\Starrys\handbooks\TaxModes; use Platron\Starrys\services\ComplexRequest; use Platron\Starrys\services\ComplexResponse; -class ComplexTest extends IntegrationTestBase { - public function testComplex(){ +class ComplexTest extends IntegrationTestBase +{ + public function testComplex() + { $client = new PostClient($this->starrysApiUrl, $this->secretKeyPath, $this->certPath); - $line = new Line('Test product', 1, 10.00, Line::TAX_VAT18); - $line->addPayAttribute(Line::PAY_ATTRIBUTE_TYPE_FULL_PAID_WITH_GET_PRODUCT); - - $complexServise = new ComplexRequest(time()); - $complexServise->addDocumentType(ComplexRequest::DOCUMENT_TYPE_BUY) - ->addEmail('test@test.ru') - ->addPhone('79050000000') - ->addPlace('www.test.ru') - ->addTaxMode($this->taxMode) - ->addLine($line) - ->addNonCash(10.00); - - $response = new ComplexResponse($client->sendRequest($complexServise)); - + $client->setLogger(new TestLogger()); + $complexRequest = $this->createComplexRequest(); + $response = new ComplexResponse($client->sendRequest($complexRequest)); $this->assertTrue($response->isValid()); } + + /** + * @return Line + */ + private function createLine() + { + $line = new Line('Test product', 1, 10.00, new Taxes(Taxes::VAT10)); + $line->addPayAttribute(new PayAttributeTypes(PayAttributeTypes::FULL_PAID_WITH_GET_PRODUCT)); + + $agentData = new AgentData('Test operation', '79050000000'); + $line->addAgentData($agentData); + + $line->addAgentModes(new AgentModes(AgentModes::PAYMENT_AGENT)); + $getPaymentOperatorData = new GetPaymentOperatorData('79050000001'); + $line->addGetPaymentOperatorData($getPaymentOperatorData); + $providerData = new ProviderData('Test provider data', '7123456789', '79050000002'); + $line->addProviderData($providerData); + $transferOperatorData = new TransferOperatorData( + 'Test transfer operator', + '7123456781', + 'Test transfer operator address', + '79050000003' + ); + $line->addTransferOperatorData($transferOperatorData); + return $line; + } + + /** + * @return ComplexRequest + */ + private function createComplexRequest() + { + $line = $this->createLine(); + + $complexRequest = new ComplexRequest(time()); + $complexRequest->addClientId('testClientId'); + $complexRequest->addDocumentType(new DocumentTypes(DocumentTypes::BUY)); + $complexRequest->addEmail('test@test.ru'); + $complexRequest->addPhone('79050000000'); + $complexRequest->addPlace('www.test.ru'); + $complexRequest->addTaxMode(new TaxModes($this->taxMode)); + $complexRequest->addLine($line); + $complexRequest->addNonCash(10.00); + return $complexRequest; + } } diff --git a/tests/integration/IntegrationTestBase.php b/tests/integration/IntegrationTestBase.php index 1b2775d..bb3c716 100644 --- a/tests/integration/IntegrationTestBase.php +++ b/tests/integration/IntegrationTestBase.php @@ -2,25 +2,25 @@ namespace Platron\Starrys\tests\integration; -use Platron\Starrys\tests\integration\MerchantSettings; - -class IntegrationTestBase extends \PHPUnit_Framework_TestCase { +class IntegrationTestBase extends \PHPUnit_Framework_TestCase +{ /** @var int */ protected $taxMode; /** @var sting Адрес для запросов */ protected $starrysApiUrl; - /** @var string Путь до приватного ключа */ - protected $secretKeyPath; - /** @var string Путь до сертифката */ - protected $certPath; - - public function __construct() { + /** @var string Путь до приватного ключа */ + protected $secretKeyPath; + /** @var string Путь до сертифката */ + protected $certPath; + + public function __construct() + { parent::__construct(); - + $this->taxMode = MerchantSettings::TAX_MODE; $this->starrysApiUrl = MerchantSettings::API_STARRYS_URL; - $this->secretKeyPath = 'tests/integration/merchant_data/'.MerchantSettings::SECRET_KEY_NAME; - $this->certPath = 'tests/integration/merchant_data/'.MerchantSettings::CERT_NAME; - } + $this->secretKeyPath = 'tests/integration/merchant_data/' . MerchantSettings::SECRET_KEY_NAME; + $this->certPath = 'tests/integration/merchant_data/' . MerchantSettings::CERT_NAME; + } } diff --git a/tests/integration/MerchantSettingsSample.php b/tests/integration/MerchantSettingsSample.php index ddceafd..10c5ffc 100644 --- a/tests/integration/MerchantSettingsSample.php +++ b/tests/integration/MerchantSettingsSample.php @@ -2,12 +2,13 @@ namespace Platron\Starrys\tests\integration; -use Platron\Starrys\services\ComplexRequest; +use Platron\Starrys\handbooks\TaxModes; -class MerchantSettings { - const - TAX_MODE = ComplexRequest::TAX_MODE_OSN, - SECRET_KEY_NAME = 'client.key', - CERT_NAME = 'client.crt', +class MerchantSettings +{ + const + TAX_MODE = TaxModes::OSN, + SECRET_KEY_NAME = 'client.key', + CERT_NAME = 'client.crt', API_STARRYS_URL = 'https://fce.starrys.ru:4443'; } diff --git a/tests/integration/TestLogger.php b/tests/integration/TestLogger.php new file mode 100644 index 0000000..e42c042 --- /dev/null +++ b/tests/integration/TestLogger.php @@ -0,0 +1,59 @@ +logToFile($message); + } + + public function alert($message, array $context = array()) + { + $this->logToFile($message); + } + + public function critical($message, array $context = array()) + { + $this->logToFile($message); + } + + public function error($message, array $context = array()) + { + $this->logToFile($message); + } + + public function warning($message, array $context = array()) + { + $this->logToFile($message); + } + + public function notice($message, array $context = array()) + { + $this->logToFile($message); + } + + public function info($message, array $context = array()) + { + $this->logToFile($message); + } + + public function debug($message, array $context = array()) + { + $this->logToFile($message); + } + + public function log($level, $message, array $context = array()) + { + $this->logToFile($message); + } + + private function logToFile($message) + { + $preparedString = date('Y-m-d H:i:s') . '; ' . $message . PHP_EOL; + file_put_contents(__DIR__ . '/logs/' . date('Y-m-d') . '.log', $preparedString, FILE_APPEND); + } +} \ No newline at end of file