Esempio n. 1
0
 function braintree($data)
 {
     foreach ($data as $k => $v) {
         ${$k} = $v;
     }
     try {
         include_once 'config.braintree.php';
         $customer = Braintree_Customer::create(['firstName' => $first_name, 'lastName' => $last_name]);
         if (!isset($nonce) || empty($nonce)) {
             throw new Exception("An unknown error has occurred");
         }
         if ($customer->success) {
             $transaction = Braintree_Transaction::sale(['amount' => $price, 'customerId' => $customer->customer->id, 'paymentMethodNonce' => $nonce]);
             if ($transaction->success) {
                 $this->save($data, __FUNCTION__, $transaction->transaction, 1);
                 return json_encode(["status" => true, "msg" => sprintf("Your payment has been %s", $transaction->transaction->status)]);
             } else {
                 throw new Exception($transaction->message);
             }
         }
     } catch (Exception $e) {
         $this->save($data, __FUNCTION__, (string) $e, 0);
         return json_encode(["status" => false, "msg" => $e->getMessage()]);
     }
 }
 public function payment()
 {
     $this->request->allowMethod('post');
     if (!isset($this->request->data['amount']) || empty($this->request->data['amount'])) {
         $this->redirect($this->referer());
     }
     $firstName = $lastName = '';
     $name = explode(' ', $this->currUser['User']['full_name']);
     if (count($name) > 0) {
         $firstName = array_shift($name);
         $lastName = implode(' ', $name);
     }
     $customerData = array('firstName' => $firstName, 'lastName' => $lastName, 'email' => $this->currUser['User']['username'], 'phone' => $this->currUser['User']['phone']);
     try {
         $customer = Braintree_Customer::find('konstruktor-' . $this->currUser['User']['id']);
         $customer = Braintree_Customer::update('konstruktor-' . $this->currUser['User']['id'], $customerData);
     } catch (Exception $e) {
         $customer = Braintree_Customer::create(Hash::merge(array('id' => 'konstruktor-' . $this->currUser['User']['id']), $customerData));
     }
     if ($customer->success) {
         $customer = $customer->customer;
     } else {
         throw new NotFoundException(__d('billing', 'Invalid billing group'));
     }
     $this->Session->write('Billing', array('amount' => $this->request->data['amount']));
     $this->layout = 'profile_new';
     $clientToken = Braintree_ClientToken::generate();
     $this->set('clientToken', $clientToken);
     $this->set('customer', $customer);
 }
Esempio n. 3
0
 private function _createCustomer($CustomerData)
 {
     $name = explode(' ', $CustomerData['Order']['customer_name']);
     $firstName = $name[0];
     $lastName = $name[1];
     $customerDetails = Braintree_Customer::create(['firstName' => $firstName, 'lastName' => $lastName]);
     return $customerDetails->customer->id;
 }
 /**
  * @param $data
  *
  * @return object
  */
 private function getCustomer($data)
 {
     $customer = $this->getCustomerById($data['customerId']);
     if ($customer == false) {
         $customer = \Braintree_Customer::create(array('id' => $data['customerId'], 'firstName' => $data['firstName'], 'lastName' => $data['lastName'], 'email' => $data['email'], 'phone' => $data['phone']));
     }
     return $customer;
 }
 function testValueForHtmlField()
 {
     $result = Braintree_Customer::create(array('email' => 'invalid-email', 'creditCard' => array('number' => 'invalid-number', 'expirationDate' => 'invalid-exp', 'billingAddress' => array('countryName' => 'invalid-country'))));
     $this->assertEquals(false, $result->success);
     $this->assertEquals('invalid-email', $result->valueForHtmlField('customer[email]'));
     $this->assertEquals('', $result->valueForHtmlField('customer[credit_card][number]'));
     $this->assertEquals('invalid-exp', $result->valueForHtmlField('customer[credit_card][expiration_date]'));
     $this->assertEquals('invalid-country', $result->valueForHtmlField('customer[credit_card][billing_address][country_name]'));
 }
