/**
  * Generate license
  */
 public function postGenerateLicense()
 {
     $rules = array('transaction_id' => 'required');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::to('admin/utilities/generate-license')->withErrors($validator)->withInput();
     } else {
         $transaction_id = Input::get('transaction_id');
         if ($transaction = Transaction::where('id', '=', $transaction_id)->first()) {
             if ($license = License::where('transaction_id', '=', $transaction_id)->first()) {
                 Session::flash('alert_error', '<strong>Ooops!</strong> License for given transaction already exists.');
                 return Redirect::to('admin/licenses?q=' . $license->license_key . '&param=key');
             }
             $plan = Plan::where('id', '=', $transaction->plan_id)->first();
             if ($plan->has_license) {
                 $product = Product::where('id', '=', $plan->product_id)->first();
                 $license_key = License::generate($product->code);
                 // Save license
                 $license = new License();
                 $license->license_key = $license_key;
                 $license->transaction_id = $transaction_id;
                 $license->allowed_usage = $plan->license_allowed_usage;
                 $license->save();
                 Session::flash('alert_message', '<strong>Well done!</strong> You successfully have generated license key.');
                 return Redirect::to('admin/licenses?q=' . $license_key . '&param=key');
             } else {
                 Session::flash('alert_error', '<strong>Ooops!</strong> This plan does not allow to generate a license key.');
                 return Redirect::to('admin/utilities/generate-license');
             }
         } else {
             Session::flash('alert_error', '<strong>Ooops!</strong> Transaction was not found.');
             return Redirect::to('admin/utilities/generate-license');
         }
     }
 }
 public static function ProrataDiscount($account_id, $month_sub, $plan_data, $new_plan_cost, $rem_day, $num_of_days, $prorata_bal)
 {
     $plan_det = Plan::where('account_id', '=', $account_id)->get()->first();
     $old_plan_code = $plan_det->plan_code;
     $old_plan_amount = PlanCostDetail::where('plan_code', '=', $old_plan_code)->get()->first()->plan_cost;
     $old_plan_cost = round($old_plan_amount + $old_plan_amount * 0.14);
     $prorata_dis = $old_plan_cost - $prorata_bal;
     if ($month_sub == 'Monthly') {
         if ($plan_data != 0) {
             $prorata_cost = $new_plan_cost;
             $prorata_dis = $prorata_dis;
             $plan_amount = $new_plan_cost - $prorata_dis;
             return array("plan_amount" => $plan_amount, "prorata_dis" => $prorata_dis, "prorata_cost" => $prorata_cost);
         } else {
             $plan_amount = round($rem_day * ($new_plan_cost / $num_of_days)) - $prorata_dis;
             //var_dump($plan_cost_tax); die;
             $prorata_cost = $plan_amount;
             $prorata_dis = $new_plan_cost - $prorata_cost;
             return array("plan_amount" => $plan_amount, "prorata_dis" => $prorata_dis, "prorata_cost" => $prorata_cost);
         }
     } else {
         $plan_amount = $new_plan_cost;
         $prorata_cost = $new_plan_cost;
         $prorata_dis = 0;
         return array("plan_amount" => $plan_amount, "prorata_dis" => $prorata_dis, "prorata_cost" => $prorata_cost);
     }
 }
