Skip to content

Commit

Permalink
Ads fix and let users change stripe credit card for subscriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Neto committed Feb 3, 2025
1 parent d5075f4 commit bec77e3
Show file tree
Hide file tree
Showing 9 changed files with 508 additions and 54 deletions.
10 changes: 7 additions & 3 deletions plugin/PlayerSkins/events/playerAdsFunctions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
118 changes: 113 additions & 5 deletions plugin/StripeYPT/StripeYPT.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
}
Expand All @@ -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 {
Expand All @@ -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']);
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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']);
}
}
}
Expand Down Expand Up @@ -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()) {
Expand Down
57 changes: 57 additions & 0 deletions plugin/StripeYPT/addCard.json.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

require_once '../../videos/configuration.php';

header('Content-Type: application/json');
$obj = new stdClass();
$obj->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);
?>
82 changes: 41 additions & 41 deletions plugin/StripeYPT/createWebhook.json.php
Original file line number Diff line number Diff line change
@@ -1,41 +1,41 @@
<?php

// check recurrent payments
header('Content-Type: application/json');

if (empty($global['systemRootPath'])) {
$global['systemRootPath'] = '../../';
}
require_once $global['systemRootPath'] . 'videos/configuration.php';

_error_log("StripeINTENT Start");
$plugin = AVideoPlugin::loadPluginIfEnabled("YPTWallet");
$walletObject = AVideoPlugin::getObjectData("YPTWallet");
$stripe = AVideoPlugin::loadPluginIfEnabled("StripeYPT");
$stripeObject = AVideoPlugin::getObjectData("StripeYPT");

$obj = new stdClass();
$obj->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));
?>
<?php

// check recurrent payments
header('Content-Type: application/json');

if (empty($global['systemRootPath'])) {
$global['systemRootPath'] = '../../';
}
require_once $global['systemRootPath'] . 'videos/configuration.php';

_error_log("StripeINTENT Webhook Start");
$plugin = AVideoPlugin::loadPluginIfEnabled("YPTWallet");
$walletObject = AVideoPlugin::getObjectData("YPTWallet");
$stripe = AVideoPlugin::loadPluginIfEnabled("StripeYPT");
$stripeObject = AVideoPlugin::getObjectData("StripeYPT");

$obj = new stdClass();
$obj->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));
?>
48 changes: 48 additions & 0 deletions plugin/StripeYPT/deleteCard.json.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

require_once '../../videos/configuration.php';

header('Content-Type: application/json');
$obj = new stdClass();
$obj->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);
?>
Loading

0 comments on commit bec77e3

Please sign in to comment.