/**
  * Returns customer credit cards if applicable
  * 
  * @return Braintree_Customer | boolean
  */
 public function getCustomerCards()
 {
     $session = Mage::getSingleton('adminhtml/session_quote');
     $applicableCards = array();
     if (Mage::getStoreConfig(self::CONFIG_PATH_VAULT, $session->getStoreId())) {
         $storedCards = false;
         if ($session->getCustomerId()) {
             $customerId = Mage::helper('braintree_payments')->generateCustomerId($session->getCustomerId(), $session->getQuote()->getCustomerEmail());
             try {
                 $storedCards = Braintree_Customer::find($customerId)->creditCards;
             } catch (Braintree_Exception $e) {
                 Mage::logException($e);
             }
         }
         if ($storedCards) {
             $country = $session->getQuote()->getBillingAddress()->getCountryId();
             $types = Mage::getModel('braintree_payments/creditcard')->getApplicableCardTypes($country);
             $applicableCards = array();
             foreach ($storedCards as $card) {
                 if (in_array(Mage::helper('braintree_payments')->getCcTypeCodeByName($card->cardType), $types)) {
                     $applicableCards[] = $card;
                 }
             }
         }
     }
     return $applicableCards;
 }
 /**
  * @param $id
  *
  * @return object
  */
 public function getCustomerById($id)
 {
     try {
         $customer = \Braintree_Customer::find($id);
     } catch (\Braintree_Exception_NotFound $e) {
         return false;
     }
     return $customer;
 }
Esempio n. 3
0
 /**
  * @depends testCustomerCreate
  */
 public function testTokenPayment()
 {
     $customer = \Braintree_Customer::find(self::$customer->id);
     $this->assertInstanceOf('\\Braintree_Customer', $customer);
     $this->assertArrayHasKey(0, $customer->paymentMethods());
     $model = new BraintreeForm();
     $model->setScenario('saleFromVault');
     $this->assertTrue($model->load(['amount' => rand(1, 200), 'paymentMethodToken' => $customer->paymentMethods()[0]->token], ''));
     $this->assertNotFalse($model->send());
 }
 public function createSubscription($customer_id, $package_code, $monthly_price)
 {
     try {
         $customer = Braintree_Customer::find($customer_id);
         $payment_method_token = $customer->creditCards[0]->token;
         $result = Braintree_Subscription::create(array('paymentMethodToken' => $payment_method_token, 'planId' => $package_code, 'price' => $monthly_price));
         return $result;
     } catch (Braintree_Exception_NotFound $e) {
         $bexcption = print_r($e, true);
         log_message('error', date('Y-m-d H:i:s') . ' ' . $bexcption, true);
         $result = new stdClass();
         $result->success = false;
         return $result;
     }
 }
Esempio n. 5
0
 function test_GatewayRespectsMakeDefault()
 {
     $result = Braintree_Customer::create();
     $this->assertTrue($result->success);
     $customerId = $result->customer->id;
     $result = Braintree_CreditCard::create(array('customerId' => $customerId, 'number' => '4111111111111111', 'expirationDate' => '11/2099'));
     $this->assertTrue($result->success);
     $clientToken = Braintree_ClientToken::generate(array("customerId" => $customerId, "options" => array("makeDefault" => true)));
     $authorizationFingerprint = json_decode($clientToken)->authorizationFingerprint;
     $response = Braintree_HttpClientApi::post('/client_api/nonces.json', json_encode(array("credit_card" => array("number" => "4242424242424242", "expirationDate" => "11/2099"), "authorization_fingerprint" => $authorizationFingerprint, "shared_customer_identifier" => "fake_identifier", "shared_customer_identifier_type" => "testing")));
     $this->assertEquals(201, $response["status"]);
     $customer = Braintree_Customer::find($customerId);
     $this->assertEquals(2, count($customer->creditCards));
     foreach ($customer->creditCards as $creditCard) {
         if ($creditCard->last4 == "4242") {
             $this->assertTrue($creditCard->default);
         }
     }
 }
 public function check($customer)
 {
     if (empty($customer)) {
         $customer = $this->_controller->currUser;
     }
     $firstName = $lastName = '';
     $name = explode(' ', $customer['User']['full_name']);
     if (count($name) > 0) {
         $firstName = array_shift($name);
         $lastName = implode(' ', $name);
     }
     $customerData = array('firstName' => $firstName, 'lastName' => $lastName, 'email' => $customer['User']['username'], 'phone' => $customer['User']['phone']);
     try {
         $_customer = Braintree_Customer::find('konstruktor-' . $customer['User']['id']);
         $_customer = Braintree_Customer::update('konstruktor-' . $customer['User']['id'], $customerData);
     } catch (Exception $e) {
         $_customer = Braintree_Customer::create(Hash::merge(array('id' => 'konstruktor-' . $customer['User']['id']), $customerData));
     }
     if ($_customer->success) {
         return $_customer->customer;
     }
     return array();
 }
