コード例 #1
0
 function testContains()
 {
     $creditCard = Braintree_SubscriptionTestHelper::createCreditCard();
     $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan();
     $trialPlan = Braintree_SubscriptionTestHelper::trialPlan();
     $trialSubscription = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $trialPlan['id'], 'price' => '9'))->subscription;
     $triallessSubscription = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '9'))->subscription;
     $collection = Braintree_Subscription::search(array(Braintree_SubscriptionSearch::planId()->contains("ration_trial_pl"), Braintree_SubscriptionSearch::price()->is("9")));
     $this->assertTrue(Braintree_TestHelper::includes($collection, $trialSubscription));
     $this->assertFalse(Braintree_TestHelper::includes($collection, $triallessSubscription));
 }
コード例 #2
0
 function testIn_multipleValues()
 {
     $creditCard = Braintree_SubscriptionTestHelper::createCreditCard();
     $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan();
     $activeSubscription = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '4'))->subscription;
     $canceledSubscription = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '4'))->subscription;
     Braintree_Subscription::cancel($canceledSubscription->id);
     $collection = Braintree_Subscription::search(array(Braintree_SubscriptionSearch::status()->in(array(Braintree_Subscription::ACTIVE, Braintree_Subscription::CANCELED)), Braintree_SubscriptionSearch::price()->is('4')));
     $this->assertTrue(Braintree_TestHelper::includes($collection, $activeSubscription));
     $this->assertTrue(Braintree_TestHelper::includes($collection, $canceledSubscription));
 }
コード例 #3
0
 function create_subscription($card_token, $plan_id, $custom = '')
 {
     $result = Braintree_Subscription::create(array('paymentMethodToken' => $card_token, 'planId' => $plan_id));
     if ($result->success === true) {
         $this->_log_subscription($result->subscription, $custom);
         /*var_dump($result->subscription);
         		die();*/
         return true;
     }
     /*$subscription = $result->subscription;
     		$transaction = $subscription->transactions[0];*/
     $this->_parse_errors($result);
     return false;
 }
コード例 #4
0
 /**
  * @param $data array
  *
  * @return mixed
  */
 public function createSubscription($data)
 {
     $customer = $this->getCustomer($data);
     if ($customer->success == false) {
     }
     $card = $this->getCard($customer, $data);
     if ($card->success == false) {
     }
     $subscription = \Braintree_Subscription::create(array('paymentMethodToken' => $card->token, 'planId' => $data['planId']));
     if ($subscription->success == false) {
     } else {
         return true;
     }
 }
コード例 #5
0
ファイル: Braintree.php プロジェクト: skamnev/members
 /**
  * Braintree sale function
  * @param bool|true $submitForSettlement
  * @param bool|true $storeInVaultOnSuccess
  * @return array
  */
 public function sendSubscription()
 {
     //$customer = \Braintree_Customer::find($this->options['customerId']);
     $subscriptionData = array('paymentMethodToken' => $this->options['paymentMethodToken'], 'planId' => $this->options['planId']);
     $result = \Braintree_Subscription::create($subscriptionData);
     if ($result->success) {
         return ['status' => true, 'result' => $result];
     } else {
         if ($result->transaction) {
             return ['status' => false, 'result' => $result];
         } else {
             return ['status' => false, 'result' => $result];
         }
     }
 }
コード例 #6
0
 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;
     }
 }
コード例 #7
0
 function testFind_returnsSubscriptionsAssociatedWithAPaypalAccount()
 {
     $customer = Braintree_Customer::createNoValidate();
     $paymentMethodToken = 'paypal-account-' . strval(rand());
     $nonce = Braintree_HttpClientApi::nonceForPayPalAccount(array('paypal_account' => array('consent_code' => 'consent-code', 'token' => $paymentMethodToken)));
     $result = Braintree_PaymentMethod::create(array('paymentMethodNonce' => $nonce, 'customerId' => $customer->id));
     $this->assertTrue($result->success);
     $token = $result->paymentMethod->token;
     $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan();
     $subscription1 = Braintree_Subscription::create(array('paymentMethodToken' => $token, 'planId' => $triallessPlan['id']))->subscription;
     $subscription2 = Braintree_Subscription::create(array('paymentMethodToken' => $token, 'planId' => $triallessPlan['id']))->subscription;
     $paypalAccount = Braintree_PayPalAccount::find($token);
     $getIds = function ($sub) {
         return $sub->id;
     };
     $subIds = array_map($getIds, $paypalAccount->subscriptions);
     $this->assertTrue(in_array($subscription1->id, $subIds));
     $this->assertTrue(in_array($subscription2->id, $subIds));
 }
