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/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 708ef53..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; - +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) { + + /** + * @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 413dbdb..a1419d0 100644 --- a/src/services/ComplexRequest.php +++ b/src/services/ComplexRequest.php @@ -5,43 +5,46 @@ use Platron\Starrys\data_objects\Line; use Platron\Starrys\handbooks\DocumentTypes; use Platron\Starrys\handbooks\TaxModes; -use Platron\Starrys\SdkException; 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; + protected $TaxMode; /** @var int */ - protected $phone; + private $phone; /** @var string */ - protected $email; + private $email; /** @var string */ - protected $place; + 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; + protected $Consideration; + /** @var string */ + protected $Address; + /** @var string */ + protected $Terminal; /** * @inheritdoc @@ -56,7 +59,7 @@ public function getUrlPath() */ public function __construct($requestId) { - $this->requestId = $requestId; + $this->RequestId = (string)$requestId; } /** @@ -65,7 +68,7 @@ public function __construct($requestId) */ public function addGroup($group) { - $this->group = $group; + $this->Group = (string)$group; } /** @@ -83,7 +86,7 @@ public function addDocumentType(DocumentTypes $documentType) */ public function addTaxMode(TaxModes $taxMode) { - $this->taxMode = $taxMode->getValue(); + $this->TaxMode = $taxMode->getValue(); } /** @@ -92,7 +95,7 @@ public function addTaxMode(TaxModes $taxMode) */ public function addPhone($phone) { - $this->phone = $phone; + $this->phone = (string)$phone; } /** @@ -101,7 +104,7 @@ public function addPhone($phone) */ public function addEmail($email) { - $this->email = $email; + $this->email = (string)$email; } /** @@ -110,7 +113,7 @@ public function addEmail($email) */ public function addCash($cash) { - $this->cash = $cash; + $this->Cash = (int)$cash; } /** @@ -121,7 +124,7 @@ public function addCash($cash) */ public function addNonCash($firstAmount, $secondAmount = 0, $thirdAmount = 0) { - $this->nonCash = [$firstAmount, $secondAmount, $thirdAmount]; + $this->NonCash = [(int)$firstAmount, (int)$secondAmount, (int)$thirdAmount]; } /** @@ -130,7 +133,7 @@ public function addNonCash($firstAmount, $secondAmount = 0, $thirdAmount = 0) */ public function addAdvancePayment($advancePayment) { - $this->advancePayment = $advancePayment; + $this->AdvancePayment = (int)$advancePayment; } /** @@ -139,7 +142,7 @@ public function addAdvancePayment($advancePayment) */ public function addCredit($credit) { - $this->credit = $credit; + $this->Credit = (int)$credit; } /** @@ -148,7 +151,7 @@ public function addCredit($credit) */ public function addConsideration($consideration) { - $this->consideration = $consideration; + $this->Consideration = (int)$consideration; } /** @@ -157,7 +160,7 @@ public function addConsideration($consideration) */ public function addPlace($place) { - $this->place = $place; + $this->Place = (string)$place; } /** @@ -175,7 +178,31 @@ public function addLine(Line $line) */ public function addPassword($password) { - $this->password = $password; + $this->Password = (string)$password; + } + + /** + * @param $clientId + */ + public function addClientId($clientId) + { + $this->ClientId = (string)$clientId; + } + + /** + * @param string $address + */ + public function addAddress($address) + { + $this->Address = (string)$address; + } + + /** + * @param $terminal + */ + public function addTerminal($terminal) + { + $this->Terminal = $terminal; } /** @@ -183,28 +210,9 @@ public function addPassword($password) */ 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, - 'PhoneOrEmail' => $this->email ? $this->email : $this->phone, - 'Place' => $this->place, - 'FullResponse' => $this->fullResponse, - ]; - + $params = parent::getParameters(); + $params['PhoneOrEmail'] = $this->email ? $this->email : $this->phone; + $params['FullResponse'] = true; 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 e4c9d42..35f59d7 100644 --- a/tests/integration/ComplexTest.php +++ b/tests/integration/ComplexTest.php @@ -3,28 +3,70 @@ 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\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(new DocumentTypes(DocumentTypes::BUY)); - $complexServise->addEmail('test@test.ru'); - $complexServise->addPhone('79050000000'); - $complexServise->addPlace('www.test.ru'); - $complexServise->addTaxMode(new TaxModes($this->taxMode)); - $complexServise->addLine($line); - $complexServise->addNonCash(10.00); - - $response = new ComplexResponse($client->sendRequest($complexServise)); - + $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 adf8b45..bb3c716 100644 --- a/tests/integration/IntegrationTestBase.php +++ b/tests/integration/IntegrationTestBase.php @@ -2,26 +2,25 @@ namespace Platron\Starrys\tests\integration; -use Platron\Starrys\handbooks\TaxModes; -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 8b95cef..10c5ffc 100644 --- a/tests/integration/MerchantSettingsSample.php +++ b/tests/integration/MerchantSettingsSample.php @@ -4,10 +4,11 @@ use Platron\Starrys\handbooks\TaxModes; -class MerchantSettings { - const +class MerchantSettings +{ + const TAX_MODE = TaxModes::OSN, - SECRET_KEY_NAME = 'client.key', - CERT_NAME = 'client.crt', + SECRET_KEY_NAME = 'client.key', + CERT_NAME = 'client.crt', API_STARRYS_URL = 'https://fce.starrys.ru:4443'; }