Beispiel #1
0
 function testAll_returnsAllPlans()
 {
     $newId = strval(rand());
     $params = array("id" => $newId, "billingDayOfMonth" => "1", "billingFrequency" => "1", "currencyIsoCode" => "USD", "description" => "some description", "name" => "php test plan", "numberOfBillingCycles" => "1", "price" => "1.00", "trialDuration" => "3", "trialDurationUnit" => "day", "trialPeriod" => "true");
     Braintree_Http::post("/plans/create_plan_for_tests", array("plan" => $params));
     $addOnParams = array("kind" => "add_on", "plan_id" => $newId, "amount" => "1.00", "name" => "add_on_name");
     Braintree_Http::post("/modifications/create_modification_for_tests", array("modification" => $addOnParams));
     $discountParams = array("kind" => "discount", "plan_id" => $newId, "amount" => "1.00", "name" => "discount_name");
     Braintree_Http::post("/modifications/create_modification_for_tests", array("modification" => $discountParams));
     $plans = Braintree_Plan::all();
     foreach ($plans as $plan) {
         if ($plan->id == $newId) {
             $actualPlan = $plan;
         }
     }
     $this->assertNotNull($actualPlan);
     $this->assertEquals($params["billingDayOfMonth"], $actualPlan->billingDayOfMonth);
     $this->assertEquals($params["billingFrequency"], $actualPlan->billingFrequency);
     $this->assertEquals($params["currencyIsoCode"], $actualPlan->currencyIsoCode);
     $this->assertEquals($params["description"], $actualPlan->description);
     $this->assertEquals($params["name"], $actualPlan->name);
     $this->assertEquals($params["numberOfBillingCycles"], $actualPlan->numberOfBillingCycles);
     $this->assertEquals($params["price"], $actualPlan->price);
     $this->assertEquals($params["trialDuration"], $actualPlan->trialDuration);
     $this->assertEquals($params["trialDurationUnit"], $actualPlan->trialDurationUnit);
     $this->assertEquals($params["trialPeriod"], $actualPlan->trialPeriod);
     $addOn = $actualPlan->addOns[0];
     $this->assertEquals($addOnParams["name"], $addOn->name);
     $discount = $actualPlan->discounts[0];
     $this->assertEquals($discountParams["name"], $discount->name);
 }
 /**
  * updatePlans
  * --------------------------------------------------
  * Updating the current braintree Plans.
  * @return The braintree plans.
  * @throws BraintreeNotConnected
  * --------------------------------------------------
  */
 public function updatePlans()
 {
     // Connecting to stripe, and making query.
     try {
         $braintreePlans = Braintree_Plan::all();
     } catch (Exception $e) {
         // Something went wrong.
         return;
     }
     // Getting the plans.
     $plans = [];
     foreach ($braintreePlans as $plan) {
         $new_plan = new BraintreePlan(array('plan_id' => $plan->id, 'name' => $plan->name, 'billing_frequency' => $plan->billingFrequency, 'price' => $plan->price, 'currency' => $plan->currencyIsoCode, 'billing_day' => $plan->billingDayOfMonth));
         $new_plan->user()->associate($this->user);
         array_push($plans, $new_plan);
     }
     // Delete old, save new.
     foreach (BraintreePlan::where('user_id', $this->user->id)->get() as $stripePlan) {
         BraintreeSubscription::where('plan_id', $stripePlan->id)->delete();
         $stripePlan->delete();
     }
     foreach ($plans as $plan) {
         $plan->save();
     }
     return $plans;
 }
 protected function _initialize($attributes)
 {
     $this->_attributes = $attributes;
     $addOnArray = array();
     if (isset($attributes['addOns'])) {
         foreach ($attributes['addOns'] as $addOn) {
             $addOnArray[] = Braintree_AddOn::factory($addOn);
         }
     }
     $this->_attributes['addOns'] = $addOnArray;
     $discountArray = array();
     if (isset($attributes['discounts'])) {
         foreach ($attributes['discounts'] as $discount) {
             $discountArray[] = Braintree_Discount::factory($discount);
         }
     }
     $this->_attributes['discounts'] = $discountArray;
     $planArray = array();
     if (isset($attributes['plans'])) {
         foreach ($attributes['plans'] as $plan) {
             $planArray[] = Braintree_Plan::factory($plan);
         }
     }
     $this->_attributes['plans'] = $planArray;
 }
 public function afterFind($results, $primary = false)
 {
     if ($primary) {
         $results = Hash::insert($results, "{n}.BraintreeSubscription", array());
         $results = Hash::insert($results, "{n}.BraintreePlan", array());
         $braintreeSubscriptions = Braintree_Subscription::search([Braintree_SubscriptionSearch::ids()->in(Hash::extract($results, "{n}.BillingSubscription.remote_subscription_id"))]);
         $braintreePlans = Braintree_Plan::all();
         foreach ($results as $key => $result) {
             foreach ($braintreeSubscriptions as $braintreeSubscription) {
                 if ($braintreeSubscription->id == $result['BillingSubscription']['remote_subscription_id']) {
                     $result['BraintreeSubscription'] = $braintreeSubscription;
                     break;
                 }
                 //$results = Hash::insert($results, "{n}.BillingSubscription[remote_subscription_id=".$braintreeSubscription->id."]", array('BraintreeSubscription' => $braintreeSubscription));
             }
             foreach ($braintreePlans as $braintreePlan) {
                 if ($braintreePlan->id == $result['BillingSubscription']['remote_plan_id']) {
                     $result['BraintreePlan'] = $braintreePlan;
                     break;
                 }
             }
             $results[$key] = $result;
         }
     }
     return $results;
 }
