Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripe cancel subscription at specific date

I'm using StripeAPI in PHP and I don't know how can I stop a customer subscription at a specific date.

I know there is an option for cancel subscription immediatly :

$subscription = \Stripe\Subscription::retrieve('sub_49ty4767H20z6a');
$subscription->cancel();

Or for cancel subscription at the end of the current billing period (for the duration of time the customer has already paid for) with :

$subscription->cancel(['at_period_end' => true]);

With this option, the cancellation is scheduled.

But how can I cancel a subscription at a specific date? In my system, a user can ask for a cancellation but he has to wait for a specific date (something like at least stay X months as a subscriber)

Do you know how can I do that? Thanks!

like image 523
Clément Andraud Avatar asked Mar 22 '18 14:03

Clément Andraud


2 Answers

Stripe just added this to their API and I happened to stumble upon it. They have a field called "cancel_at" that can be set to a date in the future. They don't have this attribute listed in their documentation since it is so new. You can see the value in the response object here:

https://stripe.com/docs/api/subscriptions/create?lang=php

I've tested this using .NET and can confirm it sets the subscription to expire at value you provide.

like image 164
Matty Avatar answered Jan 03 '23 07:01

Matty


Ah, yes. Good question. Here's a check/execute example:

$today = time();
$customer = \Stripe\Customer::retrieve('Their Customer ID');
$signUpDate = $customer->subscriptions->data[0]->created;

// This will define the date where you wish to cancel them on.
// The example here is 30 days from which they initially subscribed.
$cancelOnDate = strtotime('+30 day', $signUpDate);

// If today is passed or equal to the date you defined above, cancel them.
if ($today >= $cancelOnDate) {
    $subscription = \Stripe\Subscription::retrieve('sub_49ty4767H20z6a');
    $subscription->cancel();
}

Here's an example of setting cancellation upon them subscribing:

$today = time();

// Cancel them 30 days from today
$cancelAt = strtotime('+30 day', $today);

$subscription = \Stripe\Subscription::create(array(
    "customer" => 'Their Customer ID',
    "plan" => 'xxxxxxxxx',
    "cancel_at" => $cancelAt
));
like image 42
Dan Avatar answered Jan 03 '23 06:01

Dan