コード例 #8
0
 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);
 }
コード例 #9
0
 function testUpdate_withDescriptor()
 {
     $creditCard = Braintree_SubscriptionTestHelper::createCreditCard();
     $plan = Braintree_SubscriptionTestHelper::triallessPlan();
     $subscription = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $plan['id'], 'descriptor' => array('name' => '123*123456789012345678', 'phone' => '3334445555')))->subscription;
     $result = Braintree_Subscription::update($subscription->id, array('descriptor' => array('name' => '999*9999999', 'phone' => '8887776666')));
     $updatedSubscription = $result->subscription;
     $this->assertEquals('999*9999999', $updatedSubscription->descriptor->name);
     $this->assertEquals('8887776666', $updatedSubscription->descriptor->phone);
 }
コード例 #10
0
<?php

include '../brainTreePhp/lib/Braintree.php';
$nonceFromTheClient = $_POST['payment_method_nonce'];
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('zn8d4c74dbnp5ntw');
Braintree_Configuration::publicKey('ttwrprnsj83thjjz');
Braintree_Configuration::privateKey('a818cb5f3164585f31f4f03066f308c8');
$customer = Braintree_Customer::create(array("firstName" => $_POST["first_name"], "lastName" => $_POST["last_name"], "company" => $_POST["company"], "paymentMethodNonce" => $nonceFromTheClient));
if ($customer->success) {
    $subscription = Braintree_Subscription::create(['paymentMethodToken' => $customer->customer->paymentMethods[0]->token, 'planId' => 'qtzg']);
    //echo $subscription->subscription->id;
    $opts = [CURLOPT_URL => 'https://api.concertian.com/agents/auth/subscription', CURLOPT_HTTPHEADER => ['Authorization: ' . $_COOKIE["apiKey"]], CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => ['subscriptionId' => $subscription->subscription->id], CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_SSL_VERIFYHOST => FALSE, CURLOPT_CONNECTTIMEOUT => 25, CURLOPT_TIMEOUT => 3600, CURLOPT_HEADER => TRUE, CURLOPT_VERBOSE => TRUE];
    $curl = curl_init();
    curl_setopt_array($curl, $opts);
    curl_exec($curl);
    setcookie('successfull', 3, time() + 86400 * 30, "/");
    header('Location: ../response.html');
} else {
    setcookie('successfull', 4, time() + 86400 * 30, "/");
    header('Location: ../response.html');
}
コード例 #11
0
<?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"];
}
コード例 #12
0
 /**
  * createBraintreeSubscription
  * --------------------------------------------------
  * @param (Plan) ($newPlan) The new plan
  * @return Creates a Braintree Subscription, from this object.
  * --------------------------------------------------
  */
 private function createBraintreeSubscription($newPlan)
 {
     /* Initialize variables */
     $result = ['errors' => FALSE, 'messages' => ''];
     /* The function assumes, that everything is OK to charge the user on Braintree */
     /* Create Braintree subscription */
     $subscriptionResult = Braintree_Subscription::create(['paymentMethodToken' => $this->braintree_payment_method_token, 'planId' => $newPlan->braintree_plan_id]);
     /* Success */
     if ($subscriptionResult->success) {
         Log::info($subscriptionResult);
         /* Change the subscription plan and dates to the new in our DB */
         $this->plan()->associate($newPlan);
         $this->braintree_subscription_id = $subscriptionResult->subscription->id;
         $this->current_period_start = Carbon::now();
         $this->current_period_end = Carbon::now()->addMonth();
         /* Save object */
         $this->save();
         /* Error */
     } else {
         /* Get and store errors */
         foreach ($subscriptionResult->errors->deepAll() as $error) {
             $result['errors'] |= TRUE;
             $result['messages'] .= $error->code . ": " . $error->message . ' ';
         }
     }
     /* Return result */
     return $result;
 }
