Skip to content

Commit

Permalink
feat: Start trial on signup
Browse files Browse the repository at this point in the history
Signed-off-by: jay-dee7 <me@jsdp.dev>
  • Loading branch information
jay-dee7 committed Nov 6, 2024
1 parent bbcd11b commit 66cc81d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

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

1 change: 0 additions & 1 deletion src/controllers/admin/webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ export class WebhookController {
severity: 'info',
} satisfies INotifyMessage);

console.log('fetching stripe data');
const [product, stripeCustomer] = await Promise.all([
stripe.products.retrieve(data.productId),
stripe.customers.retrieve(data.paymentProviderId),
Expand Down
37 changes: 36 additions & 1 deletion src/services/track/admin/account-submitter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Stripe from 'stripe';
import type { IObserver } from '../types.js';
import { OperationNameEnum } from '../../../types/constants.js';
import { MaxAllowedTrialPeriodDays, OperationNameEnum } from '../../../types/constants.js';
import type { INotifyMessage } from '../../../types/track.js';
import { EventTracker } from '../tracker.js';
import { StatusCodes } from 'http-status-codes';
Expand Down Expand Up @@ -65,6 +65,16 @@ export class PortalAccountCreateSubmitter implements IObserver {
name: data.name,
paymentProviderId: stripeCustomer.id,
});

if (process.env.STRIPE_TRIAL_PLAN_PRICING_ID) {
// Start a trial for the user
await this.startTrialForPlan(
stripe,
stripeCustomer.id,
process.env.STRIPE_TRIAL_PLAN_PRICING_ID,
MaxAllowedTrialPeriodDays
);
}
}
} catch (error) {
this.notify({
Expand All @@ -76,4 +86,29 @@ export class PortalAccountCreateSubmitter implements IObserver {
} as INotifyMessage);
}
}

async startTrialForPlan(
stripe: Stripe,
paymentProviderId: string,
pricingId: string,
trialPeriodDays: number = 30
) {
const subscriptionResponse = await stripe.subscriptions.create({
customer: paymentProviderId,
items: [{ price: pricingId, quantity: 1 }],
payment_settings: {
save_default_payment_method: 'on_subscription',
},
trial_period_days: trialPeriodDays,
trial_settings: {
end_behavior: {
missing_payment_method: 'cancel',
},
},
});

if (subscriptionResponse.lastResponse.statusCode !== StatusCodes.OK) {
throw new Error(`Failed to start trial plan`);
}
}
}

0 comments on commit 66cc81d

Please sign in to comment.