Esempio n. 7
0
 /**
  * Generates token for further use
  * 
  * @return string | boolean
  */
 public function getToken()
 {
     $customerExists = false;
     $customerSession = Mage::getSingleton('customer/session');
     $magentoCustomerId = false;
     $magentoCustomerEmail = false;
     $storeId = null;
     if ($customerSession->isLoggedIn()) {
         $magentoCustomerId = $customerSession->getCustomerId();
         $magentoCustomerEmail = $customerSession->getCustomer()->getEmail();
     } else {
         if (Mage::app()->getStore()->isAdmin()) {
             $quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
             $magentoCustomerId = $quote->getCustomerId();
             $magentoCustomerEmail = $quote->getCustomerEmail();
             $storeId = $quote->getStoreId();
         }
     }
     if ($magentoCustomerId && $magentoCustomerEmail) {
         $customerId = $this->generateCustomerId($magentoCustomerId, $magentoCustomerEmail);
         try {
             $customerExists = Braintree_Customer::find($customerId);
         } catch (Exception $e) {
             $customerExists = false;
         }
     }
     $params = array("merchantAccountId" => Mage::getStoreConfig('payment/braintree/merchant_account_id', $storeId));
     if ($customerExists) {
         $params['customerId'] = $customerId;
     }
     try {
         $token = Braintree_ClientToken::generate($params);
     } catch (Exception $e) {
         Mage::logException($e);
         return false;
     }
     return $this->jsQuoteEscape($token);
 }
 function getCustomer(&$order, $force = false)
 {
     global $current_user;
     //already have it?
     if (!empty($this->customer) && !$force) {
         return $this->customer;
     }
     //try based on user id
     if (!empty($order->user_id)) {
         $user_id = $order->user_id;
     }
     //if no id passed, check the current user
     if (empty($user_id) && !empty($current_user->ID)) {
         $user_id = $current_user->ID;
     }
     //check for a braintree customer id
     if (!empty($user_id)) {
         $customer_id = get_user_meta($user_id, "pmpro_braintree_customerid", true);
     }
     //check for an existing stripe customer
     if (!empty($customer_id)) {
         try {
             $this->customer = Braintree_Customer::find($customer_id);
             //update the customer description and card
             if (!empty($order->accountnumber)) {
                 $response = Braintree_Customer::update($customer_id, array('firstName' => $order->FirstName, 'lastName' => $order->LastName, 'creditCard' => array('number' => $order->braintree->number, 'expirationDate' => $order->braintree->expiration_date, 'cardholderName' => trim($order->FirstName . " " . $order->LastName), 'options' => array('updateExistingToken' => $customer_id))));
                 if ($response->success) {
                     $this->customer = $result->customer;
                 } else {
                     $order->error = __("Failed to update customer.", "pmpro");
                     $order->shorterror = $order->error;
                     return false;
                 }
             }
             return $this->customer;
         } catch (Exception $e) {
             //assume no customer found
         }
     }
     //no customer id, create one
     if (!empty($order->accountnumber)) {
         try {
             $result = Braintree_Customer::create(array('firstName' => $order->FirstName, 'lastName' => $order->LastName, 'email' => $order->Email, 'phone' => $order->billing->phone, 'creditCard' => array('number' => $order->braintree->number, 'expirationDate' => $order->braintree->expiration_date, 'cvv' => $order->braintree->cvv, 'cardholderName' => trim($order->FirstName . " " . $order->LastName), 'billingAddress' => array('firstName' => $order->FirstName, 'lastName' => $order->LastName, 'streetAddress' => $order->Address1, 'extendedAddress' => $order->Address2, 'locality' => $order->billing->city, 'region' => $order->billing->state, 'postalCode' => $order->billing->zip, 'countryCodeAlpha2' => $order->billing->country))));
             if ($result->success) {
                 $this->customer = $result->customer;
             } else {
                 $order->error = __("Failed to create customer.", "pmpro");
                 $order->shorterror = $order->error;
                 return false;
             }
         } catch (Exception $e) {
             $order->error = __("Error creating customer record with Braintree:", "pmpro") . " " . $e->getMessage();
             $order->shorterror = $order->error;
             return false;
         }
         update_user_meta($user_id, "pmpro_braintree_customerid", $this->customer->id);
         return $this->customer;
     }
     return false;
 }