Esempio n. 6
0
 public function saveCustomer()
 {
     $result = Braintree_Customer::create($this->options['customer']);
     if ($result->success) {
         return array('status' => true, 'result' => $result);
     } else {
         return array('status' => false, 'result' => $result);
     }
 }
 function test_deepAll_givesAllErrorsDeeply()
 {
     $result = Braintree_Customer::create(array('email' => 'invalid', 'creditCard' => array('number' => '1234123412341234', 'expirationDate' => 'invalid', 'billingAddress' => array('countryName' => 'invalid'))));
     $expectedErrors = array(Braintree_Error_Codes::CUSTOMER_EMAIL_IS_INVALID, Braintree_Error_Codes::CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, Braintree_Error_Codes::CREDIT_CARD_NUMBER_IS_INVALID, Braintree_Error_Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED);
     $actualErrors = $result->errors->deepAll();
     $this->assertEquals($expectedErrors, self::mapValidationErrorsToCodes($actualErrors));
     $expectedErrors = array(Braintree_Error_Codes::CREDIT_CARD_EXPIRATION_DATE_IS_INVALID, Braintree_Error_Codes::CREDIT_CARD_NUMBER_IS_INVALID, Braintree_Error_Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED);
     $actualErrors = $result->errors->forKey('customer')->forKey('creditCard')->deepAll();
     $this->assertEquals($expectedErrors, self::mapValidationErrorsToCodes($actualErrors));
 }
 function test_paypalAccountEmail()
 {
     $nonce = Braintree_HttpClientApi::nonceForPayPalAccount(array('paypal_account' => array('consent_code' => 'PAYPAL_CONSENT_CODE')));
     $customerId = 'UNIQUE_CUSTOMER_ID-' . strval(rand());
     $customerResult = Braintree_Customer::create(array('paymentMethodNonce' => $nonce, 'id' => $customerId));
     $this->assertTrue($customerResult->success);
     $customer = $customerResult->customer;
     $collection = Braintree_Customer::search(array(Braintree_CustomerSearch::id()->is($customer->id), Braintree_CustomerSearch::paypalAccountEmail()->is('*****@*****.**')));
     $this->assertEquals(1, $collection->maximumCount());
     $this->assertEquals($customer->id, $collection->firstItem()->id);
 }
Esempio n. 9
0
 /**
  * This save customer to braintree and returns result array
  * @return array
  */
 public function saveCustomer()
 {
     if (isset($this->options['customerId'])) {
         $this->options['customer']['id'] = $this->options['customerId'];
     }
     $result = \Braintree_Customer::create($this->options['customer']);
     if ($result->success) {
         return ['status' => true, 'result' => $result];
     } else {
         return ['status' => false, 'result' => $result];
     }
 }
 function test_multipleValueNode_creditCardType()
 {
     $result = Braintree_Customer::create(array('creditCard' => array('cardholderName' => "Joe Smith", 'number' => "4000111111111115", 'expirationDate' => "12/2016", 'options' => array('verifyCard' => true))));
     $creditCardVerification = $result->creditCardVerification;
     $collection = Braintree_CreditCardVerification::search(array(Braintree_CreditCardVerificationSearch::id()->is($creditCardVerification->id), Braintree_CreditCardVerificationSearch::creditCardCardType()->is($creditCardVerification->creditCard['cardType'])));
     $this->assertEquals(1, $collection->maximumCount());
     $this->assertEquals($creditCardVerification->id, $collection->firstItem()->id);
     $collection = Braintree_CreditCardVerification::search(array(Braintree_CreditCardVerificationSearch::id()->is($creditCardVerification->id), Braintree_CreditCardVerificationSearch::creditCardCardType()->in(array($creditCardVerification->creditCard['cardType'], Braintree_CreditCard::CHINA_UNION_PAY))));
     $this->assertEquals(1, $collection->maximumCount());
     $this->assertEquals($creditCardVerification->id, $collection->firstItem()->id);
     $collection = Braintree_CreditCardVerification::search(array(Braintree_CreditCardVerificationSearch::id()->is($creditCardVerification->id), Braintree_CreditCardVerificationSearch::creditCardCardType()->is(Braintree_CreditCard::CHINA_UNION_PAY)));
     $this->assertEquals(0, $collection->maximumCount());
 }
 function test_findDuplicateCardsGivenPaymentMethodToken()
 {
     $creditCardRequest = array('number' => '63049580000009', 'expirationDate' => '05/2012');
     $jim = Braintree_Customer::create(array('firstName' => 'Jim', 'creditCard' => $creditCardRequest))->customer;
     $joe = Braintree_Customer::create(array('firstName' => 'Joe', 'creditCard' => $creditCardRequest))->customer;
     $query = array(Braintree_CustomerSearch::paymentMethodTokenWithDuplicates()->is($jim->creditCards[0]->token));
     $collection = Braintree_Customer::search($query);
     $customerIds = array();
     foreach ($collection as $customer) {
         $customerIds[] = $customer->id;
     }
     $this->assertTrue(in_array($jim->id, $customerIds));
     $this->assertTrue(in_array($joe->id, $customerIds));
 }
