1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-03 09:49:28 +02:00

Ads fix and let users change stripe credit card for subscriptions

This commit is contained in:
Daniel Neto 2025-02-03 19:25:45 -03:00
parent d5075f48e9
commit bec77e39f0
9 changed files with 508 additions and 54 deletions

View file

@ -78,12 +78,16 @@ function setupLiveAdInterval() {
}
// Function to check and play ads based on current time
var checkAndPlayAdsTryCount = 1;
function checkAndPlayAds() {
if (!Array.isArray(scheduledAdTimes) || scheduledAdTimes.length === 0) {
checkAndPlayAdsTryCount++;
if(checkAndPlayAdsTryCount < 10){
console.log('No ads scheduled.');
setTimeout(checkAndPlayAds, 500);
setTimeout(checkAndPlayAds, checkAndPlayAdsTryCount*500);
return;
}
}
const currentTime = Math.floor(player.currentTime());

View file

@ -416,11 +416,14 @@ class StripeYPT extends PluginAbstract
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 @@ class StripeYPT extends PluginAbstract
$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 @@ class StripeYPT extends PluginAbstract
$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']);
@ -812,6 +818,108 @@ class StripeYPT extends PluginAbstract
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()) {

View file

@ -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);
?>

View file

@ -8,7 +8,7 @@ if (empty($global['systemRootPath'])) {
}
require_once $global['systemRootPath'] . 'videos/configuration.php';
_error_log("StripeINTENT Start");
_error_log("StripeINTENT Webhook Start");
$plugin = AVideoPlugin::loadPluginIfEnabled("YPTWallet");
$walletObject = AVideoPlugin::getObjectData("YPTWallet");
$stripe = AVideoPlugin::loadPluginIfEnabled("StripeYPT");

View file

@ -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);
?>

View file

@ -0,0 +1,37 @@
<?php
require_once '../../videos/configuration.php';
header('Content-Type: application/json');
if (!User::isLogged()) {
gotToLoginAndComeBackHere('Please login first');
}
$subscription_id = intval($_REQUEST['subscription_id']);
if (empty($subscription_id)) {
forbiddenPage('subscription_id plugin not found');
}
$users_id = User::getId();
$stripe = AVideoPlugin::loadPlugin("StripeYPT");
$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);
$obj = new stdClass();
$obj->error = false;
$obj->msg = "";
$obj->cards = $cards;
echo json_encode($obj);

View file

@ -0,0 +1,199 @@
<?php
require_once '../../videos/configuration.php';
if (!User::isLogged()) {
gotToLoginAndComeBackHere('Please login first');
}
$subscription_id = intval($_REQUEST['subscription_id']);
if (empty($subscription_id)) {
forbiddenPage('subscription_id plugin not found');
}
$users_id = User::getId();
$stripe = AVideoPlugin::loadPlugin("StripeYPT");
//$subscriptions = $stripe->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"));
?>
<div class="container-fluid">
<div id="card-list" class="panel panel-default">
<div class="panel-heading">
<h2><i class="fa fa-credit-card"></i> Manage Your Credit Cards</h2>
</div>
<div class="panel-body">
<ul class="list-group" id="saved-cards">
<li class="list-group-item text-center">Loading cards...</li>
</ul>
</div>
<div class="panel-footer">
<!-- Add New Card -->
<form action="#" method="post" id="payment-form">
<hr>
<div class="panel panel-default">
<div class="panel-heading"><strong><i class="fa fa-plus"></i> Add a New Card</strong></div>
<div class="panel-body">
<div id="card-element"></div>
<div id="card-errors" role="alert"></div>
</div>
<div class="panel-footer">
<button class="btn btn-primary btn-block" type="submit">Add Card</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://js.stripe.com/v3/"></script>
<script>
$(document).ready(function () {
loadCreditCards(); // Load cards when page loads
});
function loadCreditCards() {
let subscriptionId = <?php echo $subscription_id; ?>;
$.ajax({
url: webSiteRootURL+'plugin/StripeYPT/listCreditCards.json.php',
type: 'GET',
data: { subscription_id: subscriptionId },
dataType: 'json',
success: function (response) {
let cardList = $("#saved-cards");
cardList.empty(); // Clear previous list
if (response.error || !response.cards.length) {
cardList.append('<li class="list-group-item text-center">No saved cards.</li>');
return;
}
// Loop through the cards and append to the list
response.cards.forEach(function (card) {
let cardItem = `
<li class="list-group-item">
<i class="fa fa-credit-card"></i>
<strong>${card.card.brand.toUpperCase()}</strong> - **** **** **** ${card.card.last4}
<span class="label label-info">Exp: ${card.card.exp_month}/${card.card.exp_year}</span>
<button class="btn btn-danger btn-xs pull-right remove-card" onclick="deleteCardFromStripe('${card.id}')">
<i class="fa fa-trash"></i> Remove
</button>
</li>
`;
cardList.append(cardItem);
});
},
error: function () {
$("#saved-cards").html('<li class="list-group-item text-center">Failed to load cards.</li>');
}
});
}
// Create a Stripe client.
var stripe = Stripe('<?php echo $obj->Publishablekey; ?>');
var elements = stripe.elements();
// Card Styling
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {
style: style
});
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
displayError.textContent = event.error ? event.error.message : '';
});
// Handle form submission.
$('#payment-form').on('submit', function(event) {
event.preventDefault();
stripe.createPaymentMethod({
type: "card",
card: card
})
.then(function(result) {
if (result.error) {
$('#card-errors').text(result.error.message);
} else {
addCardToStripe(result.paymentMethod.id);
}
});
});
function addCardToStripe(paymentMethodId) {
modal.showPleaseWait();
$.ajax({
url: webSiteRootURL + 'plugin/StripeYPT/addCard.json.php',
data: {
paymentMethodId: paymentMethodId,
subscription_id: '<?php echo $subscription_id; ?>'
},
type: 'post',
complete: function(resp) {
avideoResponse(resp);
modal.hidePleaseWait();
loadCreditCards();
}
});
}
function deleteCardFromStripe(paymentMethodId) {
modal.showPleaseWait();
$.ajax({
url: webSiteRootURL + 'plugin/StripeYPT/deleteCard.json.php',
data: {
paymentMethodId: paymentMethodId,
subscription_id: '<?php echo $subscription_id; ?>'
},
type: 'post',
complete: function(resp) {
avideoResponse(resp);
modal.hidePleaseWait();
loadCreditCards();
}
});
}
</script>
<?php
$_page->print();
?>

View file

@ -189,7 +189,7 @@ $uid = uniqid();
avideoToastInfo(response.msg);
confirmSubscriptionPayment(response.payment);
} else {
avideoAlertError("<?php echo __("Error!"); ?>");
avideoResponse(response);
setTimeout(function() {
modal.hidePleaseWait();
}, 500);

View file

@ -52,6 +52,7 @@ $users_id = User::getId();
//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")) {