Esempio n. 9
0
 public function vaultCustomer()
 {
     $customerId = $this->customerDetails->id;
     if (empty($customerId)) {
         return null;
     } else {
         return Braintree_Customer::find($customerId);
     }
 }
 public function showBTCustomer()
 {
     $aCustomerId = $_GET["id_user"];
     $customer = Braintree_Customer::find($aCustomerId);
     pr($customer);
 }
Esempio n. 11
0
 public function showBraintree()
 {
     try {
         $customer = Braintree_Customer::find('development_fruit_analytics_user_' . Auth::user()->id);
     } catch (Braintree_Exception_NotFound $e) {
         $result = Braintree_Customer::create(array('id' => 'development_fruit_analytics_user_' . Auth::user()->id, 'email' => Auth::user()->email));
         if ($result->success) {
             $customer = $result->customer;
         } else {
             // needs error handling
         }
     }
     $clientToken = Braintree_ClientToken::generate(array("customerId" => $customer->id));
     return View::make('dev.braintree', array('clientToken' => $clientToken));
 }
 public function find($id)
 {
     switch ($this->context) {
         case 'customer':
             try {
                 return Braintree_Customer::find($id);
             } catch (Exception $e) {
                 return false;
             }
             break;
     }
 }
 function testSale_andStoreShippingAddressInVault()
 {
     $customer = Braintree_Customer::create(array('firstName' => 'Mike', 'lastName' => 'Jones', 'company' => 'Jones Co.', 'email' => '*****@*****.**', 'phone' => '419.555.1234', 'fax' => '419.555.1235', 'website' => 'http://example.com'))->customer;
     $transaction = Braintree_Transaction::sale(array('amount' => '100.00', 'customerId' => $customer->id, 'creditCard' => array('cardholderName' => 'The Cardholder', 'number' => Braintree_Test_CreditCardNumbers::$visa, 'expirationDate' => '05/12'), 'shipping' => array('firstName' => 'Darren', 'lastName' => 'Stevens'), 'options' => array('storeInVault' => true, 'storeShippingAddressInVault' => true)))->transaction;
     $customer = Braintree_Customer::find($customer->id);
     $this->assertEquals('Darren', $customer->addresses[0]->firstName);
     $this->assertEquals('Stevens', $customer->addresses[0]->lastName);
 }
