📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
implemented basic Stripe webhooks backend
Blue Mousead16707a88fa
diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex f10dda172..fc83c988f 100644--- a/src/user/user.controller.ts+++ b/src/user/user.controller.ts@@ -1,5 +1,5 @@import {- Controller, Query, Req, Body, Param, Get, Post, Put, Delete, HttpCode, BadRequestException, UseGuards, MethodNotAllowedException, Redirect, Header,+ Controller, Query, Req, Body, Param, Get, Post, Put, Delete, HttpCode, BadRequestException, UseGuards, MethodNotAllowedException,} from '@nestjs/common'import { Request } from 'express'import { ApiTags, ApiQuery } from '@nestjs/swagger'@@ -162,7 +162,7 @@ export class UserController {const token = await this.actionTokensService.createForUser(user, ActionTokenType.EMAIL_VERIFICATION, user.email)const url = `${request.headers.origin}/verify/${token.id}`-+await this.userService.update(id, { emailRequests: 1 + user.emailRequests })await this.mailerService.sendEmail(user.email, LetterTemplate.SignUp, { url })return true@@ -234,13 +234,12 @@ export class UserController {@Post('/upgrade')@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)- // @Redirect('https://swetrix.com/billing', 303)async upgradePlan(@Body() body: UpgradeUserProfileDTO, @CurrentUserId() user_id: string): Promise<object> {this.logger.log({ body, user_id }, 'POST /user/upgrade')const user = await this.userService.findOne(user_id, {- select: ['email'],+ select: ['email', 'id'],})-+const { planCode } = bodyconst priceId = ACCOUNT_PLANS[planCode]?.priceId@@ -260,10 +259,11 @@ export class UserController {],success_url: 'https://swetrix.com/billing?session_id={CHECKOUT_SESSION_ID}',cancel_url: 'https://swetrix.com/billing',+ metadata: {+ uid: user.id, planCode,+ }})- console.log(session)-return {url: session.url,}diff --git a/src/webhook/webhook.controller.ts b/src/webhook/webhook.controller.tsindex 00cfb8417..acced04e0 100644--- a/src/webhook/webhook.controller.ts+++ b/src/webhook/webhook.controller.ts@@ -1,9 +1,10 @@import {- Controller, Body, Query, UseGuards, Get, Post, Headers, BadRequestException,- InternalServerErrorException, NotImplementedException, UnprocessableEntityException, PreconditionFailedException,+ Controller, Body, Post, Headers, BadRequestException,} from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'+import { PlanCode } from '../user/entities/user.entity'+import { UserService } from '../user/user.service'import { AppLoggerService } from '../logger/logger.service'import { STRIPE_WH_SECRET, STRIPE_SECRET } from '../common/constants'@@ -14,10 +15,11 @@ const stripe = require('stripe')(STRIPE_SECRET)export class WebhookController {constructor(private readonly logger: AppLoggerService,+ private readonly userService: UserService,) { }@Post('/')- async logCustom(@Body() body: Buffer, @Headers() headers): Promise<any> {+ async stripeWebhook(@Body() body: Buffer, @Headers() headers): Promise<any> {let eventtry {@@ -29,54 +31,31 @@ export class WebhookController {throw new BadRequestException('Webhook signature verification failed')}- // Extract the object from the event.const dataObject = event.data.object+ const { uid, planCode } = dataObject['metadata']- // Handle the event- // Review important events for Billing webhooks- // https://stripe.com/docs/billing/webhooks- // Remove comment to see the various objects sent for this sampleswitch (event.type) {case 'checkout.session.completed':- // Payment is successful and the subscription is created.- // You should provision the subscription and save the customer ID to your database.+ await this.userService.update(uid, { planCode })breakcase 'invoice.paid':if (dataObject['billing_reason'] == 'subscription_create') {- // The subscription automatically activates after successful payment- // Set the payment method used to pay the first invoice- // as the default payment method for that subscription+ // Setting default payment method for subscriptionconst subscription_id = dataObject['subscription']const payment_intent_id = dataObject['payment_intent']-- // Retrieve the payment intent used to pay the subscriptionconst payment_intent = await stripe.paymentIntents.retrieve(payment_intent_id)-- const subscription = await stripe.subscriptions.update(subscription_id, {+ await stripe.subscriptions.update(subscription_id, {default_payment_method: payment_intent.payment_method,})-- console.log('Default payment method set for subscription:' + payment_intent.payment_method)+ await this.userService.update(uid, { planCode })}breakcase 'invoice.payment_failed':- // If the payment fails or the customer does not have a valid payment method,- // an invoice.payment_failed event is sent, the subscription becomes past_due.- // Use this webhook to notify your user that their payment has- // failed and to retrieve new card details.+ await this.userService.update(uid, { planCode: PlanCode.free })breakcase 'customer.subscription.deleted':- if (event.request !== null) {- // handle a subscription cancelled by your request- // from above.- } else {- // handle subscription cancelled automatically based- // upon your subscription settings.- }- break- case 'customer.subscription.trial_will_end':- // Send notification to your user that the trial will end+ await this.userService.update(uid, { planCode: PlanCode.free })breakdefault:throw new BadRequestException('Unexpected event type')