/** * Display customer profile * * @param $profile * @return Response */ public function show($profile) { $p = User::where('profile_url', '=', $profile)->where('approved', '=', '0')->first(); $page = Page::where('title', '=', 'faq-customer')->first(); $follow = Follow::where('user', $p->id)->where('hub', '=', 0)->get(); $follow_hub = Follow::where('user', $p->id)->where('artist', '=', 0)->get(); $wall = new \Illuminate\Database\Eloquent\Collection(); $events = new \Illuminate\Database\Eloquent\Collection(); $comments = Comment::where('user', '=', $p->id)->orderBy('created_at', 'desc')->get(); $hidden = unserialize(Cookie::get('hide')); //dd( Cookie::get('hide') ); if (count($follow) > 0) { foreach ($follow as $f) { $s = Song::where('artist', '=', $f->artist)->where('completed', '=', '1')->get(); $e = ArtistEvent::where('artist', '=', $f->artist)->where('date', '>', \Carbon\Carbon::now())->get(); $wall = $wall->merge($s); $events = $events->merge($e); } } if (count($follow_hub) > 0) { foreach ($follow_hub as $h) { $hub = Hub::where('id', '=', $h->hub)->first(); if (!is_null($hub)) { $artists = User::where('type', '=', 'artist')->where('hub', '=', $hub->id)->get(); $artists_list = []; $songs = []; $events = []; foreach ($artists as $a) { $artists_list[] = $a->id; } if (count($artists_list) > 0) { $songs = Song::where('completed', '=', '1')->whereIn('artist', $artists_list)->orderBy('created_at', 'desc')->get(); $events = ArtistEvent::whereIn('artist', $artists_list)->get(); } $news = News::where('hub', '=', $hub->id)->take(3)->get(); $wall = $wall->merge($songs); $events = $events->merge($events); } } } $purchased = Purchase::where('customer', '=', $p->id)->get(); foreach ($purchased as $pp) { $song_purchased = Song::withTrashed()->where('id', '=', $pp->song)->get(); $download = Download::where('customer', '=', $p->id)->where('song', '=', $pp->song)->first(); $song_purchased[0]->purchased = true; if (isset($download)) { $song_purchased[0]->link = $download->url; } $wall = $wall->merge($song_purchased); } $wall->sortByDesc('created_at'); if (!isset($news)) { $news = null; } return View::make('customer.profile-new', ['profile' => $p, 'wall' => $wall, 'page' => $page, 'events' => $events, 'comments' => $comments, 'hidden' => $hidden, 'news' => $news]); }
public static function boot() { parent::boot(); static::deleted(function ($supplier) { $supplier->purchases()->delete(); $purchases = Purchase::where('supplier_id', '=', $supplier->id); dd($purchases); $purchases->items()->detach(); $purchases->receivings()->delete(); $purchases->payments()->delete(); }); }
/** * Devuelve la cantidad involucrada en compras pendientes. * @param Branche $branch * @return integer $cantidad */ public function inPurchases($branch) { $purchasesPendientes = Purchase::where('status', '=', 'pendiente')->where('branch_id', '=', $branch->id)->get(); $cantidad = 0; foreach ($purchasesPendientes as $purchase) { foreach ($purchase->purchaseItems as $item) { if ($this->id == $item->article->id) { $cantidad += $item->amount; } } } return $cantidad; }
public function getFilterById() { $TIPO_REMISION = self::TIPO_REMISION; $title = 'Compra'; $input = Input::all(); $purchases = Purchase::where('id', '=', $input['idRemision'])->orderBy('id', 'desc')->paginate(6); $mensaje = 'Compra con código ' . $input['idRemision'] . '</strong>'; return View::make('purchases.index')->with(compact('title', 'purchases', 'mensaje', 'input', 'TIPO_REMISION')); }
/** * 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; } }
/** * Show artist profile * * return @Response */ public function showprofile($user) { $profile = User::where('profile_url', '=', $user)->where('approved', '=', '0')->where('deleted_at', '=', null)->first(); if (!is_null($profile)) { $activation = Activation::where('user', '=', $profile->id)->first(); $page = Page::where('title', '=', 'faq-artist')->first(); $transactions = Purchase::where('artist', '=', $profile->id)->get(); if ($activation) { return View::make('artist.not-activated'); } else { if ($profile) { if ($profile->active == 1) { $songs = Song::where('artist', '=', $profile->id)->where('completed', '=', '1')->orderBy('id', 'desc')->paginate(10); $bundles = Bundle::where('artist', '=', $profile->id)->get(); $wall = new \Illuminate\Database\Eloquent\Collection(); $wall = $wall->merge($songs); $wall = $wall->merge($bundles); //dd($wall); $followers = Follow::where('artist', '=', $profile->id)->get(); $countries = []; foreach ($followers as $f) { if (empty($f->profile->country)) { $f->profile->country = 'Country unknown'; } if (isset($countries[$f->profile->country])) { $countries[$f->profile->country]++; } else { $countries[$f->profile->country] = 1; } } $events = ArtistEvent::where('artist', '=', $profile->id)->where('date', '>', \Carbon\Carbon::now())->orderBy('id', 'desc')->take(3)->get(); $songs_in = []; foreach ($songs as $s) { $songs_in[] = $s->id; } if (count($songs_in) > 0) { $comments = Comment::whereIn('song', $songs_in)->orderBy('id', 'desc')->take(3)->get(); } else { $comments = ""; } $wall->sortByDesc('created_at'); //dd($wall); $notifications = MyNotification::where('user', '=', $profile->id)->get(); return View::make('artist.profile-new', ['profile' => $profile, 'songs' => $songs, 'events' => $events, 'comments' => $comments, 'notifications' => $notifications, 'wall' => $wall, 'page' => $page, 'transactions' => $transactions, 'countries' => $countries]); } else { return Redirect::to('profile/settings'); } } else { App::abort(404); } } } else { App::abort(404); } }
public function create_submit() { //Image Upload $users = DB::table('users')->get(); $purchasecheck = DB::table('purchase_request')->count(); if ($purchasecheck != 0) { $purchase = Purchase::orderby('id', 'DESC')->first(); $docs = Document::orderby('id', 'DESC')->first(); $pr_id = $purchase->id + 1; $doc_id = $docs->id + 1; } else { $pr_id = 1; $doc_id = 1; } foreach (Input::file('file') as $file) { $rules = array('file' => 'required|mimes:png,gif,jpeg,jpg|max:900000000000000000000'); $validator = \Validator::make(array('file' => $file), $rules); $destine = public_path() . "/uploads"; if ($validator->passes()) { $ext = $file->guessClientExtension(); // (Based on mime type) $ext = $file->getClientOriginalExtension(); // (Based on filename) $filename = $file->getClientOriginalName(); $archivo = value(function () use($file) { $filename = str_random(10) . '.' . $file->getClientOriginalExtension(); return strtolower($filename); }); $archivo = value(function () use($file) { $date = date('m-d-Y-h-i-s', time()); $filename = $date . "-" . $file->getClientOriginalName(); return strtolower($filename); }); $attach = new Attachments(); $attach->doc_id = $doc_id; $attach->data = $archivo; $attach->save(); $filename = $doc_id . "_" . $attach->id; $file->move($destine, $archivo); $target_folder = $destine; $upload_image = $target_folder . "/" . $archivo; $thumbnail = $target_folder . "/resize" . $archivo; $actual = $target_folder . "/" . $archivo; // THUMBNAIL SIZE list($width, $height) = getimagesize($upload_image); $newwidth = $width; $newheight = $height; while ($newheight > 525) { $newheight = $newheight * 0.8; $newwidth = $newwidth * 0.8; } $source = $upload_image; $ext = strtolower($ext); $thumb = imagecreatetruecolor($newwidth, $newheight); if ($ext == "jpg" || $ext == "jpeg") { $source = imagecreatefromjpeg($upload_image); } elseif ($ext == "png") { $source = imagecreatefrompng($upload_image); } elseif ($ext == "gif") { $source = imagecreatefromgif($upload_image); } else { continue; } // RESIZE imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // MAKE NEW FILES if ($ext == "jpg" || $ext == "jpeg") { imagejpeg($thumb, $thumbnail, 100); } elseif ($ext == "png") { imagepng($thumb, $thumbnail, 9); } elseif ($ext == "gif") { imagegif($thumb, $thumbnail, 100); } else { echo "An invalid image"; } unlink($actual); // FILE RENAMES rename($thumbnail, $actual); } else { $errors = $validator->errors(); Session::put('imgerror', 'Invalid file.'); } } //End Image Upload $purchase = new Purchase(); $document = new Document(); $purchase->projectPurpose = strip_tags(Input::get('projectPurpose')); $purchase->sourceOfFund = strip_tags(Input::get('sourceOfFund')); $purchase->amount = Input::get('amount'); $purchase->office = Input::get('office'); $purchase->requisitioner = Input::get('requisitioner'); if (!Input::get('dateRequested') == '') { $purchase->dateRequested = Input::get('dateRequested'); } $purchase->dateReceived = Input::get('dateReceived'); $purchase->status = 'Active'; $purchase->otherType = Input::get('otherType'); // Get latest control number $cn = Input::get('controlNo'); $checkUniqueControlNo = Purchase::where('controlNo', '=', "{$cn}")->count(); if ($checkUniqueControlNo != 0) { $purchase->controlNo = ''; } else { $purchase->controlNo = Input::get('controlNo'); } if (Input::get('otherType') == 'Pakyaw') { $purchase->projectType = "None"; } else { $purchase->projectType = Input::get('projectType'); } // Set creator id $user_id = Auth::user()->id; $purchase->created_by = $user_id; $purchase_save = $purchase->save(); if ($purchase_save && (Session::get('imgerror') == NULL || !Input::hasfile('file'))) { $document->pr_id = $purchase->id; $document->work_id = Input::get('hide_modeOfProcurement'); $document_save = $document->save(); if ($document_save) { $doc_id = $document->id; $workflow = Workflow::find($document->work_id); $section = Section::where('workflow_id', $document->work_id)->orderBy('section_order_id', 'ASC')->get(); $firstnew = 0; // Set due date; $new_purchase = Purchase::find($purchase->id); $workflow_id = Input::get('hide_modeOfProcurement'); $workflow = Workflow::find($workflow_id); $addToDate = $workflow->totalDays; date_default_timezone_set("Asia/Manila"); $dueDate = date('Y-m-d H:i:s', strtotime("+{$addToDate} days")); $new_purchase->dueDate = $dueDate; $new_purchase->save(); $tasks = Task::where('wf_id', $document->work_id)->orderBy('section_id', 'ASC')->orderBy('order_id', 'ASC')->get(); foreach ($tasks as $task) { $task_details = new TaskDetails(); $task_details->task_id = $task->id; $stringamount = $new_purchase->amount; $stringamount = str_replace(str_split(','), '', $stringamount); $amount = (double) $stringamount; if ($firstnew == 0) { $task_details->status = "New"; } else { $task_details->status = "Pending"; } //Project Type if ($task->taskName == "PRE-PROCUREMENT CONFERENCE" || $task->taskName == "ADVERTISEMENT" || $task->taskName == "PRE-BID CONFERENCE") { $task_details->status = "Lock"; if ($new_purchase->projectType == "Goods/Services") { if ($task->taskName == "PRE-PROCUREMENT CONFERENCE" || $task->taskName == "ADVERTISEMENT") { if ($amount > 2000000) { $task_details->status = "Pending"; } } else { if ($task->taskName == "PRE-BID CONFERENCE") { if ($amount > 1000000) { $task_details->status = "Pending"; } } } } elseif ($new_purchase->projectType == "Infrastructure") { if ($task->taskName == "PRE-PROCUREMENT CONFERENCE" || $task->taskName == "ADVERTISEMENT") { if ($amount > 5000000) { $task_details->status = "Pending"; } } else { if ($task->taskName == "PRE-BID CONFERENCE") { if ($amount > 1000000) { $task_details->status = "Pending"; } } } } elseif ($new_purchase->projectType == "Consulting Services") { if ($amount > 1000000) { $task_details->status = "Pending"; } } } //End Project Type $firstnew = 1; $task_details->doc_id = $document->id; $task_details->save(); } $users = User::all(); foreach ($users as $user) { $count = new Count(); $count->user_id = $user->id; $count->doc_id = $doc_id; $count->save(); } $pr_id = Session::get('pr_id'); DB::table('attachments')->where('doc_id', $doc_id)->update(array('saved' => 1)); DB::table('attachments')->where('saved', '=', 0)->delete(); Session::forget('doc_id'); if (!Input::hasfile('file')) { Session::forget('imgerror'); } $connected = @fsockopen("www.google.com", 80); //website, port (try 80 or 443) if ($connected) { $sendee = DB::table('users')->where('id', $purchase->requisitioner)->first(); $email = $sendee->email; $fname = $sendee->firstname; $data = ['id' => $purchase->id]; Mail::send('emails.template', $data, function ($message) use($email, $fname) { $message->from('*****@*****.**', 'Procurement Tracking System Tarlac'); $message->to($email, $fname)->subject('Tarlac Procurement Tracking System: New Purchase Request Created'); }); $notice = "Purchase request created successfully. "; } else { $notice = "Purchase request created successfully. Email notice was not sent. "; } // Insert data to reports table $date_received = Input::get('dateReceived'); $date_received = substr($date_received, 0, strrpos($date_received, ' ')); $reports = Reports::whereDate($date_received)->first(); if ($reports == null) { $reports = new Reports(); $reports->date = $date_received; $reports->pRequestCount = 1; } else { $reports->pRequestCount = $reports->pRequestCount + 1; } $reports->save(); //End Reports Session::put('notice', $notice); $office = Office::all(); $users = User::all(); $workflow = Workflow::all(); return Redirect::to('purchaseRequest/view'); Session::put('imgsuccess', 'Files uploaded.'); } else { $message = "Failed to create purchase request."; Session::put('main_error', $message); // Get Other Error Messages $error_projectPurpose = $purchase->validationErrors->first('projectPurpose'); $error_projectType = $purchase->validationErrors->first('projectType'); $error_sourceOfFund = $purchase->validationErrors->first('sourceOfFund'); $error_amount = $purchase->validationErrors->first('amount'); $error_office = $purchase->validationErrors->first('office'); $error_requisitioner = $purchase->validationErrors->first('requisitioner'); $error_dateRequested = $purchase->validationErrors->first('dateRequested'); $error_dateReceived = $purchase->validationErrors->first('dateReceived'); $error_controlNo = $purchase->validationErrors->first('controlNo'); // Inserting Error Message To a Session Session::put('error_projectPurpose', $error_projectPurpose); Session::put('error_sourceOfFund', $error_sourceOfFund); Session::put('error_amount', $error_amount); Session::put('error_office', $error_office); Session::put('error_requisitioner', $error_requisitioner); Session::put('error_dateRequested', $error_dateRequested); Session::put('error_dateReceived', $error_dateReceived); Session::put('error_projectType', $error_projectType); Session::put('error_controlNo', $error_controlNo); if ($checkUniqueControlNo != 0) { Session::put('error_controlNo', 'This control no. already exists. Please enter a new one.'); } if (Input::get('hide_modeOfProcurement') == "") { Session::put('m6', 'required'); } Session::put('imgsuccess', 'Files uploaded.'); return Redirect::back()->withInput(); } } else { // Set Main Error $message = "Failed to create purchase request."; Session::put('main_error', $message); if (!Input::hasfile('file')) { Session::forget('imgerror'); } // Get Other Error Messages $error_projectPurpose = $purchase->validationErrors->first('projectPurpose'); $error_projectType = $purchase->validationErrors->first('projectType'); $error_sourceOfFund = $purchase->validationErrors->first('sourceOfFund'); $error_amount = $purchase->validationErrors->first('amount'); $error_office = $purchase->validationErrors->first('office'); $error_requisitioner = $purchase->validationErrors->first('requisitioner'); $error_dateRequested = $purchase->validationErrors->first('dateRequested'); $error_dateReceived = $purchase->validationErrors->first('dateReceived'); $error_controlNo = $purchase->validationErrors->first('controlNo'); // Inserting Error Message To a Session Session::put('error_projectPurpose', $error_projectPurpose); Session::put('error_sourceOfFund', $error_sourceOfFund); Session::put('error_amount', $error_amount); Session::put('error_office', $error_office); Session::put('error_requisitioner', $error_requisitioner); Session::put('error_dateRequested', $error_dateRequested); Session::put('error_dateReceived', $error_dateReceived); Session::put('error_projectType', $error_projectType); Session::put('error_controlNo', $error_controlNo); if ($checkUniqueControlNo != 0) { Session::put('error_controlNo', 'This control no. already exists. Please enter a new one.'); } if (Input::get('hide_modeOfProcurement') == "") { Session::put('error_modeOfProcurement', 'required'); } if (Session::get('imgerror') && Input::hasfile('file')) { $failedpurchasecount = Purchase::where('id', $purchase->id)->count(); if ($failedpurchasecount != 0) { $failedpurchase = Purchase::find($purchase->id); $failedpurchase->delete(); } Session::forget('imgsuccess'); //Image Error Return $task_details = TaskDetails::where('doc_id', $document->id)->delete(); $document->delete(); $message = "Failed to create purchase request."; // Set Main Error $message = "Failed to save purchase request."; Session::put('main_error', $message); // Get Other Error Messages $error_projectPurpose = $purchase->validationErrors->first('projectPurpose'); $error_projectType = $purchase->validationErrors->first('projectType'); $error_sourceOfFund = $purchase->validationErrors->first('sourceOfFund'); $error_amount = $purchase->validationErrors->first('amount'); $error_office = $purchase->validationErrors->first('office'); $error_requisitioner = $purchase->validationErrors->first('requisitioner'); $error_dateRequested = $purchase->validationErrors->first('dateRequested'); $error_dateReceived = $purchase->validationErrors->first('dateReceived'); $error_controlNo = $purchase->validationErrors->first('controlNo'); // Inserting Error Message To a Session Session::put('error_projectPurpose', $error_projectPurpose); Session::put('error_sourceOfFund', $error_sourceOfFund); Session::put('error_amount', $error_amount); Session::put('error_office', $error_office); Session::put('error_requisitioner', $error_requisitioner); Session::put('error_dateRequested', $error_dateRequested); Session::put('error_dateReceived', $error_dateReceived); Session::put('error_projectType', $error_projectType); Session::put('error_controlNo', $error_controlNo); if ($checkUniqueControlNo != 0) { Session::put('error_controlNo', 'This control no. already exists. Please enter a new one.'); } } return Redirect::back()->withInput(); } }
/** * Get Stripe purchase */ private function _get_stripe_customer_id($email = NULL, $product_code = NULL) { $email = $email ? $email : Input::get('email'); $product_code = $product_code ? $product_code : Input::get('code'); // Get product $product = Product::where('code', '=', $product_code)->first(); // Get buyer if (!($buyer = Buyer::where('email', '=', $email)->first())) { $this->_invalidRequest("Buyer account was not found"); } // Get purchase if (!($purchase = Purchase::where('buyer_id', '=', $buyer->id)->where('product_id', '=', $product->id)->where('pay_method', '=', '1')->first())) { $this->_invalidRequest("No purchase was found, contact support."); } // Get Stripe Customer ID if (!$purchase->stripe_token) { $this->_invalidRequest("Payment processor's customer ID is missing, contact support."); } return $purchase->stripe_token; }
public function janisawesome() { function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } function generateRandomAmount() { $length = rand(4, 8); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= rand(1, 9); } return $randomString; } $numLoop = 1; while ($numLoop < 301) { $purchase = new Purchase(); $document = new Document(); $purchase->projectPurpose = generateRandomString(); $purchase->sourceOfFund = generateRandomString(); $controlAmt = generateRandomAmount(); $controlAmt .= ".00"; $purchase->amount = number_format($controlAmt); $purchase->office = "1"; $purchase->requisitioner = "1"; $purchase->dateRequested = date('Y-m-d H:i:s'); $purchase->dateReceived = date('Y-m-d H:i:s'); $purchase->status = 'Active'; $purchase->otherType = " "; // Get latest control number $cn = 0; $purchase_controlNo = Purchase::orderBy('ControlNo', 'DESC')->first(); if (!$purchase_controlNo == NuLL) { $cn = $purchase_controlNo->controlNo; } $cn += 1; $purchase->controlNo = $cn; if (Input::get('otherType') == ' ') { $purchase->projectType = "None"; } else { $purchase->projectType = "None"; } // Set creator id $user_id = Auth::user()->id; $purchase->created_by = $user_id; $purchase_save = $purchase->save(); if ($purchase_save) { if ($controlAmt < 50000) { $amtControl = 1; } else { if ($controlAmt >= 50000 && $controlAmt <= 500000) { $amtControl = 2; } else { if ($controlAmt >= 500000) { $amtControl = 3; } } } $document->pr_id = $purchase->id; $document->work_id = $amtControl; $document_save = $document->save(); if ($document_save) { $doc_id = $document->id; $workflow = Workflow::find($document->work_id); $section = Section::where('workflow_id', $document->work_id)->orderBy('section_order_id', 'ASC')->get(); $firstnew = 0; // Set due date; $new_purchase = Purchase::find($purchase->id); $workflow_id = "1"; $workflow = Workflow::find($workflow_id); $addToDate = $workflow->totalDays; date_default_timezone_set("Asia/Manila"); $dueDate = date('Y-m-d H:i:s', strtotime("+{$addToDate} days")); $new_purchase->dueDate = $dueDate; $new_purchase->save(); $tasks = Task::where('wf_id', $document->work_id)->orderBy('section_id', 'ASC')->orderBy('order_id', 'ASC')->get(); foreach ($tasks as $task) { $task_details = new TaskDetails(); $task_details->task_id = $task->id; $stringamount = $new_purchase->amount; $stringamount = str_replace(str_split(','), '', $stringamount); $amount = (double) $stringamount; if ($firstnew == 0) { $task_details->status = "New"; } else { $task_details->status = "Pending"; } //Project Type if ($task->taskName == "PRE-PROCUREMENT CONFERENCE" || $task->taskName == "ADVERTISEMENT" || $task->taskName == "PRE-BID CONFERENCE") { $task_details->status = "Lock"; if ($new_purchase->projectType == "Goods/Services") { if ($task->taskName == "PRE-PROCUREMENT CONFERENCE" || $task->taskName == "ADVERTISEMENT") { if ($amount > 2000000) { $task_details->status = "Pending"; } } else { if ($task->taskName == "PRE-BID CONFERENCE") { if ($amount > 1000000) { $task_details->status = "Pending"; } } } } elseif ($new_purchase->projectType == "Infrastructure") { if ($task->taskName == "PRE-PROCUREMENT CONFERENCE" || $task->taskName == "ADVERTISEMENT") { if ($amount > 5000000) { $task_details->status = "Pending"; } } else { if ($task->taskName == "PRE-BID CONFERENCE") { if ($amount > 1000000) { $task_details->status = "Pending"; } } } } elseif ($new_purchase->projectType == "Consulting Services") { if ($amount > 1000000) { $task_details->status = "Pending"; } } } //End Project Type $firstnew = 1; $task_details->doc_id = $document->id; $task_details->save(); } $users = User::all(); foreach ($users as $user) { $count = new Count(); $count->user_id = $user->id; $count->doc_id = $doc_id; $count->save(); } $pr_id = Session::get('pr_id'); DB::table('attachments')->where('doc_id', $doc_id)->update(array('saved' => 1)); DB::table('attachments')->where('saved', '=', 0)->delete(); Session::forget('doc_id'); $connected = true; // $connected = @fsockopen("www.google.com", 80); //website, port (try 80 or 443) if (!$connected) { $sendee = DB::table('users')->where('id', $purchase->requisitioner)->first(); $email = $sendee->email; $fname = $sendee->firstname; $data = ['id' => $purchase->id]; Mail::send('emails.template', $data, function ($message) use($email, $fname) { $message->from('*****@*****.**', 'Procurement Tracking System Tarlac'); $message->to($email, $fname)->subject('Tarlac Procurement Tracking System: New Purchase Request Created'); }); $notice = "Purchase request created successfully. "; // Insert data to reports table $date_received = Input::get('dateReceived'); $date_received = substr($date_received, 0, strrpos($date_received, ' ')); $reports = Reports::whereDate($date_received)->first(); if ($reports == null) { $reports = new Reports(); $reports->date = $date_received; $reports->pRequestCount = 1; } else { $reports->pRequestCount = $reports->pRequestCount + 1; } $reports->save(); //End Reports } else { // Insert data to reports table $date_received = Input::get('dateReceived'); $date_received = substr($date_received, 0, strrpos($date_received, ' ')); $reports = Reports::whereDate($date_received)->first(); if ($reports == null) { $reports = new Reports(); $reports->date = $date_received; $reports->pRequestCount = 1; } else { $reports->pRequestCount = $reports->pRequestCount + 1; } $reports->save(); //End Reports $notice = "Purchase request created successfully. Email notice was not sent. "; } Session::put('notice', $notice); $office = Office::all(); $users = User::all(); $workflow = Workflow::all(); //return Redirect::to('purchaseRequest/view'); return Redirect::to('janisawesome'); Session::put('imgsuccess', 'Files uploaded.'); } else { $message = "Failed to create purchase request."; Session::put('main_error', $message); // Get Other Error Messages $error_projectPurpose = $purchase->validationErrors->first('projectPurpose'); $error_projectType = $purchase->validationErrors->first('projectType'); $error_sourceOfFund = $purchase->validationErrors->first('sourceOfFund'); $error_amount = $purchase->validationErrors->first('amount'); $error_office = $purchase->validationErrors->first('office'); $error_requisitioner = $purchase->validationErrors->first('requisitioner'); $error_dateRequested = $purchase->validationErrors->first('dateRequested'); $error_dateReceived = $purchase->validationErrors->first('dateReceived'); // Inserting Error Message To a Session Session::put('error_projectPurpose', $error_projectPurpose); Session::put('error_sourceOfFund', $error_sourceOfFund); Session::put('error_amount', $error_amount); Session::put('error_office', $error_office); Session::put('error_requisitioner', $error_requisitioner); Session::put('error_dateRequested', $error_dateRequested); Session::put('error_dateReceived', $error_dateReceived); Session::put('error_projectType', $error_projectType); if (Input::get('hide_modeOfProcurement') == "") { Session::put('m6', 'required'); } Session::put('imgsuccess', 'Files uploaded.'); return Redirect::back()->withInput(); } } else { // Set Main Error $message = "Failed to create purchase request."; Session::put('main_error', $message); // Get Other Error Messages $error_projectPurpose = $purchase->validationErrors->first('projectPurpose'); $error_projectType = $purchase->validationErrors->first('projectType'); $error_sourceOfFund = $purchase->validationErrors->first('sourceOfFund'); $error_amount = $purchase->validationErrors->first('amount'); $error_office = $purchase->validationErrors->first('office'); $error_requisitioner = $purchase->validationErrors->first('requisitioner'); $error_dateRequested = $purchase->validationErrors->first('dateRequested'); $error_dateReceived = $purchase->validationErrors->first('dateReceived'); // Inserting Error Message To a Session Session::put('error_projectPurpose', $error_projectPurpose); Session::put('error_sourceOfFund', $error_sourceOfFund); Session::put('error_amount', $error_amount); Session::put('error_office', $error_office); Session::put('error_requisitioner', $error_requisitioner); Session::put('error_dateRequested', $error_dateRequested); Session::put('error_dateReceived', $error_dateReceived); Session::put('error_projectType', $error_projectType); if (Input::get('hide_modeOfProcurement') == "") { Session::put('error_modeOfProcurement', 'required'); } if (Session::get('imgerror') && Input::hasfile('file')) { $failedpurchasecount = Purchase::where('id', $purchase->id)->count(); if ($failedpurchasecount != 0) { $failedpurchase = Purchase::find($purchase->id); $failedpurchase->delete(); } Session::forget('imgsuccess'); //Image Error Return $task_details = TaskDetails::where('doc_id', $document->id)->delete(); $document->delete(); $message = "Failed to create purchase request."; // Set Main Error $message = "Failed to save purchase request."; Session::put('main_error', $message); // Get Other Error Messages $error_projectPurpose = $purchase->validationErrors->first('projectPurpose'); $error_projectType = $purchase->validationErrors->first('projectType'); $error_sourceOfFund = $purchase->validationErrors->first('sourceOfFund'); $error_amount = $purchase->validationErrors->first('amount'); $error_office = $purchase->validationErrors->first('office'); $error_requisitioner = $purchase->validationErrors->first('requisitioner'); $error_dateRequested = $purchase->validationErrors->first('dateRequested'); $error_dateReceived = $purchase->validationErrors->first('dateReceived'); // Inserting Error Message To a Session Session::put('error_projectPurpose', $error_projectPurpose); Session::put('error_sourceOfFund', $error_sourceOfFund); Session::put('error_amount', $error_amount); Session::put('error_office', $error_office); Session::put('error_requisitioner', $error_requisitioner); Session::put('error_dateRequested', $error_dateRequested); Session::put('error_dateReceived', $error_dateReceived); Session::put('error_projectType', $error_projectType); } return Redirect::back()->withInput(); } $numLoop++; } }
/** * 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; } } } }
/** * 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; } } }