Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade Stripe library/API version to current #1800

Merged
merged 5 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions classes/Stripe.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public function __construct($stripeSecretKey) {
self::$instance = $this;

\Stripe\Stripe::setApiKey($stripeSecretKey);
\Stripe\Stripe::setApiVersion(STRIPE_API_VERSION);
}

public function getSubscription($args) {
Expand Down
101 changes: 72 additions & 29 deletions classes/Subscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class Subscription {
public $has_payment_data = false;

private static $plans = ['twfy-1k', 'twfy-5k', 'twfy-10k', 'twfy-0k'];
private static $prices = [2000, 5000, 10000, 30000];

public function __construct($arg) {
# User ID
Expand Down Expand Up @@ -62,9 +63,10 @@ public function __construct($arg) {
'customer.default_source',
'customer.invoice_settings.default_payment_method',
'latest_invoice.payment_intent',
'schedule.phases.items.plan',
],
]);
} catch (\Stripe\Error\InvalidRequest $e) {
} catch (\Stripe\Exception\InvalidRequestException $e) {
$this->db->query('DELETE FROM api_subscription WHERE stripe_id = :stripe_id', [':stripe_id' => $id]);
$this->delete_from_redis();
return;
Expand All @@ -90,7 +92,7 @@ public function __construct($arg) {

try {
$this->upcoming = $this->api->getUpcomingInvoice(["customer" => $this->stripe->customer->id]);
} catch (\Stripe\Error\Base $e) {
} catch (\Stripe\Exception\ApiErrorException $e) {
}
}

Expand All @@ -99,33 +101,74 @@ private function update_subscription($form_data) {
$this->update_payment_method($form_data['payment_method']);
}

# Update Stripe subscription
$args = [
'payment_behavior' => 'allow_incomplete',
'plan' => $form_data['plan'],
'metadata' => $form_data['metadata'],
'cancel_at_period_end' => false, # Needed in Stripe 2018-02-28
];
if ($form_data['coupon']) {
$args['coupon'] = $form_data['coupon'];
} elseif ($this->stripe->discount) {
$args['coupon'] = '';
foreach ($this::$plans as $i => $plan) {
if ($plan == $form_data['plan']) {
$new_price = $this::$prices[$i];
if ($form_data['coupon'] == 'charitable100') {
$new_price = 0;
} elseif ($form_data['coupon'] == 'charitable50') {
$new_price /= 2;
}
}
if ($plan == $this->stripe->plan->id) {
$old_price = $this::$prices[$i];
if ($this->stripe->discount && ($coupon = $this->stripe->discount->coupon)) {
if ($coupon->percent_off == 100) {
$old_price = 0;
} elseif ($coupon->percent_off == 50) {
$old_price /= 2;
}
}
}
}
\Stripe\Subscription::update($this->stripe->id, $args);

# Attempt immediate payment on the upgrade
try {
$invoice = \Stripe\Invoice::create([
'customer' => $this->stripe->customer,
'subscription' => $this->stripe,
'tax_percent' => 20,
]);
$invoice->finalizeInvoice();
$invoice->pay();
} catch (\Stripe\Error\InvalidRequest $e) {
# No invoice created if nothing to pay
} catch (\Stripe\Error\Card $e) {
# A source may still require 3DS... Stripe will have sent an email :-/
if ($old_price >= $new_price) {
if ($this->stripe->schedule) {
\Stripe\SubscriptionSchedule::release($this->stripe->schedule);
}
$schedule = \Stripe\SubscriptionSchedule::create(['from_subscription' => $this->stripe->id]);
$phases = [
[
'items' => [['price' => $schedule->phases[0]->items[0]->price]],
'start_date' => $schedule->phases[0]->start_date,
'end_date' => $schedule->phases[0]->end_date,
'proration_behavior' => 'none',
'default_tax_rates' => [STRIPE_TAX_RATE],
],
[
'items' => [['price' => $form_data['plan']]],
'iterations' => 1,
'metadata' => $form_data['metadata'],
'proration_behavior' => 'none',
'default_tax_rates' => [STRIPE_TAX_RATE],
],
];
if ($schedule->phases[0]->discounts && $schedule->phases[0]->discounts[0]->coupon) {
$phases[0]['discounts'] = [['coupon' => $schedule->phases[0]->discounts[0]->coupon]];
}
if ($form_data['coupon']) {
$phases[1]['coupon'] = $form_data['coupon'];
}
\Stripe\SubscriptionSchedule::update($schedule->id, ['phases' => $phases]);
}

if ($old_price < $new_price) {
$args = [
'payment_behavior' => 'allow_incomplete',
'plan' => $form_data['plan'],
'metadata' => $form_data['metadata'],
'cancel_at_period_end' => false, # Needed in Stripe 2018-02-28
'proration_behavior' => 'always_invoice',
];
if ($form_data['coupon']) {
$args['coupon'] = $form_data['coupon'];
} elseif ($this->stripe->discount) {
dracos marked this conversation as resolved.
Show resolved Hide resolved
$args['coupon'] = '';
}
if ($this->stripe->schedule) {
\Stripe\SubscriptionSchedule::release($this->stripe->schedule);
}
\Stripe\Subscription::update($this->stripe->id, $args);
}
}

Expand Down Expand Up @@ -158,7 +201,7 @@ private function add_subscription($form_data) {
# security code can be checked, and therefore fail
try {
$obj = $this->api->createCustomer($cust_params);
} catch (\Stripe\Error\Card $e) {
} catch (\Stripe\Exception\CardException $e) {
$body = $e->getJsonBody();
$err = $body['error'];
$error = 'Sorry, we could not process your payment, please try again. ';
Expand All @@ -176,7 +219,7 @@ private function add_subscription($form_data) {
$obj = $this->api->createSubscription([
'payment_behavior' => 'allow_incomplete',
'expand' => ['latest_invoice.payment_intent'],
'tax_percent' => 20,
'default_tax_rates' => [STRIPE_TAX_RATE],
'customer' => $customer,
'plan' => $form_data['plan'],
'coupon' => $form_data['coupon'],
Expand Down
2 changes: 1 addition & 1 deletion classes/TestStripe.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function getSubscription($args) {
'latest_invoice' => [],
'customer' => [
'id' => 'cus_123',
'account_balance' => 0,
'balance' => 0,
'default_source' => [],
'invoice_settings' => [
'default_payment_method' => [],
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"filp/whoops": "2.*",
"ircmaxell/password-compat": "1.0.4",
"facebook/graph-sdk": "^5.6",
"stripe/stripe-php": "^6.10",
"stripe/stripe-php": "^14.9",
"predis/predis": "^1.1",
"volnix/csrf": "^1.2",
"phpmailer/phpmailer": "^6.5",
Expand Down
23 changes: 11 additions & 12 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions conf/general-example
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ define('STRIPE_DONATE_SECRET_KEY', '');
define('STRIPE_PUBLIC_KEY', '');
define('STRIPE_SECRET_KEY', '');
define('STRIPE_ENDPOINT_SECRET', '');
define('STRIPE_API_VERSION', '');
define('STRIPE_TAX_RATE', '');
define('REDIS_DB_HOST', 'localhost');
define('REDIS_DB_PORT', '6379');
define('REDIS_DB_NUMBER', '0');
Expand Down
5 changes: 4 additions & 1 deletion www/docs/api/cancel-plan.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@
exit;
}

$subscription->stripe->cancel(['at_period_end' => true]);
if ($subscription->stripe->schedule) {
\Stripe\SubscriptionSchedule::release($subscription->stripe->schedule);
}
\Stripe\Subscription::update($subscription->stripe->id, ['cancel_at_period_end' => true]);
redirect('/api/key?cancelled=1');
}

Expand Down
9 changes: 5 additions & 4 deletions www/docs/api/hook.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
include_once '../../includes/easyparliament/init.php';

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);
\Stripe\Stripe::setApiVersion(STRIPE_API_VERSION);

$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
Expand All @@ -13,7 +14,7 @@
} catch (\UnexpectedValueException $e) {
http_response_code(400);
exit();
} catch (\Stripe\Error\SignatureVerification $e) {
} catch (\Stripe\Exception\SignatureVerificationException $e) {
http_response_code(400);
exit();
}
Expand Down Expand Up @@ -61,12 +62,12 @@
if ($obj->charge) {
\Stripe\Charge::update($obj->charge, [ 'description' => 'TheyWorkForYou' ]);
}
} catch (\Stripe\Error\Base $e) {
} catch (\Stripe\Exception\ApiErrorException $e) {
}
} elseif ($event->type == 'invoice.updated' && stripe_twfy_sub($obj)) {
if ($obj->forgiven && property_exists($event->data, 'previous_attributes')) {
if ($obj->status == 'uncollectible' && property_exists($event->data, 'previous_attributes')) {
$previous = $event->data->previous_attributes;
if (array_key_exists('forgiven', $previous) && !$previous['forgiven']) {
if (array_key_exists('status', $previous) && $previous['status'] != 'uncollectible') {
stripe_reset_quota($obj->subscription);
}
}
Expand Down
2 changes: 1 addition & 1 deletion www/docs/api/key.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
try {
$invoice = $sub->latest_invoice;
$invoice->pay([ 'expand' => [ 'payment_intent' ] ]);
} catch (\Stripe\Error\Card $e) {
} catch (\Stripe\Exception\CardException $e) {
$invoice = \Stripe\Invoice::retrieve($sub->latest_invoice, ['expand' => [ 'payment_intent'] ]);
}
} else {
Expand Down
4 changes: 3 additions & 1 deletion www/docs/api/update-card.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$setup_intent = \Stripe\SetupIntent::create();
$setup_intent = \Stripe\SetupIntent::create([
'automatic_payment_methods' => ["enabled" => True, "allow_redirects" => "never"],
]);
header('Content-Type: application/json');
print json_encode([
'secret' => $setup_intent->client_secret,
Expand Down
6 changes: 4 additions & 2 deletions www/docs/js/payment.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,10 @@ if (document.getElementById('id_plan_0')) {

toggle_stripe();

var stripe_key = document.getElementById('js-payment').getAttribute('data-key');
var stripe = Stripe(stripe_key);
var payment_element = document.getElementById('js-payment');
var stripe_key = payment_element.getAttribute('data-key');
var stripe_api_version = payment_element.getAttribute('data-api-version');
var stripe = Stripe(stripe_key, { apiVersion: stripe_api_version });
var elements = stripe.elements();
var card = elements.create('card');
if (document.getElementById('card-element')) {
Expand Down
4 changes: 2 additions & 2 deletions www/includes/easyparliament/templates/html/api/check.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
</div>
</form>
<script src="https://js.stripe.com/v3"></script>
<script id="js-payment" data-key="<?= STRIPE_PUBLIC_KEY ?>"
<script id="js-payment" data-key="<?= STRIPE_PUBLIC_KEY ?>" data-api-version="<?= STRIPE_API_VERSION ?>"
<?php if ($stripe) {
echo 'data-has-subscription="1"';
} ?>
Expand All @@ -64,7 +64,7 @@

<script src="https://js.stripe.com/v3"></script>
<script>
var stripe = Stripe('<?= STRIPE_PUBLIC_KEY ?>');
var stripe = Stripe('<?= STRIPE_PUBLIC_KEY ?>', { apiVersion: '<?= STRIPE_API_VERSION ?>' });
stripe.handleCardPayment('<?= $needs_processing['payment_intent_client_secret'] ?>').then(function(result) {
location.href = location.href;
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<?php

$quota_status = $subscription->quota_status();
$account_balance = $subscription->stripe->customer->account_balance;
$balance = $subscription->stripe->customer->balance;
if ($subscription->upcoming) {
if ($subscription->upcoming->total < 0) {
# Going to be credited
$account_balance += $subscription->upcoming->total;
$balance += $subscription->upcoming->total;
}
}

Expand Down Expand Up @@ -40,6 +40,10 @@
<?php } ?>
</p>

<?php if ($subscription->stripe->schedule->phases[1] && $subscription->stripe->schedule->phases[1]->items[0]->plan->nickname != $subscription->stripe->plan->nickname) { ?>
<p>You are switching to <strong><?php $subscription->stripe->schedule->phases[1]->items[0]->plan->nickname ?></strong> at the end of your current period.</p>
<?php } ?>

<?php if ($subscription->stripe->discount && $subscription->stripe->discount->end) { ?>
<p>Your discount will expire on <?= $subscription->stripe->discount->end ?>.</p>
<?php } ?>
Expand All @@ -58,8 +62,8 @@
your next invoice date is <?= date('d/m/Y', $subscription->stripe->current_period_end) ?>.
<?php } ?>

<?php if ($account_balance) { ?>
<br>Your account has a balance of £<?= number_format(-$account_balance / 100, 2); ?>.
<?php if ($balance) { ?>
<br>Your account has a balance of £<?= number_format(-$balance / 100, 2); ?>.
<?php } ?>
</p>

Expand Down Expand Up @@ -135,7 +139,7 @@ class="button">Update card details</button>
</div>
</div>
<script src="https://js.stripe.com/v3"></script>
<script id="js-payment" data-key="<?= STRIPE_PUBLIC_KEY ?>" src="<?= cache_version('js/payment.js') ?>"></script>
<script id="js-payment" data-key="<?= STRIPE_PUBLIC_KEY ?>" data-api-version="<?= STRIPE_API_VERSION ?>" src="<?= cache_version('js/payment.js') ?>"></script>
</form>

<?php } else { ?>
Expand Down
2 changes: 1 addition & 1 deletion www/includes/easyparliament/templates/html/api/update.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,5 +160,5 @@ function rdio($name, $value, $text, $id, $required = false, $checked = false) {
<?php if ($stripe) {
echo 'data-has-subscription="1"';
} ?>
data-key="<?= STRIPE_PUBLIC_KEY ?>"
data-key="<?= STRIPE_PUBLIC_KEY ?>" data-api-version="<?= STRIPE_API_VERSION ?>"
src="<?= cache_version('js/payment.js') ?>"></script>
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,5 @@ class="donate-<?=$payment_type?>-amount inline-radio-label"

<script src="https://js.stripe.com/v3"></script>
<script>
var stripe = Stripe('<?=STRIPE_DONATE_PUBLIC_KEY ?>');
var stripe = Stripe('<?=STRIPE_DONATE_PUBLIC_KEY ?>', { apiVersion: '<?= STRIPE_API_VERSION ?>' });
</script>
Loading