/** * Action to allow users to delete payment methods * * @return Mage_Core_Controller_Varien_Action * * @throws Exception */ public function removeAction() { // Check we've recieved a payment ID $token = $this->getRequest()->getParam('id'); if (!$token) { $this->_getSession()->addError('Please select a saved payment entry to remove.'); return $this->_redirectReferer(); } // Grab a new instance of the wrapper $wrapper = Mage::getModel('gene_braintree/wrapper_braintree'); // Init the braintree wrapper $wrapper->init(); // Load the payment method from Braintree try { $paymentMethod = Braintree_PaymentMethod::find($token); } catch (Exception $e) { $this->_getSession()->addError('The requested payment method cannot be found.'); return $this->_redirectReferer(); } // Check that this is the users payment method, we have to use a custom method as Braintree don't return the PayPal customer ID if (!$wrapper->customerOwnsMethod($paymentMethod)) { $this->_getSession()->addError('You do not have permission to modify this payment method.'); return $this->_redirectReferer(); } // Remove the payment method Braintree_PaymentMethod::delete($token); // Inform the user of the great news $this->_getSession()->addSuccess('Saved payment has been successfully deleted.'); return $this->_redirectReferer(); }
function testDelete_worksWithPayPalAccounts() { $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand()); $customer = Braintree_Customer::createNoValidate(); $nonce = Braintree_HttpClientApi::nonceForPayPalAccount(array('paypal_account' => array('consent_code' => 'PAYPAL_CONSENT_CODE', 'token' => $paymentMethodToken))); $paypalAccountResult = Braintree_PaymentMethod::create(array('customerId' => $customer->id, 'paymentMethodNonce' => $nonce)); $this->assertTrue($paypalAccountResult->success); Braintree_PaymentMethod::delete($paymentMethodToken); $this->setExpectedException('Braintree_Exception_NotFound'); Braintree_PaymentMethod::find($paymentMethodToken); }
function testCreate_fromPayPalACcount() { $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand()); $customer = Braintree_Customer::createNoValidate(); $plan = Braintree_SubscriptionTestHelper::triallessPlan(); $nonce = Braintree_HttpClientApi::nonceForPayPalAccount(array('paypal_account' => array('consent_code' => 'PAYPAL_CONSENT_CODE', 'token' => $paymentMethodToken))); $paypalResult = Braintree_PaymentMethod::create(array('customerId' => $customer->id, 'paymentMethodNonce' => $nonce)); $subscriptionResult = Braintree_Subscription::create(array('paymentMethodToken' => $paymentMethodToken, 'planId' => $plan['id'])); $this->assertTrue($subscriptionResult->success); $transaction = $subscriptionResult->subscription->transactions[0]; $this->assertEquals('*****@*****.**', $transaction->paypalDetails->payerEmail); }
function testCreate_withOnetimePayPalAndDoesNotVault() { $paymentMethodToken = 'PAYPAL_TOKEN-' . strval(rand()); $nonce = Braintree_HttpClientApi::nonceForPayPalAccount(array('paypal_account' => array('access_token' => 'PAYPAL_ACCESS_TOKEN', 'token' => $paymentMethodToken))); $result = Braintree_Transaction::sale(array('amount' => Braintree_Test_TransactionAmounts::$authorize, 'paymentMethodNonce' => $nonce, 'options' => array('storeInVault' => true))); $this->assertTrue($result->success); $transaction = $result->transaction; $this->assertEquals('*****@*****.**', $transaction->paypalDetails->payerEmail); $this->assertNotNull($transaction->paypalDetails->imageUrl); $this->assertNotNull($transaction->paypalDetails->debugId); $this->setExpectedException('Braintree_Exception_NotFound'); Braintree_PaymentMethod::find($paymentMethodToken); }
function testDelete() { $paymentMethodToken = 'PAYPALToken-' . strval(rand()); $customer = Braintree_Customer::createNoValidate(); $http = new Braintree_HttpClientApi(Braintree_Configuration::$global); $nonce = $http->nonceForPayPalAccount(array('paypal_account' => array('consent_code' => 'PAYPAL_CONSENT_CODE', 'token' => $paymentMethodToken))); Braintree_PaymentMethod::create(array('customerId' => $customer->id, 'paymentMethodNonce' => $nonce)); Braintree_PayPalAccount::delete($paymentMethodToken); $this->setExpectedException('Braintree_Exception_NotFound'); Braintree_PayPalAccount::find($paymentMethodToken); }
/** * Saves Credit Card and customer (if new) in vault * * @throws Mage_Core_Exception * @return boolean */ public function saveInVault($postData, $token = false) { $post = $this->_protectArray($postData); $customerId = Mage::getSingleton('customer/session')->getCustomerId(); if (!$customerId) { Mage::throwException(Mage::helper('braintree_payments')->__('Invalid Customer ID provided')); } $customerId = Mage::helper('braintree_payments')->generateCustomerId($customerId, Mage::getSingleton('customer/session')->getCustomer()->getEmail()); $nonce = isset($post['nonce']) ? $post['nonce'] : ''; if (!$this->_validateCustomerAddressData($post)) { Mage::throwException(Mage::helper('braintree_payments')->__('Invalid Address Data provided')); } $request = array('billingAddress' => array('firstName' => $post['credit_card']['billing_address']['first_name'], 'lastName' => $post['credit_card']['billing_address']['last_name'], 'streetAddress' => $post['credit_card']['billing_address']['street_address'], 'locality' => $post['credit_card']['billing_address']['locality'], 'postalCode' => $post['credit_card']['billing_address']['postal_code'], 'countryCodeAlpha2' => $post['credit_card']['billing_address']['country_code_alpha2'])); if (isset($post['credit_card']['billing_address']['extended_address']) && $post['credit_card']['billing_address']['extended_address']) { $request['billingAddress']['extendedAddress'] = $post['credit_card']['billing_address']['extended_address']; } if (isset($post['credit_card']['billing_address']['region']) && $post['credit_card']['billing_address']['region']) { $request['billingAddress']['region'] = $post['credit_card']['billing_address']['region']; } if (isset($post['credit_card']['billing_address']['company']) && $post['credit_card']['billing_address']['company']) { $request['billingAddress']['company'] = $post['credit_card']['billing_address']['company']; } if ($token) { // update card $request['billingAddress']['options'] = array('updateExisting' => true); $extendedRequest = array('creditCard' => array('paymentMethodNonce' => $nonce, 'billingAddress' => $request['billingAddress'], 'options' => array('updateExistingToken' => $token))); if (isset($post['credit_card']['options']['make_default']) && $post['credit_card']['options']['make_default']) { $extendedRequest['creditCard']['options']['makeDefault'] = true; } $this->_debug($token); $this->_debug($extendedRequest); $result = Braintree_Customer::update($customerId, $extendedRequest); $this->_debug($result); } else { if (!$this->_allowDuplicateCards()) { $request['options'] = array('failOnDuplicatePaymentMethod' => true); } if ($this->exists($customerId)) { // add new card for existing customer $request['customerId'] = $customerId; $request['paymentMethodNonce'] = $nonce; $this->_debug($request); $result = Braintree_PaymentMethod::create($request); $this->_debug($result); } else { // add new card and new customer $extendedRequest = array('id' => $customerId, 'firstName' => $post['credit_card']['billing_address']['first_name'], 'lastName' => $post['credit_card']['billing_address']['last_name'], 'email' => Mage::getSingleton('customer/session')->getCustomer()->getEmail(), 'paymentMethodNonce' => $nonce, 'creditCard' => $request); if (isset($post['credit_card']['billing_address']['company']) && $post['credit_card']['billing_address']['company']) { $extendedRequest['company'] = $post['credit_card']['billing_address']['company']; } $this->_debug($extendedRequest); $result = Braintree_Customer::create($extendedRequest); $this->_debug($result); } } if (!$result->success) { Mage::throwException(Mage::helper('braintree_payments/error')->parseBraintreeError($result)); } return true; }
/** * Returns stored payment method by token * * @return Braintree_PaymentMethod | null */ public function storedPaymentMethod($token) { try { $ret = Braintree_PaymentMethod::find($token); $this->_debug($token); $this->_debug($ret); return $ret; } catch (Braintree_Exception $e) { Mage::logException($e); } }
public function reservePayment() { if (Efiwebsetting::getData('checkOAuth') == 'yes') { IMBAuth::checkOAuth(); } $id_restaurant = $_GET["id_restaurant"]; $id_user = $_GET["id_user"]; $resto = new MasterRestaurantModel(); $resto->getByID($id_restaurant); $amount = 100000; if ($resto->verification_amount > 0) { $amount = $resto->verification_amount; } $user = new UserModel(); $user->getByID($id_user); if ($user->payment_id == null || $user->payment_id == "0") { Generic::errorMsg("No Payment Method"); } try { $result = Braintree_PaymentMethodNonce::create($user->braintree_id); $nonce = $result->paymentMethodNonce->nonce; } catch (Exception $e) { Generic::errorMsg($e->getMessage()); } $resultVerify = Braintree_PaymentMethod::create(['customerId' => $id_user, 'paymentMethodNonce' => $nonce, 'options' => ['verifyCard' => true, 'verificationMerchantAccountId' => 'm5ph2g77wgfzdyy2', 'verificationAmount' => $amount]]); $json["status_code"] = 0; if ($resultVerify) { $json["status_code"] = 1; $json['results']['amount'] = $amount; $json['results']['nonce'] = $nonce; } echo json_encode($json); die; }
public function checkout() { $this->layout = 'profile_new'; if (!$this->request->is('post')) { throw new NotFoundException(__d('billing', 'Incorrect request type')); } $customer = Braintree_Customer::find('konstruktor-' . $this->currUser['User']['id']); if (isset($this->request->data['payment_method_nonce'])) { $nonceFromTheClient = $this->request->data['payment_method_nonce']; $payment = Braintree_PaymentMethod::create(['customerId' => 'konstruktor-' . $this->currUser['User']['id'], 'paymentMethodNonce' => $nonceFromTheClient]); if (!$payment->success) { $this->Session->setFlash($payment->message); $this->redirect(array('action' => 'payment')); } $payment = $payment->paymentMethod; } elseif (isset($this->request->data['payment_method']) && !empty($this->request->data['payment_method'])) { $payment = null; foreach ($customer->paymentMethods as $payment) { if ($payment->token == $this->request->data['payment_method']) { break; } } if (empty($payment)) { throw new NotFoundException(__d('billing', 'Payment method not found')); } } else { throw new NotFoundException(__d('billing', 'Unable to create subscription')); } $braintreePlanId = $this->Session->read('Billing.plan'); $plan = $this->BillingPlan->findByRemotePlan($braintreePlanId); $braintreePlans = Braintree_Plan::all(); $braintreePlan = null; foreach ($braintreePlans as $_braintreePlan) { if ($_braintreePlan->id == $braintreePlanId) { $braintreePlan = $_braintreePlan; break; } } if (empty($braintreePlan)) { throw new NotFoundException(__d('billing', 'Unable to create subscription')); } //Important! unit setup for model must be here. Before creating Braintree subscription $unit = Configure::read('Billing.units.' . $plan['BillingGroup']['limit_units']); if (empty($unit['model']) || empty($unit['field'])) { throw new NotFoundException(__d('billing', 'Invalid billing plan')); } $this->BillingSubscription->Behaviors->load('Billing.Limitable', array('remoteModel' => $unit['model'], 'remoteField' => $unit['field'], 'scope' => isset($unit['scope']) ? $unit['scope'] : 'user_id')); //Precreate subscription $braintreeData = array('paymentMethodToken' => $payment->token, 'planId' => $braintreePlanId); $qty = $this->Session->read('Billing.qty'); if (!empty($qty)) { if (empty($braintreePlan->addOns)) { throw new NotFoundException(__d('billing', 'Unable to create subscription')); } foreach ($braintreePlan->addOns as $addOn) { $braintreeData['addOns']['update'][] = array('existingId' => $addOn->id, 'quantity' => $qty); } } $billingSubscription = $this->BillingSubscription->find('first', array('conditions' => array('BillingSubscription.group_id' => $plan['BillingGroup']['id'], 'BillingSubscription.user_id' => $this->currUser['User']['id'], 'BillingSubscription.active' => true))); //braintree unable to update subscription to a plan with a different billing frequency So we need to cancel current if (!empty($billingSubscription)) { if ($braintreePlan->billingFrequency != $billingSubscription['BraintreePlan']->billingFrequency || $billingSubscription['BraintreeSubscription']->status == 'Canceled' || $billingSubscription['BraintreeSubscription']->status == 'Expired') { if ($braintreePlan->billingFrequency != $billingSubscription['BraintreePlan']->billingFrequency || $billingSubscription['BraintreeSubscription']->status != 'Canceled') { try { $result = Braintree_Subscription::cancel($billingSubscription['BraintreeSubscription']->id); if ($result->success) { $billingSubscription['BraintreeSubscription'] = $result->subscription; } } catch (Exception $e) { } } $status = isset($billingSubscription['BraintreeSubscription']->status) ? $billingSubscription['BraintreeSubscription']->status : 'Canceled'; $this->BillingSubscription->cancel($billingSubscription['BillingSubscription']['id'], $status); $billingSubscription = null; } } if (!isset($billingSubscription['BillingSubscription'])) { $data = array('group_id' => $plan['BillingGroup']['id'], 'plan_id' => $plan['BillingPlan']['id'], 'user_id' => $this->currUser['User']['id'], 'limit_value' => !empty($qty) ? $qty : $plan['BillingPlan']['limit_value'], 'active' => false); } else { $data = $billingSubscription['BillingSubscription']; $data['limit_value'] = !empty($qty) ? $qty : $plan['BillingPlan']['limit_value']; } //No Exceptions anymore! if (!isset($data['remote_subscription_id']) || empty($data['remote_subscription_id'])) { //Subscribe user by create $result = Braintree_Subscription::create($braintreeData); } else { $data['plan_id'] = $plan['BillingPlan']['id']; //Subscribe user by update $result = Braintree_Subscription::update($data['remote_subscription_id'], $braintreeData); } if (!$result->success) { $this->Session->setFlash(__d('billing', 'Unable to subscribe on chosen plan. Please contact with resorce administration')); $this->redirect(array('action' => 'plans', $plan['BillingGroup']['slug'])); } $data = Hash::merge($data, array('remote_subscription_id' => $result->subscription->id, 'remote_plan_id' => $result->subscription->planId, 'active' => $result->subscription->status === 'Active' ? true : false, 'status' => $result->subscription->status, 'expires' => $result->subscription->billingPeriodEndDate->format('Y-m-d H:i:s'), 'created' => $result->subscription->createdAt->format('Y-m-d H:i:s'), 'modified' => $result->subscription->updatedAt->format('Y-m-d H:i:s'))); if (!isset($data['id'])) { $this->BillingSubscription->create(); } if ($this->BillingSubscription->save($data)) { $this->Session->write('Billing'); if (!isset($data['id']) || empty($data['id'])) { $data['id'] = $this->BillingSubscription->getInsertID(); } $this->redirect(array('action' => 'success', $data['id'])); } else { $this->Session->setFlash(__d('billing', 'Unable to subscribe on chosen plan. Please contact with resorce administration')); $this->redirect(array('action' => 'plans', $plan['BillingGroup']['slug'])); } }
/** * @param string $token * @param array $attribs * @return \Braintree_Result_Successful|\Braintree_Result_Error */ public function update($token, array $attribs) { return \Braintree_PaymentMethod::update($token, $attribs); }
$nonce = filter_input(INPUT_POST, 'nonce', FILTER_SANITIZE_STRING); $result = Braintree_Customer::update($un . "_FITNESS", array('creditCard' => array('paymentMethodNonce' => $nonce, 'options' => array('updateExistingToken' => $payToken)))); if ($result->success) { $successful = true; $cardn = $result->customer->creditCards[0]->maskedNumber; $expd = $result->customer->creditCards[0]->expirationDate; } else { $error_msg = 'Update failed:'; foreach ($result->errors->deepAll() as $error) { $error_msg .= $error->code . ": " . $error->message . '<br>'; } echo $error_msg . '<br><br><input type="button" value="Submit" onClick="doChangeBill();">'; exit; } } else { $result = Braintree_PaymentMethod::update($payToken, array('billingAddress' => array('postalCode' => $zip, 'options' => array('updateExisting' => true)), 'expirationDate' => $expd)); if ($result->success) { $successful = true; $cardn = $result->paymentMethod->maskedNumber; } else { $error_msg = 'Update failed:'; foreach ($result->errors->deepAll() as $error) { $error_msg .= $error->code . ": " . $error->message . '<br>'; } echo $error_msg . '<br><br><input type="button" value="Submit" onClick="doChangeBill();">'; exit; } } if ($successful) { // Update in Database if ($stmt = $mysqli->prepare("UPDATE members SET " . "FName='" . $fname . "', " . "LName='" . $lname . "', " . "Street='" . $street . "', " . "City='" . $city . "', " . "State='" . $state . "', " . "Zip='" . $zip . "', " . "Phone='" . $phone . "'" . " WHERE id = ?")) {
/** * Process capturing of a payment * * @param Varien_Object $payment * @param float $amount * * @return Mage_Payment_Model_Abstract|void */ public function capture(Varien_Object $payment, $amount) { // Has the payment already been authorized? if ($payment->getCcTransId()) { // Convert the capture amount to the correct currency $captureAmount = $this->_getWrapper()->getCaptureAmount($payment->getOrder(), $amount); // Has the authorization already been settled? Partial invoicing if ($this->authorizationUsed($payment)) { // Set the token as false $token = false; // Was the original payment created with a token? if ($additionalInfoToken = $payment->getAdditionalInformation('token')) { try { // Init the environment $this->_getWrapper()->init($payment->getOrder()->getStoreId()); // Attempt to find the token Braintree_PaymentMethod::find($additionalInfoToken); // Set the token if a success $token = $additionalInfoToken; } catch (Exception $e) { $token = false; } } // If we managed to find a token use that for the capture if ($token) { // Stop processing the rest of the method // We pass $amount instead of $captureAmount as the authorize function contains the conversion $this->_authorize($payment, $amount, true, $token); return $this; } else { // Attempt to clone the transaction $result = $this->_getWrapper()->init($payment->getOrder()->getStoreId())->cloneTransaction($payment->getLastTransId(), $captureAmount); } } else { // Init the environment $result = $this->_getWrapper()->init($payment->getOrder()->getStoreId())->submitForSettlement($payment->getCcTransId(), $captureAmount); // Log the result Gene_Braintree_Model_Debug::log(array('capture:submitForSettlement' => $result)); } if ($result->success) { $this->_processSuccessResult($payment, $result, $amount); } else { if ($result->errors->deepSize() > 0) { // Clean up Gene_Braintree_Model_Wrapper_Braintree::cleanUp(); Mage::throwException($this->_getWrapper()->parseErrors($result->errors->deepAll())); } else { // Clean up Gene_Braintree_Model_Wrapper_Braintree::cleanUp(); Mage::throwException($result->transaction->processorSettlementResponseCode . ': ' . $result->transaction->processorSettlementResponseText); } } } else { // Otherwise we need to do an auth & capture at once $this->_authorize($payment, $amount, true); } return $this; }
public function checkout() { $this->layout = 'profile_new'; if (!$this->request->is('post')) { throw new NotFoundException(__d('billing', 'Incorrect request type')); } $amount = $this->Session->read('Billing.amount'); $customer = Braintree_Customer::find('konstruktor-' . $this->currUser['User']['id']); if (isset($this->request->data['payment_method_nonce'])) { $nonceFromTheClient = $this->request->data['payment_method_nonce']; $payment = Braintree_PaymentMethod::create(['customerId' => 'konstruktor-' . $this->currUser['User']['id'], 'paymentMethodNonce' => $nonceFromTheClient]); if (!$payment->success) { $this->Session->setFlash($payment->message); $this->redirect(array('action' => 'payment')); } $payment = $payment->paymentMethod; } elseif (isset($this->request->data['payment_method']) && !empty($this->request->data['payment_method'])) { $payment = null; foreach ($customer->paymentMethods as $payment) { if ($payment->token == $this->request->data['payment_method']) { break; } } if (empty($payment)) { throw new NotFoundException(__d('billing', 'Payment method not found')); } } else { throw new NotFoundException(__d('billing', 'Unable to create subscription')); } $result = Braintree_Transaction::sale(array('paymentMethodToken' => $payment->token, 'amount' => $amount, 'options' => array('submitForSettlement' => true))); if ($result->success) { $result = $result->transaction; $this->User->id = $this->currUser['User']['id']; $balance = $this->User->field('balance') + $amount; $userResult = $this->User->save(array('id' => $this->currUser['User']['id'], 'balance' => $balance)); //if(!$userResult){ //maybe support notification here //} } $this->redirect(array('plugin' => false, 'controller' => 'User', 'action' => 'view')); }
function testErrorsOnFindWithWhitespaceCharacterArgument() { $this->setExpectedException('InvalidArgumentException'); Braintree_PaymentMethod::find('\\t'); }
} else { $updateResult = Braintree_PaymentMethod::update($_POST['token'], array('billingAddress' => array('streetAddress' => $_POST['streetAddress'], 'options' => array('updateExisting' => $_POST['updateExisting'])))); } print_r($updateResult); } else { if ($_POST['_act'] == 'findPaymentMethod') { $paymentMethod = Braintree_PaymentMethod::find($_POST['token']); print_r($paymentMethod); } else { if ($_POST['_act'] == 'deletePaymentMethod') { $search = (string) $_POST['token']; $file = './data/token.txt'; $contents = file_get_contents($file); echo $contents = str_replace($_POST['token'], trim((string) $_POST['token'] . "_DELETED\r\n"), $contents); file_put_contents($file, $contents); $paymentMethod = Braintree_PaymentMethod::delete($_POST['token']); print_r($paymentMethod); } else { if ($_POST['_act'] == 'createSubMerchant') { $result = Braintree_MerchantAccount::create(array('individual' => array('firstName' => $_POST['firstName'], 'lastName' => $_POST['lastName'], 'email' => $_POST['email'], 'phone' => $_POST['phone'], 'dateOfBirth' => $_POST['dateOfBirth'], 'ssn' => $_POST['ssn'], 'address' => array('streetAddress' => $_POST['streetAddress'], 'locality' => $_POST['locality'], 'region' => $_POST['region'], 'postalCode' => $_POST['postalCode'])), 'business' => array('legalName' => $_POST['legalName'], 'dbaName' => $_POST['dbaName'], 'taxId' => $_POST['taxId'], 'address' => array('streetAddress' => $_POST['streetAddress2'], 'locality' => $_POST['locality2'], 'region' => $_POST['region2'], 'postalCode' => $_POST['postalCode2'])), 'funding' => array('descriptor' => $_POST['descriptor'], 'destination' => Braintree_MerchantAccount::FUNDING_DESTINATION_BANK, 'email' => $_POST['email'], 'mobilePhone' => $_POST['mobilePhone'], 'accountNumber' => $_POST['accountNumber'], 'routingNumber' => $_POST['routingNumber']), 'tosAccepted' => true, 'masterMerchantAccountId' => "qzmnkckz54r94r4f", 'id' => "mc_" . time())); $file = './data/subMerchant.txt'; //[ADD Customer ID to text file] $subMerchantID = $result->merchantAccount->id . "\r\n"; // Write the contents to the file, // using the FILE_APPEND flag to append the content to the end of the file // and the LOCK_EX flag to prevent anyone else writing to the file at the same time file_put_contents($file, $subMerchantID, FILE_APPEND | LOCK_EX); print_r($result); } else { if ($_POST['_act'] == 'CreateTransEscrow') { $result = Braintree_Transaction::sale(array('merchantAccountId' => $_POST["sub_merchant_id"], 'amount' => $_POST["amount"], 'paymentMethodNonce' => $_POST["payment_method_nonce"], 'serviceFeeAmount' => $_POST["serviceFeeAmount"], 'options' => array('holdInEscrow' => true)));
/** * Delete a payment method within Braintree * * @param $token * * @return bool|\Braintree_Result_Successful */ public function deletePaymentMethod($token) { try { return Braintree_PaymentMethod::delete($token); } catch (Exception $e) { Gene_Braintree_Model_Debug::log($e); } return false; }
public function checkoutReward() { if (!$this->request->is('post')) { throw new NotFoundException(__d('billing', 'Incorrect request type')); } $customer = Braintree_Customer::find('konstruktor-' . $this->currUser['User']['id']); //TODO: payment nonce or id extrating in some places too. Refactoring needed if (isset($this->request->data['payment_method_nonce'])) { $nonceFromTheClient = $this->request->data['payment_method_nonce']; $payment = Braintree_PaymentMethod::create(['customerId' => 'konstruktor-' . $this->currUser['User']['id'], 'paymentMethodNonce' => $nonceFromTheClient]); if (!$payment->success) { $this->Session->setFlash($payment->message); $this->redirect(array('action' => 'payment')); } $payment = $payment->paymentMethod; } elseif (isset($this->request->data['payment_method']) && !empty($this->request->data['payment_method'])) { $payment = null; foreach ($customer->paymentMethods as $payment) { if ($payment->token == $this->request->data['payment_method']) { break; } } if (empty($payment)) { throw new NotFoundException(__('Payment method not found')); } } else { throw new NotFoundException(__('Unable to find payment method')); } $rewardId = $this->Session->read('InvestProject.RewardId'); $this->loadModel('InvestReward'); $this->InvestReward->Behaviors->load('Containable'); $investReward = $this->InvestReward->find('first', array('contain' => array('InvestProject'), 'conditions' => array('InvestReward.id' => $rewardId))); if (!$investReward) { throw new NotFoundException('Could not find investment reward for funds transfer'); } $result = Braintree_Transaction::sale(array('paymentMethodToken' => $payment->token, 'amount' => $investReward['InvestReward']['total'])); if (!$result->success) { $this->Session->setFlash(__('Unable to fund your money for chosen reward. Please contact with resource administration')); $this->redirect(array('action' => 'view', $investReward['InvestReward']['project_id'])); } $this->loadModel('InvestSponsor'); $this->InvestSponsor->create(); $data = array('user_id' => $this->currUserID, 'project_id' => $investReward['InvestReward']['project_id'], 'reward_id' => $investReward['InvestReward']['id'], 'amount' => $investReward['InvestReward']['total'], 'currency' => 'USD', 'remote_transaction_id' => $result->transaction->id); if (!$this->InvestSponsor->save($data)) { $result = Braintree_Transaction::void($result->transaction->id); $this->Session->setFlash(__('There is problem with sum funding. Your transaction has been cancelled.')); } else { $this->Session->setFlash(__('You are successfully invest in project')); } $this->redirect(array('action' => 'view', $investReward['InvestReward']['project_id'])); }