Beispiel #3
0
 public function plan()
 {
     $plans = Plan::where('account_id', '=', $this->account_id)->get();
     if (count($plans) != 0) {
         return $plans->first();
     }
     return null;
 }
 public static function billUpdate($id, $account_id, $for_month, $other_charges_new, $plan_code, $plan_start_date)
 {
     $bill = Bill::where('account_id', '=', $account_id)->where('for_month', $for_month)->get()->first();
     // var_dump($bill,$for_month,$account_id);die;
     if (count($bill) != 0) {
         $plan = Plan::where('account_id', '=', $account_id)->get()->first();
         $plan_cost_det = PlanCostDetail::where('plan_code', '=', $plan_code)->get()->first();
         $planChange = PlanChangeDet::where('account_id', $account_id)->where('status', 'payment pending')->first();
         if (count($planChange) != 0) {
             $planChange->plan_code = $plan_code;
             $planChange->plan_name = $plan_cost_det->plan_desc;
             $planChange->plan_change_date = $plan_start_date;
             $planChange->request_id = "44444";
             $planChange->save();
         } else {
             $planchange = new PlanChangeDet();
             $planchange->account_id = $account_id;
             $planchange->plan_code = $plan_code;
             $planchange->plan_name = $plan_cost_det->plan_desc;
             $planchange->plan_change_date = $plan_start_date;
             $planchange->request_id = "44444";
             $planchange->remarks = $bill->bill_no;
             $planchange->status = "payment pending";
             $planchange->save();
         }
         $account_id = $account_id;
         $for_month = $for_month;
         $other_charges_exit = OtherCharges::where('account_id', '=', $account_id)->where('for_month', $for_month)->where('id', '!=', $id)->sum('amount');
         $other_charges_update = OtherCharges::where('id', $id)->first();
         if (count($other_charges_update) != 0) {
             $sub_total = $bill->sub_total;
             $service_tax = $bill->service_tax;
             $total_charges = $sub_total + $service_tax;
             $amount_before_due_date = intval($bill->amount_before_due_date + $other_charges_update->amount);
             $amount_after_due_date = intval($bill->amount_before_due_date + $other_charges_update->amount);
             $other_charges_update->is_considered = 1;
             $other_charges_update->remarks = "planchange bill no " . $bill->bill_no;
             $other_charges_update->save();
             $other_charges = $other_charges_update->amount;
             $amount_paid = $bill->amount_paid;
         }
         if ($amount_paid == 0) {
             $status = "not_paid";
         } else {
             if ($amount_before_due_date > $amount_paid) {
                 $status = "partially_paid";
             } else {
                 if ($amount_before_due_date <= $amount_paid) {
                     $status = "paid";
                 }
             }
         }
         DB::table('bill_det')->where('bill_no', '=', $bill->bill_no)->update(array('other_charges' => $other_charges + $other_charges_exit, 'amount_before_due_date' => $amount_before_due_date, 'amount_after_due_date' => $amount_after_due_date, 'amount_paid' => $amount_paid, 'status' => $status));
         return DB::table('bill_det')->where('bill_no', '=', $bill->bill_no)->first();
     }
 }
 /**
  * cancelSubscription  
  * --------------------------------------------------
  * @return Cancels the subscription for the user
  * --------------------------------------------------
  */
 public function cancelSubscription()
 {
     /* Initialize variables */
     $result = ['errors' => FALSE, 'messages' => ''];
     /* Get customer and update Braintree payment fields */
     $result = $this->cancelBraintreeSubscription();
     if ($result['errors'] == FALSE) {
         /* Get the free plan */
         $freePlan = Plan::where('name', 'Free')->first();
         /* Update the DB */
         $this->plan()->associate($freePlan);
         $this->braintree_subscription_id = null;
         $this->current_period_start = Carbon::now();
         $this->current_period_end = Carbon::now();
         $this->save();
     }
     /* Return the updated result */
     return $result;
 }
 /**
  * Refund the transaction
  */
 static function refund($id, $force_refund = FALSE)
 {
     $transaction = Transaction::find($id);
     // Get Plan data
     $plan = Plan::where('id', '=', $transaction->plan_id)->first();
     // Get purchase data
     $purchase = Purchase::where('id', '=', $transaction->purchase_id)->first();
     if ($transaction->purchase->pay_method == 1) {
         // Add Stripe library
         require_once app_path() . "/libraries/stripe-php-1.9.0/lib/Stripe.php";
         // Add Stripe library
         Stripe::setApiKey(Config::get('project.stripe_secret_key'));
         try {
             $ch = Stripe_Charge::retrieve($transaction->pay_id);
             $ch->refund();
         } catch (Exception $e) {
             $error = TRUE;
         }
         // If Split pay then cancel subscription as well
         if ($plan->has_split_pay) {
             $at_period_end = FALSE;
             $customer = $purchase->stripe_token;
             $subscription_id = NULL;
             try {
                 $cu = Stripe_Customer::retrieve($customer);
                 $subscriptions = $cu->subscriptions->all(array('count' => 100));
                 foreach ($subscriptions->data as $subscription) {
                     if ($subscription->plan->id == $plan_id) {
                         if ($subscription->status == 'active') {
                             $subscription_id = $subscription->id;
                             break;
                         }
                     }
                 }
                 $cu->subscriptions->retrieve($subscription_id)->cancel(array('at_period_end' => $at_period_end));
             } catch (Exception $e) {
                 $error = TRUE;
             }
         }
     } elseif ($transaction->purchase->pay_method == 2) {
         $config = array('mode' => Config::get('project.paypal_mode'), 'acct1.UserName' => Config::get('project.paypal_api_username'), 'acct1.Password' => Config::get('project.paypal_api_password'), 'acct1.Signature' => Config::get('project.paypal_api_signature'));
         /*
         * The RefundTransaction API operation issues a refund to the PayPal account holder associated with a transaction. 
         This sample code uses Merchant PHP SDK to make API call
         */
         $refundReqest = new PayPal\PayPalAPI\RefundTransactionRequestType();
         /*
         *          Type of refund you are making. It is one of the following values:
                        
                         * `Full` - Full refund (default).
                         * `Partial` - Partial refund.
                         * `ExternalDispute` - External dispute. (Value available since
                         version
                         82.0)
                         * `Other` - Other type of refund. (Value available since version
                         82.0)
         */
         $refundReqest->RefundType = 'Full';
         /*
         *  Either the `transaction ID` or the `payer ID` must be specified.
                         PayerID is unique encrypted merchant identification number
                         For setting `payerId`,
                         `refundTransactionRequest.setPayerID("A9BVYX8XCR9ZQ");`
         
                         Unique identifier of the transaction to be refunded.
         */
         $refundReqest->TransactionID = $transaction->pay_id;
         /*
                      *  (Optional)Type of PayPal funding source (balance or eCheck) that can be used for auto refund. It is one of the following values:
            any – The merchant does not have a preference. Use any available funding source.
            default – Use the merchant's preferred funding source, as configured in the merchant's profile.
            instant – Use the merchant's balance as the funding source.
            eCheck – The merchant prefers using the eCheck funding source. If the merchant's PayPal balance can cover the refund amount, use the PayPal balance.
         */
         //$refundReqest->RefundSource = $_REQUEST['refundSource'];
         $refundReqest->Memo = "Refunded from Digital Kickstart App";
         /*
         * 
           (Optional) Maximum time until you must retry the refund. 
         */
         //$refundReqest->RetryUntil = $_REQUEST['retryUntil'];
         $refundReq = new PayPal\PayPalAPI\RefundTransactionReq();
         $refundReq->RefundTransactionRequest = $refundReqest;
         /*
          *          ## Creating service wrapper object
         Creating service wrapper object to make API call and loading
         Configuration::getAcctAndConfig() returns array that contains credential and config parameters
         */
         $paypalService = new PayPal\Service\PayPalAPIInterfaceServiceService($config);
         try {
             /* wrap API method calls on the service object with a try catch */
             $refundResponse = $paypalService->RefundTransaction($refundReq);
         } catch (Exception $ex) {
             $error = TRUE;
         }
         // If Split pay then cancel subscription as well
         if ($plan->has_split_pay) {
             $paypal_sub_id = $purchase->paypal_sub_id;
             /*
              * The ManageRecurringPaymentsProfileStatus API operation cancels, suspends, or reactivates a recurring payments profile. 
              */
             $manageRPPStatusReqestDetails = new ManageRecurringPaymentsProfileStatusRequestDetailsType();
             /*
                              *  (Required) The action to be performed to the recurring payments profile. Must be one of the following:
                Cancel – Only profiles in Active or Suspended state can be canceled.
                Suspend – Only profiles in Active state can be suspended.
                Reactivate – Only profiles in a suspended state can be reactivated.
             */
             $manageRPPStatusReqestDetails->Action = 'Cancel';
             /*
              * (Required) Recurring payments profile ID returned in the CreateRecurringPaymentsProfile response.
              */
             $manageRPPStatusReqestDetails->ProfileID = $paypal_sub_id;
             $manageRPPStatusReqest = new ManageRecurringPaymentsProfileStatusRequestType();
             $manageRPPStatusReqest->ManageRecurringPaymentsProfileStatusRequestDetails = $manageRPPStatusReqestDetails;
             $manageRPPStatusReq = new ManageRecurringPaymentsProfileStatusReq();
             $manageRPPStatusReq->ManageRecurringPaymentsProfileStatusRequest = $manageRPPStatusReqest;
             /*
              *   ## Creating service wrapper object
             Creating service wrapper object to make API call and loading
             Configuration::getAcctAndConfig() returns array that contains credential and config parameters
             */
             $paypalService = new PayPalAPIInterfaceServiceService($config);
             try {
                 /* wrap API method calls on the service object with a try catch */
                 $manageRPPStatusResponse = $paypalService->ManageRecurringPaymentsProfileStatus($manageRPPStatusReq);
             } catch (Exception $ex) {
                 $error = TRUE;
             }
             if (isset($manageRPPStatusResponse) and $manageRPPStatusResponse->Ack == 'Success') {
                 // Do nothing
             } else {
                 $error = TRUE;
             }
         }
     }
     if (empty($error) or $force_refund) {
         self::completeRefund($transaction);
         return TRUE;
     }
 }
 /**
  * Change Plan status
  */
 public function getChangePlanStatus($product_id, $plan_id)
 {
     $plan = Plan::where('id', '=', $plan_id)->first();
     $plan->status = $plan->status ? 0 : 1;
     $plan->save();
     Session::flash('alert_message', '<strong>Well done!</strong> You successfully have updated the plan status.');
     return Redirect::to("admin/products/plans/{$product_id}");
 }
 /**
  * Find Transaction
  *
  * Find a transaction by email and plan code
  */
 public function postFindTransaction()
 {
     if ($this->_isValidRequest()) {
         $plan = Input::get('plan');
         $email = Input::get('email');
         if (!$plan) {
             $this->_invalidRequest("Plan parameter is required");
         }
         if (!$email) {
             $this->_invalidRequest("Email parameter is required");
         }
         // Get Plan
         $plan = Plan::where('code', '=', $plan)->first();
         if (!$plan) {
             $this->_invalidRequest("Plan was not found, contact support.");
         }
         // Get buyer
         $buyer = Buyer::where('email', '=', $email)->first();
         if (!$buyer) {
             $this->_invalidRequest("Buyer was not found, contact support.");
         }
         $purchase = Purchase::where('product_id', '=', $plan->product_id)->where('buyer_id', '=', $buyer->id)->first();
         if (!$purchase) {
             $this->_invalidRequest("Purchase was not found, contact support.");
         }
         $transaction = Transaction::where('purchase_id', '=', $purchase->id)->where('plan_id', '=', $plan->id)->first();
         if (!$transaction) {
             $this->_invalidRequest("Transaction was not found, contact support.");
         }
         $transaction = array('id' => $transaction->id, 'amount' => $transaction->amount, 'pay_id' => $transaction->pay_id, 'is_refunded' => $transaction->is_refunded, 'commission_refunded' => $transaction->commission_refunded, 'invoice_id' => $transaction->invoice_id, 'buyer' => array('first_name' => $buyer->first_name, 'last_name' => $buyer->last_name));
         die(json_encode(array('data' => $transaction)));
     }
 }
 /**
  * createUser
  * creates a new User object (and related models)
  * from the POST data
  * --------------------------------------------------
  * @param (array) ($userdata) Array with the user data
  * @return (User) ($user) The new User object
  * --------------------------------------------------
  */
 private function createUser($userdata)
 {
     /* Create new user */
     $user = new User();
     /* Set authentication info */
     $user->email = $userdata['email'];
     $user->password = Hash::make($userdata['password']);
     $user->name = $userdata['name'];
     /* Save the user */
     $user->save();
     /* Create default settings for the user */
     $settings = new Settings();
     $settings->user()->associate($user);
     $settings->newsletter_frequency = 0;
     $settings->background_enabled = true;
     /* Save settings */
     $settings->save();
     /* Create default subscription for the user */
     $plan = Plan::where('name', 'Free')->first();
     $subscription = new Subscription();
     $subscription->user()->associate($user);
     $subscription->plan()->associate($plan);
     $subscription->status = 'active';
     $subscription->current_period_start = Carbon::now();
     $subscription->current_period_end = Carbon::now()->addDays(SiteConstants::getTrialPeriodInDays());
     $subscription->braintree_customer_id = null;
     $subscription->braintree_payment_method_token = null;
     /* Save subscription */
     $subscription->save();
     /* Return */
     return $user;
 }