コード例 #13
0
 function testFind_returnsCreditCardsWithSubscriptions()
 {
     $customer = Braintree_Customer::createNoValidate();
     $creditCardResult = Braintree_CreditCard::create(array('customerId' => $customer->id, 'number' => '5105105105105100', 'expirationDate' => '05/2011'));
     $this->assertTrue($creditCardResult->success);
     $subscriptionId = strval(rand());
     Braintree_Subscription::create(array('id' => $subscriptionId, 'paymentMethodToken' => $creditCardResult->creditCard->token, 'planId' => 'integration_trialless_plan', 'price' => '1.00'));
     $foundCreditCard = Braintree_PaymentMethod::find($creditCardResult->creditCard->token);
     $this->assertEquals($subscriptionId, $foundCreditCard->subscriptions[0]->id);
     $this->assertEquals('integration_trialless_plan', $foundCreditCard->subscriptions[0]->planId);
     $this->assertEquals('1.00', $foundCreditCard->subscriptions[0]->price);
 }
コード例 #14
0
 public function doPayPlan($planId)
 {
     if (Input::has('payment_method_nonce')) {
         // get the detials of the plan
         $plans = Braintree_Plan::all();
         $user = Auth::user();
         // find the correct plan to show
         // no way currently to get only one plan
         foreach ($plans as $plan) {
             if ($plan->id == 'fruit_analytics_plan_' . $planId) {
                 $planName = $plan->name;
             }
         }
         // lets see, if the user already has a subscripton
         if ($user->subscriptionId) {
             try {
                 $result = Braintree_Subscription::cancel($user->subscriptionId);
             } catch (Exception $e) {
                 return Redirect::route('auth.plan')->with('error', "Couldn't process subscription, try again later.");
             }
         }
         // create the new subscription
         $result = Braintree_Subscription::create(array('planId' => 'fruit_analytics_plan_' . $planId, 'paymentMethodNonce' => Input::get('payment_method_nonce')));
         if ($result->success) {
             // update user plan to subscrition
             $user->plan = $planId;
             $user->subscriptionId = $result->subscription->id;
             $user->save();
             IntercomHelper::subscribed($user, $planId);
             return Redirect::route('auth.dashboard')->with('success', 'Subscribed to ' . $planName);
         } else {
             return Redirect::route('auth.plan')->with('error', "Couldn't process subscription, try again later.");
         }
     }
 }
コード例 #15
0
 function testSnapshotPlanIdAddOnsAndDiscountsFromSubscription()
 {
     $creditCard = Braintree_SubscriptionTestHelper::createCreditCard();
     $plan = Braintree_SubscriptionTestHelper::triallessPlan();
     $result = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $plan['id'], 'addOns' => array('add' => array(array('amount' => '11.00', 'inheritedFromId' => 'increase_10', 'quantity' => 2, 'numberOfBillingCycles' => 5), array('amount' => '21.00', 'inheritedFromId' => 'increase_20', 'quantity' => 3, 'numberOfBillingCycles' => 6))), 'discounts' => array('add' => array(array('amount' => '7.50', 'inheritedFromId' => 'discount_7', 'quantity' => 2, 'neverExpires' => true)))));
     $transaction = $result->subscription->transactions[0];
     $this->assertEquals($transaction->planId, $plan['id']);
     $addOns = $transaction->addOns;
     Braintree_SubscriptionTestHelper::sortModificationsById($addOns);
     $this->assertEquals($addOns[0]->amount, "11.00");
     $this->assertEquals($addOns[0]->id, "increase_10");
     $this->assertEquals($addOns[0]->quantity, 2);
     $this->assertEquals($addOns[0]->numberOfBillingCycles, 5);
     $this->assertFalse($addOns[0]->neverExpires);
     $this->assertEquals($addOns[1]->amount, "21.00");
     $this->assertEquals($addOns[1]->id, "increase_20");
     $this->assertEquals($addOns[1]->quantity, 3);
     $this->assertEquals($addOns[1]->numberOfBillingCycles, 6);
     $this->assertFalse($addOns[1]->neverExpires);
     $discounts = $transaction->discounts;
     $this->assertEquals($discounts[0]->amount, "7.50");
     $this->assertEquals($discounts[0]->id, "discount_7");
     $this->assertEquals($discounts[0]->quantity, 2);
     $this->assertEquals($discounts[0]->numberOfBillingCycles, null);
     $this->assertTrue($discounts[0]->neverExpires);
 }