Esempio n. 14
0
 function testUpdateFromTransparentRedirect_andUpdateExistingBillingAddress()
 {
     $customer = Braintree_Customer::createNoValidate();
     $card = Braintree_CreditCard::createNoValidate(array('customerId' => $customer->id, 'number' => '5105105105105100', 'expirationDate' => '05/12', 'billingAddress' => array('firstName' => 'Drew', 'lastName' => 'Smith', 'company' => 'Smith Co.', 'streetAddress' => '123 Old St', 'extendedAddress' => 'Suite 101', 'locality' => 'Chicago', 'region' => 'IL', 'postalCode' => '60622', 'countryName' => 'United States of America')));
     $queryString = $this->updateCreditCardViaTr(array(), array('paymentMethodToken' => $card->token, 'creditCard' => array('billingAddress' => array('streetAddress' => '123 New St', 'locality' => 'St. Louis', 'region' => 'MO', 'postalCode' => '63119', 'options' => array('updateExisting' => True)))));
     $result = Braintree_CreditCard::updateFromTransparentRedirect($queryString);
     $this->assertTrue($result->success);
     $card = $result->creditCard;
     $this->assertEquals(1, sizeof(Braintree_Customer::find($customer->id)->addresses));
     $this->assertEquals('123 New St', $card->billingAddress->streetAddress);
     $this->assertEquals('St. Louis', $card->billingAddress->locality);
     $this->assertEquals('MO', $card->billingAddress->region);
     $this->assertEquals('63119', $card->billingAddress->postalCode);
 }
 /**
  * Array of customer credit cards
  * 
  * @return array
  */
 public function currentCustomerStoredCards()
 {
     if ($this->useVault() && Mage::getSingleton('customer/session')->isLoggedIn()) {
         $customerId = Mage::helper('braintree_payments')->generateCustomerId(Mage::getSingleton('customer/session')->getCustomerId(), Mage::getSingleton('customer/session')->getCustomer()->getEmail());
         try {
             $ret = Braintree_Customer::find($customerId)->creditCards;
             $this->_debug($customerId);
             $this->_debug($ret);
             return $ret;
         } catch (Braintree_Exception $e) {
             return array();
         }
     }
     return array();
 }