Beispiel #10
0
 static function getAvailableFEPlans($product_id)
 {
     return Plan::where('product_id', '=', $product_id)->where('is_oto', '=', 0)->where('status', '=', 1)->where('show_at_checkout', '=', 1)->get();
 }
 /**
  * Post OTO for stripe
  */
 public function postStripeOto()
 {
     // Add third party libraries
     require_once app_path() . "/libraries/stripe-php-1.9.0/lib/Stripe.php";
     // Add Stripe library
     Stripe::setApiKey(Config::get('project.stripe_secret_key'));
     $customer_id = Input::get('customer_id');
     $product_id = Input::get('product_id');
     $plan_id = Input::get('plan_id');
     $buyer_id = Input::get('buyer_id');
     $plan = Plan::where('id', '=', $plan_id)->first();
     $buyer = Buyer::where('id', '=', $buyer_id)->first();
     // Update Buyer IP
     Buyer::updateLastIP($buyer);
     try {
         $customer = Stripe_Customer::retrieve($customer_id);
         // If plan is recurring
         if ($plan->is_recurring) {
             // Add new subscription
             $cu->subscriptions->create(array("plan" => $plan->stripe_id));
             // Add Setup Fee
             $customer->account_balance = $plan->setup_fee * 100;
             $customer->save();
         } else {
             // Extract card token
             Stripe_Charge::create(array("amount" => $plan->price * 100, "currency" => "usd", "customer" => $customer_id, "description" => "Charge for {$plan->name} ({$buyer->email})", "metadata" => array("plan_id" => $plan->id)));
         }
     } catch (Exception $e) {
         return Response::make(json_encode(array("error" => true, "message" => "Cannot create charge")));
     }
     return Response::make(json_encode(array("success" => true)));
 }
 /**
  * Stripe IPN
  */
 private function _ipn_stripe()
 {
     // Set your secret key: remember to change this to your live secret key in production
     // See your keys here https://manage.stripe.com/account
     // Add Stripe library
     require_once app_path() . "/libraries/stripe-php-1.9.0/lib/Stripe.php";
     // Add Stripe library
     Stripe::setApiKey(Config::get('project.stripe_secret_key'));
     // Retrieve the request's body and parse it as JSON
     $body = @file_get_contents('php://input');
     $event_json = json_decode($body);
     // For extra security, retrieve from the Stripe API
     try {
         $event_id = $event_json->id;
         $event_json = Stripe_Event::retrieve($event_id);
     } catch (Exception $e) {
         exit($e->getMessage());
     }
     // Do something with $event_json
     if (isset($event_json->type)) {
         // Customer and Affiliate
         // Get user_id
         $customer_id = !empty($event_json->data->object->customer) ? $event_json->data->object->customer : NULL;
         if ($customer_id) {
             try {
                 $customer = Stripe_Customer::retrieve($customer_id);
                 $email = $customer->email;
                 $dkData = $customer->metadata;
                 $buyer = Buyer::where('email', '=', $email)->first();
                 $affiliate_id = !empty($dkData['affiliate_id']) ? $dkData['affiliate_id'] : NULL;
                 // $buyer->affiliate_id
                 $first_name = !empty($dkData['first_name']) ? $dkData['first_name'] : NULL;
                 $last_name = !empty($dkData['last_name']) ? $dkData['last_name'] : NULL;
                 // Get Product Info
                 $product = Product::where('id', '=', $dkData['product_id'])->first();
             } catch (Exception $e) {
                 header('HTTP/1.1 400 Bad Request', true, 400);
                 exit("Not able to fetch customer");
             }
         } else {
             // No customer ID was found, stop the process here
             exit('Customer was not found in object');
         }
         // If No buyer was found
         if (empty($buyer)) {
             exit($event_json->type . ' : Buyer was not found');
         }
         // If No product was found
         if (empty($product)) {
             exit($event_json->type . ' : Product was not found');
         }
         // Create subscription
         if ($event_json->type == "customer.subscription.created") {
             $plan_code = $event_json->data->object->plan->id;
             // Remove word "_split" from it
             $plan_code = str_replace('_split', '', $plan_code);
             // Get Plan and Product
             $plan = Plan::where('stripe_id', '=', $plan_code)->first();
             // Push IPN to product IPN URL
             $ipn_data = array("type" => "sales", "password" => isset($dkData['password']) ? $dkData['password'] : NULL, "plan" => $plan->code, "amount" => $plan->price, "email" => $email, "first_name" => $first_name, "last_name" => $last_name);
             // Add an encrypted key to the request
             $ipn_data['key'] = $this->_generateHash($ipn_data, $product->api_key);
             $this->_push_ipn($product->ipn_url, $ipn_data);
         }
         // Successful Charge
         if ($event_json->type == "charge.succeeded") {
             // Delay 10 seconds, so purchase can be added to database
             sleep(10);
             $pay_id = $event_json->data->object->id;
             $paid_amount = $event_json->data->object->amount / 100;
             // Check if Pay ID already exist
             if (Transaction::where('pay_id', '=', $pay_id)->first()) {
                 echo "Transaction was already recorded.";
                 return;
             }
             $chargeMetadata = $event_json->data->object->metadata;
             if (empty($chargeMetadata->plan_id)) {
                 $plan_id = $dkData['plan_id'];
             } else {
                 $plan_id = !empty($chargeMetadata->plan_id) ? $chargeMetadata->plan_id : NULL;
             }
             // Get Plan and Product
             $plan = Plan::where('id', '=', $plan_id)->first();
             $purchase = Purchase::where('product_id', '=', $product->id)->where('buyer_id', '=', $buyer->id)->first();
             if (!$purchase) {
                 header('HTTP/1.1 400 Bad Request', true, 400);
                 echo "Purchase was not found";
                 // Delete InfusionSoft Invoice
                 //$this->_delete_infusion_invoice($invoice_id);
                 return;
             }
             // User all transactions
             $user_transactions = Transaction::where('purchase_id', '=', $purchase->id)->where('plan_id', '=', $plan->id)->get();
             // If Split payment installment is received
             if ($plan->has_split_pay) {
                 if (count($user_transactions) + 1 >= $plan->total_installments) {
                     // Cancel the subscription
                     $params['stripe_customer_id'] = $customer_id;
                     $params['plan_id'] = $plan->stripe_id . '_split';
                     Log::info('Stripe Split Not Cancelled', array('product' => $product->code, 'plan' => $plan->code));
                     $this->_cancelSubscription('Stripe', $params);
                 }
             }
             // Add payment in InfusionSoft
             if ($invoice_id = $this->_infusion_sales($product, $plan, $email, $first_name, $last_name, $affiliate_id, $paid_amount)) {
                 if (!$buyer->last_used_ip) {
                     $buyer = Buyer::where('id', '=', $buyer->id)->first();
                 }
                 // Record Sales Transaction
                 $transaction = new Transaction();
                 $transaction->purchase_id = $purchase->id;
                 $transaction->plan_id = $plan->id;
                 $transaction->amount = $paid_amount;
                 //$plan->price;
                 $transaction->invoice_id = $invoice_id;
                 $transaction->pay_id = $pay_id;
                 $transaction->pay_data = '';
                 //json_encode($event_json);
                 $transaction->buyer_ip = $buyer->last_used_ip;
                 $transaction->save();
                 // Do not generate license key if this is recurring charge
                 $license_key = NULL;
                 if (count($user_transactions) + 1 === 1) {
                     // Generate and Save License Key
                     $license_key = $this->_generate_license($product, $plan, $transaction->id);
                 }
                 // Email Receipt
                 $this->_send_email_receipt($product->name, $plan->name, $email, $pay_id, $paid_amount, $license_key);
             }
             // Push IPN to product IPN URL
             $ipn_data = array("type" => "sales", "password" => isset($dkData['password']) ? $dkData['password'] : NULL, "plan" => $plan->code, "pay_id" => $event_json->data->object->id, "amount" => $plan->price, "email" => $email, "first_name" => $first_name, "last_name" => $last_name);
             // Add an encrypted key to the request
             $ipn_data['key'] = $this->_generateHash($ipn_data, $product->api_key);
             $this->_push_ipn($product->ipn_url, $ipn_data);
         }
         // Update subscription
         if ($event_json->type == "customer.subscription.updated") {
             // $event_json->data->object->cancel_at_period_end
             $stripe_plan_code = $event_json->data->object->plan->id;
             // Remove word "_split" from it
             $stripe_plan_code = str_replace('_split', '', $stripe_plan_code);
             $plan = Plan::where('stripe_id', '=', $stripe_plan_code)->first();
             // Update Customer Metadata in Stripe
             try {
                 $metadata = $customer->metadata;
                 $metadata['plan_id'] = $plan->id;
                 $customer->metadata = $metadata;
                 $customer->save();
             } catch (Exception $e) {
                 header('HTTP/1.1 400 Bad Request', true, 400);
                 echo "Customer was not update";
                 return;
             }
             // Push to IPN
             $ipn_data = array("type" => "sub-update", "plan" => $plan->code, "email" => $buyer->email);
             // Add an encrypted key to the request
             $ipn_data['key'] = $this->_generateHash($ipn_data, $product->api_key);
             $this->_push_ipn($product->ipn_url, $ipn_data);
         }
         // Delete Subscription
         if ($event_json->type == "customer.subscription.deleted") {
             $stripe_plan_code = $event_json->data->object->plan->id;
             // Remove word "_split" from it
             $stripe_plan_code = str_replace('_split', '', $stripe_plan_code);
             $plan = Plan::where('stripe_id', '=', $stripe_plan_code)->first();
             // If Split payment installment is received
             if ($plan->has_split_pay) {
                 $purchase = Purchase::where('product_id', '=', $product->id)->where('buyer_id', '=', $buyer->id)->first();
                 $total_paid_installments = Transaction::where('purchase_id', '=', $purchase->id)->where('plan_id', '=', $plan->id)->get();
                 if (count($total_paid_installments) >= $plan->total_installments) {
                     // Do not push IPN, its fine user has paid all installments
                     Log::info('Stripe Split Cancelled', array('product' => $product->code, 'plan' => $plan->code));
                     return;
                 }
             }
             // Push to IPN
             $ipn_data = array("type" => "sub-cancel", "plan" => $plan->code, "email" => $buyer->email);
             // Add an encrypted key to the request
             $ipn_data['key'] = $this->_generateHash($ipn_data, $product->api_key);
             $this->_push_ipn($product->ipn_url, $ipn_data);
         }
         // Charge Failed
         if ($event_json->type == "charge.failed") {
             // Charge failed, ask customer to update card via email
             // @TODO: Ask Mark to enable some tries after failure
         }
         // Charge refunded
         if ($event_json->type == "charge.refunded") {
             // Check if transaction has not been refunded from UI, then go ahead
             // Else stop process
             $pay_id = $event_json->data->object->id;
             $transaction = Transaction::where('pay_id', '=', $pay_id)->first();
             if ($transaction->is_refunded) {
                 return;
             }
             // Push to IPN
             $ipn_data = array("type" => "refund", "plan" => $transaction->plan->code, "email" => $buyer->email);
             // Add an encrypted key to the request
             $ipn_data['key'] = $this->_generateHash($ipn_data, $product->api_key);
             $this->_push_ipn($product->ipn_url, $ipn_data);
         }
         if (isset($error)) {
             header('HTTP/1.1 400 Bad Request', true, 400);
             echo "Unsuccessful event";
             return;
         }
     }
 }
 /**
  * Display the specified resource.
  * GET /members/{id}
  *
  * @param  int  $id
  * @return Response
  */
 public function show($team, $id)
 {
     setlocale(LC_MONETARY, "en_US");
     $user = Auth::user();
     $club = $user->Clubs()->FirstOrFail();
     $member = Member::find($id);
     $player = Player::Find($member->player_id);
     $title = 'League Together - ' . $club->name . ' Teams';
     $team = Team::where("id", "=", $team)->where("club_id", '=', $club->id)->FirstOrFail();
     $plan = Plan::where("member_id", "=", $member->id)->with("schedulepayments")->First();
     if (isset($plan)) {
         //$plan = Plan::where("member_id", "=",$member->id)->with("schedulepayments")->FirstOrFail();
         return View::make('pages.user.club.member.show')->with('page_title', $title)->with('team', $team)->with('member', $member)->with('player', $player)->with('plan', $plan)->withUser($user);
     } else {
         return View::make('pages.user.club.member.show')->with('page_title', $title)->with('team', $team)->with('member', $member)->with('player', $player)->withUser($user);
     }
 }