/** * Gets response from braintree api using the nonce * * @param string|null $nonce * @param array|null $options * @param array|null $billingAddress * @return $this * @throws LocalizedException * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function processNonce($nonce = null, $options = null, $billingAddress = null) { $customerId = $this->customerSession->getCustomerId(); if (!$customerId) { throw new LocalizedException(__('Invalid Customer ID provided')); } $billingCountry = null; if (is_array($billingAddress)) { $collection = $this->countryFactory->create()->addCountryCodeFilter($billingAddress['countryCodeAlpha2']); if ($collection->getSize()) { $billingCountry = $collection->getFirstItem()->getId(); } if (!$this->config->canUseForCountry($billingCountry)) { throw new LocalizedException(__('Selected payment type is not allowed for billing country.')); } } $ccType = null; if ($options) { $ccType = $options['ccType']; } if ($ccType) { $error = $this->config->canUseCcTypeForCountry($billingCountry, $ccType); if ($error) { throw new LocalizedException($error); } } $customer = $this->customerFactory->create()->load($customerId); $customerId = $this->braintreeHelper->generateCustomerId($customerId, $customer->getEmail()); if (!$this->exists($customerId)) { $customerRequest = ['id' => $customerId, 'firstName' => $billingAddress['firstName'], 'lastName' => $billingAddress['lastName'], 'email' => $this->customerSession->getCustomerDataObject()->getEmail()]; if (strlen($billingAddress['company'])) { $customerRequest['company'] = $billingAddress['company']; } $result = $this->braintreeCustomer->create($customerRequest); if (!$result->success) { throw new LocalizedException($this->errorHelper->parseBraintreeError($result)); } } //check if customerId is created on braintree $requestArray = ['customerId' => $customerId, 'paymentMethodNonce' => $nonce, 'options' => ['makeDefault' => $options['default'] == 'true' ? true : false, 'failOnDuplicatePaymentMethod' => $this->config->allowDuplicateCards() == '1' ? false : true, 'verifyCard' => $this->config->useCvv() == '1' ? true : false]]; if ($this->config->isFraudDetectionEnabled() && strlen($options['device_data']) > 0) { $requestArray['deviceData'] = $options['device_data']; } if ($options['update'] == 'true') { $token = $options['token']; unset($requestArray['customerId']); unset($requestArray['options']['failOnDuplicatePaymentMethod']); $requestArray['billingAddress'] = $billingAddress; $result = $this->braintreePaymentMethod->update($token, $requestArray); $this->debug($requestArray); $this->debug($result); } else { $result = $this->braintreePaymentMethod->create($requestArray); $this->debug($requestArray); $this->debug($result); } if (!$result->success) { throw new LocalizedException($this->errorHelper->parseBraintreeError($result)); } return $this; }