diff --git a/app/Http/Controllers/APIs/Customer_API/StripeWebhookController.php b/app/Http/Controllers/APIs/Customer_API/StripeWebhookController.php index b6130ec..b69d0db 100644 --- a/app/Http/Controllers/APIs/Customer_API/StripeWebhookController.php +++ b/app/Http/Controllers/APIs/Customer_API/StripeWebhookController.php @@ -142,8 +142,8 @@ class StripeWebhookController extends Controller $referralUserSubscriptionData->current_period_start = date('Y-m-d H:i:s', $SubscriptionObject->current_period_start); $referralUserSubscriptionData->current_period_end = date('Y-m-d H:i:s', $SubscriptionObject->current_period_end); $referralUserSubscriptionData->next_payment_date = date('Y-m-d H:i:s', $upcoming_invoice->next_payment_attempt); - $referralUserSubscriptionData->next_invoice_amount = $upcoming_invoice->amount_due / 100; - + $referralUserSubscriptionData->next_invoice_amount = $upcoming_invoice->amount_due / 100; + $referralUserSubscriptionData->save(); Log::info("Referral User Subscription Updated with Referral"); @@ -192,7 +192,7 @@ class StripeWebhookController extends Controller 'status' => 'complete', 'next_payment_date' => date('Y-m-d H:i:s', $upcoming_invoice->next_payment_attempt), 'next_invoice_amount' => $upcoming_invoice->amount_due / 100 - + ] ); @@ -230,8 +230,8 @@ class StripeWebhookController extends Controller $newUserSubscriptionDetails->current_period_start = date('Y-m-d H:i:s', $SubscriptionObject->current_period_start); $newUserSubscriptionDetails->current_period_end = date('Y-m-d H:i:s', $SubscriptionObject->current_period_end); $newUserSubscriptionDetails->next_payment_date = date('Y-m-d H:i:s', $upcoming_invoice->next_payment_attempt); - $newUserSubscriptionDetails->next_invoice_amount = $upcoming_invoice->amount_due / 100; - + $newUserSubscriptionDetails->next_invoice_amount = $upcoming_invoice->amount_due / 100; + $newUserSubscriptionDetails->save(); Log::info("new User Subscription Updated with Referral"); @@ -272,6 +272,71 @@ class StripeWebhookController extends Controller //end } + if ($event->type === 'invoice.payment_succeeded') { + + try { + + DB::beginTransaction(); + $invoice = $event->data->object; + + $metadata = $invoice->metadata; + + // + $productID = $invoice->lines->data[0]->price->product; + $subscriptionProductData = SubscriptionProducts::where('stripe_product_id', $productID)->first(); + + $customerID = $invoice->customer; + + $subscriptionId = $invoice->lines->data[0]->subscription; + + $subscriptionObject = $stripe->subscriptions->retrieve($subscriptionId, []); + + $upcoming_invoice = $stripe->invoices->upcoming([ + 'subscription' => $subscriptionId, // use retrieved id from subscription + ]); + + + $isCustomerStoredInSubscriptionTable = Subscriptions::where('stripe_customer_id', $customerID)->first(); + if ($isCustomerStoredInSubscriptionTable == null) { + return response('Webhook received at null ', 200); + } + + $subscriptionInDatabase = Subscriptions::where('stripe_customer_id', $customerID)->where('subscription_id', $subscriptionId)->where('is_cancelled_subscription', 0)->first(); + + $subscriptionInDatabase->subscription_status = $subscriptionObject->status; + $subscriptionInDatabase->current_period_end = date('Y-m-d H:i:s', $upcoming_invoice->next_payment_attempt); + $subscriptionInDatabase->status = 'complete'; + $subscriptionInDatabase->next_payment_date = date('Y-m-d H:i:s', $upcoming_invoice->next_payment_attempt); + $subscriptionInDatabase->save(); + + + $iamPrincialData = IamPrincipal::where('id', $subscriptionInDatabase->iam_principal_xid)->first(); + + + + $title = "Congratulations your Subscription has been Renewed"; + $message = $iamPrincialData->first_name . " has subscribed for " . $subscriptionProductData->product_name; + $content_type = "recurring_subscription"; + + onesignalhelper::sendNotificationApi($iamPrincialData->one_signal_player_id, $title, $message, $content_type, $image = null, $id = null); + + Log::info("Recurring Subscription has been Updated"); + DB::commit(); + + } catch (\Exception $e) { + Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage()); + // return response()->json(['error' => __('something_went_wrong')], 500); + + DB::rollBack(); + Log::error('Customer Subscription Invoice payment function failed:' . $e->getMessage()); + + } + // write your code here + // after successful event this actions will be taken + + //hritik code + + } return response('Webhook received', 200); } diff --git a/app/Http/Helpers/Webhelper.php b/app/Http/Helpers/Webhelper.php index 7d87aee..1f762b0 100644 --- a/app/Http/Helpers/Webhelper.php +++ b/app/Http/Helpers/Webhelper.php @@ -8,11 +8,7 @@ use Illuminate\Support\Facades\Http; use Tymon\JWTAuth\Facades\JWTAuth; use GuzzleHttp\Client; -/** - * Created By : sayli raut - * Created at : 24 Jan 2024 - * Use : Json response with success message for API - */ + if (!function_exists('jsonResponseWithSuccessMessageApi')) { function jsonResponseWithSuccessMessageApi($message, $data = [], $statusCode = 200) { @@ -33,11 +29,7 @@ if (!function_exists('jsonResponseWithSuccessMessageApi')) { } } -/** - * Created By : sayli raut - * Created at : 24 jan 2024 - * Use : Json response with error message for API - */ + if (!function_exists('jsonResponseWithErrorMessageApi')) { function jsonResponseWithErrorMessageApi($errorMessage, $statusCode = 500) { @@ -57,11 +49,29 @@ if (!function_exists('jsonResponseWithErrorMessageApi')) { } } -/** - * Created by : sayli raut - * Created at : 24 Jan 2024 - * Use : To return error json response for admin - */ + +if (!function_exists('jsonResponseWithDataErrorMessageApi')) { + function jsonResponseWithDataErrorMessageApi($errorMessage, $data = [], $statusCode = 406) + { + // Set the HTTP status code + http_response_code($statusCode); + + // Prepare the response array + $response = [ + 'status' => 'error', + 'status_code' => $statusCode, + 'message' => $errorMessage, + 'data' => $data, + + ]; + return response()->json($response, $statusCode); + + // Stop further execution (optional) + exit(); + } +} + + if (!function_exists('jsonResponseWithErrorMessage')) { function jsonResponseWithErrorMessage($errorMessage) { @@ -76,11 +86,7 @@ if (!function_exists('jsonResponseWithErrorMessage')) { } } -/** - * Created by : sayli raut - * Created at : 24 Jan 2024 - * Use : To return success json response for admin - */ + if (!function_exists('jsonResponseWithSuccessMessage')) { function jsonResponseWithSuccessMessage($message, $data = []) { @@ -99,11 +105,7 @@ if (!function_exists('jsonResponseWithSuccessMessage')) { } } -/** - * Created by : Pradyumn Dwivedi - * Created On : 11-May-2022 - * Uses: This function will be used to full search data in api. - */ + if (!function_exists('fullSearchQuery')) { function fullSearchQuery($query, $word, $columns) { @@ -117,11 +119,7 @@ if (!function_exists('fullSearchQuery')) { } } -/** - * Created by : sayli raut - * Created at : 24 Feb 2024 - * Use : To check and validate to customer token - */ + if (!function_exists('readHeaderToken')) { function readHeaderToken() { @@ -144,11 +142,7 @@ if (!function_exists('readHeaderToken')) { } } -/** - * Created by : sayli raut - * Created at : 24 jan 2024 - * Use : To check and validate login restaurant user token - */ + if (!function_exists('readRestHeaderToken')) { function readRestHeaderToken() { @@ -193,7 +187,7 @@ if (!function_exists('readRestHeaderToken')) { if (!function_exists('getOpeningHoursOfRestaurant')) { function getOpeningHoursOfRestaurant($restaurantName) { - + $googlePlaceApiKey = config('constants.googlePlaces.api_key'); // Your webhook secret key // dd($googlePlaceApiKey); @@ -209,7 +203,7 @@ if (!function_exists('getOpeningHoursOfRestaurant')) { ] ]); $placeData = json_decode($response->getBody(), true); - + if (isset($placeData['candidates'][0]['place_id'])) { $placeId = $placeData['candidates'][0]['place_id']; // return $placeId; diff --git a/app/Jobs/FetchOperatingHours.php b/app/Jobs/FetchOperatingHours.php new file mode 100644 index 0000000..775ecdb --- /dev/null +++ b/app/Jobs/FetchOperatingHours.php @@ -0,0 +1,68 @@ +restaurantName = $restaurantName; + $this->googlePlaceApiKey = $googlePlaceApiKey; + } + + public function handle() + { + $client = new Client(); + $url = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json'; + + $response = $client->get($url, [ + 'query' => [ + 'fields' => 'place_id', + 'input' => $this->restaurantName, + 'inputtype' => 'textquery', + 'key' => $this->googlePlaceApiKey + ] + ]); + $placeData = json_decode($response->getBody(), true); + + if (isset($placeData['candidates'][0]['place_id'])) { + $placeId = $placeData['candidates'][0]['place_id']; + + $url = 'https://maps.googleapis.com/maps/api/place/details/json'; + $response = $client->get($url, [ + 'query' => [ + 'fields' => 'opening_hours', + 'place_id' => $placeId, + 'key' => $this->googlePlaceApiKey + ] + ]); + + $data = json_decode($response->getBody(), true); + if (isset($data['result']['opening_hours']['weekday_text'])) { + $hours = $data['result']['opening_hours']['weekday_text']; + Cache::put('restaurant_hours_' . $this->restaurantName, $hours, now()->addHours(24)); + } else { + Cache::put('restaurant_hours_' . $this->restaurantName, "N/A", now()->addHours(24)); + } + } else { + Cache::put('restaurant_hours_' . $this->restaurantName, "N/A", now()->addHours(24)); + } + } +} diff --git a/app/Services/APIs/CustomerAPIs/RestaurantApiServices.php b/app/Services/APIs/CustomerAPIs/RestaurantApiServices.php index 2828db8..38f05af 100644 --- a/app/Services/APIs/CustomerAPIs/RestaurantApiServices.php +++ b/app/Services/APIs/CustomerAPIs/RestaurantApiServices.php @@ -16,7 +16,7 @@ use Carbon\Carbon; use Exception; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; - +use App\Jobs\FetchOperatingHours; use GuzzleHttp\Client; use GuzzleHttp\Promise; use GuzzleHttp\Promise\Utils; @@ -120,7 +120,6 @@ class RestaurantApiServices return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500); } } - public function addToFavourite($customerIamId, $request) { try { @@ -177,96 +176,96 @@ class RestaurantApiServices } } -// -public function DetailRestaurant($customerIamId, $id) -{ - try { - $rest = ManageRestaurant::select('id', 'short_id', 'name', 'description', 'restaurant_id', 'address', 'image', 'bio', 'try_on_1', 'try_on_2', 'try_on_3', 'try_on_4', 'exclusion', 'latitude', 'longtitude', 'state_xid') - ->where('short_id', $id) - ->where('is_active', '1') - ->first(); + // + public function DetailRestaurant($customerIamId, $id) + { + try { + $rest = ManageRestaurant::select('id', 'short_id', 'name', 'description', 'restaurant_id', 'address', 'image', 'bio', 'try_on_1', 'try_on_2', 'try_on_3', 'try_on_4', 'exclusion', 'latitude', 'longtitude', 'state_xid') + ->where('short_id', $id) + ->where('is_active', '1') + ->first(); - if ($rest) { - $rest->image = ListingImageUrl('restaurant_images', $rest->image); + if ($rest) { + $rest->image = ListingImageUrl('restaurant_images', $rest->image); - $isFavourite = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId) - ->where('restaurant_xid', $rest->id) - ->exists(); + $isFavourite = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId) + ->where('restaurant_xid', $rest->id) + ->exists(); $rest->is_favourite = $isFavourite; $redeem = RedeemRestaurant::where('iam_principal_xid', $customerIamId) - ->where('manage_restaurants_xid', $rest->id) - ->where('is_redeem', "1") - ->first(); + ->where('manage_restaurants_xid', $rest->id) + ->where('is_redeem', "1") + ->first(); - $restTime = RestaurantTimeInterval::where('manage_restaurants_xid', $rest->id)->first(); - $restTimeHours = $restTime->time_hours; + $restTime = RestaurantTimeInterval::where('manage_restaurants_xid', $rest->id)->first(); + $restTimeHours = $restTime->time_hours; - // Initialize Guzzle HTTP client - $client = new Client(); - $googlePlaceApiKey = config('constants.googlePlaces.api_key'); + // Initialize Guzzle HTTP client + $client = new Client(); + $googlePlaceApiKey = config('constants.googlePlaces.api_key'); - // Cache key for operating hours - $cacheKey = 'restaurant_hours_' . $rest->name; - if (Cache::has($cacheKey)) { - $rest->operating_hours = Cache::get($cacheKey); - } else { - // Prepare the first request to get the place_id - $placeResponse = $client->get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json', [ - 'query' => [ - 'fields' => 'place_id', - 'input' => $rest->name, - 'inputtype' => 'textquery', - 'key' => $googlePlaceApiKey - ] - ]); - $placeData = json_decode($placeResponse->getBody(), true); - - if (isset($placeData['candidates'][0]['place_id'])) { - $placeId = $placeData['candidates'][0]['place_id']; - - // Prepare the second request to get the operating hours - $detailResponse = $client->get('https://maps.googleapis.com/maps/api/place/details/json', [ + // Cache key for operating hours + $cacheKey = 'restaurant_hours_' . $rest->name; + if (Cache::has($cacheKey)) { + $rest->operating_hours = Cache::get($cacheKey); + } else { + // Prepare the first request to get the place_id + $placeResponse = $client->get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json', [ 'query' => [ - 'fields' => 'opening_hours', - 'place_id' => $placeId, + 'fields' => 'place_id', + 'input' => $rest->name, + 'inputtype' => 'textquery', 'key' => $googlePlaceApiKey ] ]); - $detailData = json_decode($detailResponse->getBody(), true); + $placeData = json_decode($placeResponse->getBody(), true); - if (isset($detailData['result']['opening_hours']['weekday_text'])) { - $hours = $detailData['result']['opening_hours']['weekday_text']; - Cache::put($cacheKey, $hours, now()->addHours(24)); - $rest->operating_hours = $hours; + if (isset($placeData['candidates'][0]['place_id'])) { + $placeId = $placeData['candidates'][0]['place_id']; + + // Prepare the second request to get the operating hours + $detailResponse = $client->get('https://maps.googleapis.com/maps/api/place/details/json', [ + 'query' => [ + 'fields' => 'opening_hours', + 'place_id' => $placeId, + 'key' => $googlePlaceApiKey + ] + ]); + $detailData = json_decode($detailResponse->getBody(), true); + + if (isset($detailData['result']['opening_hours']['weekday_text'])) { + $hours = $detailData['result']['opening_hours']['weekday_text']; + Cache::put($cacheKey, $hours, now()->addHours(24)); + $rest->operating_hours = $hours; + } else { + $rest->operating_hours = "N/A"; + } } else { $rest->operating_hours = "N/A"; } + } + + if ($redeem) { + $rest->is_Redeemed = true; + $rest->redeem_date = \Carbon\Carbon::parse($redeem->redeem_date)->addHours($restTimeHours)->toDateTimeString(); } else { - $rest->operating_hours = "N/A"; + $rest->is_Redeemed = false; + $rest->redeem_date = null; } } - if ($redeem) { - $rest->is_Redeemed = true; - $rest->redeem_date = \Carbon\Carbon::parse($redeem->redeem_date)->addHours($restTimeHours)->toDateTimeString(); - } else { - $rest->is_Redeemed = false; - $rest->redeem_date = null; + if (!$rest) { + return jsonResponseWithErrorMessage(__('auth.restaurant_data_not_found'), 404); } - } - if (!$rest) { - return jsonResponseWithErrorMessage(__('auth.restaurant_data_not_found'), 404); + return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $rest, 200); + } catch (Exception $e) { + Log::error("Error fetching restaurant data: " . $e->getMessage()); + return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500); } - - return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $rest, 200); - } catch (Exception $e) { - Log::error("Error fetching restaurant data: " . $e->getMessage()); - return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500); } -} @@ -360,7 +359,7 @@ public function DetailRestaurant($customerIamId, $id) if ($restaurantExist) { - return jsonResponseWithErrorMessageApi(__('auth.restaurant_already_redeemed'), 400); + return jsonResponseWithErrorMessageApi(__('auth.restaurant_already_redeemed'), 403); } $stateLimitation = TimeInterval::where('manage_state_xid', $restaurant->state_xid)->first(); @@ -381,7 +380,7 @@ public function DetailRestaurant($customerIamId, $id) ->count(); if ($redeemCountState >= $stateMaxLimitation) { - return jsonResponseWithErrorMessageApi(__('auth.state_limit_reached'), 404); + return jsonResponseWithDataErrorMessageApi(__('limitexceed') , ('You have reached the maximum limit for redeeming vouchers.')); } // Calculate the restaurant interval start date @@ -394,7 +393,7 @@ public function DetailRestaurant($customerIamId, $id) ->count(); if ($redeemCountRestaurant >= $restaurantMaxLimitation) { - return jsonResponseWithErrorMessageApi(__('auth.restaurant_limit_reached'), 404); + return jsonResponseWithDataErrorMessageApi(__('limitexceed') , ('You have reached the maximum limit for redeeming vouchers.')); } // Get the last redeem time @@ -423,14 +422,14 @@ public function DetailRestaurant($customerIamId, $id) $remainingTime = $currentTime->diff($stateAllowedRedeemTime); $hours = $remainingTime->h; $minutes = $remainingTime->i; - return jsonResponseWithErrorMessageApi(__('auth.redeem_not_allowed_yet') . " {$hours} hours and {$minutes} minutes remaining.", 404); + return jsonResponseWithDataErrorMessageApi(__('limitexceed') , ('Please wait before redeeming the next voucher.'. " {$hours} hours and {$minutes} minutes remaining.")); } if ($currentTime < $restAllowedRedeemTime) { $remainingTime = $currentTime->diff($restAllowedRedeemTime); $hours = $remainingTime->h; $minutes = $remainingTime->i; - return jsonResponseWithErrorMessageApi(__('auth.redeem_not_allowed_yet') . " {$hours} hours and {$minutes} minutes remaining.", 404); + return jsonResponseWithDataErrorMessageApi(__('limitexceed') , ('Please wait before redeeming the next voucher.'. " {$hours} hours and {$minutes} minutes remaining.")); } }