Esempio n. 12
0
 function create_customer_with_card($card_info)
 {
     $names = explode(' ', $card_info['cardholderName']);
     $data['firstName'] = isset($names[0]) ? $names[0] : NULL;
     $data['lastName'] = isset($names[1]) ? $names[1] : NULL;
     $data['creditCard'] = $card_info;
     //var_dump($data);
     $result = Braintree_Customer::create($data);
     if ($result->success === true) {
         return array('cust_id' => $result->customer->id, 'card_token' => $result->customer->creditCards[0]->token);
     }
     $this->_parse_errors($result);
     return false;
 }
Esempio n. 13
0
 public function createCustomer($data)
 {
     $result = Braintree_Customer::create($data);
     echo "<pre>";
     print_r($result);
     echo "</pre>";
     if ($result->success) {
         return array('success' => 1, 'customer_id' => $result->customer->id);
     } else {
         $errors = $result->errors->deepAll();
         if (count($errors) > 0 && ($errors[0]->code == 91609 || $errors[0]->message == 'Customer ID has already been taken.')) {
             return array('success' => 1, 'customer_id' => $data['id']);
         }
         return array('success' => 0, 'validation_errors' => $errors);
     }
 }
 function subscribe($nonce, $info)
 {
     $customerResult;
     $subscriptionResult;
     $customerResult = Braintree_Customer::create(['firstName' => $info['fname'], 'lastName' => $info['lname'], 'email' => $info['email'], 'paymentMethodNonce' => $nonce]);
     if (!$customerResult->success) {
         return $this->processErrors('subscription', $customerResult->errors->deepAll());
     }
     $r = $customerResult->customer;
     $a = $r->addresses[0];
     $sql = 'INSERT INTO users (first_name, last_name, address, city, state, zip, braintree_customer_id, created_date, email) ';
     $sql .= "VALUES ('" . $r->firstName . "','" . $r->lastName . "','" . $a->streetAddress . "','" . $a->locality . "','" . $a->region . "','" . $a->postalCode . "','" . $r->id . "', now(),'" . $r->email . "');";
     $info['userId'] = MysqlAccess::insert($sql);
     $subscriptionResult = Braintree_Subscription::create(['paymentMethodToken' => $customerResult->customer->paymentMethods[0]->token, 'planId' => 'donation', 'price' => $info['amount']]);
     if (!isset($subscriptionResult->subscription) || !$subscriptionResult->subscription) {
         return $this->processErrors('subscription', $subscriptionResult->errors->deepAll());
     }
     return $this->retrieveSubscriptionResults($subscriptionResult->success, $subscriptionResult->subscription, $info);
 }
