Files
wticreatorstudio/Modules/Subscription/Http/Controllers/SubscriptionController.php
Fritz Ramirez 10d0c477c8 Initial commit
2024-02-12 22:54:20 -05:00

1058 lines
47 KiB
PHP

<?php
namespace Modules\Subscription\Http\Controllers;
use App\Models\Cart;
use App\Repositories\CartRepository;
use App\Services\CheckoutService;
use Modules\Subscription\Rules\PhoneFormat;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Subscription\Entities\AmazeSubscription;
use Modules\Subscription\Entities\SubscriptionSetting;
use Modules\PaymentGateway\Http\Controllers\StripeController;
use Modules\Account\Repositories\TransactionRepository;
use Modules\Account\Entities\Transaction;
use Modules\FrontendCMS\Entities\SubsciptionPaymentInfo;
use App\Traits\Accounts;
use App\Traits\SendMail;
use Carbon\Carbon;
use Exception;
use Modules\UserActivityLog\Traits\LogActivity;
use Stripe;
use Illuminate\Auth\Events\Registered;
use Modules\Subscription\Entities\SellerSubscription;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Modules\Subscription\Entities\CustomerSubscription;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Modules\PaymentGateway\Services\PaymentGatewayService;
use Modules\Product\Entities\Product;
use Modules\Seller\Entities\SellerProduct;
use Modules\Subscription\Entities\SubscriptionProductMeta;
use Modules\Subscription\Repositories\SubscriptionPlansRepository;
use Modules\Subscription\Repositories\SubscriptionCouponsRepository;
use Modules\WTIJobBoard\Repositories\JobRequestCategoriesRepository;
use Modules\Subscription\Rules\ZipCodeDeliverability;
use Modules\Subscription\Services\AugmentationService;
use Illuminate\Support\Facades\Session;
use Modules\Account\Entities\ChartOfAccount;
use Modules\Shipping\Entities\ShippingMethod;
use Modules\Subscription\Entities\SubscriptionPlan;
use Modules\Subscription\Entities\SubscriptionPlanPrice;
use Modules\Subscription\Entities\SubscriptionPlanPricePaypal;
use Modules\WTIJobBoard\Entities\JobRequest;
use Modules\Subscription\Services\PaypalPaymentService;
class SubscriptionController extends Controller
{
use Accounts, SendMail;
private $checkoutService;
private $paymentGatewayService;
private $subscriptionPlansRepository;
private $subscriptionCouponsRepository;
private $jobRequestCategoriesRepository;
private $cartRepository;
private $stripePayment;
private $paypalPayment;
public function __construct(CheckoutService $checkoutService, PaymentGatewayService $paymentGatewayService)
{
$this->checkoutService = $checkoutService;
$this->paymentGatewayService = $paymentGatewayService;
$this->subscriptionPlansRepository = new SubscriptionPlansRepository();
$this->subscriptionCouponsRepository = new SubscriptionCouponsRepository();
$this->jobRequestCategoriesRepository = new JobRequestCategoriesRepository();
$this->cartRepository = new CartRepository(new Cart);
$this->paypalPayment = new PaypalPaymentService();
$credential = getPaymentInfoViaSellerId(1, 4);
$this->stripePayment = new \Stripe\StripeClient([
"api_key" => @$credential->perameter_3,
"stripe_version" => "2022-11-15"
]);
}
protected function validator(array $data)
{
$rules = [
'plan' => ['required']
];
return Validator::make($data, $rules);
}
public function index()
{
new AugmentationService();
try {
$setting = SubscriptionSetting::getData();
$plans = $this->subscriptionPlansRepository->getAll();
return view('subscription::plan.index', compact('plans', 'setting'));
} catch (\Exception $e) {
Toastr::error(trans('common.Operation failed'), trans('common.Failed'));
return redirect()->back();
}
}
public function pixelmeDashboard() {
return view('subscription::pixelme.dashboard');
}
public function checkout(Request $request) {
$user = auth()->user();
$billing_address = $user->customerBillingAddress;
$view = $request->action;
if ($request->action == 'payment') {
$name = $request->name;
$zipcode = $request->postal_code;
$view = 'payment';
$data = $request->except('_token');
$data['name'] = $name;
$cartData = [];
$cartData['name'] = $data['name'];
$cartData['email'] = $data['email'];
$cartData['phone'] = $data['phone'];
$cartData['address'] = $data['address'];
$cartData['city'] = $data['city'];
$cartData['state'] = $data['state'];
$cartData['country'] = $data['country'];
$cartData['postal_code'] = $data['postal_code'];
session()->put('shipping_address', $cartData);
$totalItemWeight = 0;
$totalItemHeight = 0;
$totalItemLength = 0;
$totalItemBreadth = 0;
$session_packages = [
'totalItemWeight'=> $totalItemWeight,
'totalItemHeight'=> $totalItemHeight,
'totalItemLength'=> $totalItemLength,
'totalItemBreadth'=> $totalItemBreadth,
];
session(['single_package_height_weight_info' => $session_packages]);
//$this->checkoutService->guestAddressStore($request->only('name','address','email','phone','country','state','city','postal_code'));
$address_data = $request->only('name', 'address_id','address','email','phone','country','state','city','postal_code');
$country = \Modules\Setup\Entities\Country::where('name', $address_data['country'])->first();
$state = \Modules\Setup\Entities\State::where('name', $address_data['state'])->first();
$city = \Modules\Setup\Entities\City::where('name', $address_data['city'])->first();
$address_data['country'] = $country ? $country->id : null;
$address_data['state'] = $state ? $state->id : null;
$address_data['city'] = $city ? $city->id : null;
$address = $user->customerBillingAddress;
if ($address) {
$address_data['address_id'] = $address->id;
$this->checkoutService->addressUpdate($address_data);
}
else {
$this->checkoutService->addressStore($address_data);
}
}
else {
$this->validator($request->all())->validate();
session()->put('subscription_payment', true);
$name = "{$user->first_name} {$user->last_name}";
$zipcode = $user->zipcode;
}
$gateway_activations = $this->checkoutService->getActivePaymentGetways();
$gateway_activations = $gateway_activations->whereIn('id', [4]); // Allow only Stripe payment methods
$gateway_activations = $gateway_activations->get();
$first_name = $user->first_name;
$last_name = $user->last_name;
$email = $user->email;
$phone = $user->phone;
$total_amount = 0;
$seller_product = SellerProduct::find($request->plan);
if ($seller_product) {
session()->put('selected_plan', $seller_product);
$plan = $seller_product->product->plan;
$cart_product['product_id'] = $seller_product->id;
$cart_product['seller_id'] = $seller_product->product->seller->id;
$cart_product['type'] = 'product';
$cart_product['qty'] = 1;
$cart_product['shipping_method_id'] = 0;
$cart_product['is_buy_now'] = 'yes';
$cart_product['price'] = $seller_product->skus->first()->selling_price;
$this->cartRepository->store($cart_product);
$cartDataGroup = $this->checkoutService->getCartItem();
$cartData = $cartDataGroup['cartData'];
$address = $this->checkoutService->activeShippingAddress();
$giftCardExist = $cartDataGroup['gift_card_exist'];
$total_amount = $seller_product->skus->first()->selling_price;
$subtotal_without_discount = $total_amount;
$discount = 0;
$number_of_package = 1;
$number_of_item = 1;
$shipping_cost = 0;
$selected_shipping_method = ShippingMethod::find(1);
$tax_total = 0;
$delivery_date = now();
$packagewise_tax = 0;
$actual_total = $total_amount;
$address = $this->checkoutService->activeShippingAddress();
$coupon = [];
$coupon_amount = 0;
$coupon = [];
$infoCompleteOrder = [
'cartData' => $cartData,
'total_amount' => number_format($total_amount,2),
'subtotal_without_discount' => $subtotal_without_discount,
'discount' => $discount,
'number_of_package' => $number_of_package,
'number_of_item' => $number_of_item,
'shipping_cost' => $shipping_cost,
'selected_shipping_method' => $selected_shipping_method,
'address' => $address,
'gateway_activations' => $gateway_activations,
'tax_total' => $tax_total,
'delivery_date' => $delivery_date,
'packagewise_tax' => $packagewise_tax,
'actual_total' => $actual_total
];
$infoCompleteOrder = array_merge($infoCompleteOrder, $coupon);
session()->put('infoCompleteOrder', $infoCompleteOrder);
}
if ($request->action == 'payment') {
for ($i = 0; $i < count($gateway_activations); $i++) {
if ($gateway_activations[$i]->id == 1 || $gateway_activations[$i]->method == 'Cash On Delivery') {
unset($gateway_activations[$i]);
break;
}
}
return response()->json([
'gateway_activations' => (string)view('subscription::components._payment_method',compact('gateway_activations','total_amount')),
]);
}
else {
return view('subscription::checkout', compact('view', 'gateway_activations', 'name', 'first_name', 'last_name', 'email', 'phone', 'zipcode', 'biling_address', 'seller_product', 'plan', 'total_amount'));
}
}
public function mySubscription(Request $request)
{
if($request->has('subscription_id')){
$subscription = CustomerSubscription::where('txn_id',$request->subscription_id)->where('status','waiting for approval')->first();
if($subscription){
//for paypal only
$response = $this->paypalPayment->showSubscription($request->subscription_id);
if(isset($response->status)){
if($response->status == 'APPROVED'){
$this->sendSubscriptionPendingApproval($subscription->user, $subscription->user->company_details['storefront']);
} else if($response->status == 'APPROVAL_PENDING'){
$subscription->delete();
}
}
}
}
return view('subscription::subscription');
}
public function mySubscriptionData()
{
try{
$subscriptions = CustomerSubscription::with('planPrice','discount.coupon')->where('customer_id', auth()->user()->id)->latest()->get();
if ($subscriptions) {
$subscriptions_data = [];
foreach ($subscriptions as $subscription) {
$payment_details = '';
if ($subscription->planPrice->billing_type == 'Recurring') {
$price = $subscription->planPrice->price;
$price_monthly = $subscription->planPrice->price / $subscription->planPrice->custom_interval;
if ($subscription->planPrice->interval == 'Custom') {
if($subscription->payment_mode == 'Monthly'){
$payment_details .= "\$".number_format($price_monthly,2)." / monthly for {$subscription->planPrice->custom_interval} Months";
} else {
$payment_details .= "\$".number_format($price,2)." for {$subscription->planPrice->custom_interval} {$subscription->planPrice->custom_interval_type}";
}
} else {
$payment_details .= "\${$subscription->planPrice->price} {$subscription->planPrice->interval}";
}
if($subscription->discount != null){
$duration = $subscription->discount->coupon->duration;
$coupon_payment_mode = $subscription->discount->coupon->payment_mode;
$discount = $subscription->discount->coupon->discount;
if ($subscription->discount->coupon->type == 'Amount') {
$discount_label = "<span class=\"text-success\">Save \${$discount}</span>";
$discounted_price_monthly = number_format($price_monthly - $discount,2);
$discounted_price_all = number_format($price - $discount,2);
} else {
$discount_label = "<span class=\"text-success\">Save \${$discount}%</span>";
$discounted_price_monthly = number_format($price_monthly - (($discount / 100) * $price_monthly),2);
$discounted_price_all = $subscription->discount->coupon->duration == 'Once' ? number_format($price - (($discount / 100) * $price_monthly),2) : number_format($price - (($discount / 100) * $price),2);
}
$payment_details .= "<br> <span class=\"badge bg-info\">{$subscription->discount->coupon->code}</span>";
if ($subscription->planPrice->payment == 'monthly' ) {
$payment_details .= $duration == 'Once' ? " - \${$discounted_price_monthly} 1st month only)" : " | \${$discounted_price_monthly} per month";
} else {
$payment_details .= " - \${$discounted_price_all} for {$subscription->planPrice->custom_interval} Months ";
}
}
} else if ($subscription->planPrice->billing_type == 'One-Time') {
if($subscription->payment_status == 'uncaptured'){
$payment_details .= 'Expires on '. Carbon::parse($subscription->created_at)->addDays(7)->format('M d, Y').' if not yet authorize / captured';
} else {
if($subscription->planPrice->access_expire_duration_type == 'Days'){
$payment_details .= "\${$subscription->planPrice->price} {$subscription->planPrice->billing_type} {$subscription->planPrice->access} access, will expire on ".Carbon::parse($subscription->created_at)->addDays($subscription->planPrice->access_expire_duration)->format('M d, Y');
} else if($subscription->planPrice->access_expire_duration_type == 'Weeks'){
$payment_details .= "\${$subscription->planPrice->price} {$subscription->planPrice->billing_type} {$subscription->planPrice->access} access, will expire on ".Carbon::parse($subscription->created_at)->addWeeks($subscription->planPrice->access_expire_duration)->format('M d, Y');
} else if($subscription->planPrice->access_expire_duration_type == 'Months'){
$payment_details .= "\${$subscription->planPrice->price} {$subscription->planPrice->billing_type} {$subscription->planPrice->access} access, will expire on ".Carbon::parse($subscription->created_at)->addMonths($subscription->planPrice->access_expire_duration)->format('M d, Y');
} else if($subscription->planPrice->access_expire_duration_type == 'Years'){
$payment_details .= "\${$subscription->planPrice->price} {$subscription->planPrice->billing_type} {$subscription->planPrice->access} access, will expire on ".Carbon::parse($subscription->created_at)->addYears($subscription->planPrice->access_expire_duration)->format('M d, Y');
}
}
}
$data = [
'id' => $subscription->id,
'plan' => [
'title' => $subscription->planPrice->plan->title,
'image' => $subscription->planPrice->plan->image_url,
'price' => $subscription->planPrice->price,
'billing_type' => $subscription->planPrice->billing_type,
'interval' => $subscription->planPrice->interval,
'custom_interval' => $subscription->planPrice->custom_interval,
'custom_interval_type' => $subscription->planPrice->custom_interval_type,
],
'payment_details' => $payment_details,
'status' => $subscription->status == 'trialing' ? 'Waiting for approval' : $subscription->status,
'approved' => $subscription->approved,
'payment_method' => $subscription->payment_method,
'payment_mode' => $subscription->payment_mode,
'payment_status' => $subscription->payment_status,
'last_payment_date' => Carbon::parse($subscription->last_payment_date)->format('M j, Y'),
'next_payment_date' => Carbon::parse($subscription->next_payment_at)->format('M j, Y'),
'created_at' => Carbon::parse($subscription->created_at)->format('M j, Y, g:i a'),
];
if($subscription->discount != null){
$data['discount'] = [
'code' => $subscription->discount->coupon->code,
'type' => $subscription->discount->coupon->type,
'discount' => $subscription->discount->coupon->discount,
'duration' => $subscription->discount->coupon->duration,
];
}
array_push($subscriptions_data, $data);
}
}
$current_subscription = CustomerSubscription::select(['approved','message','status'])->where('customer_id', auth()->user()->id)->latest()->first();
$subscription_plans = $this->subscriptionPlansRepository->getAllSubscriptionPlans();
$categories = $this->jobRequestCategoriesRepository->all(['active' => 1]);
return response()->json([
'current_subscription' => $current_subscription,
'company_details' => auth()->user()->wti_data != NULL ? true : false,
'subscriptions' => $subscriptions_data,
'subscription_plans' => $subscription_plans,
'categories' => $categories
], 200);
}catch(Exception $e){
LogActivity::errorLog($e->getMessage());
return $e->getMessage();
}
}
public function companyDetails(Request $request)
{
try {
$user = auth()->user();
$user->wti_data = json_encode($request->all());
$user->save();
return response()->json([
'message' => 'Company Details successfuly saved.'
]);
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage()
], 500);
}
}
public function status(Request $request)
{
try {
return response()->json([
'subscription' => auth()->user()->subscription_status
]);
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage()
], 500);
}
}
public function store(Request $request)
{
$request->validate([
'title' => 'required|unique:subscription_plans,title',
'price' => 'required'
]);
try {
$this->subscriptionPlansRepository->create($request);
return response()->json([
'message' => 'Plan has been successfully saved.'
]);
} catch (\Exception $e) {
return response()->json([
'message' => 'an error occurred. Failed to save plan.'
], 500);
}
}
public function update(Request $request)
{
$request->validate([
'title' => 'required|unique:subscription_plans,title,' . $request->id,
'price' => 'required'
]);
try {
$ret = $this->subscriptionPlansRepository->update($request);
if ($ret) {
return response()->json([
'message' => "Plan has been successfully updated."
]);
}
else {
return response()->json([
'message' => 'Failed to update plan. Plan not found.'
], 500);
}
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage()
], 500);
}
}
public function destroy(Request $request)
{
try {
$ret = $this->subscriptionPlansRepository->delete($request);
if ($ret === true) {
return response()->json([
'message' => 'Plan has been successfully deleted.'
]);
}
else {
if ($ret == 'in_use') {
return response()->json([
'message' => 'Unable to delete plan. Plan is in use.'
], 403);
}
else {
return response()->json([
'message' => 'Failed to delete plan. Plan not found.'
], 500);
}
}
}
catch (\Exception $e) {
return response()->json([
'message' => 'An error occurred. Failed to delete plan.'
], 500);
}
}
public function changePlanPosition(Request $request)
{
$ids = $request->get('ids');
if (count($ids) != 0) {
foreach ($ids as $key => $id) {
$plan = SubscriptionPlan::find($id);
if ($plan) {
$plan->order = $key + 1;
$plan->save();
}
}
}
return true;
}
public function register(Request $request) {
$this->validator($request->all())->validate();
session()->put('subscription_payment', '1');
if ($request->method == "Stripe") {
$data['gateway_id'] = encrypt(4);
$response = $this->stripePost($request->all(), $request);
if (gettype($response) == 'object'){
return redirect()->back();
}
}
$data['payment_id'] = encrypt($response);
$data['step'] = 'complete_payment';
if (session()->has('new_user')) {
$user = clone session()->get('new_user');
session()->forget('new_user');
Auth::login($user);
Toastr::success(__('auth.successfully_registered'), __('common.success'));
LogActivity::addLoginLog(Auth::user()->id, Auth::user()->first_name . ' - logged in at : ' . Carbon::now());
return redirect('/profile/dashboard');
}
}
public function stripePost($data, Request $request, $mode = null)
{
$currency_code = getCurrencyCode();
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
try{
$stripe = Stripe\Charge::create ([
"amount" => round($data['amount'] * 100),
"currency" => $currency_code,
"source" => $data['stripeToken'],
"description" => "Payment from ". url('/'),
"capture" => false
]);
}catch(Exception $e){
Toastr::error($e->getMessage(), __('common.error'));
return redirect()->back();
}
if ($stripe['status'] == "succeeded") {
$return_data = $stripe['id'];
if (session()->has('subscription_payment')) {
if ($mode == 'add') {
$user = auth()->user();
if ($user) {
$plan = $data['plan'];
$customer_subscription = new CustomerSubscription();
$customer_subscription->customer_id = $user->id;
$customer_subscription->plan_id = $plan;
$customer_subscription->status = 'active';
$customer_subscription->is_paid = true;
$customer_subscription->save();
$defaultIncomeAccount = $this->defaultIncomeAccount();
$transactionRepo = new TransactionRepository(new Transaction);
$transaction = $transactionRepo->makeTransaction($user->first_name." - Subsriction Payment", "in", "Stripe", "subscription_payment", $defaultIncomeAccount, "Subscription Payment", $customer_subscription, $data['amount'], Carbon::now()->format('Y-m-d'), $user->id, null, null);
SubsciptionPaymentInfo::create([
'transaction_id' => $transaction->id,
'txn_id' => $return_data,
'customer_id' => $user->id,
'plan_id' => $customer_subscription->plan_id,
]);
LogActivity::successLog('Subscription payment successful.');
return true;
}
else {
redirect('/login');
}
}
else if ($mode == 'renew') {
$customer_subscription = CustomerSubscription::find($data['subscription_id']);
if ($customer_subscription) {
$user = $customer_subscription->user;
$defaultIncomeAccount = $this->defaultIncomeAccount();
$transactionRepo = new TransactionRepository(new Transaction);
$transaction = $transactionRepo->makeTransaction($user->first_name." - Subsriction Payment", "in", "Stripe", "subscription_payment", $defaultIncomeAccount, "Subscription Payment", $customer_subscription, $data['amount'], Carbon::now()->format('Y-m-d'), $user->id, null, null);
$customer_subscription->update([
'last_payment_date' => Carbon::now()->format('Y-m-d'),
'is_paid' => 1,
'status' => 'active'
]);
SubsciptionPaymentInfo::create([
'transaction_id' => $transaction->id,
'txn_id' => $return_data,
'customer_id' => $user->id,
'plan_id' => $customer_subscription->plan_id,
]);
LogActivity::successLog('Subscription payment successful.');
return true;
}
}
else {
$plan = $data['plan'];
event(new Registered($user = app(\App\Http\Controllers\Auth\RegisterController::class)->create($request)));
$customer_subscription = new CustomerSubscription();
$customer_subscription->customer_id = $user->id;
$customer_subscription->plan_id = $plan;
$customer_subscription->status = 'active';
$customer_subscription->is_paid = true;
$customer_subscription->save();
$defaultIncomeAccount = $this->defaultIncomeAccount();
$transactionRepo = new TransactionRepository(new Transaction);
$transaction = $transactionRepo->makeTransaction($user->first_name." - Subsriction Payment", "in", "Stripe", "subscription_payment", $defaultIncomeAccount, "Subscription Payment", $customer_subscription, $data['amount'], Carbon::now()->format('Y-m-d'), $user->id, null, null);
$customer_subscription->update(['last_payment_date' => Carbon::now()->format('Y-m-d')]);
SubsciptionPaymentInfo::create([
'transaction_id' => $transaction->id,
'txn_id' => $return_data,
'customer_id' => $user->id,
'plan_id' => $plan,
]);
LogActivity::successLog('Subscription payment successful.');
session()->put('new_user', $user);
return true;
}
}
}else {
return redirect()->route('frontend.welcome');
}
}
public function add(Request $request) {
session()->put('subscription_payment', '1');
if ($request->method == "Stripe") {
$data['gateway_id'] = encrypt(4);
$response = $this->stripePost($request->all(), $request, 'add');
if (gettype($response) == 'object'){
return redirect()->back();
}
}
$data['payment_id'] = encrypt($response);
$data['step'] = 'complete_payment';
return redirect('/my-subscription');
}
public function subscribe(Request $request) {
try {
$planPrice = SubscriptionPlanPrice::find($request->subscription_price_id);
if(!$planPrice){
return response()->json([
'message' => 'Subscription Plan Price not found!'
], 404);
}
//lets check first if theres active subscription
$active_subscription = CustomerSubscription::where('customer_id',auth()->user()->id)->where('status','active')->where('payment_status','succeeded')->first();
$prorate_discount = 0;
if ($active_subscription && $active_subscription->planPrice->payment =='monthly' && $active_subscription->planPrice->subscription_plan_id != $planPrice->subscription_plan_id && $planPrice->payment == 'monthly') {
if($active_subscription->payment_method == 'stripe'){
$response = $this->stripePayment->subscriptions->retrieve($active_subscription->txn_id, []);
$startDate = Carbon::createFromTimestamp($response['current_period_start']);
} else if($active_subscription->payment_method == 'paypal'){
$response = $this->paypalPayment->showSubscription($active_subscription->txn_id);
if(isset($response->billing_info->last_payment->time)){
$startDate = Carbon::parse($response->billing_info->last_payment->time);
}
}
if(isset($startDate)){
$endDate = Carbon::now();
$diffInDays = $startDate->diffInDays($endDate);
if($planPrice->subscription_plan_id > $active_subscription->planPrice->subscription_plan_id){
//for upgrade
$prorate_discount = (($active_subscription->planPrice->price / $active_subscription->planPrice->custom_interval) / 30 ) * $diffInDays;
} else {
//for downgrade
$prorate_discount = (($planPrice->price / $planPrice->custom_interval) / 30 ) * $diffInDays;
}
}
}
$payment_details = $planPrice->plan->title;
$coupon_id = null;
if($request->promo_code != null){
$storefront = auth()->user()->company_details['storefront'];
$promoCode = $this->subscriptionCouponsRepository->validate($request->promo_code,$storefront);
if(isset($promoCode->stripe_coupon_id) && in_array($planPrice->id, $promoCode->subscription_plan_price_id)){
$coupon_id = $promoCode->stripe_coupon_id;
$price_monthly = $planPrice->price / $planPrice->custom_interval;
if ($promoCode->type == 'Amount') {
$discounted_price_monthly = number_format($price_monthly - $promoCode->discount,2);
$discounted_price_all = number_format($planPrice->price - $promoCode->discount,2);
} else {
$discounted_price_monthly = number_format($price_monthly - (($promoCode->discount / 100) * $price_monthly),2);
$discounted_price_all = number_format($planPrice->price - (($promoCode->discount / 100) * $planPrice->price),2);
}
if($planPrice->payment == 'monthly'){
$payment_details .= $promoCode->duration == 'Once' ? ' - $'.number_format($planPrice->price / $planPrice->custom_interval,2).' for '.$planPrice->custom_interval.' Months ($'.$discounted_price_monthly.' 1st month only)' : ' - '.$planPrice->custom_interval.' Months ($'.$discounted_price_monthly.' per month)';
} else {
$payment_details .= '($'.$discounted_price_all.' for '.$planPrice->custom_interval.' Months)';
}
// if ($promoCode->payment_mode == 'Monthly' || $promoCode->payment_mode == 'Both') {
// $payment_details .= $promoCode->duration == 'Once' ? ' - $'.number_format($planPrice->price / $planPrice->custom_interval,2).' for '.$planPrice->custom_interval.' Months ( $'.$discounted_price_monthly.' 1st month only )' : ' - '.$planPrice->custom_interval.' Months ( $'.$discounted_price_monthly.' per month )';
// }
// if ($promoCode->payment_mode == 'All' || $promoCode->payment_mode == 'Both') {
// $payment_details .= '( $'.$discounted_price_all.' for '.$planPrice->custom_interval.' Months )';
// }
}
} else {
if($prorate_discount > 0){
$payment_details .= $planPrice->payment == 'monthly' ? ' - '.$planPrice->custom_interval.' Months ($'.number_format(($planPrice->price / $planPrice->custom_interval) - $prorate_discount,2).' prorated 1st month only then $'.number_format($planPrice->price / $planPrice->custom_interval,2).' per month)' : ' - '.$planPrice->custom_interval.' Months ($'.number_format($planPrice->price,2).')';
} else {
$payment_details .= $planPrice->payment == 'monthly' ? ' - '.$planPrice->custom_interval.' Months ($'.number_format($planPrice->price / $planPrice->custom_interval,2).' per month)' : ' - '.$planPrice->custom_interval.' Months ($'.number_format($planPrice->price,2).')';
}
}
if($request->payment_method == 'stripe'){
$sessionData = [
'mode' => 'setup',
'payment_method_types' => ['card'],
'setup_intent_data' => [
//'description' => 'This is a test description',
'metadata' => [
'user_id' => auth()->user()->id,
'user_name' => auth()->user()->name,
'user_email' => auth()->user()->email,
'subscription_plan_price_id' => $planPrice->stripe_price_id,
'prorate_discount' => (float)$prorate_discount,
'coupon_id' => $coupon_id
]
],
'custom_text' => [
'submit' => [
'message' => $payment_details .', your card will not be charged until your subscription is approved.'
]
],
'customer_email' => auth()->user()->email,
'client_reference_id' => auth()->user()->id,
'success_url' => url('/my-subscription'),
'cancel_url' => url('/my-subscription')
];
$response = $this->stripePayment->checkout->sessions->create($sessionData);
return response()->json([
'session_id' => $response['id']
]);
} else {
if($active_subscription && ($planPrice->subscription_plan_id == $active_subscription->planPrice->subscription_plan_id || $planPrice->payment == 'upfront')){
if($active_subscription->payment_method == 'stripe'){
$response = $this->stripePayment->subscriptions->retrieve($active_subscription->txn_id, []);
$trial_end = $response['current_period_end'];
} else if($active_subscription->payment_method == 'paypal' && $active_subscription->expired_at != null){
$trial_end = $active_subscription->expired_at->timestamp;
}
if(isset($trial_end)){
$startDate = Carbon::createFromTimestamp($trial_end);
$endDate = Carbon::now();
$trial_days = $startDate->diffInDays($endDate);
}
}
$data = [
'quantity' => 1,
'start_time' => isset($trial_days) ? Carbon::now()->addDays($trial_days)->toIso8601ZuluString() : null,
'subscriber' => [
'email_address' => auth()->user()->email,
'name' => [
'given_name' => auth()->user()->first_name,
'surname' => auth()->user()->last_name
]
],
'application_context' => [
'brand_name' => 'Vurn Media LLC',
'shipping_preference' => 'NO_SHIPPING',
'user_action' => 'CONTINUE',
'payment_method' => [
'payer_selected' => 'PAYPAL',
'payee_preferred' => 'IMMEDIATE_PAYMENT_REQUIRED'
],
'return_url' => url('/my-subscription'),
'cancel_url' => url('/my-subscription')
]
];
if($coupon_id != null){
$data['custom_id'] = json_encode([
'user_id' => auth()->user()->id,
'coupon_id' => $coupon_id
]);
//lets create new plan price with discount
$response = $this->paypalPayment->createProductPriceWithDiscount($planPrice,$promoCode->duration,$discounted_price_monthly,$discounted_price_all,$payment_details);
if(isset($response->id)){
$data['plan_id'] = $response->id;
$paypalPlanPrice = new SubscriptionPlanPricePaypal;
$paypalPlanPrice->user_id = auth()->user()->id;
$paypalPlanPrice->subscription_plan_price_id = $planPrice->id;
$paypalPlanPrice->paypal_price_id = $response->id;
$paypalPlanPrice->save();
} else {
return response()->json([
'message' => 'Something went wrong, please try again later.'
], 404);
}
} else {
$data['plan_id'] = $planPrice->paypal_price_id;
$data['custom_id'] = json_encode([
'user_id' => auth()->user()->id
]);
}
$response = $this->paypalPayment->createSubscription(json_encode($data,true));
if($response->links[0]->rel != 'approve'){
return response()->json([
'message' => 'Something went wrong, please try again later.'
], 404);
}
return response()->json([
'redirect_url' => $response->links[0]->href
]);
}
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage()
], 404);
}
}
public function cancel(Request $request) {
try {
$subscription = CustomerSubscription::find($request->id);
if ($subscription) {
if($subscription->planPrice->billing_type == 'Recurring'){
$response = $this->stripePayment->subscriptions->cancel(
$subscription->txn_id,
[]
);
if ($response['status'] != "canceled") {
return response()->json([
'message' => 'Subscription cannot be cancelled!'
], 500);
}
$subscription->status = $response['status'];
$subscription->payment_status = 'cancelled';
$subscription->update();
return response()->json([
'message' => 'Subscription successfully cancelled.'
], 200);
}
}
return response()->json([
'message' => 'Subscription not found!'
], 500);
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage()
], 404);
}
}
public function refund(Request $request) {
$id = $request->id;
$subscription = CustomerSubscription::find($id);
if ($subscription) {
$response = $this->stripePayment->refunds->create([
'charge' => $subscription->txn_id,
]);
if ($response['status'] == "succeeded") {
$subscription->status = 'inactive';
$subscription->status = 'refunded';
$subscription->is_paid = false;
$subscription->update();
}
return redirect('/my-subscription');
}
return redirect('/profile/dashboard');
}
public function pay(Request $request) {
session()->put('subscription_payment', '1');
if ($request->method == "Stripe") {
$data['gateway_id'] = encrypt(4);
$response = $this->stripePost($request->all(), $request, 'renew');
if(gettype($response) == 'object'){
return redirect()->back();
}
}
$data['payment_id'] = encrypt($response);
$data['step'] = 'complete_payment';
return redirect('/my-subscription');
}
public function captureFunds(Request $request) {
try {
$subscription = CustomerSubscription::find($request->id);
if ($subscription && $subscription->billing_type == 'One-Time') {
$charge_id = $subscription->txn_id;
$credential = $this->getCredential();
Stripe\Stripe::setApiKey(@$credential->perameter_3);
$stripe = new Stripe\StripeClient(@$credential->perameter_3);
$response = $stripe->charges->capture($charge_id, []);
if ($response['status'] == 'succeeded') {
$subscription->status = 'active';
$subscription->update();
return response()->json([
'message' => __('Funds has been successfully released.')
], 200);
}
return response()->json([
'message' => 'Failed to release funds. Please check your account if you have sufficient balance. The charge might have also expired.'
], 404);
}
return response()->json([
'message' => 'Subscription not found.'
], 404);
} catch (\Exception $e) {
return response()->json([
'message' => trans('common.Operation failed')
], 404);
}
}
public function isAddToCartAllowed() {
$subscription_settings = SubscriptionSetting::getData();
if ($subscription_settings->customer_subscription) {
$user = auth()->user();
if ($user) {
$subscription = CustomerSubscription::where('customer_id', $user->id)->latest()->first();
if ($subscription && $subscription->status == 'active' && $subscription->is_paid) {
return true;
}
}
return false;
}
return true;
}
private function getCredential(){
$url = explode('?',url()->previous());
if(isset($url[0]) && $url[0] == url('/checkout')){
$is_checkout = true;
}else{
$is_checkout = false;
}
if(session()->has('order_payment') && app('general_setting')->seller_wise_payment && session()->has('seller_for_checkout') && $is_checkout){
$credential = getPaymentInfoViaSellerId(session()->get('seller_for_checkout'), 4);
}else{
$credential = getPaymentInfoViaSellerId(1, 4);
}
return $credential;
}
}