Esempio n. 16
0
     echo "<div> <h3>API response</h3>";
     //echo json_encode($result, JSON_PRETTY_PRINT);
     //echo json_encode($result);
     echo "<pre>";
     print_r($result);
     echo "</div>";
 } else {
     if ($_POST['_act'] == 'updateCustomer') {
         $updateResult = Braintree_Customer::update($_POST['customer_id'], array('firstName' => $_POST['firstName'], 'lastName' => $_POST['lastName'], 'company' => $_POST['company'], 'email' => $_POST['email'], 'phone' => $_POST['phone'], 'fax' => $_POST['fax'], 'website' => $_POST['website']));
         $updateResult->success;
         print_r($updateResult);
     } else {
         if ($_POST['_act'] == 'findCustomer') {
             //echo $_POST['customer_id'];
             //$_POST['customer_id'] = '57306224';
             $findResult = Braintree_Customer::find((string) $_POST['customer_id']);
             print_r($findResult);
         } else {
             if ($_POST['_act'] == 'deleteCustomer') {
                 $search = (string) $_POST['customer_id'];
                 $file = './data/customerID.txt';
                 $contents = file_get_contents($file);
                 echo $contents = str_replace($_POST['customer_id'], trim((string) $_POST['customer_id'] . "_DELETED\r\n"), $contents);
                 file_put_contents($file, $contents);
                 $deleteResult = Braintree_Customer::delete((string) $_POST['customer_id']);
                 print_r($deleteResult);
             } else {
                 if ($_POST['_act'] == 'createPaymentMethod') {
                     $para_Arr = array();
                     if (isset($_POST['data'])) {
                         $postData = explode("&", urldecode($_POST['data']));
Esempio n. 17
0
 if ($role[0] == "f") {
     $cust = "_FITNESS";
 } else {
     if ($role[0] == "t") {
         $cust = "_TRAINING";
     } else {
         if ($role[0] == "r") {
             $cust = "_REP";
         } else {
             if ($role[0] == "l") {
                 $cust = "_LICENSEE";
             }
         }
     }
 }
 $result = Braintree_Customer::find($un . $cust);
 $payToken = $result->creditCards[0]->token;
 $plan = "";
 if ($role[0] == "f") {
     $plan = "fitness";
 } else {
     if ($role[0] == "t") {
         $plan = "training";
     } else {
         if ($role[0] == "r") {
             $plan = "rep";
         } else {
             if ($role[0] == "l") {
                 $plan = "licensee";
             }
         }
 /**
  * If customer exists in Braintree
  * 
  * @param int $customerId
  * @return boolean
  */
 public function exists($customerId)
 {
     try {
         Braintree_Customer::find($customerId);
     } catch (Braintree_Exception $e) {
         return false;
     }
     return true;
 }
 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']));
     }
 }
 function getCustomer(&$order, $force = false)
 {
     global $current_user;
     //already have it?
     if (!empty($this->customer) && !$force) {
         return $this->customer;
     }
     //try based on user id
     if (!empty($order->user_id)) {
         $user_id = $order->user_id;
     }
     //if no id passed, check the current user
     if (empty($user_id) && !empty($current_user->ID)) {
         $user_id = $current_user->ID;
     }
     //check for a braintree customer id
     if (!empty($user_id)) {
         $customer_id = get_user_meta($user_id, "pmpro_braintree_customerid", true);
     }
     //check for an existing stripe customer
     if (!empty($customer_id)) {
         try {
             $this->customer = Braintree_Customer::find($customer_id);
             //update the customer address, description and card
             if (!empty($order->accountnumber)) {
                 //put data in array for Braintree API calls
                 $update_array = array('firstName' => $order->FirstName, 'lastName' => $order->LastName, 'creditCard' => array('number' => $order->braintree->number, 'expirationDate' => $order->braintree->expiration_date, 'cardholderName' => trim($order->FirstName . " " . $order->LastName), 'options' => array('updateExistingToken' => $this->customer->creditCards[0]->token)));
                 //address too?
                 if (!empty($order->billing)) {
                     //make sure Address2 is set
                     if (!isset($order->Address2)) {
                         $order->Address2 = '';
                     }
                 }
                 //add billing address to array
                 $update_array['creditCard']['billingAddress'] = array('firstName' => $order->FirstName, 'lastName' => $order->LastName, 'streetAddress' => $order->Address1, 'extendedAddress' => $order->Address2, 'locality' => $order->billing->city, 'region' => $order->billing->state, 'postalCode' => $order->billing->zip, 'countryCodeAlpha2' => $order->billing->country, 'options' => array('updateExisting' => true));
                 //update
                 $response = Braintree_Customer::update($customer_id, $update_array);
                 if ($response->success) {
                     $this->customer = $response->customer;
                     return $this->customer;
                 } else {
                     $order->error = __("Failed to update customer.", "pmpro") . " " . $response->message;
                     $order->shorterror = $order->error;
                     return false;
                 }
             }
             return $this->customer;
         } catch (Exception $e) {
             //assume no customer found
         }
     }
     //no customer id, create one
     if (!empty($order->accountnumber)) {
         try {
             $result = Braintree_Customer::create(array('firstName' => $order->FirstName, 'lastName' => $order->LastName, 'email' => $order->Email, 'phone' => $order->billing->phone, 'creditCard' => array('number' => $order->braintree->number, 'expirationDate' => $order->braintree->expiration_date, 'cvv' => $order->braintree->cvv, 'cardholderName' => trim($order->FirstName . " " . $order->LastName), 'billingAddress' => array('firstName' => $order->FirstName, 'lastName' => $order->LastName, 'streetAddress' => $order->Address1, 'extendedAddress' => $order->Address2, 'locality' => $order->billing->city, 'region' => $order->billing->state, 'postalCode' => $order->billing->zip, 'countryCodeAlpha2' => $order->billing->country))));
             if ($result->success) {
                 $this->customer = $result->customer;
             } else {
                 $order->error = __("Failed to create customer.", "pmpro") . " " . $result->message;
                 $order->shorterror = $order->error;
                 return false;
             }
         } catch (Exception $e) {
             $order->error = __("Error creating customer record with Braintree:", "pmpro") . " " . $e->getMessage();
             $order->shorterror = $order->error;
             return false;
         }
         //if we have no user id, we need to set the customer id after the user is created
         if (empty($user_id)) {
             global $pmpro_braintree_customerid;
             $pmpro_braintree_customerid = $this->customer->id;
             add_action('user_register', array('PMProGateway_braintree', 'user_register'));
         } else {
             update_user_meta($user_id, "pmpro_braintree_customerid", $this->customer->id);
         }
         return $this->customer;
     }
     return false;
 }
Esempio n. 21
0
 function testFind_throwsExceptionIfNotFound()
 {
     $this->setExpectedException('Braintree_Exception_NotFound');
     Braintree_Customer::find("does-not-exist");
 }
Esempio n. 22
0
 public function showPayPlan($planId)
 {
     try {
         $customer = Braintree_Customer::find('fruit_analytics_user_' . Auth::user()->id);
     } catch (Braintree_Exception_NotFound $e) {
         $result = Braintree_Customer::create(array('id' => 'fruit_analytics_user_' . Auth::user()->id, 'email' => Auth::user()->email, 'firstName' => Auth::user()->email));
         if ($result->success) {
             $customer = $result->customer;
         } else {
             // needs error handling
         }
     }
     // generate clientToken for the user to make payment
     $clientToken = Braintree_ClientToken::generate(array("customerId" => $customer->id));
     // get the detials of the plan
     $plans = Braintree_Plan::all();
     // find the correct plan to show
     // no way currently to get only one plan
     foreach ($plans as $plan) {
         // the plan id needs to be in .env.php (or any other assocc array) for easy access
         if ($plan->id == 'fruit_analytics_plan_' . $planId) {
             $planName = $plan->name;
         }
     }
     return View::make('auth.payplan', array('planName' => $planName, 'clientToken' => $clientToken));
 }
Esempio n. 23
0
 public function createUpdateForm()
 {
     $user = $this->getDi()->auth->getUser(true);
     if (!$user) {
         throw new Am_Exception_InputError("You are not logged-in");
     }
     if (!($bid = $user->data()->get(Am_Paysystem_Braintree::CUSTOMER_ID))) {
         throw new Am_Exception_Paysystem('Customer braintree id is empty');
     }
     if (!($bt_member = Braintree_Customer::find($bid))) {
         throw new Am_Exception_Paysystem('Wrong customer braintree id');
     }
     if (!($token = $bt_member->creditCards[0]->token)) {
         throw new Am_Exception_Paysystem('Empty token for credit card');
     }
     $form = $this->plugin->createForm(Am_Form_CreditCard::USER_UPDATE);
     $form->setDataSources(array($this->_request, new HTML_QuickForm2_DataSource_Array($form->getDefaultValuesSalem($bt_member))));
     $form->addHidden('tr_data')->setValue(Braintree_TransparentRedirect::updateCreditCardData(array('redirectUrl' => $this->plugin->getPluginUrl(Am_Paysystem_Braintree::ACTION_UPDATE), 'paymentMethodToken' => $token, 'creditCard' => array('billingAddress' => array('options' => array('updateExisting' => true))))));
     return $form;
 }
<?php

require_once 'environment.php';
$collection = Braintree_Customer::find('57937176');
echo "<pre>";
print_r($collection);
Esempio n. 25
0
 function testFindErrorsOnWhitespaceId()
 {
     $this->setExpectedException('InvalidArgumentException');
     Braintree_Customer::find('\\t');
 }
Esempio n. 26
0
 /**
  * getBraintreeCustomer
  * --------------------------------------------------
  * @param (string) ($paymentMethodNonce) The authorization token for the payment
  * @return Creates a Braintree Subscription, from this object.
  * --------------------------------------------------
  */
 private function getBraintreeCustomer($paymentMethodNonce)
 {
     /* Initialize variables */
     $result = ['errors' => FALSE, 'messages' => ''];
     /* Get or create the Braintree customer */
     /* Get existing customer */
     try {
         /* Customer ID is not set, proceed with create */
         if ($this->braintree_customer_id == null) {
             throw new Braintree_Exception_NotFound();
         }
         /* Get the customer */
         $customer = Braintree_Customer::find($this->braintree_customer_id);
         /* Update braintree customer and payment information */
         $this->braintree_customer_id = $customer->id;
         $this->braintree_payment_method_token = $customer->paymentMethods()[0]->token;
         $this->save();
         /* Return result */
         return $result;
         /* No customer found with the ID, create a new */
     } catch (Braintree_Exception_NotFound $e) {
         /* Create new customer */
         $customerResult = Braintree_Customer::create(['firstName' => $this->user->name, 'email' => $this->user->email, 'paymentMethodNonce' => $paymentMethodNonce]);
         /* Success */
         if ($customerResult->success) {
             /* Store braintree customer and payment information */
             $this->braintree_customer_id = $customerResult->customer->id;
             $this->braintree_payment_method_token = $customerResult->customer->paymentMethods()[0]->token;
             $this->save();
             /* Error */
         } else {
             /* Get and store errors */
             foreach ($customerResult->errors->deepAll() as $error) {
                 $result['errors'] |= TRUE;
                 $result['messages'] .= $error->code . ": " . $error->message . ' ';
             }
         }
         /* Return result */
         return $result;
     }
 }
Esempio n. 27
0
 function testFromNonce()
 {
     $customer = Braintree_Customer::createNoValidate();
     $http = new Braintree_HttpClientApi(Braintree_Configuration::$global);
     $nonce = $http->nonce_for_new_card(array("credit_card" => array("number" => "4009348888881881", "expirationMonth" => "11", "expirationYear" => "2099"), "customerId" => $customer->id));
     $creditCard = Braintree_CreditCard::fromNonce($nonce);
     $customer = Braintree_Customer::find($customer->id);
     $this->assertEquals($customer->creditCards[0], $creditCard);
 }
<?php

require_once 'environment.php';
$customerID = $_POST['customerID'];
try {
    $customer_id = $customerID;
    $customer = Braintree_Customer::find($customer_id);
    $payment_method_token = $customer->creditCards[0]->token;
    $result = Braintree_Subscription::create(array('paymentMethodToken' => $payment_method_token, 'planId' => 'test_plan_1'));
    if ($result->success) {
        echo "Success! Subscription " . $result->subscription->id . " is " . $result->subscription->status;
    } else {
        echo "Validation errors:<br/>";
        foreach ($result->errors->deepAll() as $error) {
            echo "- " . $error->message . "<br/>";
        }
    }
} catch (Braintree_Exception_NotFound $e) {
    echo "Failure: no customer found with ID " . $_GET["customer_id"];
}
Esempio n. 29
0
 /**
  * Try and load the Braintree customer from the stored customer ID
  *
  * @param $braintreeCustomerId
  *
  * @return Braintree_Customer
  */
 public function getCustomer($braintreeCustomerId)
 {
     // Try and load it from the customer
     if (!$this->customer && !isset($this->customer[$braintreeCustomerId])) {
         try {
             $this->customer[$braintreeCustomerId] = Braintree_Customer::find($braintreeCustomerId);
         } catch (Exception $e) {
             return false;
         }
     }
     return $this->customer[$braintreeCustomerId];
 }
Esempio n. 30
0
 public function getPaymentMethodToken($customer_id)
 {
     try {
         $customer = Braintree_Customer::find($customer_id);
     } catch (Exception $e) {
         return array('success' => 0, 'message' => 'Customer with ' . $customer_id . " is not found");
     }
     if (isset($customer->creditCards[0]->token)) {
         return array('success' => 1, 'payment_method_token' => $customer->creditCards[0]->token);
         /*
           Array
         			  (
         			      [success] => 1
         			      [payment_method_token] => 7nv6bm
         			  )
         */
     } else {
         return array('success' => 0, 'message' => 'no creditCards found for the customer:' . $customer_id);
     }
 }