Beispiel #5
0
 public function afterFind($results, $primary = false)
 {
     if (!empty($results)) {
         $braintreePlans = Braintree_Plan::all();
         foreach ($results as $resultKey => $result) {
             if (isset($result['BillingPlan']) && !empty($result['BillingPlan'])) {
                 foreach ($result['BillingPlan'] as $key => $plan) {
                     $_arr = array();
                     $_arr[0]['BillingPlan'] = $plan;
                     $_arr = Hash::extract($this->BillingPlan->decodeItems($_arr), "0.BillingPlan");
                     foreach ($_arr['remote_plans'] as $remotePlan) {
                         foreach ($braintreePlans as $braintreePlan) {
                             if ($remotePlan == $braintreePlan->id) {
                                 $_arr['BraintreePlan'][] = $braintreePlan;
                             }
                         }
                     }
                     $result['BillingPlan'][$key] = $_arr;
                 }
             }
             $results[$resultKey] = $result;
         }
     }
     return $results;
 }
Beispiel #6
0
 public function afterFind($results, $primary = false)
 {
     if (!empty($results) && $primary == true) {
         $braintreePlans = Braintree_Plan::all();
         foreach ($results as $key => $result) {
             foreach ($braintreePlans as $braintreePlan) {
                 if (!empty($result['BillingPlan']['remote_plans']) && is_array($result['BillingPlan']['remote_plans']) && in_array($braintreePlan->id, $result['BillingPlan']['remote_plans'])) {
                     $results[$key]['BraintreePlan'][] = $braintreePlan;
                 }
             }
         }
     }
     return $results;
 }
Beispiel #7
0
 public function find($type = 'first', $query = array())
 {
     $plans = Braintree_Plan::all();
     ksort($plans);
     switch ($type) {
         case 'all':
             break;
         case 'list':
             ksort($plans);
             $_plans = array();
             foreach ($plans as $i => $plan) {
                 $_plans[$plan->id] = $plan->name;
             }
             $plans = $_plans;
             break;
         default:
         case 'first':
             $plans = $plans[0];
             break;
     }
     return $plans;
 }
 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.");
         }
     }
 }
 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']));
     }
 }
 public static function getPlanById($id, $userId = null)
 {
     // we are okay, if we search through our plans,
     // but we have to set users credentials, if
     // we go through our user's plans
     if ($userId) {
         self::setBraintreeCredentials(User::find($userId));
     }
     $plans = Braintree_Plan::all();
     foreach ($plans as $plan) {
         if ($plan->id == $id) {
             return $plan;
         }
     }
     return null;
 }