diff --git a/src/bb-library/Payment/Adapter/Interkassa.php b/src/bb-library/Payment/Adapter/Interkassa.php index 4978b5433..1a44a2388 100644 --- a/src/bb-library/Payment/Adapter/Interkassa.php +++ b/src/bb-library/Payment/Adapter/Interkassa.php @@ -10,11 +10,32 @@ * with this source code in the file LICENSE */ -class Payment_Adapter_Interkassa extends Payment_AdapterAbstract +class Payment_Adapter_Interkassa extends Payment_AdapterAbstract implements \Box\InjectionAwareInterface { + /** + * @var Box_Di + */ + protected $di; + + /** + * @param Box_Di $di + */ + public function setDi($di) + { + $this->di = $di; + } + + /** + * @return Box_Di + */ + public function getDi() + { + return $this->di; + } + public function init() { - if(!$this->getParam('ik_shop_id')) { + if(!$this->getParam('ik_co_id')) { throw new Payment_Exception('Shop ID is missing in gateway configuration'); } if(!$this->getParam('ik_secret_key')) { @@ -39,7 +60,7 @@ class Payment_Adapter_Interkassa extends Payment_AdapterAbstract 'supports_subscriptions' => false, 'description' => 'это удобный в использовании сервис, подключение к которому позволит Интернет-магазинам, веб-сайтам и прочим торговым площадкам принимать все возможные формы оплаты в максимально короткие сроки. http://www.interkassa.com/', 'form' => array( - 'ik_shop_id' => array('text', array( + 'ik_co_id' => array('text', array( 'label' => 'Shop ID which is registered in "INTERKASSA" system. Can be found under area "Настройки магазина". Example: 64C18529-4B94-0B5D-7405-F2752F2B716C', 'value' => '', ), @@ -49,6 +70,11 @@ class Payment_Adapter_Interkassa extends Payment_AdapterAbstract 'value' => '', ), ), + 'ik_secret_key_test' => array('password', array( + 'label' => 'Test Key.', + 'value' => '', + ), + ), ), ); } @@ -60,33 +86,38 @@ class Payment_Adapter_Interkassa extends Payment_AdapterAbstract */ public function getServiceUrl() { - return 'https://api.interkassa.com/v1/'; + if($this->getParam('test_mode')) { + return 'https://sci.interkassa.com/demo/'; + } + return 'https://sci.interkassa.com/'; } /** * Init single payment call to webservice * Invoice id is passed via notify_url * - * @return mixed + * @param Payment_Invoice $invoice + * @return array */ public function singlePayment(Payment_Invoice $invoice) { - $buyer = $invoice->getBuyer(); return array( - 'ik_shop_id' => $this->getParam('ik_shop_id'), - 'ik_payment_amount' => $invoice->getTotalWithTax(), - 'ik_payment_id' => $invoice->getId(), - 'ik_payment_desc' => $invoice->getTitle(), - 'ik_paysystem_alias' => '', + 'ik_co_id' => $this->getParam('ik_co_id'), + 'ik_pm_no' => $invoice->getId(), + 'ik_am' => $invoice->getTotal(), + 'ik_desc' => $invoice->getTitle(), + 'ik_cur' => $invoice->getCurrency(), - 'ik_baggage_fields' => $buyer->getEmail(), + 'ik_ia_u' => $this->getParam('notify_url'), + 'ik_ia_m' => 'post', + 'ik_suc_u' => $this->getParam('return_url'), + 'ik_suc_m' => 'get', + 'ik_pnd_u' => $this->getParam('return_url'), + 'ik_pnd_m' => 'get', + 'ik_fal_u' => $this->getParam('cancel_url'), + 'ik_fal_m' => 'get', - 'ik_success_url' => $this->getParam('return_url'), - 'ik_success_method' => 'GET', - 'ik_fail_url' => $this->getParam('cancel_url'), - 'ik_fail_method' => 'GET', - 'ik_status_url' => $this->getParam('notify_url'), - 'ik_status_method' => 'POST', + 'ik_x_iid' => $invoice->getId(), ); } @@ -109,40 +140,100 @@ class Payment_Adapter_Interkassa extends Payment_AdapterAbstract $ipn = $data['post']; $tx = new Payment_Transaction(); - $tx->setId($ipn['ik_payment_id']); - $tx->setAmount($ipn['ik_payment_amount']); - $tx->setCurrency($invoice->getCurrency()); + $tx->setId($ipn['ik_trn_id']); + $tx->setAmount($ipn['ik_am']); + $tx->setCurrency($ipn['ik_cur']); $tx->setType(Payment_Transaction::TXTYPE_PAYMENT); - if($ipn['ik_payment_state'] == 'success' || $ipn['ik_payment_state'] == 'completed') { + if($ipn['ik_inv_st'] == 'success') { $tx->setStatus(Payment_Transaction::STATUS_COMPLETE); } return $tx; } - public function isIpnValid($data, Payment_Invoice $invoice) + public function isIpnValid($data) { $status_data = $data['post']; - $shop_id = $this->getParam('ik_shop_id'); + $shop_id = $this->getParam('ik_co_id'); $secret_key = $this->getParam('ik_secret_key'); - - if($shop_id != $status_data['ik_shop_id']) { + if($this->getParam('test_mode')) { + $secret_key = $this->getParam('ik_secret_key_test'); + } + + if($shop_id != $status_data['ik_co_id']) { error_log('Shop ids does not match'); return false; } - $sing_hash_str = $status_data['ik_shop_id'].':'. - $status_data['ik_payment_amount'].':'. - $status_data['ik_payment_id'].':'. - $status_data['ik_paysystem_alias'].':'. - $status_data['ik_baggage_fields'].':'. - $status_data['ik_payment_state'].':'. - $status_data['ik_trans_id'].':'. - $status_data['ik_currency_exch'].':'. - $status_data['ik_fees_payer'].':'. - $secret_key; - $sign_hash = strtoupper(md5($sing_hash_str)); - return ($status_data['ik_sign_hash'] === $sign_hash); + $dataSet = $status_data; + unset($dataSet["ik_sign"]); + ksort($dataSet, SORT_STRING); // sort by the keys in alphabetical order array elements + array_push($dataSet, $secret_key); // add in the end of array “secret key” + $signString = implode(':', $dataSet); // concatenate value through the ":" symbol + $sign = base64_encode(md5($signString, true)); // take MD5 hash in a binary form by the + + return ($status_data["ik_sign"] == $sign); + } + + public function processTransaction($api_admin, $id, $data, $gateway_id) + { + if(!$this->isIpnValid($data)) { + throw new Exception('IPN is not valid'); + } + + $ipn = $data['post']; + + $tx = $this->di['db']->load('Transaction', $id); + + if(!$tx->invoice_id) { + $tx->invoice_id = $ipn['ik_x_iid']; + } + + if(!$tx->txn_id) { + $tx->txn_id = $ipn['ik_trn_id']; + } + + if(!$tx->txn_status) { + $tx->txn_status = $ipn['ik_inv_st']; + } + + if(!$tx->amount) { + $tx->amount = $ipn['ik_am']; + } + + if(!$tx->currency) { + $tx->currency = $ipn['ik_cur']; + } + $this->di['db']->store($tx); + + if ($ipn['ik_inv_st'] == 'success') { + $invoiceModel = $this->di['db']->load('Invoice', $data['get']['bb_invoice_id']); + $clientModel = $this->di['db']->load('Client', $invoiceModel->client_id); + + $bd = array( + 'id' => $clientModel->id, + 'amount' => $ipn['ik_am'], + 'description' => 'Interkassa transaction '.$ipn['ik_trn_id'], + 'type' => 'Interkassa', + 'rel_id' => $ipn['ik_trn_id'], + ); + + $clientService = $this->di['mod_service']('Client'); + $clientService->addFunds($clientModel, $bd['amount'], $bd['description'], $bd); + + $invoiceService = $this->di['mod_service']('Invoice'); + if($tx->invoice_id) { + $invoiceService->payInvoiceWithCredits($invoiceModel); + } + $invoiceService->doBatchPayWithCredits(array('client_id' => $clientModel->id)); + } + + $tx->error = ''; + $tx->error_code = ''; + $tx->status = 'processed'; + $tx->updated_at = date('c'); + $this->di['db']->store($tx); + return true; } } \ No newline at end of file diff --git a/src/bb-modules/Invoice/Service.php b/src/bb-modules/Invoice/Service.php index f24d50395..c4bd5f2f0 100644 --- a/src/bb-modules/Invoice/Service.php +++ b/src/bb-modules/Invoice/Service.php @@ -37,55 +37,6 @@ class Service implements InjectionAwareInterface return $this->di; } - public function getPaymentAdapter(\Model_PayGateway $pg, \Model_Invoice $model = null, $optional = array()) - { - $defaults = array(); - $config = $this->di['tools']->decodeJ($pg->config); - - $cancel_url = $this->di['url']->link('invoice', array('status' => 'cancel')); - $return_url = $this->di['url']->link('invoice', array('status' => 'ok')); - $callback_url = $this->di['url']->get('bb-ipn.php?bb_gateway_id='.$pg->id); - $callback_redirect_url = $callback_url; - - if($model instanceof \Model_Invoice) { - $cancel_url = $this->di['url']->get('invoice/'.$model->hash.'?status=cancel'); - $return_url = $this->di['url']->get('invoice/'.$model->hash.'?status=ok'); - $callback_url .= '&bb_invoice_id='.$model->id; - $callback_redirect_url .= '&bb_invoice_id='.$model->id.'&bb_redirect_=1&&bb_invoice_hash='.$model->hash; - $defaults['thankyou_url'] = $this->di['url']->get('invoice/thank-you/'.$model->hash); - $defaults['invoice_url'] = $this->di['url']->get('invoice/'.$model->hash); - } - - $defaults['auto_redirect'] = false; - $defaults['test_mode'] = (bool)$pg->test_mode; - $defaults['return_url'] = $return_url; - $defaults['cancel_url'] = $cancel_url; - $defaults['notify_url'] = $callback_url; - $defaults['redirect_url'] = $callback_redirect_url; - $defaults['continue_shopping_url'] = $this->di['url']->get('order'); - $defaults['single_page'] = true; - - if(isset($optional['auto_redirect'])) { - $defaults['auto_redirect'] = $optional['auto_redirect']; - } - - $config = array_merge($config, $defaults); - $class = sprintf('Payment_Adapter_%s', $pg->gateway); - - if(!class_exists($class)) { - throw new \Box_Exception("Payment gateway :adapter was not found", array(':adapter'=>$class)); - } - - $adapter = new $class($config); - - //set dependency injection without interface - if(method_exists($adapter, 'setDi')) { - $adapter->setDi($this->di); - } - - return $adapter; - } - public function getSearchQuery($data) { $sql="SELECT p.* diff --git a/src/bb-modules/Invoice/ServicePayGateway.php b/src/bb-modules/Invoice/ServicePayGateway.php index 1953f1719..c570206df 100644 --- a/src/bb-modules/Invoice/ServicePayGateway.php +++ b/src/bb-modules/Invoice/ServicePayGateway.php @@ -246,6 +246,11 @@ class ServicePayGateway implements InjectionAwareInterface } $adapter = new $class($config); + + if(method_exists($adapter, 'setDi')) { + $adapter->setDi($this->di); + } + return $adapter; } diff --git a/tests/bb-library/Payment/Adapter/Payment_Adapter_InterkassaTest.php b/tests/bb-library/Payment/Adapter/Payment_Adapter_InterkassaTest.php new file mode 100644 index 000000000..b89903586 --- /dev/null +++ b/tests/bb-library/Payment/Adapter/Payment_Adapter_InterkassaTest.php @@ -0,0 +1,408 @@ +defaultConfig = array( + 'url' => 'boxbilling.test', + 'return_url' => 'boxbilling.test', + 'notify_url' => 'boxbilling.test', + 'cancel_url' => 'boxbilling.test', + 'redirect_url' => 'boxbilling.test', + + 'ik_co_id' => '64C18529-4B94-0B5D-7405-F2752F2B716C', + 'ik_secret_key' => 'RhAAaJ2AwydMbKzN', + ); + } + + public function testDi() + { + $di = new \Box_Di(); + + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa')->disableOriginalConstructor() + ->setMethods(array('setDi', 'getDi')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('setDi') + ->with($di); + $adapterMock->setDi($di); + + $adapterMock->expects($this->atLeastOnce()) + ->method('getDi') + ->willReturn($di); + + $getDi = $adapterMock->getDi(); + $this->assertEquals($di, $getDi); + } + + public function testinit() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa')->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $adapterMock->expects($this->exactly(2)) + ->method('getParam') + ->withConsecutive(array('ik_co_id'), array('ik_secret_key')) + ->willReturnOnConsecutiveCalls('shop_id', 'secret_key_value'); + + $adapterMock->init(); + } + + public function testinitShopIdMissing() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa')->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('getParam') + ->with('ik_co_id'); + + $this->setExpectedException('Payment_Exception', 'Shop ID is missing in gateway configuration'); + $adapterMock->init(); + } + + public function testinitSecrectKeyMissing() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa')->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('getParam') + ->withConsecutive(array('ik_co_id'), array('ik_secret_key')) + ->willReturnOnConsecutiveCalls('shop_id_value', null); + + $this->setExpectedException('Payment_Exception', 'Secret key is missing in gateway configuration'); + $adapterMock->init(); + } + + public function testgetType() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(null) + ->getMock(); + $this->assertEquals(Payment_AdapterAbstract::TYPE_FORM, $adapterMock->getType()); + } + + public function testgetConfig() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(null) + ->getMock(); + $config = $adapterMock->getConfig(); + + $this->assertArrayHasKey('supports_one_time_payments', $config); + $this->assertArrayHasKey('supports_subscriptions', $config); + $this->assertArrayHasKey('description', $config); + $this->assertArrayHasKey('form', $config); + + $this->assertArrayHasKey('ik_co_id', $config['form']); + $this->assertArrayHasKey('ik_secret_key', $config['form']); + $this->assertArrayHasKey('ik_secret_key_test', $config['form']); + } + + public function testgetServiceUrl() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('getParam') + ->with('test_mode') + ->willReturn(false); + + $result = $adapterMock->getServiceUrl(); + $this->assertEquals('https://sci.interkassa.com/', $result); + } + + public function testgetServiceUrl_TestEnabled() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('getParam') + ->with('test_mode') + ->willReturn(true); + + $result = $adapterMock->getServiceUrl(); + $this->assertEquals('https://sci.interkassa.com/demo/', $result); + } + + public function testsinglePayment() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + $adapterMock->expects($this->atLeastOnce()) + ->method('getParam') + ->withConsecutive('notify_url', 'return_url', 'return_url', 'cancel_url'); + + $paymentInvoiceMock = $this->getMockBuilder('Payment_Invoice') + ->getMock(); + $paymentInvoiceMock->expects($this->atLeastOnce()) + ->method('getId'); + $paymentInvoiceMock->expects($this->atLeastOnce()) + ->method('getTotal'); + $paymentInvoiceMock->expects($this->atLeastOnce()) + ->method('getTitle'); + $paymentInvoiceMock->expects($this->atLeastOnce()) + ->method('getCurrency'); + $paymentInvoiceMock->expects($this->atLeastOnce()) + ->method('getTotal'); + + + $result = $adapterMock->singlePayment($paymentInvoiceMock); + + $this->assertArrayHasKey('ik_co_id', $result); + $this->assertArrayHasKey('ik_pm_no', $result); + $this->assertArrayHasKey('ik_am', $result); + $this->assertArrayHasKey('ik_desc', $result); + $this->assertArrayHasKey('ik_cur', $result); + + $this->assertArrayHasKey('ik_ia_u', $result); + $this->assertArrayHasKey('ik_ia_m', $result); + $this->assertArrayHasKey('ik_suc_u', $result); + $this->assertArrayHasKey('ik_suc_m', $result); + $this->assertArrayHasKey('ik_pnd_u', $result); + $this->assertArrayHasKey('ik_pnd_m', $result); + $this->assertArrayHasKey('ik_fal_u', $result); + $this->assertArrayHasKey('ik_fal_m', $result); + + $this->assertArrayHasKey('ik_x_iid', $result); + } + + public function testrecurrentPayment() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(null) + ->getMock(); + + $paymentInvoiceMock = $this->getMockBuilder('Payment_Invoice') + ->getMock(); + + $this->setExpectedException('Payment_Exception', 'Interkassa payment gateway do not support recurrent payments'); + $adapterMock->recurrentPayment($paymentInvoiceMock); + } + + public function testgetTransaction() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(null) + ->getMock(); + + $data = array( + 'post' => array( + 'ik_trn_id' => 1, + 'ik_am' => 0.10, + 'ik_cur' => 'USD', + 'ik_inv_st' => 'success', + ), + ); + $paymentInvoiceMock = $this->getMockBuilder('Payment_Invoice') + ->getMock(); + $result = $adapterMock->getTransaction($data, $paymentInvoiceMock); + $this->assertInstanceOf('Payment_Transaction', $result); + } + + public function testisIpnValid() + { + $shop_id = '123'; + $secret_key = '123'; + $signValue = '1NKiNTfKnBLzl8KYPhbNUA=='; + + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('getParam') + ->withConsecutive('ik_co_id', 'ik_secret_key') + ->willReturnOnConsecutiveCalls($shop_id, $secret_key); + + $data = array( + 'post' => array( + 'ik_co_id' => $shop_id, + 'ik_trn_id' => 1, + 'ik_am' => 0.10, + 'ik_cur' => 'USD', + 'ik_inv_st' => 'success', + 'ik_sign' => $signValue, + ), + ); + + $result = $adapterMock->isIpnValid($data); + $this->assertTrue($result); + } + + public function testisIpnValid_MismatchShopId() + { + $shop_id = '12345'; + $secret_key = '123'; + $signValue = '1NKiNTfKnBLzl8KYPhbNUA=='; + + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('getParam') + ->withConsecutive('ik_co_id', 'ik_secret_key') + ->willReturnOnConsecutiveCalls($shop_id, $secret_key); + + $data = array( + 'post' => array( + 'ik_co_id' => 123, + ), + ); + + $result = $adapterMock->isIpnValid($data); + $this->assertFalse($result); + } + + public function testisIpnValid_TestMode() + { + $shop_id = '123'; + $secret_key = '123'; + $signValue = '1NKiNTfKnBLzl8KYPhbNUA=='; + + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('getParam') + ->withConsecutive('ik_co_id', 'ik_secret_key', 'test_mode', 'ik_secret_key_test') + ->willReturnOnConsecutiveCalls($shop_id, $secret_key, true, $secret_key); + + $data = array( + 'post' => array( + 'ik_co_id' => $shop_id, + 'ik_trn_id' => 1, + 'ik_am' => 0.10, + 'ik_cur' => 'USD', + 'ik_inv_st' => 'success', + 'ik_sign' => $signValue, + ), + ); + + $result = $adapterMock->isIpnValid($data); + $this->assertTrue($result); + } + + public function testprocessTransaction() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(array('isIpnValid')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('isIpnValid') + ->willReturn(false); + + $this->setExpectedException('Exception', 'IPN is not valid'); + + $adminModel = new \Model_Admin(); + $api_admin = new \Api_Handler($adminModel); + + $transaction_id = 1; + $data = array(); + $gateway_id = 1; + $adapterMock->processTransaction($api_admin, $transaction_id, $data, $gateway_id); + } + + public function testprocessTransaction_Success() + { + $adapterMock = $this->getMockBuilder('\Payment_Adapter_Interkassa') + ->disableOriginalConstructor() + ->setMethods(array('isIpnValid')) + ->getMock(); + + $adapterMock->expects($this->atLeastOnce()) + ->method('isIpnValid') + ->willReturn(true); + + $dbMock = $this->getMockBuilder('\Box_Database')->getMock(); + + $transactionModel = new \Model_Transaction(); + $transactionModel->loadBean(new \RedBeanPHP\OODBBean()); + + $invoiceModel= new \Model_Invoice(); + $invoiceModel->loadBean(new \RedBeanPHP\OODBBean()); + + $clientModel = new \Model_Client(); + $clientModel ->loadBean(new \RedBeanPHP\OODBBean()); + + $dbMock->expects($this->atLeastOnce()) + ->method('load') + ->withConsecutive('Transaction', 'Invoice', 'Client') + ->willReturnOnConsecutiveCalls($transactionModel, $invoiceModel, $clientModel); + + $dbMock->expects($this->atLeastOnce()) + ->method('store') + ->with($transactionModel); + + $clientServiceMock = $this->getMockBuilder('\Box\Mod\Client\Service')->getMock(); + $clientServiceMock->expects($this->atLeastOnce()) + ->method('addFunds'); + + $invoiceServiceMock = $this->getMockBuilder('\Box\Mod\Invoice\Service')->getMock(); + $invoiceServiceMock->expects($this->atLeastOnce()) + ->method('payInvoiceWithCredits') + ->with($invoiceModel); + $invoiceServiceMock->expects($this->atLeastOnce()) + ->method('doBatchPayWithCredits'); + + $di = new \Box_Di(); + $di['mod_service'] = $di->protect(function ($serviceName) use($clientServiceMock, $invoiceServiceMock){ + if ($serviceName == 'Client'){ + return $clientServiceMock; + } + if ($serviceName == 'Invoice'){ + return $invoiceServiceMock; + } + }); + $di['db'] = $dbMock; + $adapterMock->setDi($di); + + $adminModel = new \Model_Admin(); + $api_admin = new \Api_Handler($adminModel); + + $transaction_id = 1; + $data = array( + 'post' => array( + 'ik_x_iid' => 1, + 'ik_trn_id' => 2, + 'ik_inv_st' => 'success', + 'ik_am' => 1.00, + 'ik_cur' => 'USD', + ), + ); + $gateway_id = 1; + $adapterMock->processTransaction($api_admin, $transaction_id, $data, $gateway_id); + } + + + + +}