コード例 #16
0
 function subscribe(&$order)
 {
     //create a code for the order
     if (empty($order->code)) {
         $order->code = $order->getRandomCode();
     }
     //set up customer
     $this->getCustomer($order);
     if (empty($this->customer) || !empty($order->error)) {
         return false;
     }
     //error retrieving customer
     //figure out the amounts
     $amount = $order->PaymentAmount;
     $amount_tax = $order->getTaxForPrice($amount);
     $amount = round((double) $amount + (double) $amount_tax, 2);
     /*
     	There are two parts to the trial. Part 1 is simply the delay until the first payment
     	since we are doing the first payment as a separate transaction.
     	The second part is the actual "trial" set by the admin.
     	
     	Stripe only supports Year or Month for billing periods, but we account for Days and Weeks just in case.
     */
     //figure out the trial length (first payment handled by initial charge)
     if ($order->BillingPeriod == "Year") {
         $trial_period_days = $order->BillingFrequency * 365;
     } elseif ($order->BillingPeriod == "Day") {
         $trial_period_days = $order->BillingFrequency * 1;
     } elseif ($order->BillingPeriod == "Week") {
         $trial_period_days = $order->BillingFrequency * 7;
     } else {
         $trial_period_days = $order->BillingFrequency * 30;
     }
     //assume monthly
     //convert to a profile start date
     $order->ProfileStartDate = date("Y-m-d", strtotime("+ " . $trial_period_days . " Day", current_time("timestamp"))) . "T0:0:0";
     //filter the start date
     $order->ProfileStartDate = apply_filters("pmpro_profile_start_date", $order->ProfileStartDate, $order);
     //convert back to days
     $trial_period_days = ceil(abs(strtotime(date("Y-m-d")) - strtotime($order->ProfileStartDate, current_time("timestamp"))) / 86400);
     //now add the actual trial set by the site
     if (!empty($order->TrialBillingCycles)) {
         $trialOccurrences = (int) $order->TrialBillingCycles;
         if ($order->BillingPeriod == "Year") {
             $trial_period_days = $trial_period_days + 365 * $order->BillingFrequency * $trialOccurrences;
         } elseif ($order->BillingPeriod == "Day") {
             $trial_period_days = $trial_period_days + 1 * $order->BillingFrequency * $trialOccurrences;
         } elseif ($order->BillingPeriod == "Week") {
             $trial_period_days = $trial_period_days + 7 * $order->BillingFrequency * $trialOccurrences;
         } else {
             $trial_period_days = $trial_period_days + 30 * $order->BillingFrequency * $trialOccurrences;
         }
         //assume monthly
     }
     //subscribe to the plan
     try {
         $details = array('paymentMethodToken' => $this->customer->creditCards[0]->token, 'planId' => 'pmpro_' . $order->membership_id, 'price' => $amount);
         if (!empty($trial_period_days)) {
             $details['trialPeriod'] = true;
             $details['trialDuration'] = $trial_period_days;
             $details['trialDurationUnit'] = "day";
         }
         if (!empty($order->TotalBillingCycles)) {
             $details['numberOfBillingCycles'] = $order->TotalBillingCycles;
         }
         $result = Braintree_Subscription::create($details);
     } catch (Exception $e) {
         $order->error = __("Error subscribing customer to plan with Braintree:", "pmpro") . " " . $e->getMessage();
         //return error
         $order->shorterror = $order->error;
         return false;
     }
     if ($result->success) {
         //if we got this far, we're all good
         $order->status = "success";
         $order->subscription_transaction_id = $result->subscription->id;
         return true;
     } else {
         $order->error = __("Failed to subscribe with Braintree:", "pmpro") . " " . $result->message;
         $order->shorterror = $result->message;
         return false;
     }
 }
コード例 #17
0
 function testSearch_price()
 {
     $creditCard = Braintree_SubscriptionTestHelper::createCreditCard();
     $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan();
     $subscription_850 = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '8.50'))->subscription;
     $subscription_851 = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '8.51'))->subscription;
     $subscription_852 = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id'], 'price' => '8.52'))->subscription;
     $collection = Braintree_Subscription::search(array(Braintree_SubscriptionSearch::price()->between('8.51', '8.52')));
     $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_851));
     $this->assertTrue(Braintree_TestHelper::includes($collection, $subscription_852));
     $this->assertFalse(Braintree_TestHelper::includes($collection, $subscription_850));
 }
コード例 #18
0
 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']));
     }
 }
