From bec77e39f0175c940f237b4c8bebf5a40562819d Mon Sep 17 00:00:00 2001 From: Daniel Neto Date: Mon, 3 Feb 2025 19:25:45 -0300 Subject: [PATCH] Ads fix and let users change stripe credit card for subscriptions --- .../PlayerSkins/events/playerAdsFunctions.js | 10 +- plugin/StripeYPT/StripeYPT.php | 118 ++++++++++- plugin/StripeYPT/addCard.json.php | 57 +++++ plugin/StripeYPT/createWebhook.json.php | 82 ++++---- plugin/StripeYPT/deleteCard.json.php | 48 +++++ plugin/StripeYPT/listCreditCards.json.php | 37 ++++ plugin/StripeYPT/listCreditCards.php | 199 ++++++++++++++++++ .../confirmRecurrentButton.php | 6 +- .../requestSubscription.json.php | 5 +- 9 files changed, 508 insertions(+), 54 deletions(-) create mode 100644 plugin/StripeYPT/addCard.json.php create mode 100644 plugin/StripeYPT/deleteCard.json.php create mode 100644 plugin/StripeYPT/listCreditCards.json.php create mode 100644 plugin/StripeYPT/listCreditCards.php diff --git a/plugin/PlayerSkins/events/playerAdsFunctions.js b/plugin/PlayerSkins/events/playerAdsFunctions.js index 34a91370ac89..75652748ca98 100644 --- a/plugin/PlayerSkins/events/playerAdsFunctions.js +++ b/plugin/PlayerSkins/events/playerAdsFunctions.js @@ -78,11 +78,15 @@ function setupLiveAdInterval() { } // Function to check and play ads based on current time +var checkAndPlayAdsTryCount = 1; function checkAndPlayAds() { if (!Array.isArray(scheduledAdTimes) || scheduledAdTimes.length === 0) { - console.log('No ads scheduled.'); - setTimeout(checkAndPlayAds, 500); - return; + checkAndPlayAdsTryCount++; + if(checkAndPlayAdsTryCount < 10){ + console.log('No ads scheduled.'); + setTimeout(checkAndPlayAds, checkAndPlayAdsTryCount*500); + return; + } } const currentTime = Math.floor(player.currentTime()); diff --git a/plugin/StripeYPT/StripeYPT.php b/plugin/StripeYPT/StripeYPT.php index 970e92dc4b92..0fc0ed732cf6 100644 --- a/plugin/StripeYPT/StripeYPT.php +++ b/plugin/StripeYPT/StripeYPT.php @@ -374,7 +374,7 @@ static function getSubscriptions($stripe_costumer_id, $plans_id) _error_log("StripeYPT::getSubscriptions We could not find the subscription trying to list from subscription $stripe_costumer_id, $plans_id " . json_encode($costumer)); */ - // I guess only this is enought + // I guess only this is enought $subscriptions = \Stripe\Subscription::all(['customer' => $stripe_costumer_id, 'status' => 'active']); if (!empty($subscriptions)) { foreach ($subscriptions->data as $value) { @@ -416,11 +416,14 @@ function userHasActiveSubscriptionOnPlan($plans_id) public function setUpSubscription($plans_id, $stripeToken) { + global $setUpSubscriptionErrorResponse; if (!User::isLogged()) { + $setUpSubscriptionErrorResponse = 'User not logged'; _error_log("setUpSubscription: User not logged"); return false; } if (empty($plans_id)) { + $setUpSubscriptionErrorResponse = 'plans_id is empty'; _error_log("setUpSubscription: plans_id is empty"); return false; } @@ -429,11 +432,13 @@ public function setUpSubscription($plans_id, $stripeToken) $obj = AVideoPlugin::getObjectData('YPTWallet'); if (empty($subs)) { + $setUpSubscriptionErrorResponse = 'Plan not found"'; _error_log("setUpSubscription: Plan not found"); return false; } $subscription = $this->userHasActiveSubscriptionOnPlan($plans_id); if (!empty($subscription)) { + $setUpSubscriptionErrorResponse = 'the user already have an active subscription for this plan'; _error_log("setUpSubscription: the user already have an active subscription for this plan " . json_encode($subscription)); return false; } else { @@ -451,6 +456,7 @@ public function setUpSubscription($plans_id, $stripeToken) $sub['stripe_costumer_id'] = $this->getCostumerId(User::getId(), $stripeToken); if (empty($sub['stripe_costumer_id'])) { _error_log("setUpSubscription: Could not create a Stripe costumer"); + $setUpSubscriptionErrorResponse = 'Could not create a Stripe costumer'; return false; } Subscription::getOrCreateStripeSubscription(User::getId(), $plans_id, $sub['stripe_costumer_id']); @@ -617,9 +623,9 @@ function processSubscriptionIPN($payload) if (!empty($metadata['users_id'])) { $pluginS->addBalance($metadata['users_id'], $payment_amount, "Stripe recurrent (no plan detected): " . $payload->data->object->description, json_encode($payload)); } - } else { + } else { $ipnFIle = "{$global['systemRootPath']}plugin/DiskUploadQuota/Subscription/Stripe/ipn.php"; - require_once $ipnFIle ; + require_once $ipnFIle; exit; } } else { @@ -719,10 +725,10 @@ static function getMetadataOrFromSubscription($payload) _error_log("getMetadataOrFromSubscription Customer::retrieve [$customer_id] => " . json_encode($c->metadata)); $obj = self::getMetadata($c->metadata); _error_log("getMetadataOrFromSubscription Customer::retrieve done " . json_encode($obj)); - if(empty($obj) && !empty($c->email)){ + if (empty($obj) && !empty($c->email)) { _error_log("getMetadataOrFromSubscription try from email " . json_encode($c->email)); $user = User::getUserFromEmail($c->email); - $obj = array('users_id'=>$user['id']); + $obj = array('users_id' => $user['id']); } } } @@ -812,6 +818,108 @@ function getAllSubscriptionsSearch($users_id, $plans_id) return $subscriptions; } + function getAllCreditCards($plans_id) + { + + $s = new SubscriptionTable($plans_id); + $customer_id = $s->getStripe_costumer_id(); + + $this->start(); + + // Retrieve the stored Stripe customer ID from the database + //$customer_id = getCustomerIdFromDB($users_id); + if (empty($customer_id)) { + _error_log("getAllCreditCards: No Stripe customer ID found for plan {$plans_id}"); + return false; + } + + try { + // Fetch all payment methods (cards) for the customer + $cards = \Stripe\Customer::allPaymentMethods($customer_id, ['type' => 'card']); + + return $cards->data; + } catch (Exception $e) { + _error_log("getAllCreditCards: Error fetching cards - " . $e->getMessage()); + return false; + } + } + + function addCard($customer_id, $paymentMethodId) + { + global $addCardErrorMessage; + $addCardErrorMessage = ''; + + try { + $this->start(); + + + // Retrieve the Payment Method object + $paymentMethod = \Stripe\PaymentMethod::retrieve($paymentMethodId); + + // Attach the payment method to the customer + $paymentMethod->attach(['customer' => $customer_id]); + + // Optionally, set this as the default payment method for future payments + \Stripe\Customer::update( + $customer_id, + [ + 'invoice_settings' => ['default_payment_method' => $paymentMethodId] + ] + ); + + return $paymentMethod; + } catch (\Stripe\Exception\ApiErrorException $exc) { + _error_log("addCard: Error: " . $exc->getMessage()); + $addCardErrorMessage = $exc->getMessage(); + return false; + } + } + + function addCardToSubscription($subscription, $paymentMethod) + { + try { + // Attach the payment method to the customer + $paymentMethod->attach(['customer' => $subscription->customer]); + + // Set this payment method as the default for future invoices + \Stripe\Customer::update( + $subscription->customer, + ['invoice_settings' => ['default_payment_method' => $paymentMethod->id]] + ); + + // Update the subscription to use the new payment method + \Stripe\Subscription::update( + $subscription->id, + ['default_payment_method' => $paymentMethod->id] + ); + + return true; + } catch (\Stripe\Exception\ApiErrorException $e) { + _error_log("addCardToSubscription: Error: " . $e->getMessage()); + return false; + } + } + + + function deleteCard($customerId, $paymentMethodId) + { + try { + $this->start(); + + var_dump(array($customerId, $paymentMethodId)); + // Retrieve the Payment Method object + $paymentMethod = \Stripe\PaymentMethod::retrieve($paymentMethodId); + // Detach the payment method from the customer + $response = $paymentMethod->detach(); + + return $response; + } catch (\Stripe\Exception\ApiErrorException $exc) { + _error_log("deleteCard: Error: " . $exc->getMessage()); + return false; + } + } + + function cancelSubscriptions($id) { if (!User::isLogged()) { diff --git a/plugin/StripeYPT/addCard.json.php b/plugin/StripeYPT/addCard.json.php new file mode 100644 index 000000000000..101223e9a9c0 --- /dev/null +++ b/plugin/StripeYPT/addCard.json.php @@ -0,0 +1,57 @@ +error = true; +$obj->msg = ""; + +if (empty($_POST['paymentMethodId'])) { + forbiddenPage('Invalid paymentMethodId'); +} + +if (empty($_REQUEST['subscription_id'])) { + forbiddenPage('subscription_id not found'); +} + +if (!User::isLogged()) { + forbiddenPage('Invalid user'); +} + +$users_id = User::getId(); + +$plugin = AVideoPlugin::loadPluginIfEnabled("StripeYPT"); + +if (empty($plugin)) { + forbiddenPage('Invalid StripeYPT'); +} + +$s = new SubscriptionTable($_REQUEST['subscription_id']); + +if($s->getUsers_id() != User::getId()){ + forbiddenPage('This plan does not belong to you'); +} + +$customer_id = $s->getStripe_costumer_id(); + +if (empty($customer_id)) { + forbiddenPage('Invalid customer_id'); +} + +$stripe = AVideoPlugin::loadPlugin("StripeYPT"); + +$paymentMethod = $stripe->addCard($customer_id, $_POST['paymentMethodId']); + +if(!empty($paymentMethod )){ + $subscription = $stripe->userHasActiveSubscriptionOnPlan($s->getSubscriptions_plans_id()); + if(!empty($subscription)){ + + } +} + +$obj->error = !$stripe->addCard($customer_id, $_POST['paymentMethodId']); +$obj->msg = $addCardErrorMessage; + +echo json_encode($obj); +?> diff --git a/plugin/StripeYPT/createWebhook.json.php b/plugin/StripeYPT/createWebhook.json.php index 55e1f2692f2c..8694efe0cf77 100644 --- a/plugin/StripeYPT/createWebhook.json.php +++ b/plugin/StripeYPT/createWebhook.json.php @@ -1,41 +1,41 @@ -error = true; -$obj->msg = ""; - -if (!User::isAdmin()) { - $obj->msg = "Admin only"; - die(json_encode($obj)); -} - -if (empty($stripe)) { - $obj->msg = "Stripe Plugin Disabled"; - die(json_encode($obj)); -} -if (empty($plugin)) { - $obj->msg = "Wallet Plugin Disabled"; - die(json_encode($obj)); -} - - -StripeYPT::_start(); -$obj->webhook = StripeYPT::getWebhook(); -$obj->error = empty($obj->webhook); - -die(json_encode($obj)); -?> \ No newline at end of file +error = true; +$obj->msg = ""; + +if (!User::isAdmin()) { + $obj->msg = "Admin only"; + die(json_encode($obj)); +} + +if (empty($stripe)) { + $obj->msg = "Stripe Plugin Disabled"; + die(json_encode($obj)); +} +if (empty($plugin)) { + $obj->msg = "Wallet Plugin Disabled"; + die(json_encode($obj)); +} + + +StripeYPT::_start(); +$obj->webhook = StripeYPT::getWebhook(); +$obj->error = empty($obj->webhook); + +die(json_encode($obj)); +?> diff --git a/plugin/StripeYPT/deleteCard.json.php b/plugin/StripeYPT/deleteCard.json.php new file mode 100644 index 000000000000..03566465b2e6 --- /dev/null +++ b/plugin/StripeYPT/deleteCard.json.php @@ -0,0 +1,48 @@ +error = true; +$obj->msg = ""; + +if (empty($_POST['paymentMethodId'])) { + forbiddenPage('Invalid paymentMethodId'); +} + +if (empty($_REQUEST['subscription_id'])) { + forbiddenPage('subscription_id not found'); +} + +if (!User::isLogged()) { + forbiddenPage('Invalid user'); +} + +$users_id = User::getId(); + +$plugin = AVideoPlugin::loadPluginIfEnabled("StripeYPT"); + +if (empty($plugin)) { + forbiddenPage('Invalid StripeYPT'); +} + +$s = new SubscriptionTable($_REQUEST['subscription_id']); + +if($s->getUsers_id() != User::getId()){ + forbiddenPage('This plan does not belong to you'); +} + +$customer_id = $s->getStripe_costumer_id(); + +if (empty($customer_id)) { + forbiddenPage('Invalid customer_id'); +} + +$stripe = AVideoPlugin::loadPlugin("StripeYPT"); + +$obj->error = !$stripe->deleteCard($customer_id, $_POST['paymentMethodId']); +$obj->msg = $addCardErrorMessage; + +echo json_encode($obj); +?> diff --git a/plugin/StripeYPT/listCreditCards.json.php b/plugin/StripeYPT/listCreditCards.json.php new file mode 100644 index 000000000000..20020cf82bb2 --- /dev/null +++ b/plugin/StripeYPT/listCreditCards.json.php @@ -0,0 +1,37 @@ +getUsers_id()) { + forbiddenPage('This plan does not belong to you'); +} + +$cards = $stripe->getAllCreditCards($subscription_id); + + +$obj = new stdClass(); +$obj->error = false; +$obj->msg = ""; +$obj->cards = $cards; + +echo json_encode($obj); diff --git a/plugin/StripeYPT/listCreditCards.php b/plugin/StripeYPT/listCreditCards.php new file mode 100644 index 000000000000..9f525043ce5e --- /dev/null +++ b/plugin/StripeYPT/listCreditCards.php @@ -0,0 +1,199 @@ +getAllSubscriptionsSearch($users_id, 0); +//var_dump($subscriptions->data);exit; + +$subs = AVideoPlugin::loadPluginIfEnabled("Subscription"); + +if (empty($subs)) { + forbiddenPage('Subscription plugin not found'); +} + +$s = new SubscriptionTable($subscription_id); + +if (!User::isAdmin() && $users_id != $s->getUsers_id()) { + forbiddenPage('This plan does not belong to you'); +} + +$cards = $stripe->getAllCreditCards($subscription_id); + +global $planTitle; +$obj = AVideoPlugin::getObjectData('StripeYPT'); +$_page = new Page(array("Credit cards")); +?> + +
+
+
+