Esempio n. 15
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();
 }
 public function addcardtoken()
 {
     $payment_token = Input::get('payment_token');
     $last_four = Input::get('last_four');
     $token = Input::get('token');
     $owner_id = Input::get('id');
     if (Input::has('card_type')) {
         $card_type = strtoupper(Input::get('card_type'));
     } else {
         $card_type = strtoupper("VISA");
     }
     $validator = Validator::make(array('last_four' => $last_four, 'payment_token' => $payment_token, 'token' => $token, 'owner_id' => $owner_id), array('last_four' => 'required', 'payment_token' => 'required', 'token' => 'required', 'owner_id' => 'required|integer'));
     $payments = array();
     if ($validator->fails()) {
         $error_messages = $validator->messages();
         $response_array = array('success' => false, 'error' => 'Invalid Input', 'error_code' => 401, 'payments' => $payments);
         $response_code = 200;
     } else {
         $is_admin = $this->isAdmin($token);
         if ($owner_data = $this->getOwnerData($owner_id, $token, $is_admin)) {
             // check for token validity
             if (is_token_active($owner_data->token_expiry) || $is_admin) {
                 try {
                     if (Config::get('app.default_payment') == 'stripe') {
                         Stripe::setApiKey(Config::get('app.stripe_secret_key'));
                         $customer = Stripe_Customer::create(array("card" => $payment_token, "description" => $owner_data->email));
                         /* Log::info('customer = ' . print_r($customer, true)); */
                         if ($customer) {
                             $card_count = DB::table('payment')->where('owner_id', '=', $owner_id)->count();
                             $customer_id = $customer->id;
                             $payment = new Payment();
                             $payment->owner_id = $owner_id;
                             $payment->customer_id = $customer_id;
                             $payment->last_four = $last_four;
                             $payment->card_type = $card_type;
                             $payment->card_token = $customer->sources->data[0]->id;
                             if ($card_count > 0) {
                                 $payment->is_default = 0;
                             } else {
                                 $payment->is_default = 1;
                             }
                             $payment->save();
                             $payment_data = Payment::where('owner_id', $owner_id)->orderBy('is_default', 'DESC')->get();
                             foreach ($payment_data as $data1) {
                                 $default = $data1->is_default;
                                 if ($default == 1) {
                                     $data['is_default_text'] = "default";
                                 } else {
                                     $data['is_default_text'] = "not_default";
                                 }
                                 $data['id'] = $data1->id;
                                 $data['owner_id'] = $data1->owner_id;
                                 $data['customer_id'] = $data1->customer_id;
                                 $data['last_four'] = $data1->last_four;
                                 $data['card_token'] = $data1->card_token;
                                 $data['card_type'] = $data1->card_type;
                                 $data['card_id'] = $data1->card_token;
                                 $data['is_default'] = $default;
                                 array_push($payments, $data);
                             }
                             $response_array = array('success' => true, 'payments' => $payments);
                             $response_code = 200;
                         } else {
                             $payment_data = Payment::where('owner_id', $owner_id)->orderBy('is_default', 'DESC')->get();
                             foreach ($payment_data as $data1) {
                                 $default = $data1->is_default;
                                 if ($default == 1) {
                                     $data['is_default_text'] = "default";
                                 } else {
                                     $data['is_default_text'] = "not_default";
                                 }
                                 $data['id'] = $data1->id;
                                 $data['owner_id'] = $data1->owner_id;
                                 $data['customer_id'] = $data1->customer_id;
                                 $data['last_four'] = $data1->last_four;
                                 $data['card_token'] = $data1->card_token;
                                 $data['card_type'] = $data1->card_type;
                                 $data['card_id'] = $data1->card_token;
                                 $data['is_default'] = $default;
                                 array_push($payments, $data);
                             }
                             $response_array = array('success' => false, 'error' => 'Could not create client ID', 'error_code' => 450, 'payments' => $payments);
                             $response_code = 200;
                         }
                     } else {
                         Braintree_Configuration::environment(Config::get('app.braintree_environment'));
                         Braintree_Configuration::merchantId(Config::get('app.braintree_merchant_id'));
                         Braintree_Configuration::publicKey(Config::get('app.braintree_public_key'));
                         Braintree_Configuration::privateKey(Config::get('app.braintree_private_key'));
                         $result = Braintree_Customer::create(array('paymentMethodNonce' => $payment_token));
                         Log::info('result = ' . print_r($result, true));
                         if ($result->success) {
                             $card_count = DB::table('payment')->where('owner_id', '=', $owner_id)->count();
                             $customer_id = $result->customer->id;
                             $payment = new Payment();
                             $payment->owner_id = $owner_id;
                             $payment->customer_id = $customer_id;
                             $payment->last_four = $last_four;
                             $payment->card_type = $card_type;
                             $payment->card_token = $result->customer->creditCards[0]->token;
                             if ($card_count > 0) {
                                 $payment->is_default = 0;
                             } else {
                                 $payment->is_default = 1;
                             }
                             $payment->save();
                             $payment_data = Payment::where('owner_id', $owner_id)->orderBy('is_default', 'DESC')->get();
                             foreach ($payment_data as $data1) {
                                 $default = $data1->is_default;
                                 if ($default == 1) {
                                     $data['is_default_text'] = "default";
                                 } else {
                                     $data['is_default_text'] = "not_default";
                                 }
                                 $data['id'] = $data1->id;
                                 $data['owner_id'] = $data1->owner_id;
                                 $data['customer_id'] = $data1->customer_id;
                                 $data['last_four'] = $data1->last_four;
                                 $data['card_token'] = $data1->card_token;
                                 $data['card_type'] = $data1->card_type;
                                 $data['card_id'] = $data1->card_token;
                                 $data['is_default'] = $default;
                                 array_push($payments, $data);
                             }
                             $response_array = array('success' => true, 'payments' => $payments);
                             $response_code = 200;
                         } else {
                             $payment_data = Payment::where('owner_id', $owner_id)->orderBy('is_default', 'DESC')->get();
                             foreach ($payment_data as $data1) {
                                 $default = $data1->is_default;
                                 if ($default == 1) {
                                     $data['is_default_text'] = "default";
                                 } else {
                                     $data['is_default_text'] = "not_default";
                                 }
                                 $data['id'] = $data1->id;
                                 $data['owner_id'] = $data1->owner_id;
                                 $data['customer_id'] = $data1->customer_id;
                                 $data['last_four'] = $data1->last_four;
                                 $data['card_token'] = $data1->card_token;
                                 $data['card_type'] = $data1->card_type;
                                 $data['card_id'] = $data1->card_token;
                                 $data['is_default'] = $default;
                                 array_push($payments, $data);
                             }
                             $response_array = array('success' => false, 'error' => 'Could not create client ID', 'error_code' => 450, 'payments' => $payments);
                             $response_code = 200;
                         }
                     }
                 } catch (Exception $e) {
                     $response_array = array('success' => false, 'error' => $e, 'error_code' => 405);
                     $response_code = 200;
                 }
             } else {
                 $response_array = array('success' => false, 'error' => 'Token Expired', 'error_code' => 405);
                 $response_code = 200;
             }
         } else {
             if ($is_admin) {
                 /* $var = Keywords::where('id', 2)->first();
                    $response_array = array('success' => false, 'error' => '' . $var->keyword . ' ID not Found', 'error_code' => 410); */
                 $response_array = array('success' => false, 'error' => '' . Config::get('app.generic_keywords.User') . ' ID not Found', 'error_code' => 410);
             } else {
                 $response_array = array('success' => false, 'error' => 'Not a valid token', 'error_code' => 406);
             }
             $response_code = 200;
         }
     }
     $response = Response::json($response_array, $response_code);
     return $response;
 }
