snoob dogg
snoob dogg

Reputation: 2875

Testing subscription trial periods with Stripe

I'm implementing a Client / Server integration of Stripe and I want to simulate the trial end of a user.

According to the docs https://stripe.com/docs/billing/testing#trials :

There’s a quick solution here: create a new subscription with a trial_end value only a few minutes in the future.

So here is how I create my Stripe Session :

$session_configuration = [
    'payment_method_types' => ['card'],
    'customer' => $stripeIdCustomer,
    'subscription_data' => [
        'items' => [[
        'plan' => $planId,
        ]],
        'trial_end'=>  time() + 60 * 1
    ],
    'success_url' => $success_url,
    'cancel_url' => $cancel_url,
];

$session = Session::create($session_configuration);

But then, I got an InvalidRequestException :

The trial_end date has to be at least 2 days in the future.

Whereas I'm in testing mode, what should I do ? Also, what are the relevant WebHooks to watch in this case ?

Upvotes: 2

Views: 1216

Answers (1)

Ben Senescu
Ben Senescu

Reputation: 171

According to the api, any date less than 48 hours away is invalid.

https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-subscription_data-trial_end

The way that we got around this issue was by creating this function. Forgive the javascript, but I'm sure you can make it work.

    const includeTrialIfElligible = (trialEndsAtUtc) => {
      if (!trialEndsAtUtc || isPast(trialEndsAtUtc)) {
        return
      }
      const daysTillTrialEnd = differenceInCalendarDays(trialEndsAtUtc, new Date())

      // ex. if the trial period is ending in 1 hour, the user will 
      // get one trial period day and will get charged the "next day" or in one hour.
      if (daysTillTrialEnd <= 2) {
        return {
          trial_period_days: daysTillTrialEnd,
        }
      }
     
      return {
        trial_end: trialEndsAtUtc,
      }
    }

We then spread the response in subscription data and achieved the behavior that we wanted.

   const session = await stripe.checkout.sessions.create(
      {
        mode: 'subscription',
        ...
        subscription_data: {
          application_fee_percent: DEFAULT_PLATFORM_FEE_PERCENTAGE,
          ...includeTrialIfElligible(trialEndsAtUtc),
        },
        ...
    )

Upvotes: 1

Related Questions