コード例 #19
0
ファイル: YiiBraintree.php プロジェクト: tejrajs/yiibraintree
 public function createSubscription($payment_method_token)
 {
     $result = Braintree_Subscription::create(array('paymentMethodToken' => $payment_method_token, 'planId' => 'fxtb'));
     if ($result->success) {
         return array('success' => 1, 'subscription_id' => $result->subscription->id, 'subscription_status' => $result->subscription->status);
         /*
                           eg:Array
         			  (
         			      [success] => 1
         			      [subscription_id] => 59btqg
         			      [subscription_status] => Active
         			  )
         */
     } else {
         return array('success' => 0, 'validation_errors' => $result->errors->deepAll());
     }
 }
コード例 #20
0
 function testUpdate_canReplaceEntireSetOfAddonsAndDiscounts()
 {
     $oldCreditCard = Braintree_SubscriptionTestHelper::createCreditCard();
     $plan = Braintree_SubscriptionTestHelper::addOnDiscountPlan();
     $subscription = Braintree_Subscription::create(array('paymentMethodToken' => $oldCreditCard->token, 'price' => '54.99', 'planId' => $plan['id']))->subscription;
     $result = Braintree_Subscription::update($subscription->id, array('addOns' => array('add' => array(array('inheritedFromId' => 'increase_30'), array('inheritedFromId' => 'increase_20'))), 'discounts' => array('add' => array(array('inheritedFromId' => 'discount_15'))), 'options' => array('replaceAllAddOnsAndDiscounts' => true)));
     $this->assertTrue($result->success);
     $subscription = $result->subscription;
     $this->assertEquals(2, sizeof($subscription->addOns));
     $addOns = $subscription->addOns;
     Braintree_SubscriptionTestHelper::sortModificationsById($addOns);
     $this->assertEquals($addOns[0]->id, "increase_20");
     $this->assertEquals($addOns[1]->id, "increase_30");
     $this->assertEquals(1, sizeof($subscription->discounts));
     $discounts = $subscription->discounts;
     $this->assertEquals($discounts[0]->id, "discount_15");
 }
コード例 #21
0
 function testSearch_transactionId()
 {
     $creditCard = Braintree_SubscriptionTestHelper::createCreditCard();
     $triallessPlan = Braintree_SubscriptionTestHelper::triallessPlan();
     $matchingSubscription = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id']))->subscription;
     $nonMatchingSubscription = Braintree_Subscription::create(array('paymentMethodToken' => $creditCard->token, 'planId' => $triallessPlan['id']))->subscription;
     $collection = Braintree_Subscription::search(array(Braintree_SubscriptionSearch::transactionId()->is($matchingSubscription->transactions[0]->id)));
     $this->assertTrue(Braintree_TestHelper::includes($collection, $matchingSubscription));
     $this->assertFalse(Braintree_TestHelper::includes($collection, $nonMatchingSubscription));
 }
