Laravel Cashier with Stripe final trial on last day of the month and start subscription

I am 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 end date of the trial to the last day of the month so that they wouldn't be announced 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 are ignoring this, and in my database and in Stripe admin I have the default testing end date set by Stripe (40 days from today). If I try to install it on a Stripe account without a trial, it immediately logs out the test user.

What am I doing wrong?

If I comment out the line $user->subscription...

, it keeps the correct time in the DB.

+3


source to share


1 answer


After enough confusion, I used Cashier to create a subscription. I was then able to use that to use the Client ID with the Stripe API to set the test end date.

This bit is unnecessary in the beginning as Cashier just overwrote it with a trial version in Stripe.

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

      

Set up your subscription with Cashier. There is a trial set, so the card won't charge.

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

      

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

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

      



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

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

      

Now we also need to update the database table

$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();

      

+5


source







All Articles