Files
cheerstothe_season_2.0/app/Http/Controllers/APIs/Customer_API/SubscriptionController.php
2024-07-08 13:08:01 +05:30

352 lines
12 KiB
PHP

<?php
namespace App\Http\Controllers\APIs\Customer_API;
use App\Http\Controllers\Controller;
use App\Models\IamPrincipal;
use App\Models\SubscriptionProducts;
use App\Models\Subscriptions;
use App\Services\APIs\CustomerAPIs\RulesApiServices;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
class SubscriptionController extends Controller
{
//created by; Hritik
//On - 28th June ,2024
//use - to get Data of User in Webview and show list of product
public function mySubscription(Request $request)
{
try {
// dd($request->header('access-token'));
$token = readHeaderToken();
// dd("acc",$token);
// $token = true;
// dd($token, Session::get('vendorToken'));
if ($token) {
// $user_id = 12;
$user_id = $token['sub'];
$dateTime = now();
$formattedDateTime = $dateTime->format('Y-m-d H:i:s');
$isSubscribedUser = Subscriptions::where('iam_principal_xid', $user_id)
->where('next_payment_date', '>=', $formattedDateTime)
->first();
$userData = IamPrincipal::where('id', $user_id)->first();
// $request['iam_principal_id'] = $user_id;
$products = SubscriptionProducts::where('is_active', '1')->get();
if ($isSubscribedUser) {
return view("Admin.pages.subscriptions.my-subscription", compact('user_id', 'userData', 'isSubscribedUser', 'products'));
}
$productList = SubscriptionProducts::where('is_active', 1)->first();
return view('Admin.pages.subscriptions.list-of-products', compact('productList', 'userData'));
} else {
return jsonResponseWithErrorMessageApi(__('auth.user_deleted'), 409);
}
} catch (\Exception $e) {
Log::error("An error occurred in " . _METHOD_ . ": " . $e->getMessage(), ['exception' => $e]);
return jsonResponseWithErrorMessage(__('auth.something_went_wrong'));
}
}
//created by; Hritik
//On - 28th June ,2024
//use - to get Data of User in Webview and show list of product
public function listOfProduct(Request $request)
{
try {
$productList = SubscriptionProducts::where('is_active', 1)->first();
return view('Admin.pages.subscriptions.list-of-products', compact('productList'));
} catch (\Exception $e) {
Log::error("An error occurred in " . _METHOD_ . ": " . $e->getMessage(), ['exception' => $e]);
return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
}
}
//created by; Hritik
//On - 02th July ,2024
//use - to Create Subscription Product & price for Monthly
public function createStripeProduct(Request $request)
{
try {
DB::beginTransaction();
$stripeSecret = (config('constants.subscription.stripe_secret_key'));
// $stripeSecret = env('STRIPE_SECRET');
$stripe = new \Stripe\StripeClient($stripeSecret);
// dd($stripeSecret,$stripe,$request->all());
$validator = $this->validateSubscriptionsproductForm($request);
if ($validator->fails()) {
$validationErrors = $validator->errors()->all();
Log::error("Stripe subscriptions plan validation error: " . implode(", ", $validationErrors));
return jsonResponseWithErrorMessageApi($validationErrors, 203);
}
$id = SubscriptionProducts::create([
'product_name' => $request->product_name,
'product_value' => $request->product_value,
'product_details' => $request->product_details,
]);
$productCreate = $stripe->products->create([
'name' => $request->product_name,
]);
$updateCreatedPlan = SubscriptionProducts::where('id', $id->id)->update([
'stripe_product_id' => $productCreate->id
]);
$totalPrice = $request->product_value;
if ($totalPrice && $totalPrice != 0 && $totalPrice != null) {
$productPrice1 = $stripe->prices->create([
'unit_amount' => $totalPrice * 100,
// amount entered by Admin (in cents)
'currency' => 'usd',
'recurring' => ['interval' => 'month'],
'product' => $productCreate->id,
'nickname' => 'Monthly Price',
]);
$updateCreatedPlan = SubscriptionProducts::where('id', $id->id)->update([
'stripe_price_id' => $productPrice1->id
]);
}
DB::commit();
return jsonResponseWithSuccessMessage(__('success.save_data'), 200);
} catch (\Exception $ex) {
DB::rollBack();
Log::error('Favourite Restaurant service failed: ' . $ex->getMessage());
return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
}
}
public function validateSubscriptionsproductForm(Request $request)
{
return Validator::make(
$request->all(),
[
'product_name' => 'required',
'product_value' => 'required',
'product_details' => 'required',
]
);
}
//created by; Hritik
//On - 02th July ,2024
//use - to Create Subscription
public function subscriptionToPlan(Request $request)
{
// dd($request->all());
try {
$isReferralSubscription = 0;
$referralUserId = $request->referral_user_id;
if( $referralUserId && $referralUserId != null){
$isReferralSubscription = 1;
}else{
$isReferralSubscription = 0;
}
$userId = $request->user_id;
$subscriptionProductXid = $request->subscription_product_xid;
$stripeSecret = (config('constants.subscription.stripe_secret_key'));
$stripe = new \Stripe\StripeClient($stripeSecret);
// $taxId = (config('services.stripe.tax_id'));
$userData = IamPrincipal::where('id', $userId)->first();
if ($userData) {
$subscriptionPlan = SubscriptionProducts::where('id', $subscriptionProductXid)->first();
if ($subscriptionPlan && $subscriptionPlan->stripe_price_id && $subscriptionPlan->stripe_price_id != null) {
$checkout = $stripe->checkout->sessions->create([
'customer_email' => $userData->email_address,
'line_items' => [
[
'price' => $subscriptionPlan->stripe_price_id,
'quantity' => 1,
// 'tax_rates'=>[$taxId],
],
],
'mode' => 'subscription',
// 'allow_promotion_codes' => true,
// 'tax_id_collection' => ['enabled' => true],
'metadata' => [
'userId' => $userData->id,
'userEmail' => $userData->email_address,
'subscriptionProductXid' => $subscriptionProductXid ,
'is_referral_subscription'=>$isReferralSubscription,
'referral_user_id'=>$referralUserId,
],
'success_url' => route('thankyou'),
// 'cancel_url' => "http://localhost/cheerstothe_season_2_o/my-subscription-page",
]);
return Redirect::away($checkout->url);
//note:-for now i am just sending the cveonly=0 and lmacve=1 for reference .'&lmacve=1&cveonly=0'
} else {
return redirect()->back()->with(['error' => "Something went wrong while subscription!"]);
}
}
} catch (\Exception $e) {
Log::error("An error occurred in " . _METHOD_ . ": " . $e->getMessage(), ['exception' => $e]);
return jsonResponseWithErrorMessage(__('auth.something_went_wrong'));
// return redirect()->back()->with(['error' => "Something went wrong while subscription!" . $e->getMessage()]);
}
}
public function thankyou(Request $request)
{
return view('Admin.pages.subscriptions.thank-you');
}
//created by; Hritik
//On - 28th May ,2024
//use - To cancel the subscription of user on end of subscription end period
public function cancelSubscription(Request $request)
{
try {
DB::beginTransaction();
$stripeSecret = (config('constants.subscription.stripe_secret_key'));
// $stripeSecret = env('STRIPE_SECRET');
$stripe = new \Stripe\StripeClient($stripeSecret);
$userId = $request->iam_principal_xid;
// dd($request->all(),$stripeSecret);
$getSubscriptionData = Subscriptions::where('iam_principal_xid', $userId)->where('subscription_status', 'active')->first();
$subscriptionId = $getSubscriptionData->subscription_id;
$cancelledSubscription = $stripe->subscriptions->update(
$subscriptionId,
['cancel_at_period_end' => true]
);
$subscriptionFromDatabase = Subscriptions::where('subscription_id', $subscriptionId)->first();
$subscriptionFromDatabase->cancelled_at = date('Y-m-d H:i:s', $cancelledSubscription->canceled_at);
$subscriptionFromDatabase->subscription_status = $cancelledSubscription->status;
$subscriptionFromDatabase->is_cancelled_subscription = 1; //2 for cancelled
$subscriptionFromDatabase->status = "cancelled";
$subscriptionFromDatabase->save();
$getSubscription = $stripe->subscriptions->retrieve($subscriptionFromDatabase->subscription_id, []);
$getSubscribeCustomer = $stripe->customers->retrieve(
$subscriptionFromDatabase->stripe_customer_id,
[]
);
DB::commit();
return redirect()->back()->with(['success' => "Your Subscription Cancelled Successfully!"]);
} catch (\Exception $e) {
DB::rollBack();
return redirect()->back()->with(['error' => "Something went wrong while cancelling subscription!" . $e->getMessage()]);
// Log::error("An error occurred in " . _METHOD_ . ": " . $e->getMessage(), ['exception' => $e]);
// return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
}
}
/**
* Created By : Hritik
* Created at : 05 Jult 2024
* Use : To Apply Referral Code and return the User Id.
*/
public function applyReferralCode(Request $request)
{
try {
$referralCode = $request->input('referral_code');
$currentUserId = $request->input('current_iam_principal_xid');
$code = IamPrincipal::where('referral_code', $referralCode)->where('id', '!=', $currentUserId)->where('principal_type_xid', 3)->first();
if ($code) {
return response()->json(['success' => true, 'message' => 'Referral code applied successfully.', 'referralUserId' => $code->id]);
} else {
return response()->json(['success' => false, 'message' => 'Invalid referral code.']);
}
} catch (\Exception $e) {
Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);
return jsonResponseWithErrorMessage(__('auth.something_went_wrong'));
}
}
}