Manage Your Credit Cards

+
+
+
    +
  • Loading cards...
  • +
+
+ +
+
+ + + + +print(); +?> diff --git a/plugin/YPTWallet/plugins/YPTWalletStripe/confirmRecurrentButton.php b/plugin/YPTWallet/plugins/YPTWalletStripe/confirmRecurrentButton.php index b8137306b7ec..a80d09d37fdb 100644 --- a/plugin/YPTWallet/plugins/YPTWalletStripe/confirmRecurrentButton.php +++ b/plugin/YPTWallet/plugins/YPTWalletStripe/confirmRecurrentButton.php @@ -189,12 +189,12 @@ function checkPayment(response) { avideoToastInfo(response.msg); confirmSubscriptionPayment(response.payment); } else { - avideoAlertError(""); + avideoResponse(response); setTimeout(function() { modal.hidePleaseWait(); }, 500); } - + } modal.showPleaseWait(); @@ -211,4 +211,4 @@ function checkPayment(response) { success: checkPayment }); } - \ No newline at end of file + diff --git a/plugin/YPTWallet/plugins/YPTWalletStripe/requestSubscription.json.php b/plugin/YPTWallet/plugins/YPTWalletStripe/requestSubscription.json.php index f3cce3370f21..75086a66b225 100644 --- a/plugin/YPTWallet/plugins/YPTWalletStripe/requestSubscription.json.php +++ b/plugin/YPTWallet/plugins/YPTWalletStripe/requestSubscription.json.php @@ -35,7 +35,7 @@ if($obj->plans_id > 0 || !User::isAdmin()){ $subs = new SubscriptionPlansTable($obj->plans_id); - + if(empty($subs)){ forbiddenPage("Plan Not found"); } @@ -52,6 +52,7 @@ //setUpSubscription($invoiceNumber, $redirect_url, $cancel_url, $total = '1.00', $currency = "USD", $frequency = "Month", $interval = 1, $name = 'Base Agreement') _error_log("Request subscription setUpSubscription: ". json_encode($_POST)); $payment = $plugin->setUpSubscription($obj->plans_id, $_POST['stripeToken']); +$obj->msg = $setUpSubscriptionErrorResponse; $obj->payment = $payment; _error_log("Request subscription setUpSubscription Done "); if (!empty($payment) && !empty($payment->status) && ($payment->status=="active" || $payment->status=="trialing")) { @@ -66,4 +67,4 @@ $obj->msg = "Please Confirm your Payment"; $obj->customer = $payment->customer; } -die(json_encode($obj)); \ No newline at end of file +die(json_encode($obj));