diff --git a/DependencyInjection/Compiler/AddPaymentMethodFormTypesPass.php b/DependencyInjection/Compiler/AddPaymentMethodFormTypesPass.php index a253873a..bd9e5def 100755 --- a/DependencyInjection/Compiler/AddPaymentMethodFormTypesPass.php +++ b/DependencyInjection/Compiler/AddPaymentMethodFormTypesPass.php @@ -1,41 +1,41 @@ - - */ -class AddPaymentMethodFormTypesPass implements CompilerPassInterface -{ - public function process(ContainerBuilder $container) - { - if (!$container->hasDefinition('payment.form.choose_payment_method_type')) { - return; - } - - $paymentMethodFormTypes = array(); - foreach ($container->findTaggedServiceIds('payment.method_form_type') as $id => $attributes) { - $definition = $container->getDefinition($id); - - // check that this definition is also registered as a form type - $attributes = $definition->getTag('form.type'); - if (!$attributes) { - throw new \RuntimeException(sprintf('The service "%s" is marked as payment method form type (tagged with "payment.method_form_type"), but is not registered as a form type with the Form Component. Please also add a "form.type" tag.', $id)); - } - - if (!isset($attributes[0]['alias'])) { - throw new \RuntimeException(sprintf('Please define an alias attribute for tag "form.type" of service "%s".', $id)); - } - - $paymentMethodFormTypes[] = $attributes[0]['alias']; - } - - $container->getDefinition('payment.form.choose_payment_method_type') - ->addArgument($paymentMethodFormTypes); - } + + */ +class AddPaymentMethodFormTypesPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition('payment.form.choose_payment_method_type')) { + return; + } + + $paymentMethodFormTypes = array(); + foreach ($container->findTaggedServiceIds('payment.method_form_type') as $id => $attributes) { + $definition = $container->getDefinition($id); + + // check that this definition is also registered as a form type + $attributes = $definition->getTag('form.type'); + if (!$attributes) { + throw new \RuntimeException(sprintf('The service "%s" is marked as payment method form type (tagged with "payment.method_form_type"), but is not registered as a form type with the Form Component. Please also add a "form.type" tag.', $id)); + } + + if (!isset($attributes[0]['alias'])) { + throw new \RuntimeException(sprintf('Please define an alias attribute for tag "form.type" of service "%s".', $id)); + } + + $paymentMethodFormTypes[] = $attributes[0]['alias']; + } + + $container->getDefinition('payment.form.choose_payment_method_type') + ->addArgument($paymentMethodFormTypes); + } } \ No newline at end of file diff --git a/Form/ChoosePaymentMethodType.php b/Form/ChoosePaymentMethodType.php index 707a8058..2b4ba686 100755 --- a/Form/ChoosePaymentMethodType.php +++ b/Form/ChoosePaymentMethodType.php @@ -1,229 +1,229 @@ - - */ -class ChoosePaymentMethodType extends AbstractType -{ - private $pluginController; - private $paymentMethods; - - public function __construct(PluginControllerInterface $pluginController, array $paymentMethods) - { - if (!$paymentMethods) { - throw new \InvalidArgumentException('There is no payment method available. Did you forget to register concrete payment provider bundles such as JMSPaymentPaypalBundle?'); - } - - $this->pluginController = $pluginController; - $this->paymentMethods = $paymentMethods; - } - - public function buildForm(FormBuilderInterface $builder, array $options) - { - $allowAllMethods = !count($options['allowed_methods']); - - $options['available_methods'] = array(); - foreach ($this->paymentMethods as $method) { - if (!$allowAllMethods && !in_array($method, $options['allowed_methods'], true)) { - continue; - } - - $options['available_methods'][] = $method; - } - - if (!$options['available_methods']) { - throw new \RuntimeException(sprintf('You have not selected any payment methods. Available methods: "%s"', implode(', ', $this->paymentMethods))); - } - - $builder->add('method', 'choice', array( - 'choices' => $this->buildChoices($options['available_methods']), - 'expanded' => true, - 'data' => $options['default_method'], - )); - - foreach ($options['available_methods'] as $method) { - $methodOptions = isset($options['method_options'][$method]) ? $options['method_options'] : array(); - $builder->add('data_'.$method, $method, $methodOptions); - } - - $self = $this; - $builder->addEventListener(FormEvents::POST_BIND, function($form) use ($self, $options) { - $self->validate($form, $options); - }); - $builder->addModelTransformer(new CallbackTransformer( - function($data) use ($self, $options) { - return $self->transform($data, $options); - }, - function($data) use ($self, $options) { - return $self->reverseTransform($data, $options); - } - ), true); - } - - public function transform($data, array $options) - { - if (null === $data) { - return null; - } - - if ($data instanceof PaymentInstruction) { - $method = $data->getPaymentSystemName(); - $methodData = array_map(function($v) { return $v[0]; }, $data->getExtendedData()->all()); - if (isset($options['predefined_data'][$method])) { - $methodData = array_diff_key($methodData, $options['predefined_data'][$method]); - } - - return array( - 'method' => $method, - 'data_'.$method => $methodData, - ); - } - - throw new \RuntimeException(sprintf('Unsupported data of type "%s".', ('object' === $type = gettype($data)) ? get_class($data) : $type)); - } - - public function reverseTransform($data, array $options) - { - $method = isset($data['method']) ? $data['method'] : null; - $data = isset($data['data_'.$method]) ? $data['data_'.$method] : array(); - - $extendedData = new ExtendedData(); - foreach ($data as $k => $v) { - $extendedData->set($k, $v); - } - - if (isset($options['predefined_data'][$method])) { - if (!is_array($options['predefined_data'][$method])) { - throw new \RuntimeException(sprintf('"predefined_data" is expected to be an array for each method, but got "%s" for method "%s".', json_encode($options['extra_data'][$method]), $method)); - } - - foreach ($options['predefined_data'][$method] as $k => $v) { - $extendedData->set($k, $v); - } - } - - $amount = $this->computeAmount($options['amount'], $options['currency'], $method, $extendedData); - - return new PaymentInstruction($amount, $options['currency'], $method, $extendedData); - } - - public function validate(FormEvent $event, array $options) - { - $form = $event->getForm(); - $instruction = $form->getData(); - - if (null === $instruction->getPaymentSystemName()) { - $form->addError(new FormError('form.error.payment_method_required')); - - return; - } - if (!in_array($instruction->getPaymentSystemName(), $options['available_methods'], true)) { - $form->addError(new FormError('form.error.invalid_payment_method')); - - return; - } - - $result = $this->pluginController->checkPaymentInstruction($instruction); - if (Result::STATUS_SUCCESS !== $result->getStatus()) { - $this->applyErrorsToForm($form, $result); - - return; - } - - $result = $this->pluginController->validatePaymentInstruction($instruction); - if (Result::STATUS_SUCCESS !== $result->getStatus()) { - $this->applyErrorsToForm($form, $result); - } - } - - public function setDefaultOptions(OptionsResolverInterface $resolver) - { - $resolver->setDefaults(array( - 'allowed_methods' => array(), - 'default_method' => null, - 'predefined_data' => array(), - )); - - $resolver->setRequired(array( - 'amount', - 'currency', - )); - - $resolver->setAllowedTypes(array( - 'allowed_methods' => 'array', - 'amount' => array('numeric', 'closure'), - 'currency' => 'string', - 'predefined_data' => 'array', - )); - } - - public function getName() - { - return 'jms_choose_payment_method'; - } - - private function applyErrorsToForm(FormInterface $form, Result $result) - { - $ex = $result->getPluginException(); - - $globalErrors = $ex->getGlobalErrors(); - $dataErrors = $ex->getDataErrors(); - - // add a generic error message - if (!$dataErrors && !$globalErrors) { - $form->addError(new FormError('form.error.invalid_payment_instruction')); - - return; - } - - foreach ($globalErrors as $error) { - $form->addError(new FormError($error)); - } - - foreach ($dataErrors as $path => $error) { - $path = explode('.', $path); - $field = $form; - do { - $field = $field->get(array_shift($path)); - } while ($path); - - $field->addError(new FormError($error)); - } - } - - private function buildChoices(array $methods) - { - $choices = array(); - foreach ($methods as $method) { - $choices[$method] = 'form.label.'.$method; - } - - return $choices; - } - - private function computeAmount($amount, $currency, $method, ExtendedData $extendedData) - { - if ($amount instanceof \Closure) { - return $amount($currency, $method, $extendedData); - } - - return $amount; - } -} + + */ +class ChoosePaymentMethodType extends AbstractType +{ + private $pluginController; + private $paymentMethods; + + public function __construct(PluginControllerInterface $pluginController, array $paymentMethods) + { + if (!$paymentMethods) { + throw new \InvalidArgumentException('There is no payment method available. Did you forget to register concrete payment provider bundles such as JMSPaymentPaypalBundle?'); + } + + $this->pluginController = $pluginController; + $this->paymentMethods = $paymentMethods; + } + + public function buildForm(FormBuilderInterface $builder, array $options) + { + $allowAllMethods = !count($options['allowed_methods']); + + $options['available_methods'] = array(); + foreach ($this->paymentMethods as $method) { + if (!$allowAllMethods && !in_array($method, $options['allowed_methods'], true)) { + continue; + } + + $options['available_methods'][] = $method; + } + + if (!$options['available_methods']) { + throw new \RuntimeException(sprintf('You have not selected any payment methods. Available methods: "%s"', implode(', ', $this->paymentMethods))); + } + + $builder->add('method', 'choice', array( + 'choices' => $this->buildChoices($options['available_methods']), + 'expanded' => true, + 'data' => $options['default_method'], + )); + + foreach ($options['available_methods'] as $method) { + $methodOptions = isset($options['method_options'][$method]) ? $options['method_options'] : array(); + $builder->add('data_'.$method, $method, $methodOptions); + } + + $self = $this; + $builder->addEventListener(FormEvents::POST_BIND, function($form) use ($self, $options) { + $self->validate($form, $options); + }); + $builder->addModelTransformer(new CallbackTransformer( + function($data) use ($self, $options) { + return $self->transform($data, $options); + }, + function($data) use ($self, $options) { + return $self->reverseTransform($data, $options); + } + ), true); + } + + public function transform($data, array $options) + { + if (null === $data) { + return null; + } + + if ($data instanceof PaymentInstruction) { + $method = $data->getPaymentSystemName(); + $methodData = array_map(function($v) { return $v[0]; }, $data->getExtendedData()->all()); + if (isset($options['predefined_data'][$method])) { + $methodData = array_diff_key($methodData, $options['predefined_data'][$method]); + } + + return array( + 'method' => $method, + 'data_'.$method => $methodData, + ); + } + + throw new \RuntimeException(sprintf('Unsupported data of type "%s".', ('object' === $type = gettype($data)) ? get_class($data) : $type)); + } + + public function reverseTransform($data, array $options) + { + $method = isset($data['method']) ? $data['method'] : null; + $data = isset($data['data_'.$method]) ? $data['data_'.$method] : array(); + + $extendedData = new ExtendedData(); + foreach ($data as $k => $v) { + $extendedData->set($k, $v); + } + + if (isset($options['predefined_data'][$method])) { + if (!is_array($options['predefined_data'][$method])) { + throw new \RuntimeException(sprintf('"predefined_data" is expected to be an array for each method, but got "%s" for method "%s".', json_encode($options['extra_data'][$method]), $method)); + } + + foreach ($options['predefined_data'][$method] as $k => $v) { + $extendedData->set($k, $v); + } + } + + $amount = $this->computeAmount($options['amount'], $options['currency'], $method, $extendedData); + + return new PaymentInstruction($amount, $options['currency'], $method, $extendedData); + } + + public function validate(FormEvent $event, array $options) + { + $form = $event->getForm(); + $instruction = $form->getData(); + + if (null === $instruction->getPaymentSystemName()) { + $form->addError(new FormError('form.error.payment_method_required')); + + return; + } + if (!in_array($instruction->getPaymentSystemName(), $options['available_methods'], true)) { + $form->addError(new FormError('form.error.invalid_payment_method')); + + return; + } + + $result = $this->pluginController->checkPaymentInstruction($instruction); + if (Result::STATUS_SUCCESS !== $result->getStatus()) { + $this->applyErrorsToForm($form, $result); + + return; + } + + $result = $this->pluginController->validatePaymentInstruction($instruction); + if (Result::STATUS_SUCCESS !== $result->getStatus()) { + $this->applyErrorsToForm($form, $result); + } + } + + public function setDefaultOptions(OptionsResolverInterface $resolver) + { + $resolver->setDefaults(array( + 'allowed_methods' => array(), + 'default_method' => null, + 'predefined_data' => array(), + )); + + $resolver->setRequired(array( + 'amount', + 'currency', + )); + + $resolver->setAllowedTypes(array( + 'allowed_methods' => 'array', + 'amount' => array('numeric', 'closure'), + 'currency' => 'string', + 'predefined_data' => 'array', + )); + } + + public function getName() + { + return 'jms_choose_payment_method'; + } + + private function applyErrorsToForm(FormInterface $form, Result $result) + { + $ex = $result->getPluginException(); + + $globalErrors = $ex->getGlobalErrors(); + $dataErrors = $ex->getDataErrors(); + + // add a generic error message + if (!$dataErrors && !$globalErrors) { + $form->addError(new FormError('form.error.invalid_payment_instruction')); + + return; + } + + foreach ($globalErrors as $error) { + $form->addError(new FormError($error)); + } + + foreach ($dataErrors as $path => $error) { + $path = explode('.', $path); + $field = $form; + do { + $field = $field->get(array_shift($path)); + } while ($path); + + $field->addError(new FormError($error)); + } + } + + private function buildChoices(array $methods) + { + $choices = array(); + foreach ($methods as $method) { + $choices[$method] = 'form.label.'.$method; + } + + return $choices; + } + + private function computeAmount($amount, $currency, $method, ExtendedData $extendedData) + { + if ($amount instanceof \Closure) { + return $amount($currency, $method, $extendedData); + } + + return $amount; + } +} diff --git a/Plugin/ErrorBuilder.php b/Plugin/ErrorBuilder.php index eff56930..a3c77573 100755 --- a/Plugin/ErrorBuilder.php +++ b/Plugin/ErrorBuilder.php @@ -1,40 +1,40 @@ - - */ -class ErrorBuilder -{ - private $dataErrors = array(); - private $globalErrors = array(); - - public function addDataError($field, $messageTemplate) - { - $this->dataErrors[$field] = $messageTemplate; - } - - public function addGlobalError($messageTemplate) - { - $this->globalErrors[] = $messageTemplate; - } - - public function hasErrors() - { - return $this->dataErrors || $this->globalErrors; - } - - public function getException() - { - $ex = new InvalidPaymentInstructionException(); - $ex->setDataErrors($this->dataErrors); - $ex->setGlobalErrors($this->globalErrors); - - return $ex; - } + +/** + * Convenience class for building up error messages. + * + * @author Johannes M. Schmitt + */ +class ErrorBuilder +{ + private $dataErrors = array(); + private $globalErrors = array(); + + public function addDataError($field, $messageTemplate) + { + $this->dataErrors[$field] = $messageTemplate; + } + + public function addGlobalError($messageTemplate) + { + $this->globalErrors[] = $messageTemplate; + } + + public function hasErrors() + { + return $this->dataErrors || $this->globalErrors; + } + + public function getException() + { + $ex = new InvalidPaymentInstructionException(); + $ex->setDataErrors($this->dataErrors); + $ex->setGlobalErrors($this->globalErrors); + + return $ex; + } } \ No newline at end of file diff --git a/PluginController/EntityPluginController.php b/PluginController/EntityPluginController.php index 60c49041..4d94f4c2 100644 --- a/PluginController/EntityPluginController.php +++ b/PluginController/EntityPluginController.php @@ -14,7 +14,7 @@ use JMS\Payment\CoreBundle\Plugin\Exception\FunctionNotSupportedException as PluginFunctionNotSupportedException; use Doctrine\DBAL\LockMode; use Doctrine\ORM\EntityManager; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; /* * Copyright 2010 Johannes M. Schmitt diff --git a/PluginController/PluginController.php b/PluginController/PluginController.php index 36691d06..1e9b073d 100644 --- a/PluginController/PluginController.php +++ b/PluginController/PluginController.php @@ -1,1104 +1,1104 @@ - - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -abstract class PluginController implements PluginControllerInterface -{ - protected $options; - - private $plugins; - private $dispatcher; - - public function __construct(array $options = array(), EventDispatcherInterface $dispatcher = null) - { - $this->options = $options; - - $this->dispatcher = $dispatcher; - $this->plugins = array(); - } - - public function addPlugin(PluginInterface $plugin) - { - $this->plugins[] = $plugin; - } - - /** - * {@inheritDoc} - */ - public function checkPaymentInstruction(PaymentInstructionInterface $instruction) - { - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - - try { - $plugin->checkPaymentInstruction($instruction); - - return $this->onSuccessfulPaymentInstructionValidation($instruction); - } catch (PluginFunctionNotSupportedException $notSupported) { - return $this->onSuccessfulPaymentInstructionValidation($instruction); - } catch (PluginInvalidPaymentInstructionException $invalidInstruction) { - return $this->onUnsuccessfulPaymentInstructionValidation($instruction, $invalidInstruction); - } - } - - /** - * {@inheritDoc} - */ - public function closePaymentInstruction(PaymentInstructionInterface $instruction) - { - $oldState = $instruction->getState(); - - $instruction->setState(PaymentInstructionInterface::STATE_CLOSED); - - $this->dispatchPaymentInstructionStateChange($instruction, $oldState); - } - - /** - * {@inheritDoc} - */ - public function createPayment($instructionId, $amount) - { - $instruction = $this->getPaymentInstruction($instructionId, false); - - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('The PaymentInstruction must be in STATE_VALID.'); - } - - // FIXME: Is it practical to check this at all? There can be many payments, credits, etc. - // Verify that this is consistent with the checks related to transactions -// if (Number::compare($amount, $instruction->getAmount()) === 1) { -// throw new Exception('The Payment\'s target amount must not be greater than the PaymentInstruction\'s amount.'); -// } - - return $this->doCreatePayment($instruction, $amount); - } - - /** - * {@inheritDoc} - */ - public function createPaymentInstruction(PaymentInstructionInterface $paymentInstruction) - { - if (PaymentInstructionInterface::STATE_NEW === $paymentInstruction->getState()) { - $result = $this->validatePaymentInstruction($paymentInstruction); - - if (Result::STATUS_SUCCESS !== $result->getStatus()) { - throw new InvalidPaymentInstructionException('The PaymentInstruction could not be validated.'); - } - } else if (PaymentInstructionInterface::STATE_VALID !== $paymentInstruction->getState()) { - throw new InvalidPaymentInstructionException('The PaymentInstruction\'s state must be VALID, or NEW.'); - } - - $this->doCreatePaymentInstruction($paymentInstruction); - } - - public function getPaymentInstruction($instructionId, $maskSensitiveData = true) - { - $paymentInstruction = $this->doGetPaymentInstruction($instructionId); - - if (true === $maskSensitiveData) { - // FIXME: mask sensitive data - } - - return $paymentInstruction; - } - - /** - * {@inheritDoc} - */ - public function getRemainingValueOnPaymentInstruction(PaymentInstructionInterface $instruction) - { - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - - if (!$plugin instanceof QueryablePluginInterface) { - return null; - } - - return $plugin->getAvailableBalance($instruction); - } - - /** - * {@inheritDoc} - */ - public function validatePaymentInstruction(PaymentInstructionInterface $paymentInstruction) - { - $plugin = $this->getPlugin($paymentInstruction->getPaymentSystemName()); - - try { - $plugin->validatePaymentInstruction($paymentInstruction); - - return $this->onSuccessfulPaymentInstructionValidation($paymentInstruction); - } catch (PluginFunctionNotSupportedException $notSupported) { - return $this->checkPaymentInstruction($paymentInstruction); - } catch (PluginInvalidPaymentInstructionException $invalid) { - return $this->onUnsuccessfulPaymentInstructionValidation($paymentInstruction, $invalid); - } - } - - protected function buildFinancialTransactionResult(FinancialTransactionInterface $transaction, $status, $reasonCode) - { - $class = &$this->options['result_class']; - - return new $class($transaction, $status, $reasonCode); - } - - protected function buildPaymentInstructionResult(PaymentInstructionInterface $instruction, $status, $reasonCode) - { - $class = &$this->options['result_class']; - - return new $class($instruction, $status, $reasonCode); - } - - abstract protected function buildCredit(PaymentInstructionInterface $paymentInstruction, $amount); - - abstract protected function buildFinancialTransaction(); - - protected function doApprove(PaymentInterface $payment, $amount) - { - $instruction = $payment->getPaymentInstruction(); - - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('The PaymentInstruction\'s state must be STATE_VALID.'); - } - - $paymentState = $payment->getState(); - if (PaymentInterface::STATE_NEW === $paymentState) { - if (Number::compare($payment->getTargetAmount(), $amount) < 0) { - throw new Exception('The Payment\'s target amount is less than the requested amount.'); - } - - if ($instruction->hasPendingTransaction()) { - throw new InvalidPaymentInstructionException('The PaymentInstruction can only ever have one pending transaction.'); - } - - $retry = false; - - $transaction = $this->buildFinancialTransaction(); - $transaction->setPayment($payment); - $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_APPROVE); - $transaction->setRequestedAmount($amount); - $payment->addTransaction($transaction); - - $payment->setState(PaymentInterface::STATE_APPROVING); - $payment->setApprovingAmount($amount); - $instruction->setApprovingAmount($instruction->getApprovingAmount() + $amount); - - $this->dispatchPaymentStateChange($payment, PaymentInterface::STATE_NEW); - } else if (PaymentInterface::STATE_APPROVING === $paymentState) { - if (Number::compare($payment->getTargetAmount(), $amount) !== 0) { - throw new Exception('The Payment\'s target amount must equal the requested amount in a retry transaction.'); - } - - $transaction = $payment->getApproveTransaction(); - $retry = true; - } else { - throw new InvalidPaymentException('The Payment\'s state must be STATE_NEW, or STATE_APPROVING.'); - } - - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - $oldState = $payment->getState(); - - try { - $plugin->approve($transaction, $retry); - - if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { - $payment->setState(PaymentInterface::STATE_APPROVED); - $payment->setApprovingAmount(0.0); - $payment->setApprovedAmount($transaction->getProcessedAmount()); - $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); - $instruction->setApprovedAmount($instruction->getApprovedAmount() + $transaction->getProcessedAmount()); - $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); - - $this->dispatchPaymentStateChange($payment, $oldState); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); - } else { - $payment->setState(PaymentInterface::STATE_FAILED); - $payment->setApprovingAmount(0.0); - $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - $this->dispatchPaymentStateChange($payment, $oldState); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } - } catch (PluginFinancialException $ex) { - $payment->setState(PaymentInterface::STATE_FAILED); - $payment->setApprovingAmount(0.0); - $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - $this->dispatchPaymentStateChange($payment, $oldState); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - $result->setPluginException($ex); - - return $result; - } catch (PluginBlockedException $blocked) { - $transaction->setState(FinancialTransactionInterface::STATE_PENDING); - - if ($blocked instanceof PluginTimeoutException) { - $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; - } else if ($blocked instanceof PluginActionRequiredException) { - $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; - } else if (null === $reasonCode = $transaction->getReasonCode()) { - $reasonCode = PluginInterface::REASON_CODE_BLOCKED; - } - $transaction->setReasonCode($reasonCode); - $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); - $result->setPluginException($blocked); - $result->setRecoverable(); - - return $result; - } - } - - /** - * {@inheritDoc} - */ - protected function doApproveAndDeposit(PaymentInterface $payment, $amount) - { - $instruction = $payment->getPaymentInstruction(); - - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('PaymentInstruction\'s state must be VALID.'); - } - - $paymentState = $payment->getState(); - if (PaymentInterface::STATE_NEW === $paymentState) { - if ($instruction->hasPendingTransaction()) { - throw new InvalidPaymentInstructionException('PaymentInstruction can only ever have one pending transaction.'); - } - - if (1 === Number::compare($amount, $payment->getTargetAmount())) { - throw new \InvalidArgumentException('$amount must not be greater than Payment\'s target amount.'); - } - - $transaction = $this->buildFinancialTransaction(); - $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_APPROVE_AND_DEPOSIT); - $transaction->setPayment($payment); - $transaction->setRequestedAmount($amount); - $payment->addTransaction($transaction); - - $payment->setApprovingAmount($amount); - $payment->setDepositingAmount($amount); - $payment->setState(PaymentInterface::STATE_APPROVING); - - $instruction->setApprovingAmount($instruction->getApprovingAmount() + $amount); - $instruction->setDepositingAmount($instruction->getDepositingAmount() + $amount); - - $this->dispatchPaymentStateChange($payment, $paymentState); - - $retry = false; - } else if (PaymentInterface::STATE_APPROVING === $paymentState) { - if (0 !== Number::compare($amount, $payment->getApprovingAmount())) { - throw new \InvalidArgumentException('$amount must be equal to Payment\'s approving amount.'); - } - - if (0 !== Number::compare($amount, $payment->getDepositingAmount())) { - throw new \InvalidArgumentException('$amount must be equal to Payment\'s depositing amount.'); - } - - $transaction = $payment->getApproveTransaction(); - - $retry = true; - } else { - throw new InvalidPaymentException('Payment\'s state must be NEW, or APPROVING.'); - } - - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - $oldState = $payment->getState(); - - try { - $plugin->approveAndDeposit($transaction, $retry); - - if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { - $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); - $processedAmount = $transaction->getProcessedAmount(); - - $payment->setState(PaymentInterface::STATE_DEPOSITED); - $payment->setApprovingAmount(0.0); - $payment->setDepositingAmount(0.0); - $payment->setApprovedAmount($processedAmount); - $payment->setDepositedAmount($processedAmount); - - $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); - $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); - $instruction->setApprovedAmount($instruction->getApprovedAmount() + $processedAmount); - $instruction->setDepositedAmount($instruction->getDepositedAmount() + $processedAmount); - - $this->dispatchPaymentStateChange($payment, $oldState); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); - } else { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - $payment->setState(PaymentInterface::STATE_FAILED); - $payment->setApprovingAmount(0.0); - $payment->setDepositingAmount(0.0); - - $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); - $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); - - $this->dispatchPaymentStateChange($payment, $oldState); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } - } catch (PluginFinancialException $ex) { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - $payment->setState(PaymentInterface::STATE_FAILED); - $payment->setApprovingAmount(0.0); - $payment->setDepositingAmount(0.0); - - $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); - $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); - - $this->dispatchPaymentStateChange($payment, $oldState); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - $result->setPluginException($ex); - - return $result; - } catch (PluginBlockedException $blocked) { - $transaction->setState(FinancialTransactionInterface::STATE_PENDING); - - if ($blocked instanceof PluginTimeoutException) { - $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; - } else if ($blocked instanceof PluginActionRequiredException) { - $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; - } else if (null === $reasonCode = $transaction->getReasonCode()) { - $reasonCode = PluginInterface::REASON_CODE_BLOCKED; - } - $transaction->setReasonCode($reasonCode); - $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); - $result->setPluginException($blocked); - $result->setRecoverable(); - - return $result; - } - } - - protected function doCreateDependentCredit(PaymentInterface $payment, $amount) - { - $instruction = $payment->getPaymentInstruction(); - - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('PaymentInstruction\'s state must be VALID.'); - } - - $paymentState = $payment->getState(); - if (PaymentInterface::STATE_APPROVED !== $paymentState && PaymentInterface::STATE_EXPIRED !== $paymentState) { - throw new InvalidPaymentException('Payment\'s state must be APPROVED, or EXPIRED.'); - } - - $credit = $this->buildCredit($instruction, $amount); - $credit->setPayment($payment); - - return $credit; - } - - protected function doCreateIndependentCredit(PaymentInstructionInterface $instruction, $amount) - { - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('PaymentInstruction\'s state must be VALID.'); - } - - return $this->buildCredit($instruction, $amount); - } - - abstract protected function doCreatePayment(PaymentInstructionInterface $instruction, $amount); - - abstract protected function doCreatePaymentInstruction(PaymentInstructionInterface $instruction); - - protected function doCredit(CreditInterface $credit, $amount) - { - $instruction = $credit->getPaymentInstruction(); - - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('PaymentInstruction must be in STATE_VALID.'); - } - - $creditState = $credit->getState(); - if (CreditInterface::STATE_NEW === $creditState) { - if (1 === Number::compare($amount, $max = $instruction->getDepositedAmount() - $instruction->getReversingDepositedAmount() - $instruction->getCreditingAmount() - $instruction->getCreditedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $max)); - } - - if (1 === Number::compare($amount, $credit->getTargetAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Credit restriction).', $credit->getTargetAmount())); - } - - if (false === $credit->isIndependent()) { - $payment = $credit->getPayment(); - $paymentState = $payment->getState(); - if (PaymentInterface::STATE_APPROVED !== $paymentState && PaymentInterface::STATE_EXPIRED !== $paymentState) { - throw new InvalidPaymentException('Payment\'s state must be APPROVED, or EXPIRED.'); - } - - if (1 === Number::compare($amount, $max = $payment->getDepositedAmount() - $payment->getReversingDepositedAmount() - $payment->getCreditingAmount() - $payment->getCreditedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $max)); - } - } - - $transaction = $this->buildFinancialTransaction(); - $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_CREDIT); - $transaction->setRequestedAmount($amount); - $credit->addTransaction($transaction); - - $credit->setCreditingAmount($amount); - $instruction->setCreditingAmount($instruction->getCreditingAmount() + $amount); - - if (false === $credit->isIndependent()) { - $payment->setCreditingAmount($payment->getCreditingAmount() + $amount); - } - - $retry = false; - } else if (CreditInterface::STATE_CREDITING === $creditState) { - if (1 === Number::compare($amount, $instruction->getCreditingAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $instruction->getCreditingAmount())); - } - if (0 !== Number::compare($amount, $credit->getCreditingAmount())) { - throw new \InvalidArgumentException(sprintf('$amount must be equal to %.2f (Credit restriction).', $credit->getCreditingAmount())); - } - - if (false === $credit->isIndependent()) { - $payment = $credit->getPayment(); - $paymentState = $payment->getState(); - if (PaymentInterface::STATE_APPROVED !== $paymentState && PaymentInterface::STATE_EXPIRED !== $paymentState) { - throw new InvalidPaymentException('Payment\'s state must be APPROVED, or EXPIRED.'); - } - - if (1 === Number::compare($amount, $payment->getCreditingAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $payment->getCreditingAmount())); - } - } - - $transaction = $credit->getCreditTransaction(); - - $retry = true; - } else { - throw new InvalidCreditException('Credit\'s state must be NEW, or CREDITING.'); - } - - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - - try { - $plugin->credit($transaction, $retry); - $processedAmount = $transaction->getProcessedAmount(); - - if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { - $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); - $credit->setState(CreditInterface::STATE_CREDITED); - - $credit->setCreditingAmount(0.0); - $credit->setCreditedAmount($processedAmount); - $instruction->setCreditingAmount($instruction->getCreditingAmount() - $amount); - $instruction->setCreditedAmount($instruction->getCreditedAmount() + $processedAmount); - - if (false === $credit->isIndependent()) { - $payment->setCreditingAmount($payment->getCreditingAmount() - $amount); - $payment->setCreditedAmount($payment->getCreditedAmount() + $processedAmount); - } - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); - } else { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - $credit->setState(CreditInterface::STATE_FAILED); - - $credit->setCreditingAmount(0.0); - $instruction->setCreditingAmount($instruction->getCreditingAmount() - $amount); - - if (false === $credit->isIndependent()) { - $payment->setCreditingAmount($payment->getCreditingAmount() - $amount); - } - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } - } catch (PluginFinancialException $ex) { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - $credit->setState(CreditInterface::STATE_FAILED); - - $credit->setCreditingAmount(0.0); - $instruction->setCreditingAmount($instruction->getCreditingAmount() - $amount); - - if (false === $credit->isIndependent()) { - $payment->setCreditingAmount($payment->getCreditingAmount() - $amount); - } - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } catch (PluginBlockedException $blocked) { - $transaction->setState(FinancialTransactionInterface::STATE_PENDING); - - if ($blocked instanceof PluginTimeoutException) { - $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; - } else if ($blocked instanceof PluginActionRequiredException) { - $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; - } else if (null === $reasonCode = $transaction->getReasonCode()) { - $reasonCode = PluginInterface::REASON_CODE_BLOCKED; - } - $transaction->setReasonCode($reasonCode); - $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); - $result->setPluginException($blocked); - $result->setRecoverable(); - - return $result; - } - } - - protected function doDeposit(PaymentInterface $payment, $amount) - { - $instruction = $payment->getPaymentInstruction(); - - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('The PaymentInstruction must be in STATE_VALID.'); - } - - $paymentState = $payment->getState(); - if (PaymentInterface::STATE_APPROVED === $paymentState) { - if ($instruction->hasPendingTransaction()) { - throw new InvalidPaymentInstructionException('The PaymentInstruction can only have one pending transaction at a time.'); - } - - if (Number::compare($amount, $payment->getApprovedAmount()) === 1) { - throw new Exception('The amount cannot be greater than the approved amount of the Payment.'); - } - - $retry = false; - - $transaction = $this->buildFinancialTransaction(); - $transaction->setPayment($payment); - $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_DEPOSIT); - $transaction->setRequestedAmount($amount); - - $payment->setState(PaymentInterface::STATE_DEPOSITING); - $payment->setDepositingAmount($amount); - $instruction->setDepositingAmount($instruction->getDepositingAmount() + $amount); - - $this->dispatchPaymentStateChange($payment, $paymentState); - } else if (PaymentInterface::STATE_DEPOSITING === $paymentState) { - $transaction = $instruction->getPendingTransaction(); - if (null === $transaction) { - if (Number::compare($amount, $payment->getApprovedAmount() - $payment->getDepositedAmount()) === 1) { - throw new Exception('The amount cannot be greater than the approved amount minus the already deposited amount.'); - } - - $retry = false; - - $transaction = $this->buildFinancialTransaction(); - $transaction->setPayment($payment); - $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_DEPOSIT); - $transaction->setRequestedAmount($amount); - - $payment->setDepositingAmount($amount); - $instruction->setDepositingAmount($instruction->getDepositingAmount() + $amount); - } else { - if ($transaction->getPayment()->getId() !== $payment->getId()) { - throw new InvalidPaymentInstructionException('The PaymentInstruction has a pending transaction on another Payment.'); - } - - if (Number::compare($transaction->getRequestedAmount(), $amount) !== 0) { - throw new Exception('The requested amount must be equal to the transaction\'s amount when retrying.'); - } - - $retry = true; - } - } else { - throw new InvalidPaymentException('The Payment must be in STATE_APPROVED, or STATE_DEPOSITING.'); - } - - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - $oldState = $payment->getState(); - - try { - $plugin->deposit($transaction, $retry); - - if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { - $payment->setDepositingAmount(0.0); - $payment->setDepositedAmount($depositedAmount = $payment->getDepositedAmount() + $transaction->getProcessedAmount()); - - $changePaymentState = Number::compare($depositedAmount, $payment->getApprovedAmount()) >= 0; - if ($changePaymentState) { - $payment->setState(PaymentInterface::STATE_DEPOSITED); - } - - $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); - $instruction->setDepositedAmount($instruction->getDepositedAmount() + $transaction->getProcessedAmount()); - - if ($changePaymentState) { - $this->dispatchPaymentStateChange($payment, $oldState); - } - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); - } else { - $payment->setState(PaymentInterface::STATE_FAILED); - $payment->setDepositingAmount(0.0); - $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); - - $this->dispatchPaymentStateChange($payment, $oldState); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } - } catch (PluginFinancialException $ex) { - $payment->setState(PaymentInterface::STATE_FAILED); - $payment->setDepositingAmount(0.0); - $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); - - $this->dispatchPaymentStateChange($payment, $oldState); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } catch (PluginBlockedException $blocked) { - $transaction->setState(FinancialTransactionInterface::STATE_PENDING); - - if ($blocked instanceof PluginTimeoutException) { - $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; - } else if ($blocked instanceof PluginActionRequiredException) { - $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; - } else if (null === $reasonCode = $transaction->getReasonCode()) { - $reasonCode = PluginInterface::REASON_CODE_BLOCKED; - } - $transaction->setReasonCode($reasonCode); - $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); - $result->setPluginException($blocked); - $result->setRecoverable(); - - return $result; - } - } - - abstract protected function doGetPaymentInstruction($instructionId); - - protected function doReverseApproval(PaymentInterface $payment, $amount) - { - $instruction = $payment->getPaymentInstruction(); - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('PaymentInstruction must be in STATE_VALID.'); - } - - if (PaymentInterface::STATE_APPROVED !== $payment->getState()) { - throw new InvalidPaymentException('Payment must be in STATE_APPROVED.'); - } - - $transaction = $instruction->getPendingTransaction(); - if (null === $transaction) { - if (1 === Number::compare($amount, $max = $instruction->getApprovedAmount() - $instruction->getReversingApprovedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $max)); - } - - if (1 === Number::compare($amount, $payment->getApprovedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $payment->getApprovedAmount())); - } - - $transaction = $this->buildFinancialTransaction(); - $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_APPROVAL); - $transaction->setRequestedAmount($amount); - $payment->addTransaction($transaction); - - $payment->setReversingApprovedAmount($amount); - $instruction->setReversingApprovedAmount($instruction->getReversingApprovedAmount() + $amount); - - $retry = false; - } else { - if (FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_APPROVAL !== $transaction->getState()) { - throw new InvalidPaymentInstructionException('PaymentInstruction has another pending transaction.'); - } - - if ($payment->getId() !== $transaction->getPayment()->getId()) { - throw new \RuntimeException('Pending transaction belongs to another Payment.'); - } - - if (1 === Number::compare($amount, $instruction->getReversingApprovedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $instruction->getReversingApprovedAmount())); - } - - if (0 !== Number::compare($amount, $payment->getReversingApprovedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount must be equal to %.2f (Payment restriction).', $payment->getReversingApprovedAmount())); - } - - $retry = true; - } - - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - - try { - $plugin->reverseApproval($transaction, $retry); - $processedAmount = $transaction->getProcessedAmount(); - - if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { - $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); - - $payment->setReversingApprovedAmount(0.0); - $instruction->setReversingApprovedAmount($instruction->getReversingApprovedAmount() - $amount); - - $payment->setApprovedAmount($payment->getApprovedAmount() - $processedAmount); - $instruction->setApprovedAmount($instruction->getApprovedAmount() - $processedAmount); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); - } else { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - $payment->setReversingApprovedAmount(0.0); - $instruction->setReversingApprovedAmount($instruction->getReversingApprovedAmount() - $amount); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } - } catch (PluginFinancialException $ex) { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - $payment->setReversingApprovedAmount(0.0); - $instruction->setReversingApprovedAmount($instruction->getReversingApprovedAmount() - $amount); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } catch (PluginBlockedException $blocked) { - $transaction->setState(FinancialTransactionInterface::STATE_PENDING); - - if ($blocked instanceof PluginTimeoutException) { - $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; - } else if ($blocked instanceof PluginActionRequiredException) { - $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; - } else if (null === $reasonCode = $transaction->getReasonCode()) { - $reasonCode = PluginInterface::REASON_CODE_BLOCKED; - } - $transaction->setReasonCode($reasonCode); - $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); - $result->setPluginException($blocked); - $result->setRecoverable(); - - return $result; - } - } - - protected function doReverseCredit(CreditInterface $credit, $amount) - { - $instruction = $credit->getPaymentInstruction(); - - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('PaymentInstruction must be in STATE_VALID.'); - } - - if (CreditInterface::STATE_CREDITED !== $credit->getState()) { - throw new InvalidCreditException('Credit must be in STATE_CREDITED.'); - } - - if (false === $credit->isIndependent()) { - $payment = $credit->getPayment(); - if (PaymentInterface::STATE_APPROVED !== $payment->getState() && PaymentInterface::STATE_EXPIRED !== $payment->getState()) { - throw new InvalidPaymentException('Payment must be in STATE_APPROVED, or STATE_EXPIRED.'); - } - } - - $transaction = $instruction->getPendingTransaction(); - if (null === $transaction) { - if (1 === Number::compare($amount, $max = $instruction->getCreditedAmount() - $instruction->getReversingCreditedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $max)); - } - - if (1 === Number::compare($amount, $credit->getCreditedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Credit restriction).', $credit->getCreditedAmount())); - } - - if (false === $credit->isIndependent() && 1 === Number::compare($amount, $max = $payment->getCreditedAmount() - $payment->getReversingCreditedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $max)); - } - - $transaction = $this->buildFinancialTransaction(); - $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_CREDIT); - $transaction->setRequestedAmount($amount); - $credit->addTransaction($transaction); - - $credit->setReversingCreditedAmount($amount); - $instruction->setReversingCreditedAmount($instruction->getReversingCreditedAmount() + $amount); - - if (false === $credit->isIndependent()) { - $payment->setReversingCreditedAmount($payment->getReversingCreditedAmount() + $amount); - } - - $retry = false; - } else { - if (FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_CREDIT !== $transaction->getTransactionType()) { - throw new InvalidPaymentInstructionException('Pending transaction is not of TYPE_REVERSE_CREDIT.'); - } - - if ($credit->getId() !== $transaction->getCredit()->getId()) { - throw new InvalidCreditException('Pending transaction belongs to another Credit.'); - } - - if (1 === Number::compare($amount, $instruction->getReversingCreditedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $instruction->getReversingCreditedAmount())); - } - - if (0 !== Number::compare($amount, $credit->getReversingCreditedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount must be equal to %.2f (Credit restriction).', $credit->getReversingCreditedAmount())); - } - - if (false === $credit->isIndependent() && 1 === Number::compare($amount, $payment->getReversingCreditedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $payment->getReversingCreditedAmount())); - } - - $retry = true; - } - - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - - try { - $plugin->reverseCredit($transaction, $amount); - $processedAmount = $transaction->getProcessedAmount(); - - if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { - $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); - - $credit->setReversingCreditedAmount(0.0); - $instruction->setReversingCreditedAmount($instruction->getReversingCreditedAmount() - $amount); - $credit->setCreditedAmount($credit->getCreditedAmount() - $processedAmount); - $instruction->setCreditedAmount($instruction->getCreditedAmount() - $processedAmount); - - if (false === $credit->isIndependent()) { - $payment->setReversingCreditedAmount($payment->getReversingCreditedAmount() - $amount); - $payment->setCreditedAmount($payment->getCreditedAmount() - $processedAmount); - } - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); - } else { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - $credit->setReversingCreditedAmount(0.0); - $instruction->setReversingCreditedAmount($instruction->getReversingCreditedAmount() - $amount); - - if (false === $credit->isIndependent()) { - $payment->setReversingCreditedAmount($payment->getReversingCreditedAmount() - $amount); - } - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } - } catch (PluginFinancialException $ex) { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - $credit->setReversingCreditedAmount(0.0); - $instruction->setReversingCreditedAmount($instruction->getReversingCreditedAmount() - $amount); - - if (false === $credit->isIndependent()) { - $payment->setReversingCreditedAmount($payment->getReversingCreditedAmount() - $amount); - } - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } catch (PluginBlockedException $blocked) { - $transaction->setState(FinancialTransactionInterface::STATE_PENDING); - - if ($blocked instanceof PluginTimeoutException) { - $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; - } else if ($blocked instanceof PluginActionRequiredException) { - $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; - } else if (null === $reasonCode = $transaction->getReasonCode()) { - $reasonCode = PluginInterface::REASON_CODE_BLOCKED; - } - $transaction->setReasonCode($reasonCode); - $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); - $result->setPluginException($blocked); - $result->setRecoverable(); - - return $result; - } - } - - protected function doReverseDeposit(PaymentInterface $payment, $amount) - { - $instruction = $payment->getPaymentInstruction(); - if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { - throw new InvalidPaymentInstructionException('PaymentInstruction must be in STATE_VALID.'); - } - - if (PaymentInterface::STATE_APPROVED !== $payment->getState()) { - throw new InvalidPaymentException('Payment must be in STATE_APPROVED.'); - } - - $transaction = $instruction->getPendingTransaction(); - if ($transaction === null) { - if (1 === Number::compare($amount, $max = $instruction->getDepositedAmount() - $instruction->getReversingDepositedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $max)); - } - - if (1 === Number::compare($amount, $payment->getDepositedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $payment->getDepositedAmount())); - } - - $transaction = $this->buildFinancialTransaction(); - $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_DEPOSIT); - $transaction->setState(FinancialTransactionInterface::STATE_PENDING); - $transaction->setRequestedAmount($amount); - - $payment->setReversingDepositedAmount($amount); - $instruction->setReversingDepositedAmount($instruction->getReversingDepositedAmount() + $amount); - - $retry = false; - } else { - if (FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_DEPOSIT !== $transaction->getTransactionType()) { - throw new InvalidPaymentInstructionException('There is another pending transaction on this payment.'); - } - - if ($payment->getId() !== $transaction->getPayment()->getId()) { - throw new InvalidPaymentException('The pending transaction belongs to another Payment.'); - } - - if (1 === Number::compare($amount, $instruction->getReversingDepositedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $instruction->getReversingDepositedAmount())); - } - - if (0 !== Number::compare($amount, $payment->getReversingDepositedAmount())) { - throw new \InvalidArgumentException(sprintf('$amount must be equal to %.2f (Payment restriction).', $payment->getReversingDepositedAmount())); - } - - $retry = true; - } - - $plugin = $this->getPlugin($instruction->getPaymentSystemName()); - - try { - $plugin->reverseDeposit($transaction, $retry); - $processedAmount = $transaction->getProcessedAmount(); - - $payment->setReversingDepositedAmount(0.0); - $instruction->setReversingDepositedAmount($instruction->getReversingDepositedAmount() - $amount); - - if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { - $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); - - $payment->setDepositedAmount($payment->getDepositedAmount() - $processedAmount); - $instruction->setDepositedAmount($instruction->getDepositedAmount() - $processedAmount); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); - } else { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } - } catch (PluginFinancialException $ex) { - $transaction->setState(FinancialTransactionInterface::STATE_FAILED); - - return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); - } catch (PluginBlockedException $blocked) { - $transaction->setState(FinancialTransactionInterface::STATE_PENDING); - - if ($blocked instanceof PluginTimeoutException) { - $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; - } else if ($blocked instanceof PluginActionRequiredException) { - $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; - } else if (null === $reasonCode = $transaction->getReasonCode()) { - $reasonCode = PluginInterface::REASON_CODE_BLOCKED; - } - $transaction->setReasonCode($reasonCode); - $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); - - $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); - $result->setPluginException($blocked); - $result->setRecoverable(); - - return $result; - } - } - - protected function getPlugin($paymentSystemName) - { - foreach ($this->plugins as $plugin) { - if ($plugin->processes($paymentSystemName)) { - return $plugin; - } - } - - throw new PluginNotFoundException(sprintf('There is no plugin that processes payments for "%s".', $paymentSystemName)); - } - - protected function onSuccessfulPaymentInstructionValidation(PaymentInstructionInterface $instruction) - { - $oldState = $instruction->getState(); - - $instruction->setState(PaymentInstructionInterface::STATE_VALID); - - $this->dispatchPaymentInstructionStateChange($instruction, $oldState); - - return $this->buildPaymentInstructionResult($instruction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); - } - - protected function onUnsuccessfulPaymentInstructionValidation(PaymentInstructionInterface $instruction, PluginInvalidPaymentInstructionException $invalid) - { - $oldState = $instruction->getState(); - - $instruction->setState(PaymentInstructionInterface::STATE_INVALID); - - $this->dispatchPaymentInstructionStateChange($instruction, $oldState); - - $result = $this->buildPaymentInstructionResult($instruction, Result::STATUS_FAILED, PluginInterface::REASON_CODE_INVALID); - $result->setPluginException($invalid); - - return $result; - } - - private function dispatchPaymentInstructionStateChange(PaymentInstructionInterface $instruction, $oldState) - { - if (null === $this->dispatcher) { - return; - } - - $event = new PaymentInstructionStateChangeEvent($instruction, $oldState); - $this->dispatcher->dispatch(Events::PAYMENT_INSTRUCTION_STATE_CHANGE, $event); - } - - private function dispatchPaymentStateChange(PaymentInterface $payment, $oldState) - { - if (null === $this->dispatcher) { - return; - } - - $event = new PaymentStateChangeEvent($payment, $oldState); - $this->dispatcher->dispatch(Events::PAYMENT_STATE_CHANGE, $event); - } -} + + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +abstract class PluginController implements PluginControllerInterface +{ + protected $options; + + private $plugins; + private $dispatcher; + + public function __construct(array $options = array(), EventDispatcherInterface $dispatcher = null) + { + $this->options = $options; + + $this->dispatcher = $dispatcher; + $this->plugins = array(); + } + + public function addPlugin(PluginInterface $plugin) + { + $this->plugins[] = $plugin; + } + + /** + * {@inheritDoc} + */ + public function checkPaymentInstruction(PaymentInstructionInterface $instruction) + { + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + + try { + $plugin->checkPaymentInstruction($instruction); + + return $this->onSuccessfulPaymentInstructionValidation($instruction); + } catch (PluginFunctionNotSupportedException $notSupported) { + return $this->onSuccessfulPaymentInstructionValidation($instruction); + } catch (PluginInvalidPaymentInstructionException $invalidInstruction) { + return $this->onUnsuccessfulPaymentInstructionValidation($instruction, $invalidInstruction); + } + } + + /** + * {@inheritDoc} + */ + public function closePaymentInstruction(PaymentInstructionInterface $instruction) + { + $oldState = $instruction->getState(); + + $instruction->setState(PaymentInstructionInterface::STATE_CLOSED); + + $this->dispatchPaymentInstructionStateChange($instruction, $oldState); + } + + /** + * {@inheritDoc} + */ + public function createPayment($instructionId, $amount) + { + $instruction = $this->getPaymentInstruction($instructionId, false); + + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('The PaymentInstruction must be in STATE_VALID.'); + } + + // FIXME: Is it practical to check this at all? There can be many payments, credits, etc. + // Verify that this is consistent with the checks related to transactions +// if (Number::compare($amount, $instruction->getAmount()) === 1) { +// throw new Exception('The Payment\'s target amount must not be greater than the PaymentInstruction\'s amount.'); +// } + + return $this->doCreatePayment($instruction, $amount); + } + + /** + * {@inheritDoc} + */ + public function createPaymentInstruction(PaymentInstructionInterface $paymentInstruction) + { + if (PaymentInstructionInterface::STATE_NEW === $paymentInstruction->getState()) { + $result = $this->validatePaymentInstruction($paymentInstruction); + + if (Result::STATUS_SUCCESS !== $result->getStatus()) { + throw new InvalidPaymentInstructionException('The PaymentInstruction could not be validated.'); + } + } else if (PaymentInstructionInterface::STATE_VALID !== $paymentInstruction->getState()) { + throw new InvalidPaymentInstructionException('The PaymentInstruction\'s state must be VALID, or NEW.'); + } + + $this->doCreatePaymentInstruction($paymentInstruction); + } + + public function getPaymentInstruction($instructionId, $maskSensitiveData = true) + { + $paymentInstruction = $this->doGetPaymentInstruction($instructionId); + + if (true === $maskSensitiveData) { + // FIXME: mask sensitive data + } + + return $paymentInstruction; + } + + /** + * {@inheritDoc} + */ + public function getRemainingValueOnPaymentInstruction(PaymentInstructionInterface $instruction) + { + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + + if (!$plugin instanceof QueryablePluginInterface) { + return null; + } + + return $plugin->getAvailableBalance($instruction); + } + + /** + * {@inheritDoc} + */ + public function validatePaymentInstruction(PaymentInstructionInterface $paymentInstruction) + { + $plugin = $this->getPlugin($paymentInstruction->getPaymentSystemName()); + + try { + $plugin->validatePaymentInstruction($paymentInstruction); + + return $this->onSuccessfulPaymentInstructionValidation($paymentInstruction); + } catch (PluginFunctionNotSupportedException $notSupported) { + return $this->checkPaymentInstruction($paymentInstruction); + } catch (PluginInvalidPaymentInstructionException $invalid) { + return $this->onUnsuccessfulPaymentInstructionValidation($paymentInstruction, $invalid); + } + } + + protected function buildFinancialTransactionResult(FinancialTransactionInterface $transaction, $status, $reasonCode) + { + $class = &$this->options['result_class']; + + return new $class($transaction, $status, $reasonCode); + } + + protected function buildPaymentInstructionResult(PaymentInstructionInterface $instruction, $status, $reasonCode) + { + $class = &$this->options['result_class']; + + return new $class($instruction, $status, $reasonCode); + } + + abstract protected function buildCredit(PaymentInstructionInterface $paymentInstruction, $amount); + + abstract protected function buildFinancialTransaction(); + + protected function doApprove(PaymentInterface $payment, $amount) + { + $instruction = $payment->getPaymentInstruction(); + + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('The PaymentInstruction\'s state must be STATE_VALID.'); + } + + $paymentState = $payment->getState(); + if (PaymentInterface::STATE_NEW === $paymentState) { + if (Number::compare($payment->getTargetAmount(), $amount) < 0) { + throw new Exception('The Payment\'s target amount is less than the requested amount.'); + } + + if ($instruction->hasPendingTransaction()) { + throw new InvalidPaymentInstructionException('The PaymentInstruction can only ever have one pending transaction.'); + } + + $retry = false; + + $transaction = $this->buildFinancialTransaction(); + $transaction->setPayment($payment); + $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_APPROVE); + $transaction->setRequestedAmount($amount); + $payment->addTransaction($transaction); + + $payment->setState(PaymentInterface::STATE_APPROVING); + $payment->setApprovingAmount($amount); + $instruction->setApprovingAmount($instruction->getApprovingAmount() + $amount); + + $this->dispatchPaymentStateChange($payment, PaymentInterface::STATE_NEW); + } else if (PaymentInterface::STATE_APPROVING === $paymentState) { + if (Number::compare($payment->getTargetAmount(), $amount) !== 0) { + throw new Exception('The Payment\'s target amount must equal the requested amount in a retry transaction.'); + } + + $transaction = $payment->getApproveTransaction(); + $retry = true; + } else { + throw new InvalidPaymentException('The Payment\'s state must be STATE_NEW, or STATE_APPROVING.'); + } + + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + $oldState = $payment->getState(); + + try { + $plugin->approve($transaction, $retry); + + if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { + $payment->setState(PaymentInterface::STATE_APPROVED); + $payment->setApprovingAmount(0.0); + $payment->setApprovedAmount($transaction->getProcessedAmount()); + $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); + $instruction->setApprovedAmount($instruction->getApprovedAmount() + $transaction->getProcessedAmount()); + $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); + + $this->dispatchPaymentStateChange($payment, $oldState); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); + } else { + $payment->setState(PaymentInterface::STATE_FAILED); + $payment->setApprovingAmount(0.0); + $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + $this->dispatchPaymentStateChange($payment, $oldState); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } + } catch (PluginFinancialException $ex) { + $payment->setState(PaymentInterface::STATE_FAILED); + $payment->setApprovingAmount(0.0); + $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + $this->dispatchPaymentStateChange($payment, $oldState); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + $result->setPluginException($ex); + + return $result; + } catch (PluginBlockedException $blocked) { + $transaction->setState(FinancialTransactionInterface::STATE_PENDING); + + if ($blocked instanceof PluginTimeoutException) { + $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; + } else if ($blocked instanceof PluginActionRequiredException) { + $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; + } else if (null === $reasonCode = $transaction->getReasonCode()) { + $reasonCode = PluginInterface::REASON_CODE_BLOCKED; + } + $transaction->setReasonCode($reasonCode); + $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); + $result->setPluginException($blocked); + $result->setRecoverable(); + + return $result; + } + } + + /** + * {@inheritDoc} + */ + protected function doApproveAndDeposit(PaymentInterface $payment, $amount) + { + $instruction = $payment->getPaymentInstruction(); + + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('PaymentInstruction\'s state must be VALID.'); + } + + $paymentState = $payment->getState(); + if (PaymentInterface::STATE_NEW === $paymentState) { + if ($instruction->hasPendingTransaction()) { + throw new InvalidPaymentInstructionException('PaymentInstruction can only ever have one pending transaction.'); + } + + if (1 === Number::compare($amount, $payment->getTargetAmount())) { + throw new \InvalidArgumentException('$amount must not be greater than Payment\'s target amount.'); + } + + $transaction = $this->buildFinancialTransaction(); + $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_APPROVE_AND_DEPOSIT); + $transaction->setPayment($payment); + $transaction->setRequestedAmount($amount); + $payment->addTransaction($transaction); + + $payment->setApprovingAmount($amount); + $payment->setDepositingAmount($amount); + $payment->setState(PaymentInterface::STATE_APPROVING); + + $instruction->setApprovingAmount($instruction->getApprovingAmount() + $amount); + $instruction->setDepositingAmount($instruction->getDepositingAmount() + $amount); + + $this->dispatchPaymentStateChange($payment, $paymentState); + + $retry = false; + } else if (PaymentInterface::STATE_APPROVING === $paymentState) { + if (0 !== Number::compare($amount, $payment->getApprovingAmount())) { + throw new \InvalidArgumentException('$amount must be equal to Payment\'s approving amount.'); + } + + if (0 !== Number::compare($amount, $payment->getDepositingAmount())) { + throw new \InvalidArgumentException('$amount must be equal to Payment\'s depositing amount.'); + } + + $transaction = $payment->getApproveTransaction(); + + $retry = true; + } else { + throw new InvalidPaymentException('Payment\'s state must be NEW, or APPROVING.'); + } + + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + $oldState = $payment->getState(); + + try { + $plugin->approveAndDeposit($transaction, $retry); + + if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { + $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); + $processedAmount = $transaction->getProcessedAmount(); + + $payment->setState(PaymentInterface::STATE_DEPOSITED); + $payment->setApprovingAmount(0.0); + $payment->setDepositingAmount(0.0); + $payment->setApprovedAmount($processedAmount); + $payment->setDepositedAmount($processedAmount); + + $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); + $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); + $instruction->setApprovedAmount($instruction->getApprovedAmount() + $processedAmount); + $instruction->setDepositedAmount($instruction->getDepositedAmount() + $processedAmount); + + $this->dispatchPaymentStateChange($payment, $oldState); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); + } else { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + $payment->setState(PaymentInterface::STATE_FAILED); + $payment->setApprovingAmount(0.0); + $payment->setDepositingAmount(0.0); + + $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); + $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); + + $this->dispatchPaymentStateChange($payment, $oldState); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } + } catch (PluginFinancialException $ex) { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + $payment->setState(PaymentInterface::STATE_FAILED); + $payment->setApprovingAmount(0.0); + $payment->setDepositingAmount(0.0); + + $instruction->setApprovingAmount($instruction->getApprovingAmount() - $amount); + $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); + + $this->dispatchPaymentStateChange($payment, $oldState); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + $result->setPluginException($ex); + + return $result; + } catch (PluginBlockedException $blocked) { + $transaction->setState(FinancialTransactionInterface::STATE_PENDING); + + if ($blocked instanceof PluginTimeoutException) { + $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; + } else if ($blocked instanceof PluginActionRequiredException) { + $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; + } else if (null === $reasonCode = $transaction->getReasonCode()) { + $reasonCode = PluginInterface::REASON_CODE_BLOCKED; + } + $transaction->setReasonCode($reasonCode); + $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); + $result->setPluginException($blocked); + $result->setRecoverable(); + + return $result; + } + } + + protected function doCreateDependentCredit(PaymentInterface $payment, $amount) + { + $instruction = $payment->getPaymentInstruction(); + + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('PaymentInstruction\'s state must be VALID.'); + } + + $paymentState = $payment->getState(); + if (PaymentInterface::STATE_APPROVED !== $paymentState && PaymentInterface::STATE_EXPIRED !== $paymentState) { + throw new InvalidPaymentException('Payment\'s state must be APPROVED, or EXPIRED.'); + } + + $credit = $this->buildCredit($instruction, $amount); + $credit->setPayment($payment); + + return $credit; + } + + protected function doCreateIndependentCredit(PaymentInstructionInterface $instruction, $amount) + { + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('PaymentInstruction\'s state must be VALID.'); + } + + return $this->buildCredit($instruction, $amount); + } + + abstract protected function doCreatePayment(PaymentInstructionInterface $instruction, $amount); + + abstract protected function doCreatePaymentInstruction(PaymentInstructionInterface $instruction); + + protected function doCredit(CreditInterface $credit, $amount) + { + $instruction = $credit->getPaymentInstruction(); + + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('PaymentInstruction must be in STATE_VALID.'); + } + + $creditState = $credit->getState(); + if (CreditInterface::STATE_NEW === $creditState) { + if (1 === Number::compare($amount, $max = $instruction->getDepositedAmount() - $instruction->getReversingDepositedAmount() - $instruction->getCreditingAmount() - $instruction->getCreditedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $max)); + } + + if (1 === Number::compare($amount, $credit->getTargetAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Credit restriction).', $credit->getTargetAmount())); + } + + if (false === $credit->isIndependent()) { + $payment = $credit->getPayment(); + $paymentState = $payment->getState(); + if (PaymentInterface::STATE_APPROVED !== $paymentState && PaymentInterface::STATE_EXPIRED !== $paymentState) { + throw new InvalidPaymentException('Payment\'s state must be APPROVED, or EXPIRED.'); + } + + if (1 === Number::compare($amount, $max = $payment->getDepositedAmount() - $payment->getReversingDepositedAmount() - $payment->getCreditingAmount() - $payment->getCreditedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $max)); + } + } + + $transaction = $this->buildFinancialTransaction(); + $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_CREDIT); + $transaction->setRequestedAmount($amount); + $credit->addTransaction($transaction); + + $credit->setCreditingAmount($amount); + $instruction->setCreditingAmount($instruction->getCreditingAmount() + $amount); + + if (false === $credit->isIndependent()) { + $payment->setCreditingAmount($payment->getCreditingAmount() + $amount); + } + + $retry = false; + } else if (CreditInterface::STATE_CREDITING === $creditState) { + if (1 === Number::compare($amount, $instruction->getCreditingAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $instruction->getCreditingAmount())); + } + if (0 !== Number::compare($amount, $credit->getCreditingAmount())) { + throw new \InvalidArgumentException(sprintf('$amount must be equal to %.2f (Credit restriction).', $credit->getCreditingAmount())); + } + + if (false === $credit->isIndependent()) { + $payment = $credit->getPayment(); + $paymentState = $payment->getState(); + if (PaymentInterface::STATE_APPROVED !== $paymentState && PaymentInterface::STATE_EXPIRED !== $paymentState) { + throw new InvalidPaymentException('Payment\'s state must be APPROVED, or EXPIRED.'); + } + + if (1 === Number::compare($amount, $payment->getCreditingAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $payment->getCreditingAmount())); + } + } + + $transaction = $credit->getCreditTransaction(); + + $retry = true; + } else { + throw new InvalidCreditException('Credit\'s state must be NEW, or CREDITING.'); + } + + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + + try { + $plugin->credit($transaction, $retry); + $processedAmount = $transaction->getProcessedAmount(); + + if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { + $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); + $credit->setState(CreditInterface::STATE_CREDITED); + + $credit->setCreditingAmount(0.0); + $credit->setCreditedAmount($processedAmount); + $instruction->setCreditingAmount($instruction->getCreditingAmount() - $amount); + $instruction->setCreditedAmount($instruction->getCreditedAmount() + $processedAmount); + + if (false === $credit->isIndependent()) { + $payment->setCreditingAmount($payment->getCreditingAmount() - $amount); + $payment->setCreditedAmount($payment->getCreditedAmount() + $processedAmount); + } + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); + } else { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + $credit->setState(CreditInterface::STATE_FAILED); + + $credit->setCreditingAmount(0.0); + $instruction->setCreditingAmount($instruction->getCreditingAmount() - $amount); + + if (false === $credit->isIndependent()) { + $payment->setCreditingAmount($payment->getCreditingAmount() - $amount); + } + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } + } catch (PluginFinancialException $ex) { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + $credit->setState(CreditInterface::STATE_FAILED); + + $credit->setCreditingAmount(0.0); + $instruction->setCreditingAmount($instruction->getCreditingAmount() - $amount); + + if (false === $credit->isIndependent()) { + $payment->setCreditingAmount($payment->getCreditingAmount() - $amount); + } + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } catch (PluginBlockedException $blocked) { + $transaction->setState(FinancialTransactionInterface::STATE_PENDING); + + if ($blocked instanceof PluginTimeoutException) { + $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; + } else if ($blocked instanceof PluginActionRequiredException) { + $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; + } else if (null === $reasonCode = $transaction->getReasonCode()) { + $reasonCode = PluginInterface::REASON_CODE_BLOCKED; + } + $transaction->setReasonCode($reasonCode); + $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); + $result->setPluginException($blocked); + $result->setRecoverable(); + + return $result; + } + } + + protected function doDeposit(PaymentInterface $payment, $amount) + { + $instruction = $payment->getPaymentInstruction(); + + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('The PaymentInstruction must be in STATE_VALID.'); + } + + $paymentState = $payment->getState(); + if (PaymentInterface::STATE_APPROVED === $paymentState) { + if ($instruction->hasPendingTransaction()) { + throw new InvalidPaymentInstructionException('The PaymentInstruction can only have one pending transaction at a time.'); + } + + if (Number::compare($amount, $payment->getApprovedAmount()) === 1) { + throw new Exception('The amount cannot be greater than the approved amount of the Payment.'); + } + + $retry = false; + + $transaction = $this->buildFinancialTransaction(); + $transaction->setPayment($payment); + $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_DEPOSIT); + $transaction->setRequestedAmount($amount); + + $payment->setState(PaymentInterface::STATE_DEPOSITING); + $payment->setDepositingAmount($amount); + $instruction->setDepositingAmount($instruction->getDepositingAmount() + $amount); + + $this->dispatchPaymentStateChange($payment, $paymentState); + } else if (PaymentInterface::STATE_DEPOSITING === $paymentState) { + $transaction = $instruction->getPendingTransaction(); + if (null === $transaction) { + if (Number::compare($amount, $payment->getApprovedAmount() - $payment->getDepositedAmount()) === 1) { + throw new Exception('The amount cannot be greater than the approved amount minus the already deposited amount.'); + } + + $retry = false; + + $transaction = $this->buildFinancialTransaction(); + $transaction->setPayment($payment); + $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_DEPOSIT); + $transaction->setRequestedAmount($amount); + + $payment->setDepositingAmount($amount); + $instruction->setDepositingAmount($instruction->getDepositingAmount() + $amount); + } else { + if ($transaction->getPayment()->getId() !== $payment->getId()) { + throw new InvalidPaymentInstructionException('The PaymentInstruction has a pending transaction on another Payment.'); + } + + if (Number::compare($transaction->getRequestedAmount(), $amount) !== 0) { + throw new Exception('The requested amount must be equal to the transaction\'s amount when retrying.'); + } + + $retry = true; + } + } else { + throw new InvalidPaymentException('The Payment must be in STATE_APPROVED, or STATE_DEPOSITING.'); + } + + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + $oldState = $payment->getState(); + + try { + $plugin->deposit($transaction, $retry); + + if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { + $payment->setDepositingAmount(0.0); + $payment->setDepositedAmount($depositedAmount = $payment->getDepositedAmount() + $transaction->getProcessedAmount()); + + $changePaymentState = Number::compare($depositedAmount, $payment->getApprovedAmount()) >= 0; + if ($changePaymentState) { + $payment->setState(PaymentInterface::STATE_DEPOSITED); + } + + $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); + $instruction->setDepositedAmount($instruction->getDepositedAmount() + $transaction->getProcessedAmount()); + + if ($changePaymentState) { + $this->dispatchPaymentStateChange($payment, $oldState); + } + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); + } else { + $payment->setState(PaymentInterface::STATE_FAILED); + $payment->setDepositingAmount(0.0); + $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); + + $this->dispatchPaymentStateChange($payment, $oldState); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } + } catch (PluginFinancialException $ex) { + $payment->setState(PaymentInterface::STATE_FAILED); + $payment->setDepositingAmount(0.0); + $instruction->setDepositingAmount($instruction->getDepositingAmount() - $amount); + + $this->dispatchPaymentStateChange($payment, $oldState); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } catch (PluginBlockedException $blocked) { + $transaction->setState(FinancialTransactionInterface::STATE_PENDING); + + if ($blocked instanceof PluginTimeoutException) { + $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; + } else if ($blocked instanceof PluginActionRequiredException) { + $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; + } else if (null === $reasonCode = $transaction->getReasonCode()) { + $reasonCode = PluginInterface::REASON_CODE_BLOCKED; + } + $transaction->setReasonCode($reasonCode); + $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); + $result->setPluginException($blocked); + $result->setRecoverable(); + + return $result; + } + } + + abstract protected function doGetPaymentInstruction($instructionId); + + protected function doReverseApproval(PaymentInterface $payment, $amount) + { + $instruction = $payment->getPaymentInstruction(); + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('PaymentInstruction must be in STATE_VALID.'); + } + + if (PaymentInterface::STATE_APPROVED !== $payment->getState()) { + throw new InvalidPaymentException('Payment must be in STATE_APPROVED.'); + } + + $transaction = $instruction->getPendingTransaction(); + if (null === $transaction) { + if (1 === Number::compare($amount, $max = $instruction->getApprovedAmount() - $instruction->getReversingApprovedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $max)); + } + + if (1 === Number::compare($amount, $payment->getApprovedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $payment->getApprovedAmount())); + } + + $transaction = $this->buildFinancialTransaction(); + $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_APPROVAL); + $transaction->setRequestedAmount($amount); + $payment->addTransaction($transaction); + + $payment->setReversingApprovedAmount($amount); + $instruction->setReversingApprovedAmount($instruction->getReversingApprovedAmount() + $amount); + + $retry = false; + } else { + if (FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_APPROVAL !== $transaction->getState()) { + throw new InvalidPaymentInstructionException('PaymentInstruction has another pending transaction.'); + } + + if ($payment->getId() !== $transaction->getPayment()->getId()) { + throw new \RuntimeException('Pending transaction belongs to another Payment.'); + } + + if (1 === Number::compare($amount, $instruction->getReversingApprovedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $instruction->getReversingApprovedAmount())); + } + + if (0 !== Number::compare($amount, $payment->getReversingApprovedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount must be equal to %.2f (Payment restriction).', $payment->getReversingApprovedAmount())); + } + + $retry = true; + } + + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + + try { + $plugin->reverseApproval($transaction, $retry); + $processedAmount = $transaction->getProcessedAmount(); + + if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { + $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); + + $payment->setReversingApprovedAmount(0.0); + $instruction->setReversingApprovedAmount($instruction->getReversingApprovedAmount() - $amount); + + $payment->setApprovedAmount($payment->getApprovedAmount() - $processedAmount); + $instruction->setApprovedAmount($instruction->getApprovedAmount() - $processedAmount); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); + } else { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + $payment->setReversingApprovedAmount(0.0); + $instruction->setReversingApprovedAmount($instruction->getReversingApprovedAmount() - $amount); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } + } catch (PluginFinancialException $ex) { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + $payment->setReversingApprovedAmount(0.0); + $instruction->setReversingApprovedAmount($instruction->getReversingApprovedAmount() - $amount); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } catch (PluginBlockedException $blocked) { + $transaction->setState(FinancialTransactionInterface::STATE_PENDING); + + if ($blocked instanceof PluginTimeoutException) { + $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; + } else if ($blocked instanceof PluginActionRequiredException) { + $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; + } else if (null === $reasonCode = $transaction->getReasonCode()) { + $reasonCode = PluginInterface::REASON_CODE_BLOCKED; + } + $transaction->setReasonCode($reasonCode); + $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); + $result->setPluginException($blocked); + $result->setRecoverable(); + + return $result; + } + } + + protected function doReverseCredit(CreditInterface $credit, $amount) + { + $instruction = $credit->getPaymentInstruction(); + + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('PaymentInstruction must be in STATE_VALID.'); + } + + if (CreditInterface::STATE_CREDITED !== $credit->getState()) { + throw new InvalidCreditException('Credit must be in STATE_CREDITED.'); + } + + if (false === $credit->isIndependent()) { + $payment = $credit->getPayment(); + if (PaymentInterface::STATE_APPROVED !== $payment->getState() && PaymentInterface::STATE_EXPIRED !== $payment->getState()) { + throw new InvalidPaymentException('Payment must be in STATE_APPROVED, or STATE_EXPIRED.'); + } + } + + $transaction = $instruction->getPendingTransaction(); + if (null === $transaction) { + if (1 === Number::compare($amount, $max = $instruction->getCreditedAmount() - $instruction->getReversingCreditedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $max)); + } + + if (1 === Number::compare($amount, $credit->getCreditedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Credit restriction).', $credit->getCreditedAmount())); + } + + if (false === $credit->isIndependent() && 1 === Number::compare($amount, $max = $payment->getCreditedAmount() - $payment->getReversingCreditedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $max)); + } + + $transaction = $this->buildFinancialTransaction(); + $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_CREDIT); + $transaction->setRequestedAmount($amount); + $credit->addTransaction($transaction); + + $credit->setReversingCreditedAmount($amount); + $instruction->setReversingCreditedAmount($instruction->getReversingCreditedAmount() + $amount); + + if (false === $credit->isIndependent()) { + $payment->setReversingCreditedAmount($payment->getReversingCreditedAmount() + $amount); + } + + $retry = false; + } else { + if (FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_CREDIT !== $transaction->getTransactionType()) { + throw new InvalidPaymentInstructionException('Pending transaction is not of TYPE_REVERSE_CREDIT.'); + } + + if ($credit->getId() !== $transaction->getCredit()->getId()) { + throw new InvalidCreditException('Pending transaction belongs to another Credit.'); + } + + if (1 === Number::compare($amount, $instruction->getReversingCreditedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $instruction->getReversingCreditedAmount())); + } + + if (0 !== Number::compare($amount, $credit->getReversingCreditedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount must be equal to %.2f (Credit restriction).', $credit->getReversingCreditedAmount())); + } + + if (false === $credit->isIndependent() && 1 === Number::compare($amount, $payment->getReversingCreditedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $payment->getReversingCreditedAmount())); + } + + $retry = true; + } + + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + + try { + $plugin->reverseCredit($transaction, $amount); + $processedAmount = $transaction->getProcessedAmount(); + + if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { + $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); + + $credit->setReversingCreditedAmount(0.0); + $instruction->setReversingCreditedAmount($instruction->getReversingCreditedAmount() - $amount); + $credit->setCreditedAmount($credit->getCreditedAmount() - $processedAmount); + $instruction->setCreditedAmount($instruction->getCreditedAmount() - $processedAmount); + + if (false === $credit->isIndependent()) { + $payment->setReversingCreditedAmount($payment->getReversingCreditedAmount() - $amount); + $payment->setCreditedAmount($payment->getCreditedAmount() - $processedAmount); + } + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); + } else { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + $credit->setReversingCreditedAmount(0.0); + $instruction->setReversingCreditedAmount($instruction->getReversingCreditedAmount() - $amount); + + if (false === $credit->isIndependent()) { + $payment->setReversingCreditedAmount($payment->getReversingCreditedAmount() - $amount); + } + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } + } catch (PluginFinancialException $ex) { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + $credit->setReversingCreditedAmount(0.0); + $instruction->setReversingCreditedAmount($instruction->getReversingCreditedAmount() - $amount); + + if (false === $credit->isIndependent()) { + $payment->setReversingCreditedAmount($payment->getReversingCreditedAmount() - $amount); + } + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } catch (PluginBlockedException $blocked) { + $transaction->setState(FinancialTransactionInterface::STATE_PENDING); + + if ($blocked instanceof PluginTimeoutException) { + $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; + } else if ($blocked instanceof PluginActionRequiredException) { + $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; + } else if (null === $reasonCode = $transaction->getReasonCode()) { + $reasonCode = PluginInterface::REASON_CODE_BLOCKED; + } + $transaction->setReasonCode($reasonCode); + $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); + $result->setPluginException($blocked); + $result->setRecoverable(); + + return $result; + } + } + + protected function doReverseDeposit(PaymentInterface $payment, $amount) + { + $instruction = $payment->getPaymentInstruction(); + if (PaymentInstructionInterface::STATE_VALID !== $instruction->getState()) { + throw new InvalidPaymentInstructionException('PaymentInstruction must be in STATE_VALID.'); + } + + if (PaymentInterface::STATE_APPROVED !== $payment->getState()) { + throw new InvalidPaymentException('Payment must be in STATE_APPROVED.'); + } + + $transaction = $instruction->getPendingTransaction(); + if ($transaction === null) { + if (1 === Number::compare($amount, $max = $instruction->getDepositedAmount() - $instruction->getReversingDepositedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $max)); + } + + if (1 === Number::compare($amount, $payment->getDepositedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (Payment restriction).', $payment->getDepositedAmount())); + } + + $transaction = $this->buildFinancialTransaction(); + $transaction->setTransactionType(FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_DEPOSIT); + $transaction->setState(FinancialTransactionInterface::STATE_PENDING); + $transaction->setRequestedAmount($amount); + + $payment->setReversingDepositedAmount($amount); + $instruction->setReversingDepositedAmount($instruction->getReversingDepositedAmount() + $amount); + + $retry = false; + } else { + if (FinancialTransactionInterface::TRANSACTION_TYPE_REVERSE_DEPOSIT !== $transaction->getTransactionType()) { + throw new InvalidPaymentInstructionException('There is another pending transaction on this payment.'); + } + + if ($payment->getId() !== $transaction->getPayment()->getId()) { + throw new InvalidPaymentException('The pending transaction belongs to another Payment.'); + } + + if (1 === Number::compare($amount, $instruction->getReversingDepositedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount cannot be greater than %.2f (PaymentInstruction restriction).', $instruction->getReversingDepositedAmount())); + } + + if (0 !== Number::compare($amount, $payment->getReversingDepositedAmount())) { + throw new \InvalidArgumentException(sprintf('$amount must be equal to %.2f (Payment restriction).', $payment->getReversingDepositedAmount())); + } + + $retry = true; + } + + $plugin = $this->getPlugin($instruction->getPaymentSystemName()); + + try { + $plugin->reverseDeposit($transaction, $retry); + $processedAmount = $transaction->getProcessedAmount(); + + $payment->setReversingDepositedAmount(0.0); + $instruction->setReversingDepositedAmount($instruction->getReversingDepositedAmount() - $amount); + + if (PluginInterface::RESPONSE_CODE_SUCCESS === $transaction->getResponseCode()) { + $transaction->setState(FinancialTransactionInterface::STATE_SUCCESS); + + $payment->setDepositedAmount($payment->getDepositedAmount() - $processedAmount); + $instruction->setDepositedAmount($instruction->getDepositedAmount() - $processedAmount); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); + } else { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } + } catch (PluginFinancialException $ex) { + $transaction->setState(FinancialTransactionInterface::STATE_FAILED); + + return $this->buildFinancialTransactionResult($transaction, Result::STATUS_FAILED, $transaction->getReasonCode()); + } catch (PluginBlockedException $blocked) { + $transaction->setState(FinancialTransactionInterface::STATE_PENDING); + + if ($blocked instanceof PluginTimeoutException) { + $reasonCode = PluginInterface::REASON_CODE_TIMEOUT; + } else if ($blocked instanceof PluginActionRequiredException) { + $reasonCode = PluginInterface::REASON_CODE_ACTION_REQUIRED; + } else if (null === $reasonCode = $transaction->getReasonCode()) { + $reasonCode = PluginInterface::REASON_CODE_BLOCKED; + } + $transaction->setReasonCode($reasonCode); + $transaction->setResponseCode(PluginInterface::RESPONSE_CODE_PENDING); + + $result = $this->buildFinancialTransactionResult($transaction, Result::STATUS_PENDING, $reasonCode); + $result->setPluginException($blocked); + $result->setRecoverable(); + + return $result; + } + } + + protected function getPlugin($paymentSystemName) + { + foreach ($this->plugins as $plugin) { + if ($plugin->processes($paymentSystemName)) { + return $plugin; + } + } + + throw new PluginNotFoundException(sprintf('There is no plugin that processes payments for "%s".', $paymentSystemName)); + } + + protected function onSuccessfulPaymentInstructionValidation(PaymentInstructionInterface $instruction) + { + $oldState = $instruction->getState(); + + $instruction->setState(PaymentInstructionInterface::STATE_VALID); + + $this->dispatchPaymentInstructionStateChange($instruction, $oldState); + + return $this->buildPaymentInstructionResult($instruction, Result::STATUS_SUCCESS, PluginInterface::REASON_CODE_SUCCESS); + } + + protected function onUnsuccessfulPaymentInstructionValidation(PaymentInstructionInterface $instruction, PluginInvalidPaymentInstructionException $invalid) + { + $oldState = $instruction->getState(); + + $instruction->setState(PaymentInstructionInterface::STATE_INVALID); + + $this->dispatchPaymentInstructionStateChange($instruction, $oldState); + + $result = $this->buildPaymentInstructionResult($instruction, Result::STATUS_FAILED, PluginInterface::REASON_CODE_INVALID); + $result->setPluginException($invalid); + + return $result; + } + + private function dispatchPaymentInstructionStateChange(PaymentInstructionInterface $instruction, $oldState) + { + if (null === $this->dispatcher) { + return; + } + + $event = new PaymentInstructionStateChangeEvent($instruction, $oldState); + $this->dispatcher->dispatch(Events::PAYMENT_INSTRUCTION_STATE_CHANGE, $event); + } + + private function dispatchPaymentStateChange(PaymentInterface $payment, $oldState) + { + if (null === $this->dispatcher) { + return; + } + + $event = new PaymentStateChangeEvent($payment, $oldState); + $this->dispatcher->dispatch(Events::PAYMENT_STATE_CHANGE, $event); + } +} diff --git a/Resources/config/routing.yml b/Resources/config/routing.yml deleted file mode 100644 index fe2bb820..00000000 --- a/Resources/config/routing.yml +++ /dev/null @@ -1,3 +0,0 @@ -payment: - pattern: /payment - defaults: { _controller: JMSPaymentCoreBundle:Demo:index } \ No newline at end of file diff --git a/Resources/doc/LICENSE b/Resources/doc/LICENSE index a9aba5c6..5e568df6 100755 --- a/Resources/doc/LICENSE +++ b/Resources/doc/LICENSE @@ -1,55 +1,55 @@ -THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. - -BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. - -1. Definitions - - "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. - "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined above) for the purposes of this License. - "Distribute" means to make available to the public the original and copies of the Work through sale or other transfer of ownership. - "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. - "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. - "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. - "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. - "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. - "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. - -2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. - -3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: - - to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; and, - to Distribute and Publicly Perform the Work including as incorporated in Collections. - -The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats, but otherwise you have no rights to make Adaptations. Subject to 8(f), all rights not expressly granted by Licensor are hereby reserved, including but not limited to the rights set forth in Section 4(d). - -4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: - - You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. - You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed toward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted works by means of digital file-sharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted works. - If You Distribute, or Publicly Perform the Work or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work. The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Collection, at a minimum such credit will appear, if a credit for all contributing authors of Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. - - For the avoidance of doubt: - Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; - Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License if Your exercise of such rights is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b) and otherwise waives the right to collect royalties through any statutory or compulsory licensing scheme; and, - Voluntary License Schemes. The Licensor reserves the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License that is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b). - Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. - -5. Representations, Warranties and Disclaimer - -UNLESS OTHERWISE MUTUALLY AGREED BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. - -6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. Termination - - This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. - Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. - -8. Miscellaneous - - Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. - If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. - This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. - The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. +THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. + +BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. + +1. Definitions + + "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. + "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined above) for the purposes of this License. + "Distribute" means to make available to the public the original and copies of the Work through sale or other transfer of ownership. + "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. + "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. + "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. + "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. + "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. + "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. + +2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. + +3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: + + to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; and, + to Distribute and Publicly Perform the Work including as incorporated in Collections. + +The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats, but otherwise you have no rights to make Adaptations. Subject to 8(f), all rights not expressly granted by Licensor are hereby reserved, including but not limited to the rights set forth in Section 4(d). + +4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: + + You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. + You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed toward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted works by means of digital file-sharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted works. + If You Distribute, or Publicly Perform the Work or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work. The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Collection, at a minimum such credit will appear, if a credit for all contributing authors of Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. + + For the avoidance of doubt: + Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; + Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License if Your exercise of such rights is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b) and otherwise waives the right to collect royalties through any statutory or compulsory licensing scheme; and, + Voluntary License Schemes. The Licensor reserves the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License that is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b). + Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. + +5. Representations, Warranties and Disclaimer + +UNLESS OTHERWISE MUTUALLY AGREED BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. + +6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. Termination + + This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. + Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. + +8. Miscellaneous + + Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. + If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. + This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. + The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. diff --git a/Resources/doc/configuration.rst b/Resources/doc/configuration.rst index 528a1165..62b3e6fd 100755 --- a/Resources/doc/configuration.rst +++ b/Resources/doc/configuration.rst @@ -1,30 +1,30 @@ -Configuration -============= - -Initial Configuration ---------------------- -The configuration is as easy as choosing a random secret string which we will -be using for encrypting your data if you have requested this: - -.. configuration-block :: - - .. code-block :: yaml - - jms_payment_core: - secret: someS3cretP4ssw0rd - - .. code-block :: xml - - - -.. note :: - - If you change the secret, then all data encrypted with the old secret - will become unreadable. - -Payment Backend Configuration ------------------------------ -The different :doc:`payment backends ` which are provided by -additional bundles likely also require some form of configuration; please see -their documentation. - +Configuration +============= + +Initial Configuration +--------------------- +The configuration is as easy as choosing a random secret string which we will +be using for encrypting your data if you have requested this: + +.. configuration-block :: + + .. code-block :: yaml + + jms_payment_core: + secret: someS3cretP4ssw0rd + + .. code-block :: xml + + + +.. note :: + + If you change the secret, then all data encrypted with the old secret + will become unreadable. + +Payment Backend Configuration +----------------------------- +The different :doc:`payment backends ` which are provided by +additional bundles likely also require some form of configuration; please see +their documentation. + diff --git a/Resources/doc/installation.rst b/Resources/doc/installation.rst index 57fbd95c..bc3a5374 100755 --- a/Resources/doc/installation.rst +++ b/Resources/doc/installation.rst @@ -1,91 +1,91 @@ -Installation -============ - -1. Using Composer (recommended) -------------------------------- - -To install JMSPaymentCoreBundle with Composer just add the following to your -`composer.json` file: - -.. code-block :: js - - // composer.json - { - // ... - require: { - // ... - "jms/payment-core-bundle": "master-dev" - } - } - -.. note :: - - Please replace `master-dev` in the snippet above with the latest stable - branch, for example ``1.0.*``. - -Then, you can install the new dependencies by running Composer's ``update`` -command from the directory where your ``composer.json`` file is located: - -.. code-block :: bash - - $ php composer.phar update - -Now, Composer will automatically download all required files, and install them -for you. All that is left to do is to update your ``AppKernel.php`` file, and -register the new bundle: - -.. code-block :: php - - registerNamespaces(array( - // ... - 'JMS' => __DIR__.'/../vendor/bundles', - // ... - )); - -Now use the ``vendors`` script to clone the newly added repositories -into your project: - -.. code-block :: bash - - $ php bin/vendors install +Installation +============ + +1. Using Composer (recommended) +------------------------------- + +To install JMSPaymentCoreBundle with Composer just add the following to your +`composer.json` file: + +.. code-block :: js + + // composer.json + { + // ... + require: { + // ... + "jms/payment-core-bundle": "master-dev" + } + } + +.. note :: + + Please replace `master-dev` in the snippet above with the latest stable + branch, for example ``1.0.*``. + +Then, you can install the new dependencies by running Composer's ``update`` +command from the directory where your ``composer.json`` file is located: + +.. code-block :: bash + + $ php composer.phar update + +Now, Composer will automatically download all required files, and install them +for you. All that is left to do is to update your ``AppKernel.php`` file, and +register the new bundle: + +.. code-block :: php + + registerNamespaces(array( + // ... + 'JMS' => __DIR__.'/../vendor/bundles', + // ... + )); + +Now use the ``vendors`` script to clone the newly added repositories +into your project: + +.. code-block :: bash + + $ php bin/vendors install diff --git a/Resources/doc/model.rst b/Resources/doc/model.rst index fa061c87..b87ad92c 100755 --- a/Resources/doc/model.rst +++ b/Resources/doc/model.rst @@ -1,99 +1,99 @@ -The Model -========= - -Introduction ------------- -Before we are going to see how we can conduct payments, let me -give you a quick overlook over the model classes, and their purpose. - -PaymentInstruction ------------------- -A ``PaymentInstruction`` is the first object that you need to create. It contains -information such as the total amount, the payment method, the currency, and -any data that is necessary for the payment method, for example credit card -information. - -.. tip :: - - Any payment related data may be automatically encrypted if you request this. - -Below you find the different states that a ``PaymentInstruction`` can go through: - -.. uml :: - :alt: PaymentInstruction State Flow - - left to right direction - - [*] --> New - New --> Valid - New --> Invalid - Valid --> Closed - Invalid --> [*] - Closed --> [*] - -Payment -------- -Each ``PaymentInstruction`` may be splitted up into several payments. A ``Payment`` -always holds an amount, and the current state of the work-flow, such as -initiated, approved, deposited, etc. - -This allows you for example to request a fraction of the total amount to be -deposited before an order ships, and the rest afterwards. - -Below, you find the different states that a ``Payment`` can go through: - -.. uml :: - :alt: Payment State Flow - - left to right direction - - [*] --> New - - New --> Canceled - New --> Approving - - Approving --> Approved - Approving --> Failed - - Approved --> Depositing - - Depositing --> Deposited - Depositing --> Expired - Depositing --> Failed - - Canceled --> [*] - Failed --> [*] - Expired --> [*] - Deposited --> [*] - -FinancialTransaction --------------------- -Each ``Payment`` may have several transactions. Each ``FinancialTransaction`` -represents a specific interaction with the payment backend. In the case of -a credit card payment, this could for example be an authorization transaction. - -.. note :: - - There may only ever be one open transaction for each ``PaymentInstruction`` - at a time. This is enforced, and guaranteed. - -Below, you find the different states that a ``FinancialTransaction`` can go through: - -.. uml :: - :alt: Financial Transaction State Flow - - left to right direction - - [*] --> New - - New --> Pending - New --> Failed - New --> Success - New --> Canceled - - Pending --> Failed - Pending --> Success - - Failed --> [*] - Success --> [*] - Canceled --> [*] +The Model +========= + +Introduction +------------ +Before we are going to see how we can conduct payments, let me +give you a quick overlook over the model classes, and their purpose. + +PaymentInstruction +------------------ +A ``PaymentInstruction`` is the first object that you need to create. It contains +information such as the total amount, the payment method, the currency, and +any data that is necessary for the payment method, for example credit card +information. + +.. tip :: + + Any payment related data may be automatically encrypted if you request this. + +Below you find the different states that a ``PaymentInstruction`` can go through: + +.. uml :: + :alt: PaymentInstruction State Flow + + left to right direction + + [*] --> New + New --> Valid + New --> Invalid + Valid --> Closed + Invalid --> [*] + Closed --> [*] + +Payment +------- +Each ``PaymentInstruction`` may be splitted up into several payments. A ``Payment`` +always holds an amount, and the current state of the work-flow, such as +initiated, approved, deposited, etc. + +This allows you for example to request a fraction of the total amount to be +deposited before an order ships, and the rest afterwards. + +Below, you find the different states that a ``Payment`` can go through: + +.. uml :: + :alt: Payment State Flow + + left to right direction + + [*] --> New + + New --> Canceled + New --> Approving + + Approving --> Approved + Approving --> Failed + + Approved --> Depositing + + Depositing --> Deposited + Depositing --> Expired + Depositing --> Failed + + Canceled --> [*] + Failed --> [*] + Expired --> [*] + Deposited --> [*] + +FinancialTransaction +-------------------- +Each ``Payment`` may have several transactions. Each ``FinancialTransaction`` +represents a specific interaction with the payment backend. In the case of +a credit card payment, this could for example be an authorization transaction. + +.. note :: + + There may only ever be one open transaction for each ``PaymentInstruction`` + at a time. This is enforced, and guaranteed. + +Below, you find the different states that a ``FinancialTransaction`` can go through: + +.. uml :: + :alt: Financial Transaction State Flow + + left to right direction + + [*] --> New + + New --> Pending + New --> Failed + New --> Success + New --> Canceled + + Pending --> Failed + Pending --> Success + + Failed --> [*] + Success --> [*] + Canceled --> [*] diff --git a/Resources/doc/payment_backends.rst b/Resources/doc/payment_backends.rst index 33e0731a..2aa82a75 100755 --- a/Resources/doc/payment_backends.rst +++ b/Resources/doc/payment_backends.rst @@ -1,40 +1,40 @@ -Available Payment Backends -========================== -.. note :: - - If you have implemented a payment backend, feel free to add yourself - to this list by sending a pull request on GitHub. - -This is an incomplete list of implemented payment backends: - -- Paypal: JMSPaymentPaypalBundle_ -- Dotpay: ETSPaymentDotpayBundle_ -- Ogone: ETSPaymentOgoneBundle_ -- Merchant e-Solutions (Trident): PaymentMeSBundle_ -- Qiwi: ChewbaccoPaymentQiwiWalletBundle_ -- Be2Bill (Rentabiliweb): PaymentBe2billBundle_ -- Robokassa: KarserRobokassaBundle_ -- Adyen: RuudkPaymentAdyenBundle_ -- Mollie: RuudkPaymentMollieBundle_ -- Multisafepay: RuudkPaymentMultisafepayBundle_ -- Stripe: RuudkPaymentStripeBundle_ -- Atos SIPS: KptivePaymentSipsBundle_ -- Paymill: MemeoirsPaymillBundle_ -- Webpay: JakubZapletalPaymentWebpayBundle_ -- YandexKassa: RsipoYandexKassaBundle_ - -.. _JMSPaymentPaypalBundle: http://jmsyst.com/bundles/JMSPaymentPaypalBundle -.. _ETSPaymentDotpayBundle: https://github.com/ETSGlobal/ETSPaymentDotpayBundle -.. _ETSPaymentOgoneBundle: https://github.com/ETSGlobal/ETSPaymentOgoneBundle -.. _PaymentMeSBundle: https://github.com/immersivelabs/PaymentMeSBundle -.. _ChewbaccoPaymentQiwiWalletBundle: https://github.com/chewbacco/ChewbaccoPaymentQiwiWalletBundle -.. _PaymentBe2billBundle: https://github.com/rezzza/PaymentBe2billBundle -.. _KarserRobokassaBundle: https://github.com/karser/RobokassaBundle -.. _RuudkPaymentAdyenBundle: https://github.com/ruudk/PaymentAdyenBundle -.. _RuudkPaymentMollieBundle: https://github.com/ruudk/PaymentMollieBundle -.. _RuudkPaymentMultisafepayBundle: https://github.com/ruudk/PaymentMultisafepayBundle -.. _RuudkPaymentStripeBundle: https://github.com/ruudk/PaymentStripeBundle -.. _KptivePaymentSipsBundle: https://github.com/KptiveStudio/KptivePaymentSipsBundle -.. _MemeoirsPaymillBundle: https://github.com/memeoirs/paymill-bundle -.. _JakubZapletalPaymentWebpayBundle: https://github.com/jakubzapletal/payment-webpay-bundle -.. _RsipoYandexKassaBundle: https://github.com/rispo-service/RispoYandexKassaBundle +Available Payment Backends +========================== +.. note :: + + If you have implemented a payment backend, feel free to add yourself + to this list by sending a pull request on GitHub. + +This is an incomplete list of implemented payment backends: + +- Paypal: JMSPaymentPaypalBundle_ +- Dotpay: ETSPaymentDotpayBundle_ +- Ogone: ETSPaymentOgoneBundle_ +- Merchant e-Solutions (Trident): PaymentMeSBundle_ +- Qiwi: ChewbaccoPaymentQiwiWalletBundle_ +- Be2Bill (Rentabiliweb): PaymentBe2billBundle_ +- Robokassa: KarserRobokassaBundle_ +- Adyen: RuudkPaymentAdyenBundle_ +- Mollie: RuudkPaymentMollieBundle_ +- Multisafepay: RuudkPaymentMultisafepayBundle_ +- Stripe: RuudkPaymentStripeBundle_ +- Atos SIPS: KptivePaymentSipsBundle_ +- Paymill: MemeoirsPaymillBundle_ +- Webpay: JakubZapletalPaymentWebpayBundle_ +- YandexKassa: RsipoYandexKassaBundle_ + +.. _JMSPaymentPaypalBundle: http://jmsyst.com/bundles/JMSPaymentPaypalBundle +.. _ETSPaymentDotpayBundle: https://github.com/ETSGlobal/ETSPaymentDotpayBundle +.. _ETSPaymentOgoneBundle: https://github.com/ETSGlobal/ETSPaymentOgoneBundle +.. _PaymentMeSBundle: https://github.com/immersivelabs/PaymentMeSBundle +.. _ChewbaccoPaymentQiwiWalletBundle: https://github.com/chewbacco/ChewbaccoPaymentQiwiWalletBundle +.. _PaymentBe2billBundle: https://github.com/rezzza/PaymentBe2billBundle +.. _KarserRobokassaBundle: https://github.com/karser/RobokassaBundle +.. _RuudkPaymentAdyenBundle: https://github.com/ruudk/PaymentAdyenBundle +.. _RuudkPaymentMollieBundle: https://github.com/ruudk/PaymentMollieBundle +.. _RuudkPaymentMultisafepayBundle: https://github.com/ruudk/PaymentMultisafepayBundle +.. _RuudkPaymentStripeBundle: https://github.com/ruudk/PaymentStripeBundle +.. _KptivePaymentSipsBundle: https://github.com/KptiveStudio/KptivePaymentSipsBundle +.. _MemeoirsPaymillBundle: https://github.com/memeoirs/paymill-bundle +.. _JakubZapletalPaymentWebpayBundle: https://github.com/jakubzapletal/payment-webpay-bundle +.. _RsipoYandexKassaBundle: https://github.com/rispo-service/RispoYandexKassaBundle diff --git a/Resources/doc/usage.rst b/Resources/doc/usage.rst index a6f4ce3d..c25cc23f 100755 --- a/Resources/doc/usage.rst +++ b/Resources/doc/usage.rst @@ -1,263 +1,263 @@ -Usage -===== - -Introduction ------------- -In this chapter, we will explore how you can integrate JMSPaymentCoreBundle -into your application. We will assume that you already have created an order -object or equivalent. This could look like: - -.. code-block :: php - - amount = $amount; - $this->orderNumber = $orderNumber; - } - - public function getOrderNumber() - { - return $this->orderNumber; - } - - public function getAmount() - { - return $this->amount; - } - - public function getPaymentInstruction() - { - return $this->paymentInstruction; - } - - public function setPaymentInstruction(PaymentInstruction $instruction) - { - $this->paymentInstruction = $instruction; - } - - // ... - } - -.. note :: - - An order object, or the like is not strictly necessary, but since it is - regularly available, we will be using it in this chapter for demonstration - purposes. - -Choosing the Payment Method ---------------------------- -Usually, you want to give a potential customer some options on how to pay. For -this, JMSPaymentCoreBundle ships with a special form type, ``jms_choose_payment_method``, -which we will leverage. - -.. note :: - - In the following examples, we will make use of JMSDiExtraBundle_, and - SensioFrameworkExtraBundle_. This is by no means required when you implement - this in your own application though. - -.. warning :: - - We have completely left out any security considerations, in a real-world - scenario, you have to make sure the following actions are sufficiently - covered by access rules, for example by using @PreAuthorize from - JMSSecurityExtraBundle_. - -.. code-block :: php - - getFormFactory()->create('jms_choose_payment_method', null, array( - 'amount' => $order->getAmount(), - 'currency' => 'EUR', - 'default_method' => 'payment_paypal', // Optional - 'predefined_data' => array( - 'paypal_express_checkout' => array( - 'return_url' => $this->router->generate('payment_complete', array( - 'orderNumber' => $order->getOrderNumber(), - ), true), - 'cancel_url' => $this->router->generate('payment_cancel', array( - 'orderNumber' => $order->getOrderNumber(), - ), true) - ), - ), - )); - - if ('POST' === $this->request->getMethod()) { - $form->bindRequest($this->request); - - if ($form->isValid()) { - $this->ppc->createPaymentInstruction($instruction = $form->getData()); - - $order->setPaymentInstruction($instruction); - $this->em->persist($order); - $this->em->flush($order); - - return new RedirectResponse($this->router->generate('payment_complete', array( - 'orderNumber' => $order->getOrderNumber(), - ))); - } - } - - return array( - 'form' => $form->createView() - ); - } - - // ... - - /** @DI\LookupMethod("form.factory") */ - protected function getFormFactory() { } - } - -The ``jms_choose_payment_method`` form type will automatically render a form -with all available payment methods. Upon binding, the form type will validate -the data for the chosen payment method, and on success will give us a valid -``PaymentInstruction`` instance back. - -You might want to add extra costs for a specific payment method. You can easily -handle this by passing on a closure to the ``amount`` of the form: - -.. code-block :: php - - getFormFactory()->create('jms_choose_payment_method', null, array( - 'amount' => function($currency, $paymentSystemName, ExtendedData $data) use ($order) { - if ('paypal_express_checkout' == $paymentSystemName) { - return $order->getAmount() * 1.05; - } - - return $order->getAmount(); - }, - - // ... - )); - -Depositing Money ----------------- -In the previous section, we have created our ``PaymentInstruction``. Now, we -will see how we can actually deposit money in our account. As you saw above -in the ``detailsAction``, we redirected the user to the ``payment_complete`` -route for which we will now create the corresponding action in our controller: - -.. code-block :: php - - getPaymentInstruction(); - if (null === $pendingTransaction = $instruction->getPendingTransaction()) { - $payment = $this->ppc->createPayment($instruction->getId(), $instruction->getAmount() - $instruction->getDepositedAmount()); - } else { - $payment = $pendingTransaction->getPayment(); - } - - $result = $this->ppc->approveAndDeposit($payment->getId(), $payment->getTargetAmount()); - if (Result::STATUS_PENDING === $result->getStatus()) { - $ex = $result->getPluginException(); - - if ($ex instanceof ActionRequiredException) { - $action = $ex->getAction(); - - if ($action instanceof VisitUrl) { - return new RedirectResponse($action->getUrl()); - } - - throw $ex; - } - } else if (Result::STATUS_SUCCESS !== $result->getStatus()) { - throw new \RuntimeException('Transaction was not successful: '.$result->getReasonCode()); - } - - // payment was successful, do something interesting with the order - } - } - -.. _JMSDiExtraBundle: http://jmsyst.com/bundles/JMSDiExtraBundle -.. _JMSSecurityExtraBundle: http://jmsyst.com/bundles/JMSSecurityExtraBundle -.. _SensioFrameworkExtraBundle: http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/index.html +Usage +===== + +Introduction +------------ +In this chapter, we will explore how you can integrate JMSPaymentCoreBundle +into your application. We will assume that you already have created an order +object or equivalent. This could look like: + +.. code-block :: php + + amount = $amount; + $this->orderNumber = $orderNumber; + } + + public function getOrderNumber() + { + return $this->orderNumber; + } + + public function getAmount() + { + return $this->amount; + } + + public function getPaymentInstruction() + { + return $this->paymentInstruction; + } + + public function setPaymentInstruction(PaymentInstruction $instruction) + { + $this->paymentInstruction = $instruction; + } + + // ... + } + +.. note :: + + An order object, or the like is not strictly necessary, but since it is + regularly available, we will be using it in this chapter for demonstration + purposes. + +Choosing the Payment Method +--------------------------- +Usually, you want to give a potential customer some options on how to pay. For +this, JMSPaymentCoreBundle ships with a special form type, ``jms_choose_payment_method``, +which we will leverage. + +.. note :: + + In the following examples, we will make use of JMSDiExtraBundle_, and + SensioFrameworkExtraBundle_. This is by no means required when you implement + this in your own application though. + +.. warning :: + + We have completely left out any security considerations, in a real-world + scenario, you have to make sure the following actions are sufficiently + covered by access rules, for example by using @PreAuthorize from + JMSSecurityExtraBundle_. + +.. code-block :: php + + getFormFactory()->create('jms_choose_payment_method', null, array( + 'amount' => $order->getAmount(), + 'currency' => 'EUR', + 'default_method' => 'payment_paypal', // Optional + 'predefined_data' => array( + 'paypal_express_checkout' => array( + 'return_url' => $this->router->generate('payment_complete', array( + 'orderNumber' => $order->getOrderNumber(), + ), true), + 'cancel_url' => $this->router->generate('payment_cancel', array( + 'orderNumber' => $order->getOrderNumber(), + ), true) + ), + ), + )); + + if ('POST' === $this->request->getMethod()) { + $form->bindRequest($this->request); + + if ($form->isValid()) { + $this->ppc->createPaymentInstruction($instruction = $form->getData()); + + $order->setPaymentInstruction($instruction); + $this->em->persist($order); + $this->em->flush($order); + + return new RedirectResponse($this->router->generate('payment_complete', array( + 'orderNumber' => $order->getOrderNumber(), + ))); + } + } + + return array( + 'form' => $form->createView() + ); + } + + // ... + + /** @DI\LookupMethod("form.factory") */ + protected function getFormFactory() { } + } + +The ``jms_choose_payment_method`` form type will automatically render a form +with all available payment methods. Upon binding, the form type will validate +the data for the chosen payment method, and on success will give us a valid +``PaymentInstruction`` instance back. + +You might want to add extra costs for a specific payment method. You can easily +handle this by passing on a closure to the ``amount`` of the form: + +.. code-block :: php + + getFormFactory()->create('jms_choose_payment_method', null, array( + 'amount' => function($currency, $paymentSystemName, ExtendedData $data) use ($order) { + if ('paypal_express_checkout' == $paymentSystemName) { + return $order->getAmount() * 1.05; + } + + return $order->getAmount(); + }, + + // ... + )); + +Depositing Money +---------------- +In the previous section, we have created our ``PaymentInstruction``. Now, we +will see how we can actually deposit money in our account. As you saw above +in the ``detailsAction``, we redirected the user to the ``payment_complete`` +route for which we will now create the corresponding action in our controller: + +.. code-block :: php + + getPaymentInstruction(); + if (null === $pendingTransaction = $instruction->getPendingTransaction()) { + $payment = $this->ppc->createPayment($instruction->getId(), $instruction->getAmount() - $instruction->getDepositedAmount()); + } else { + $payment = $pendingTransaction->getPayment(); + } + + $result = $this->ppc->approveAndDeposit($payment->getId(), $payment->getTargetAmount()); + if (Result::STATUS_PENDING === $result->getStatus()) { + $ex = $result->getPluginException(); + + if ($ex instanceof ActionRequiredException) { + $action = $ex->getAction(); + + if ($action instanceof VisitUrl) { + return new RedirectResponse($action->getUrl()); + } + + throw $ex; + } + } else if (Result::STATUS_SUCCESS !== $result->getStatus()) { + throw new \RuntimeException('Transaction was not successful: '.$result->getReasonCode()); + } + + // payment was successful, do something interesting with the order + } + } + +.. _JMSDiExtraBundle: http://jmsyst.com/bundles/JMSDiExtraBundle +.. _JMSSecurityExtraBundle: http://jmsyst.com/bundles/JMSSecurityExtraBundle +.. _SensioFrameworkExtraBundle: http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/index.html diff --git a/Resources/views/.symfony b/Resources/views/.symfony deleted file mode 100644 index e69de29b..00000000 diff --git a/Resources/views/Demo/index.php b/Resources/views/Demo/index.php deleted file mode 100644 index 5e548733..00000000 --- a/Resources/views/Demo/index.php +++ /dev/null @@ -1 +0,0 @@ -Your transaction was successful. \ No newline at end of file diff --git a/Tests/Functional/TestBundle/Controller/OrderController.php b/Tests/Functional/TestBundle/Controller/OrderController.php index b04a8837..dfdc033a 100755 --- a/Tests/Functional/TestBundle/Controller/OrderController.php +++ b/Tests/Functional/TestBundle/Controller/OrderController.php @@ -1,72 +1,72 @@ -getFormFactory()->create('jms_choose_payment_method', null, array( - 'currency' => 'EUR', - 'amount' => $order->getAmount(), - 'csrf_protection' => false, - 'predefined_data' => array( - 'paypal_express_checkout' => array( - 'foo' => 'bar', - ), - ), - )); - - if ('POST' === $this->request->getMethod()) { - if (method_exists($form, 'submit')) { - $form->submit($this->request); - } else { - $form->bindRequest($this->request); - } - - if ($form->isValid()) { - $instruction = $form->getData(); - $this->ppc->createPaymentInstruction($instruction); - - $order->setPaymentInstruction($instruction); - $this->em->persist($order); - $this->em->flush(); - - return new Response('', 201); - } - } - - return array('form' => $form->createView()); - } - - /** @DI\LookupMethod("form.factory") */ - protected function getFormFactory() { } -} +getFormFactory()->create('jms_choose_payment_method', null, array( + 'currency' => 'EUR', + 'amount' => $order->getAmount(), + 'csrf_protection' => false, + 'predefined_data' => array( + 'paypal_express_checkout' => array( + 'foo' => 'bar', + ), + ), + )); + + if ('POST' === $this->request->getMethod()) { + if (method_exists($form, 'submit')) { + $form->submit($this->request); + } else { + $form->bindRequest($this->request); + } + + if ($form->isValid()) { + $instruction = $form->getData(); + $this->ppc->createPaymentInstruction($instruction); + + $order->setPaymentInstruction($instruction); + $this->em->persist($order); + $this->em->flush(); + + return new Response('', 201); + } + } + + return array('form' => $form->createView()); + } + + /** @DI\LookupMethod("form.factory") */ + protected function getFormFactory() { } +} diff --git a/Tests/Functional/TestBundle/Entity/Order.php b/Tests/Functional/TestBundle/Entity/Order.php index f611f3c7..3fc55d23 100755 --- a/Tests/Functional/TestBundle/Entity/Order.php +++ b/Tests/Functional/TestBundle/Entity/Order.php @@ -1,50 +1,50 @@ - - */ -class Order -{ - /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ - private $id; - - /** @ORM\Column(type="decimal", precision = 2) */ - private $amount; - - /** @ORM\OneToOne(targetEntity="JMS\Payment\CoreBundle\Entity\PaymentInstruction") */ - private $paymentInstruction; - - public function __construct($amount) - { - $this->amount = $amount; - } - - public function getId() - { - return $this->id; - } - - public function getAmount() - { - return $this->amount; - } - - public function getPaymentInstruction() - { - return $this->paymentInstruction; - } - - public function setPaymentInstruction(PaymentInstruction $instruction) - { - $this->paymentInstruction = $instruction; - } +use Doctrine\ORM\Mapping as ORM; + +/** + * @ORM\Entity + * @ORM\Table(name = "orders") + * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT") + * + * @author Johannes M. Schmitt + */ +class Order +{ + /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ + private $id; + + /** @ORM\Column(type="decimal", precision = 2) */ + private $amount; + + /** @ORM\OneToOne(targetEntity="JMS\Payment\CoreBundle\Entity\PaymentInstruction") */ + private $paymentInstruction; + + public function __construct($amount) + { + $this->amount = $amount; + } + + public function getId() + { + return $this->id; + } + + public function getAmount() + { + return $this->amount; + } + + public function getPaymentInstruction() + { + return $this->paymentInstruction; + } + + public function setPaymentInstruction(PaymentInstruction $instruction) + { + $this->paymentInstruction = $instruction; + } } \ No newline at end of file diff --git a/Tests/Functional/TestBundle/Resources/views/Order/paymentDetails.html.twig b/Tests/Functional/TestBundle/Resources/views/Order/paymentDetails.html.twig index 530e22e9..568d4694 100755 --- a/Tests/Functional/TestBundle/Resources/views/Order/paymentDetails.html.twig +++ b/Tests/Functional/TestBundle/Resources/views/Order/paymentDetails.html.twig @@ -1,5 +1,5 @@ -
-{{ form_widget(form) }} - - + +{{ form_widget(form) }} + +
\ No newline at end of file diff --git a/Tests/Functional/TestBundle/TestBundle.php b/Tests/Functional/TestBundle/TestBundle.php index d8129d1c..05a2fc60 100755 --- a/Tests/Functional/TestBundle/TestBundle.php +++ b/Tests/Functional/TestBundle/TestBundle.php @@ -1,9 +1,9 @@ -loadFromExtension('doctrine', array( - 'dbal' => array( - 'driver' => 'pdo_sqlite', - 'path' => tempnam(sys_get_temp_dir(), 'database'), - ), +loadFromExtension('doctrine', array( + 'dbal' => array( + 'driver' => 'pdo_sqlite', + 'path' => tempnam(sys_get_temp_dir(), 'database'), + ), )); \ No newline at end of file diff --git a/Tests/Functional/config/framework.yml b/Tests/Functional/config/framework.yml index 9ec792c3..701edc1b 100644 --- a/Tests/Functional/config/framework.yml +++ b/Tests/Functional/config/framework.yml @@ -5,8 +5,8 @@ framework: storage_id: session.storage.mock_file form: true csrf_protection: true - validation: + validation: enabled: true enable_annotations: true router: - resource: "%kernel.root_dir%/config/routing.yml" \ No newline at end of file + resource: "%kernel.root_dir%/config/routing.yml" diff --git a/Tests/Functional/config/routing.yml b/Tests/Functional/config/routing.yml index 3d019371..b6a06718 100644 --- a/Tests/Functional/config/routing.yml +++ b/Tests/Functional/config/routing.yml @@ -1,7 +1,3 @@ -JMSPaymentCoreBundle: - resource: "@JMSPaymentCoreBundle/Resources/config/routing.yml" - TestBundle: resource: "@TestBundle/Controller/" type: annotation - \ No newline at end of file diff --git a/Tests/Plugin/ErrorBuilderTest.php b/Tests/Plugin/ErrorBuilderTest.php index 78aecde0..6c7ca579 100755 --- a/Tests/Plugin/ErrorBuilderTest.php +++ b/Tests/Plugin/ErrorBuilderTest.php @@ -1,34 +1,34 @@ -assertFalse($this->builder->hasErrors()); - - $this->builder->addGlobalError('foo'); - $this->assertTrue($this->builder->hasErrors()); - } - - public function testGetException() - { - $this->builder->addDataError('foo', 'bar'); - $this->builder->addGlobalError('baz'); - - $ex = $this->builder->getException(); - $this->assertInstanceOf('JMS\Payment\CoreBundle\Plugin\Exception\InvalidPaymentInstructionException', $ex); - $this->assertSame(array('foo' => 'bar'), $ex->getDataErrors()); - $this->assertSame(array('baz'), $ex->getGlobalErrors()); - } - - protected function setUp() - { - $this->builder = new ErrorBuilder(); - } + +class ErrorBuilderTest extends \PHPUnit_Framework_TestCase +{ + private $builder; + + public function testHasErrors() + { + $this->assertFalse($this->builder->hasErrors()); + + $this->builder->addGlobalError('foo'); + $this->assertTrue($this->builder->hasErrors()); + } + + public function testGetException() + { + $this->builder->addDataError('foo', 'bar'); + $this->builder->addGlobalError('baz'); + + $ex = $this->builder->getException(); + $this->assertInstanceOf('JMS\Payment\CoreBundle\Plugin\Exception\InvalidPaymentInstructionException', $ex); + $this->assertSame(array('foo' => 'bar'), $ex->getDataErrors()); + $this->assertSame(array('baz'), $ex->getGlobalErrors()); + } + + protected function setUp() + { + $this->builder = new ErrorBuilder(); + } } \ No newline at end of file