4
votes

I'm trying to create a subscription for a user based on the last day of the month using Stripe and Laravel, and Laravel Cashier. So, I just set the trial end date for the last day of the month to stop them being billed immediately:

$user = Auth::user();

$user->trial_ends_at = Carbon::now()->lastOfMonth();
$user->save();
$user->subscription(Input::get('subscription'))->create(Input::get('stripeToken'), [
    'email' => $user->email
]);

return Redirect::to('/profile');

But for some reason, Stripe and Laravel ignore this, and in my database and Stripe admin I have the trial end date set to the Stripe default (40 days from today). If I try and set it up on a Stripe account with no trial, it bills the test user immediately.

What am I doing wrong?

If I comment out the $user->subscription... line it keeps the correct time in the DB.

1

1 Answers

5
votes

After a fair amount of confusion, I used Cashier to create the subscription. Next, I was able to use this to use the customer ID with the Stripe API to adjust the trial end date.

This bit wasn't needed at the beginning, as Cashier would just overwrite it with the trial based in Stripe.

// $user->trial_ends_at = Carbon::now()->lastOfMonth();
// $user->save();

Set up the subscription with Cashier. There is a trial set so the card isn't charged.

$user->subscription(Input::get('subscription'))->create(Input::get('stripeToken'), [
    'email' => $user->email
]);

Now, use the Stripe API to grab the customer we just created, along with their subscription

$cu = Stripe_Customer::retrieve($user->stripe_id);
$subscription = $cu->subscriptions->retrieve($user->stripe_subscription);

Now, and only now, can we amend the date (unless I'm doing this wrong / missing a trick)

$subscription->trial_end = Carbon::now()->lastOfMonth()->timestamp;
$subscription->save();

Now, we need to update the database table as well

$user->trial_ends_at = Carbon::now()->lastOfMonth();
$user->save();

So, all together:

    $user = Auth::user();

    $user->subscription(Input::get('subscription'))->create(Input::get('stripeToken'), [
        'email' => $user->email,
    ]);

    $cu = Stripe_Customer::retrieve($user->stripe_id);
    $subscription = $cu->subscriptions->retrieve($user->stripe_subscription);
    $subscription->trial_end = Carbon::now()->lastOfMonth()->timestamp;
    $subscription->save();

    $user->trial_ends_at = Carbon::now()->lastOfMonth();
    $user->save();