Esempio n. 18
0
 function testUpdateFromTransparentRedirect_withUpdateExisting()
 {
     Braintree_TestHelper::suppressDeprecationWarnings();
     $customer = Braintree_Customer::create(array('firstName' => 'Mike', 'lastName' => 'Jones', 'creditCard' => array('number' => '5105105105105100', 'expirationDate' => '05/12', 'cardholderName' => 'Mike Jones', 'billingAddress' => array('firstName' => 'Drew', 'lastName' => 'Smith'))))->customer;
     $queryString = $this->updateCustomerViaTr(array(), array('customerId' => $customer->id, 'customer' => array('firstName' => 'New First', 'lastName' => 'New Last', 'creditCard' => array('number' => '4111111111111111', 'expirationDate' => '05/13', 'cardholderName' => 'New Cardholder', 'options' => array('updateExistingToken' => $customer->creditCards[0]->token), 'billingAddress' => array('firstName' => 'New First Billing', 'lastName' => 'New Last Billing', 'options' => array('updateExisting' => true))))));
     $result = Braintree_Customer::updateFromTransparentRedirect($queryString);
     $this->assertTrue($result->success);
     $this->assertEquals(true, $result->success);
     $customer = $result->customer;
     $this->assertEquals('New First', $customer->firstName);
     $this->assertEquals('New Last', $customer->lastName);
     $this->assertEquals(1, sizeof($result->customer->creditCards));
     $creditCard = $customer->creditCards[0];
     $this->assertEquals('411111', $creditCard->bin);
     $this->assertEquals('1111', $creditCard->last4);
     $this->assertEquals('New Cardholder', $creditCard->cardholderName);
     $this->assertEquals('05/2013', $creditCard->expirationDate);
     $this->assertEquals(1, sizeof($result->customer->addresses));
     $address = $customer->addresses[0];
     $this->assertEquals($address, $creditCard->billingAddress);
     $this->assertEquals('New First Billing', $address->firstName);
     $this->assertEquals('New Last Billing', $address->lastName);
 }
 public function saveUserPayment()
 {
     $payment_token = Input::get('stripeToken');
     $owner_id = Session::get('user_id');
     $owner_data = Owner::find($owner_id);
     try {
         if (Config::get('app.default_payment') == 'stripe') {
             Stripe::setApiKey(Config::get('app.stripe_secret_key'));
             $customer = Stripe_Customer::create(array("card" => $payment_token, "description" => $owner_data->email));
             $last_four = substr(Input::get('number'), -4);
             if ($customer) {
                 $customer_id = $customer->id;
                 $payment = new Payment();
                 $payment->owner_id = $owner_id;
                 $payment->customer_id = $customer_id;
                 $payment->last_four = $last_four;
                 $payment->card_token = $customer->cards->data[0]->id;
                 $payment->save();
                 $message = "Your Card is successfully added.";
                 $type = "success";
                 return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
             } else {
                 $message = "Sorry something went wrong.";
                 $type = "danger";
                 return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
             }
         } else {
             Braintree_Configuration::environment(Config::get('app.braintree_environment'));
             Braintree_Configuration::merchantId(Config::get('app.braintree_merchant_id'));
             Braintree_Configuration::publicKey(Config::get('app.braintree_public_key'));
             Braintree_Configuration::privateKey(Config::get('app.braintree_private_key'));
             $result = Braintree_Customer::create(array("firstName" => $owner_data->first_name, "lastName" => $owner_data->last_name, "creditCard" => array("number" => Input::get('number'), "expirationMonth" => Input::get('month'), "expirationYear" => Input::get('year'), "cvv" => Input::get('cvv'))));
             Log::info('result = ' . print_r($result, true));
             if ($result->success) {
                 $num = $result->customer->creditCards[0]->maskedNumber;
                 $last_four = substr($num, -4);
                 $customer_id = $result->customer->id;
                 $payment = new Payment();
                 $payment->owner_id = $owner_id;
                 $payment->customer_id = $customer_id;
                 $payment->last_four = $last_four;
                 $payment->card_token = $result->customer->creditCards[0]->token;
                 $payment->save();
                 $message = "Your Card is successfully added.";
                 $type = "success";
                 return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
             } else {
                 $message = "Sorry something went wrong.";
                 $type = "danger";
                 return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
             }
         }
     } catch (Exception $e) {
         $message = "Sorry something went wrong.";
         $type = "danger";
         return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
     }
 }
 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
 if ($stmt) {
     $stmt->bind_param('ss', $username, $user_role);
     $stmt->execute();
     $stmt->store_result();
     if ($stmt->num_rows == 1) {
         // A user with this username already exists
         $error_msg .= '<p class="error">A fitness user with this username already exists</p>';
         $stmt->close();
     }
     $stmt->close();
 } else {
     $error_msg .= '<p class="error">Database error line 127</p>';
     $stmt->close();
 }
 if (empty($error_msg)) {
     $result = Braintree_Customer::create(array('id' => $username . '_FITNESS', 'paymentMethodNonce' => $nonce, 'email' => $email, 'firstName' => $fname, 'lastName' => $lname, 'phone' => $phone, 'customFields' => array('role' => $user_role)));
     /*$result = Braintree_Transaction::sale(array(
     			  	'amount' => '0.00',
     			  	'paymentMethodNonce' => $nonce,
     			  	'customer' => array(
     					'id' => $username,
     					'email' => $email,
     					'firstName' => $fname,
     					'lastName' => $lname,
     					'phone' => $phone
     			  	),
     			  	'options' => array(
     					'submitForSettlement' => True,
     					'storeInVaultOnSuccess' => True
     			  	),
     			 	'customFields' => array(
 function testOnHtmlField_returnsEmptyForCustomFieldsIfNoErrors()
 {
     $result = Braintree_Customer::create(array('email' => 'invalid', 'creditCard' => array('number' => '5105105105105100', 'expirationDate' => '05/12'), 'customFields' => array('storeMe' => 'value')));
     $this->assertEquals(false, $result->success);
     $this->assertEquals(array(), $result->errors->onHtmlField('customer[custom_fields][store_me]'));
 }
Esempio n. 23
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;
     }
 }
 function testUpdateCreditCardFromTransparentRedirect()
 {
     $customer = Braintree_Customer::create(array('firstName' => 'Mike', 'lastName' => 'Jonez'))->customer;
     $creditCard = Braintree_CreditCard::create(array('customerId' => $customer->id, 'number' => Braintree_Test_CreditCardNumbers::$masterCard, 'expirationMonth' => '10', 'expirationYear' => '10'))->creditCard;
     $params = array('credit_card' => array('number' => Braintree_Test_CreditCardNumbers::$visa));
     $trParams = array('paymentMethodToken' => $creditCard->token, 'creditCard' => array('expirationMonth' => '11', 'expirationYear' => '11'));
     $trData = Braintree_TransparentRedirect::updateCreditCardData(array_merge($trParams, array("redirectUrl" => "http://www.example.com")));
     $queryString = Braintree_TestHelper::submitTrRequest(Braintree_TransparentRedirect::url(), $params, $trData);
     Braintree_TransparentRedirect::confirm($queryString);
     $creditCard = Braintree_CreditCard::find($creditCard->token);
     $this->assertequals('401288', $creditCard->bin);
     $this->assertequals('1881', $creditCard->last4);
     $this->assertequals('11/2011', $creditCard->expirationDate);
 }
<?php

require_once "PATH_TO_BRAINTREE/lib/Braintree.php";
Braintree_Configuration::environment("sandbox");
Braintree_Configuration::merchantId("your_merchant_id");
Braintree_Configuration::publicKey("your_public_key");
Braintree_Configuration::privateKey("your_private_key");
$result = Braintree_Customer::create(array("firstName" => $_POST["first_name"], "lastName" => $_POST["last_name"], "creditCard" => array("number" => $_POST["number"], "expirationMonth" => $_POST["month"], "expirationYear" => $_POST["year"], "cvv" => $_POST["cvv"], "billingAddress" => array("postalCode" => $_POST["postal_code"]))));
if ($result->success) {
    echo "Success! Customer ID: " . $result->customer->id;
} else {
    echo "Validation errors:<br/>";
    foreach ($result->errors->deepAll() as $error) {
        echo "- " . $error->message . "<br/>";
    }
}
Esempio n. 26
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));
 }
 private function createCust($userModel)
 {
     //        pr($userModel);
     $result = Braintree_Customer::create(['firstName' => $userModel->full_name, 'email' => $userModel->email, 'phone' => $userModel->phone_no, "id" => $userModel->id_user]);
     //        pr($result);
     if ($result->success) {
         $userModel->device_ids = $result->customer->id;
         $userModel->save();
     }
     return $result->success;
 }
Esempio n. 28
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. 29
0
 /**
  * If the customer is not logged in, but we still need to vault, we're going to create a fake customer
  *
  * @param $nonce
  * @param $billingAddress
  *
  * @return \Braintree_Customer
  */
 public function storeInGuestVault($nonce, $billingAddress = false)
 {
     $guestCustomerCreate = array('id' => $this->getBraintreeId(), 'creditCard' => array('paymentMethodNonce' => $nonce, 'options' => array('verifyCard' => true, 'verificationMerchantAccountId' => $this->getMerchantAccountId())));
     // Include billing address information into the customer
     if ($billingAddress) {
         // Add in the billing address
         $guestCustomerCreate['creditCard']['cardholderName'] = $billingAddress['firstName'] . ' ' . $billingAddress['lastName'];
         $guestCustomerCreate['creditCard']['billingAddress'] = $billingAddress;
         // Make sure the customer is created with a first name and last name
         $guestCustomerCreate['firstName'] = $billingAddress['firstName'];
         $guestCustomerCreate['lastName'] = $billingAddress['lastName'];
         // Conditionally copy over these fields
         if (isset($billingAddress['email']) && !empty($billingAddress['email'])) {
             $guestCustomerCreate['email'] = $billingAddress['email'];
         }
         if (isset($billingAddress['company']) && !empty($billingAddress['company'])) {
             $guestCustomerCreate['company'] = $billingAddress['company'];
         }
         if (isset($billingAddress['phone']) && !empty($billingAddress['phone'])) {
             $guestCustomerCreate['phone'] = $billingAddress['phone'];
         }
     }
     // Dispatch an event to allow modification of the store in vault
     $object = new Varien_Object();
     $object->setAttributes($guestCustomerCreate);
     Mage::dispatchEvent('gene_braintree_store_in_guest_vault', array('object' => $object));
     $guestCustomerCreate = $object->getAttributes();
     return Braintree_Customer::create($guestCustomerCreate);
 }
Esempio n. 30
0
 /**
  * Connect braintree for monthly payment system
  *
  * @param $ammount
  * @return array
  */
 public function braintreeConnectForMonthly()
 {
     $customer_data = array('firstName' => $this->input->post('customer_fname'), 'lastName' => $this->input->post('customer_lname'), 'email' => $this->input->post('customer_email'), 'company' => $this->input->post('customer_company'), 'fax' => $this->input->post('customer_fax'), 'website' => $this->input->post('customer_web'), 'phone' => $this->input->post('customer_phone'), 'creditCard' => $this->creditCardDetails());
     $customer_data['creditCard']['billingAddress'] = $this->billingDetails();
     try {
         return Braintree_Customer::create($customer_data);
     } catch (InvalidArgumentException $BraintreeException) {
         $bexcption = print_r($BraintreeException, true);
         log_message('error', date('Y-m-d H:i:s') . ' ' . $bexcption);
         $result = new stdClass();
         $result->success = false;
         return $result;
     }
 }