/** * 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 . '¶m=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 . '¶m=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'); } } }
/** * Update the specified resource in storage. * PUT /transactions/{id} * * @param int $id * @return Response */ public function update($id) { $transactions = Transaction::where('id', $id)->update(Input::all()); if ($transactions) { return ['status' => true, 'data' => $transactions]; } else { return ['status' => false]; } }
public function reservation($id) { $reservation = Reservation::findOrFail($id); if ($this->user->id == $reservation->user_id) { $transaction = Transaction::where('reservation_id', $reservation->id)->first(); $pdf = storage_path() . '/reservations/reservation-' . $transaction->reference_number . '.pdf'; if (file_exists($pdf)) { return Response::download($pdf); } else { return Redirect::to('clients')->with('error', 'PDF was not found.'); } } else { return App::abort(404); } }
} $view->with('data', $data)->with('moneyAvailable', $userMoneyAvailable)->with('lastInvest', $lastInvest); }); View::creator('backend.user.withdraw', function ($view) { $uid = Auth::user()->id; $user = User::where('id', '=', $uid)->first(); $totalAdded = $user->userMoney->ammount_added; $totalInvested = $user->userMoney->ammount_invested; $totalRewarded = $user->userMoney->ammount_won; $totalWithdrawn = $user->userMoney->ammount_withdrawn; $userMoneyAvailable = $totalAdded + $totalRewarded - ($totalInvested + $totalWithdrawn); $view->with('moneyAvailable', $userMoneyAvailable); }); View::creator('includes.backend.cycles', function ($view) { $uid = Auth::user()->id; $lastInvest = Transaction::where('user_id', '=', $uid)->where('transaction_direction', '=', 'invested')->orderBy('id', 'DESC')->first(); $amount = 0; if ($lastInvest) { $amount = $lastInvest->ammount; } $view->with('lastInvestedAmmount', $amount); }); View::creator('homepage', function ($view) { $blocks = Block::all(); // TODO: Improve this part. Add validation. foreach ($blocks as $block) { $block->content = json_decode($block->content); } $view->with('blocks', $blocks); }); App::missing(function ($exception) {
public function relatorios() { $data = Input::all(); if (!isset($data['view'])) { $data['view'] = 'month'; } if (!isset($data['date_from'])) { $data['date_from'] = date('Y-m-d'); } // NAVIGATION if (!isset($data['next'])) { $data['next'] = 0; } if (!isset($data['prev'])) { $data['prev'] = 0; } if (@$data['next'] == @$data['prev']) { $data['next'] = $data['prev'] = 0; } // echo "<pre>"; // print_r($data); // echo "</pre>"; // exit; //MESSAGES $info = array(); /* FILTROS DE EXIBIÇÃO */ switch ($data['view']) { case 'day': $view = "transactions.views.day"; $date = Carbon::createFromFormat('Y-m-d', $data['date_from'])->addDays($data['next'])->subDays($data['prev']); $transactions = Transaction::where('date', $date->format('Y-m-d'))->where('user_id', Auth::id())->orderBy('date')->get(); if ($date->isToday()) { $title = "hoje"; $labels['end'] = 'fim do dia'; } else { if ($date->isTomorrow()) { $title = "amanhã"; $labels['end'] = 'depois de amanhã'; } else { if ($date->isYesterday()) { $title = "ontem"; $labels['end'] = 'hoje'; } else { $title = strftime("%d de %B", strtotime($date)); $labels['end'] = strftime("%A, %d de %B", strtotime($date->addDay())); } } } break; case 'week': $view = "transactions.views.week"; $date = Carbon::createFromFormat('Y-m-d', $data['date_from'])->addWeeks($data['next'])->subWeeks($data['prev']); $transactions = Transaction::where('date', '>=', $date->startOfWeek()->format('Y-m-d'))->where('date', '<=', $date->endOfWeek()->format('Y-m-d'))->where('user_id', Auth::id())->orderBy('date')->get(); $title = strftime("%a %d/%m", strtotime($date->startOfWeek())) . " à " . strftime("%a %d/%m", strtotime($date->endOfWeek())); $labels['end'] = strftime("%A, %d de %B", strtotime($date->endOfWeek()->addDay())); break; case 'range': $view = "transactions.views.index"; $transactions = Transaction::where('date', '>=', $data['date_from'])->where('date', '<=', $data['date_to'])->where('user_id', Auth::id())->orderBy('date')->get(); $date = Carbon::createFromFormat('Y-m-d', @$data['date_to']); $title = strftime("%d de %B", strtotime($data['date_from'])) . " à " . strftime("%d de %B", strtotime(@$data['date_to'])); $labels['end'] = strftime("%A, %d de %B", strtotime($date)); break; case 'overdue': $view = "transactions.views.overdue"; $date = Carbon::now(); $transactions = Transaction::where('done', 0)->where('date', '<', $date->format('Y-m-d'))->orderBy('date')->where('user_id', Auth::id())->get(); if (count($transactions) <= 0) { $info[] = ['class' => 'alert-success', 'message' => "Nenhum lançamento pendente. Muito bem!"]; } else { $info[] = ['class' => 'alert-warning', 'message' => '<strong><i class="fa fa-warning"></i></strong> Você tem <strong>' . count($transactions) . '</strong> lançamentos pendentes.']; } $title = "pendentes"; $labels['end'] = strftime("%d de %B", strtotime($date)); break; default: // case 'month': $view = "transactions.views.month"; $date = Carbon::createFromFormat('Y-m-d', $data['date_from'])->addMonths($data['next'])->subMonths($data['prev']); $transactions = Transaction::where('date', '>=', $date->startOfMonth()->format('Y-m-d'))->where('date', '<=', $date->endOfMonth()->format('Y-m-d'))->where('user_id', Auth::id())->orderBy('date', 'DESC')->get(); $title = strftime("%B de %Y", strtotime($date)); $labels['end'] = "fim de " . strftime("%B", strtotime($date)); break; } // STATUS NO PERÍODO $receitas = $transactions->filter(function ($transaction) { if ($transaction->type == 'receita') { return $transaction; } }); $receitas_ok = $receitas->filter(function ($transaction) { if ($transaction->done == '1') { return $transaction; } }); $despesas = $transactions->filter(function ($transaction) { if ($transaction->type == 'despesa') { return $transaction; } }); $despesas_ok = $despesas->filter(function ($transaction) { if ($transaction->done == '1') { return $transaction; } }); $balance['receitas'] = $receitas->sum('amount'); $balance['receitas_ok'] = $receitas_ok->sum('amount'); $balance['despesas'] = $despesas->sum('amount'); $balance['despesas_ok'] = $despesas_ok->sum('amount'); $balance['saldo'] = $transactions->sum('amount'); // SALDO NO PERÍODO // SALDO ATUAL $balance['saldo_atual'] = Transaction::where('done', 1)->where('date', '<=', date('Y-m-d'))->where('user_id', Auth::id())->sum('amount'); // echo '<pre>'; // print_r( $balance ); // exit; $transactionsOverdue = Transaction::where('done', "!=", 1)->where('date', '<', date('Y-m-d'))->where('user_id', Auth::id())->orderBy('date')->get(); if (count($transactionsOverdue) > 0 && $data['view'] != 'overdue') { $info[] = ['class' => 'alert-warning', 'message' => '<strong><i class="fa fa-warning"></i></strong> Você tem <strong>' . count($transactionsOverdue) . '</strong> lançamentos pendentes. <a href="' . url("financeiro/lancamentos?view=overdue") . '" class="">Ver lançamentos</a>']; } Session::flash('info', $info); // AGRUPA POR DIA $transactions_days = $transactions->groupBy(function ($transaction) { return $transaction->date; }); // echo "<pre>"; // print_r($transactions_days); // echo "</pre>"; // exit; /* DADOS PRA NAVEGAÇÃO */ $navigation = array(); $view = 'transactions.novo.relatorios'; return View::make($view, compact('transactions', 'transactions_days', 'view', 'title', 'data', 'balance', 'labels')); }
<a href="{{url('tarefas')}}" class="btn btn-link tarefas-info"> <i class="fa fa-check-square-o fa-2x"></i> <?php $tarefas_info = count(Tarefa::where('done', 0)->where('date', '<=', date('Y-m-d'))->get()); ?> @if ($tarefas_info) <span class="badge badge-danger">{{ $tarefas_info }}</span> @endif </a> <a href="{{url('financeiro')}}" class="btn btn-link transactions_info"> <i class="icon-dollar fa-2x"></i> <?php $transactions_info = count(Transaction::where('done', 0)->where('date', '<=', date('Y-m-d'))->where('user_id', Auth::id())->get()); ?> @if ($transactions_info) <span class="badge badge-danger">{{ $transactions_info }}</span> @endif </a> </div> </div> <a id="logo" class="pull-right hidden-xs" href="<?php echo url('/');
/** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { $transaction = Transaction::where('id', '=', $id)->first(); $transaction->delete(); return Response::json(array('message' => 'transaction deleted'), 200); }
public function postOpensession() { $outlet = Input::get('outlet_id'); $open_session = Transaction::where('outletId', $outlet)->where('sessionStatus', 'open')->distinct('sessionId')->get()->toArray(); $open_sessions = array(); foreach ($open_session as $op) { $open_sessions[] = $op[0]; } $result = array('opensession' => $open_sessions, 'result' => 'OK'); return Response::json($result); }
/** * Execute the console command. * * @return mixed */ public function fire() { $users = User::all(); foreach ($users as $user) { $dateInvested = new DateTime($user->invested_date); $days = Config::get('rate.days'); $dateInvested->modify('+' . $days . ' days'); $formattedDate = $dateInvested->format('Y-m-d H:i:s'); $currentDate = date('Y-m-d H:i:s'); if ($formattedDate <= $currentDate) { $transactions = Transaction::where('user_id', '=', $user->id)->where('transaction_direction', '=', 'invested')->get(); $transactionsCount = count($transactions); if (count($transactions) == 0) { $ammount = 0; } else { $ammount = $transactions[$transactionsCount - 1]->ammount; } if ($user->investor == 0 || $user->investor == 1 && $ammount < 1000) { $lastInvest = Transaction::where('user_id', '=', $user->id)->where('transaction_direction', '=', 'invested')->orderBy('id', 'DESC')->first(); $reward = new Transaction(); $reward->ammount = Helper::reward($ammount, $user->cycle_duration, $user->investment_rate); $reward->transaction_direction = 'reward'; $reward->user_id = $user->id; $reward->confirmed = 1; $reward->date = date('Y-m-d H:i:s'); $reward->save(); $user->investor = 1; $user->awarded = 1; $user->awaiting_award = 0; $user->invested_date = NULL; $user->cycle_duration = NULL; $user->investment_rate = 0; $user->save(); $user->userMoney->current_available += $reward->ammount + $lastInvest->ammount; $user->userMoney->times_won++; $user->userMoney->ammount_won += $reward->ammount; $user->userMoney->save(); } elseif ($user->investor == 1) { $offer = Offer::where('recipient_id', '=', $user->id)->orderBy('id', 'DESC')->first(); if ($offer != null) { $rate = $offer->daily_rate; } else { $rate = $user->investment_rate; } $lastInvest = Transaction::where('user_id', '=', $user->id)->where('transaction_direction', '=', 'invested')->orderBy('id', 'DESC')->first(); $reward = new Transaction(); $reward->ammount = Helper::reward($ammount, $user->cycle_duration, $rate); $reward->transaction_direction = 'reward'; $reward->user_id = $user->id; $reward->confirmed = 1; $reward->date = date('Y-m-d H:i:s'); $reward->save(); $user->awarded = 1; $user->awaiting_award = 0; $user->invested_date = NULL; $user->cycle_duration = NULL; $user->investment_rate = 0; $user->save(); $user->userMoney->current_available += $reward->ammount + $lastInvest->ammount; $user->userMoney->times_won++; $user->userMoney->ammount_won += $reward->ammount; $user->userMoney->save(); } } } }
private function getUnactionedLoanCount() { $newLoans = Loan::where('status_id', 1)->get()->toArray(); foreach ($newLoans as $index => $loan) { $transactions = Transaction::where('loan_id', $loan['id'])->where('user_id', '!=', $loan['user_id'])->get()->toArray(); if (isset($transactions[0])) { // Remove this loan unset($newLoans[$index]); } } return array('unactionedLoanCount' => count($newLoans)); }
private function saveFee($new_transaction) { $tx_hash = $new_transaction->tx_id; /* get for that transaction a miners fee, at this point we know it already */ Queue::push(function ($job) use($tx_hash) { // get_transaction from bitcoin core $tx_info = $this->bitcoin_core->gettransaction($tx_hash); $fee = isset($tx_info['fee']) ? abs(bcmul($tx_info['fee'], SATOSHIS_FRACTION)) : null; // save fee for that transaction hash Transaction::where('tx_id', $tx_hash)->update(['network_fee' => $fee]); $job->delete(); }); }
/** * 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))); } }
public function usersListNext() { $sortby = Input::get('sortby'); $order = Input::get('order'); $controller = 'usersListNext'; if ($sortby && $order) { $users = User::where('users.investor', '=', 1)->where('users.role', '=', 2)->where('users.investor', '=', 1)->where('users.awaiting_award', '=', 0)->join('user_money_info', 'users.id', '=', 'user_money_info.id')->orderBy($sortby, $order)->get(); } else { $users = User::where('users.investor', '=', 1)->where('users.role', '=', 2)->where('users.investor', '=', 1)->where('users.awaiting_award', '=', 0)->join('user_money_info', 'users.id', '=', 'user_money_info.id')->get(); } foreach ($users as $key => $user) { $lastTransaction = Transaction::where('user_id', '=', $user->id)->where('ammount', '>=', '1000')->where('confirmed', '=', 0)->where('transaction_direction', '=', 'invested')->first(); $lastOffer = count($user->userOffer); if ($lastOffer == 0) { $lastOffer = null; } else { $lastOffer = $user->userOffer[$lastOffer - 1]->offer_ends; } $currentDate = date('Y-m-d H:i:s'); if ($lastTransaction == null && ($lastOffer == null || $currentDate < $lastOffer)) { unset($users[$key]); } if ($lastOffer != null && $currentDate < $lastOffer) { unset($users[$key]); } } return View::make('backend.admin.userslist', ['users' => $users, 'controller' => $controller, 'sortby' => $sortby, 'order' => $order]); }
/** * Check if user has already purchase the plan */ private function _check_already_purchase($buyer_email, $product, $plan) { // Get Buyer $buyer = Buyer::where('email', '=', $buyer_email)->first(); if ($buyer) { $purchase = Purchase::where('buyer_id', '=', $buyer->id)->first(); if ($purchase) { if ($transaction = Transaction::where('purchase_id', '=', $purchase->id)->where('plan_id', '=', $plan->id)->where('is_refunded', '=', 0)->first()) { // Redirect to next page header("location: " . $plan->next_page_url); exit; } } } }
public function investMoney() { $uid = Auth::user()->id; // Check for custom offer. $lastTransaction = Transaction::where('user_id', '=', $uid)->where('transaction_direction', '=', 'invested')->where('ammount', '>=', '1000')->orderBy('created_at', 'DESC')->first(); // Approve offer. if ($lastTransaction != null && $lastTransaction->confirmed == 0) { $lastTransaction->confirmed = 1; $lastTransaction->date = date('Y-m-d H:i:s'); $user = User::where('id', '=', $uid)->first(); $user->awaiting_award = 1; $user->invested_date = date('Y-m-d H:i:s'); $user->cycle_duration = Config::get('rate.days'); $user->investment_rate = Config::get('rate.rate'); $user->userMoney->ammount_invested += $lastTransaction->ammount; $user->userMoney->current_available -= $lastTransaction->ammount; $user->userMoney->times_invested++; $user->userMoney->save(); $user->save(); $lastTransaction->user_id = $uid; $lastTransaction->save(); $user = Auth::user(); $data = MailHelper::prepareData($user); $data += ['ammount' => $lastTransaction->ammount]; Mail::send('emails.invested', $data, function ($message) use($user) { $message->to($user->email)->subject('Successful transfer!'); }); return Redirect::back(); } elseif (Input::get('ammount') > Input::get('moneyAvailable')) { return Redirect::to('user/addmoney')->with('msg', "You don't have enough money to invest."); } else { // Input validation. $rules = ['ammount' => ['required', 'numeric', 'min:' . Config::get('rate.min')]]; $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator); } $transaction = new Transaction(); $transaction->ammount = Input::get('ammount'); $transaction->transaction_direction = 'invested'; if (Auth::user()->investor == 1 && Input::get('ammount') < 1000) { $user = User::where('id', '=', $uid)->first(); $transaction->confirmed = 1; $user->userMoney->ammount_invested += Input::get('ammount'); $user->userMoney->current_available -= Input::get('ammount'); $user->userMoney->times_invested++; $user->userMoney->save(); $transaction->date = date('Y-m-d H:i:s'); $user = User::where('id', '=', $uid)->first(); $user->awaiting_award = 1; $user->invested_date = date('Y-m-d H:i:s'); $user->cycle_duration = Config::get('rate.days'); $user->investment_rate = Config::get('rate.rate'); $user->save(); } elseif (Auth::user()->investor == 1) { $transaction->confirmed = 0; } else { $user = User::where('id', '=', $uid)->first(); $transaction->confirmed = 1; $user->userMoney->ammount_invested += Input::get('ammount'); $user->userMoney->current_available -= Input::get('ammount'); $user->userMoney->times_invested++; $user->userMoney->save(); $transaction->date = date('Y-m-d H:i:s'); $user = User::where('id', '=', $uid)->first(); $user->awaiting_award = 1; $user->invested_date = date('Y-m-d H:i:s'); $user->cycle_duration = Config::get('rate.days'); $user->investment_rate = Config::get('rate.rate'); $user->save(); } $transaction->user_id = $uid; $transaction->save(); $user = Auth::user(); $data = MailHelper::prepareData($user); $data += ['ammount' => $transaction->ammount, 'invested' => 'pending']; Mail::send('emails.invested', $data, function ($message) use($user) { $message->to($user->email)->subject('Successful transfer!'); }); return Redirect::back(); } }
/** * 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; } } }