コード例 #22
0
ファイル: prau.php プロジェクト: beevo/disruptivestrong
     $plan = "fitness";
 } else {
     if ($role[0] == "t") {
         $plan = "training";
     } else {
         if ($role[0] == "r") {
             $plan = "rep";
         } else {
             if ($role[0] == "l") {
                 $plan = "licensee";
             }
         }
     }
 }
 $plan .= "_plan_basic";
 $result = Braintree_Subscription::create(array('paymentMethodToken' => $payToken, 'planId' => $plan));
 if (!$result->success) {
     $error_msg = '<p class="error">Subscription Not Started:</p>';
     foreach ($result->errors->deepAll() as $error) {
         $error_msg .= '<p class="error">' . $error->code . ": " . $error->message . '</p>';
     }
     echo $error_msg;
 } else {
     // Set Account Status to Active
     if ($stmt = $mysqli->prepare("UPDATE members SET account_status='" . ACCOUNT_STATUS_ACTIVE . "', askee='' " . "WHERE id = ?")) {
         // Bind "$si" to parameter.
         $stmt->bind_param('i', $si);
         $stmt->execute();
         // Execute the prepared query.
         global $subdomain;
         if ($role[0] == "f") {
コード例 #23
0
 static function createSubscription()
 {
     $plan = Braintree_SubscriptionTestHelper::triallessPlan();
     $result = Braintree_Subscription::create(array('paymentMethodToken' => Braintree_SubscriptionTestHelper::createCreditCard()->token, 'price' => '54.99', 'planId' => $plan['id']));
     return $result->subscription;
 }
コード例 #24
0
 function testFindReturnsAssociatedSubscriptions()
 {
     $customer = Braintree_Customer::createNoValidate();
     $result = Braintree_CreditCard::create(array('customerId' => $customer->id, 'cardholderName' => 'Cardholder', 'number' => '5105105105105100', 'expirationDate' => '05/12', 'billingAddress' => array('firstName' => 'Drew', 'lastName' => 'Smith', 'company' => 'Smith Co.', 'streetAddress' => '1 E Main St', 'extendedAddress' => 'Suite 101', 'locality' => 'Chicago', 'region' => 'IL', 'postalCode' => '60622', 'countryName' => 'United States of America')));
     $id = strval(rand());
     Braintree_Subscription::create(array('id' => $id, 'paymentMethodToken' => $result->creditCard->token, 'planId' => 'integration_trialless_plan', 'price' => '1.00'));
     $creditCard = Braintree_CreditCard::find($result->creditCard->token);
     $this->assertEquals($id, $creditCard->subscriptions[0]->id);
     $this->assertEquals('integration_trialless_plan', $creditCard->subscriptions[0]->planId);
     $this->assertEquals('1.00', $creditCard->subscriptions[0]->price);
 }
コード例 #25
0
    function do_process()
    {
        $action = ym_request('action');
        if ($action == 'js') {
            header('Content-Type: text/javascript');
            ?>
jQuery(document).ready(function() {
	jQuery('.ym_braintree_button').click(function(event) {
		event.preventDefault();

		jQuery('.ym_form').slideUp();
		jQuery('#<?php 
            echo $this->code;
            ?>
_cc_form_unique_' + jQuery(this).attr('data-unique')).slideDown();
	});

	var braintree = Braintree.create("<?php 
            echo $this->encryptionkey;
            ?>
");
	jQuery('.<?php 
            echo $this->code;
            ?>
_cc_form').submit(function(e) {
		e.preventDefault();

		jQuery('.ym_braintree_icon').addClass('ym_ajax_loading_image');

		var target = jQuery(this);
		target.find('.error').remove();

		var data = jQuery(this).clone();
		data.find('#braintree_credit_card_number').val(braintree.encrypt(jQuery(this).find('#braintree_credit_card_number').val()));
		data.find('#braintree_credit_card_ccv').val(braintree.encrypt(jQuery(this).find('#braintree_credit_card_ccv').val()));
		data.find('#braintree_credit_card_exp').val(braintree.encrypt(jQuery(this).find('#braintree_credit_card_exp').val()));

		target.find('input').attr('disabled', 'disabled');

		jQuery.post('<?php 
            echo $this->action_url;
            ?>
&action=ajax', data.serialize(), function(resp) {
			jQuery('.ym_braintree_icon').removeClass('ym_ajax_loading_image');

			resp = jQuery.parseJSON(resp);
			if (resp['ok']) {
				target.find('#braintree_credit_card_number').val('');
				target.find('#braintree_credit_card_ccv').val('');
				target.find('#braintree_credit_card_exp').val('');

				jQuery('<div class="success"><p>' + resp['message'] + '</p></div>').prependTo(target);

				document.location = resp['url'];
			} else {
				target.find('input').removeAttr('disabled');
				jQuery('<div class="error"><p>' + resp['message'] + '</p></div>').prependTo(target);
			}
		});
	});
});
<?php 
            exit;
        } else {
            if ($action == 'ajax') {
                ob_start();
                $this->_braintree();
                // issue sale or subscribe
                $code = $_POST['code'];
                list($buy, $what, $pack_id, $user_id) = explode('_', $code);
                // credit card update
                $result = Braintree_Customer::update('ym_' . $user_id, array('creditCard' => array('number' => $_POST['customer']['credit_card']['number'], 'cvv' => $_POST['customer']['credit_card']['cvv'], 'expirationDate' => $_POST['customer']['credit_card']['expiration_date'])));
                if ($result->success) {
                    // grab token and subscribe
                    //				if ($pack['num_cycles'] == 1 || $planId) {
                    if ($what == 'subscription') {
                        // above catches both kinds of package/subscription
                        $pack = ym_get_pack_by_id($pack_id);
                        $planId = isset($pack['braintree_plan_id']) ? $pack['braintree_plan_id'] : false;
                        // initiate charge against just added credit card
                        if ($planId) {
                            $result = Braintree_Subscription::create(array('planId' => $planId, 'paymentMethodToken' => $result->customer->creditCards[0]->token));
                            $amount = $result->subscription->transactions[0]->amount;
                        } else {
                            $result = Braintree_Transaction::sale(array('amount' => $pack['cost'], 'options' => array('submitForSettlement' => true), 'customerId' => $result->customer->id, 'paymentMethodToken' => $result->customer->creditCards[0]->token));
                            $amount = $result->transaction->amount;
                        }
                        if ($result->success) {
                            // common
                            $this->common_process($code, $amount, true, false);
                            // thanks
                            $url = $this->redirectlogic($pack);
                            $r = array('ok' => true, 'url' => $url, 'message' => __('Payment Complete', 'ym'));
                        } else {
                            $r = $this->_failedBraintree($result, true);
                        }
                    } else {
                        if ($what == 'bundle' || $what == 'post') {
                            // post or bundle purchase
                            if ($what == 'post') {
                                $cost = get_post_meta($pack_id, '_ym_post_purchasable_cost', true);
                            } else {
                                $bundle = ym_get_bundle($pack_id);
                                if (!$bundle) {
                                    $r = array('ok' => false, 'message' => __('Bundle Error', 'ym'));
                                } else {
                                    $cost = $bundle->cost;
                                }
                            }
                            if ($cost) {
                                $result = Braintree_Transaction::sale(array('amount' => $cost, 'options' => array('submitForSettlement' => true), 'customerId' => $result->customer->id, 'paymentMethodToken' => $result->customer->creditCards[0]->token));
                                $amount = $result->transaction->amount;
                                if ($result->success) {
                                    // common
                                    $this->common_process($code, $amount, true, false);
                                    // thanks
                                    if ($what == 'subscription') {
                                        $url = $this->redirectlogic($pack);
                                    } else {
                                        if ($what == 'post') {
                                            $url = $this->redirectlogic(array('ppp' => true, 'post_id' => $pack_id));
                                        } else {
                                            $url = $this->redirectlogic(array('ppp' => true, 'ppp_pack_id' => $pack_id));
                                        }
                                    }
                                    $r = array('ok' => true, 'url' => $url, 'message' => __('Payment Complete', 'ym'));
                                } else {
                                    $r = $this->_failedBraintree($result, true);
                                }
                            }
                        } else {
                            // unhandled purchase
                            $r = $this->_failedBraintree($result, true);
                        }
                    }
                } else {
                    $r = $this->_failedBraintree($result, true);
                }
                ob_clean();
                echo json_encode($r);
                // bugger
                exit;
                // non ajax/primary js failed
                // transparent redirect handlers
            } else {
                if ($action == 'process') {
                    $this->_braintree();
                    $queryString = $_SERVER['QUERY_STRING'];
                    try {
                        $result = Braintree_TransparentRedirect::confirm($queryString);
                    } catch (Exception $e) {
                        if (get_class($e) == 'Braintree_Exception_NotFound') {
                            echo 'not found';
                        } else {
                            echo '<pre>';
                            print_r($e);
                            echo $e->getMessage();
                        }
                        exit;
                    }
                    if ($result->success) {
                        $code = ym_request('code');
                        // grab token and subscribe
                        list($buy, $what, $pack_id, $user_id) = explode('_', $code);
                        $pack = ym_get_pack_by_id($pack_id);
                        $planId = isset($pack['braintree_plan_id']) ? $pack['braintree_plan_id'] : false;
                        if ($pack['num_cycles'] == 1 || $planId) {
                            // initiate charge against just added credit card
                            if ($planId) {
                                $result = Braintree_Subscription::create(array('planId' => $planId, 'paymentMethodToken' => $result->customer->creditCards[0]->token));
                                $amount = $result->subscription->transactions[0]->amount;
                            } else {
                                $result = Braintree_Transaction::sale(array('amount' => $pack['cost'], 'options' => array('submitForSettlement' => true), 'customerId' => $result->customer->id, 'paymentMethodToken' => $result->customer->creditCards[0]->token));
                                $amount = $result->transaction->amount;
                            }
                            if ($result->success) {
                                // common
                                $this->common_process($code, $amount, true, false);
                                // thanks
                                $this->redirectlogic($pack, true);
                                exit;
                            } else {
                                $this->_failedBraintree($result);
                            }
                        } else {
                            $this->_failedBraintree($result);
                        }
                        exit;
                    }
                    $this->_failedBraintree($result);
                } else {
                    $this->_failedBraintree();
                }
            }
        }
    }