📈 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
Partial integration of Stripe payments
Blue Mouseb5d711642007
diff --git a/.env.example b/.env.exampleindex cc4203a08..e5230081a 100644--- a/.env.example+++ b/.env.example@@ -17,6 +17,10 @@ CLICKHOUSE_PORT=8123CLICKHOUSE_PASSWORD=passwordCLICKHOUSE_DATABASE=analytics+# Payments+STRIPE_SECRET=sk_liveortest_yourstripesecretkey513+STRIPE_WH_SECRET=sk_wh_secret+# EMAIL SERVICESMTP_HOST='localhost'SMTP_PORT=1025diff --git a/package.json b/package.jsonindex d5f910ba1..f61894a6c 100644--- a/package.json+++ b/package.json@@ -52,6 +52,7 @@"rimraf": "^3.0.2","rxjs": "^6.6.6","sqlstring": "^2.3.2",+ "stripe": "^8.169.0","swagger-ui-express": "^4.1.6","typeorm": "^0.2.31","ua-parser-js": "^0.7.28",diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.tsindex 07698ce30..fca1d11a1 100644--- a/src/analytics/analytics.service.ts+++ b/src/analytics/analytics.service.ts@@ -149,7 +149,7 @@ export class AnalyticsService {so: {},me: {},ca: {},- lt: {},+ // lt: {},}const whitelist = _keys(res)diff --git a/src/common/constants.ts b/src/common/constants.tsindex dc4cb769e..f265cbc5d 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -3,6 +3,7 @@ import Redis from 'ioredis'import * as _toNumber from 'lodash/toNumber'import * as _size from 'lodash/size'import * as _round from 'lodash/round'+require('dotenv').config()const redis = new Redis({@@ -76,8 +77,12 @@ const UNIQUE_SESSION_LIFE_TIME = 1800// how often can user request a fresh GDPR export of their data; in days.const GDPR_EXPORT_TIMEFRAME = 14+const STRIPE_SECRET = process.env.STRIPE_SECRET+const STRIPE_WH_SECRET = process.env.STRIPE_WH_SECRET+export {clickhouse, JWT_LIFE_TIME, HISTORY_LIFE_TIME_DAYS, redis, isValidPID, getRedisProjectKey,redisProjectCacheTimeout, getPercentageChange, UNIQUE_SESSION_LIFE_TIME, REDIS_LOG_DATA_CACHE_KEY,GDPR_EXPORT_TIMEFRAME, getRedisUserCountKey, redisProjectCountCacheTimeout, REDIS_LOG_CUSTOM_CACHE_KEY,+ STRIPE_SECRET, STRIPE_WH_SECRET,}diff --git a/src/user/dto/upgrade-user.dto.ts b/src/user/dto/upgrade-user.dto.tsnew file mode 100644index 000000000..96402777e--- /dev/null+++ b/src/user/dto/upgrade-user.dto.ts@@ -0,0 +1,6 @@+import { ApiProperty } from '@nestjs/swagger'++export class UpgradeUserProfileDTO {+ @ApiProperty({ required: true })+ planCode: string+}diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex baa46c538..de954f853 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -17,6 +17,7 @@ export const ACCOUNT_PLANS = {displayName: 'Startup plan',monthlyUsageLimit: 500000,maxProjects: 10,+ priceId: 'price_1JOUvrCQYBdiXzBaYbOu3wnB',},enterprise: {displayName: 'Enterprise plan',diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex 0b67dc6ab..f10dda172 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,+ Controller, Query, Req, Body, Param, Get, Post, Put, Delete, HttpCode, BadRequestException, UseGuards, MethodNotAllowedException, Redirect, Header,} from '@nestjs/common'import { Request } from 'express'import { ApiTags, ApiQuery } from '@nestjs/swagger'@@ -12,12 +12,17 @@ import * as _isEmpty from 'lodash/isEmpty'import { UserService } from './user.service'import { ProjectService } from '../project/project.service'-import { User, UserType, MAX_EMAIL_REQUESTS } from './entities/user.entity'+import {+ User, UserType, MAX_EMAIL_REQUESTS, ACCOUNT_PLANS,+} from './entities/user.entity'import { Roles } from '../common/decorators/roles.decorator'import { Pagination } from '../common/pagination/pagination'-import { GDPR_EXPORT_TIMEFRAME, clickhouse } from '../common/constants'+import {+ GDPR_EXPORT_TIMEFRAME, clickhouse, STRIPE_SECRET,+} from '../common/constants'import { RolesGuard } from 'src/common/guards/roles.guard'import { UpdateUserProfileDTO } from './dto/update-user.dto'+import { UpgradeUserProfileDTO } from './dto/upgrade-user.dto'import { CurrentUserId } from 'src/common/decorators/current-user-id.decorator'import { ActionTokensService } from '../action-tokens/action-tokens.service'import { MailerService } from '../mailer/mailer.service'@@ -27,6 +32,8 @@ import { LetterTemplate } from 'src/mailer/letter'import { AppLoggerService } from 'src/logger/logger.service'import { UserProfileDTO } from './dto/user.dto'+const stripe = require('stripe')(STRIPE_SECRET)+dayjs.extend(utc)@ApiTags('User')@@ -224,6 +231,44 @@ 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'],+ })++ const { planCode } = body+ const priceId = ACCOUNT_PLANS[planCode]?.priceId++ if (_isEmpty(priceId)) {+ throw new BadRequestException('Incorrect planCode provided')+ }++ const session = await stripe.checkout.sessions.create({+ mode: 'subscription',+ payment_method_types: ['card'],+ customer_email: user.email,+ line_items: [+ {+ price: priceId,+ quantity: 1,+ },+ ],+ success_url: 'https://swetrix.com/billing?session_id={CHECKOUT_SESSION_ID}',+ cancel_url: 'https://swetrix.com/billing',+ })++ console.log(session)++ return {+ url: session.url,+ }+ }+@Get('/export')@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)diff --git a/src/webhook/analytics.module.ts b/src/webhook/analytics.module.tsnew file mode 100644index 000000000..78b5e08b4--- /dev/null+++ b/src/webhook/analytics.module.ts@@ -0,0 +1,14 @@+import { Module, forwardRef } from '@nestjs/common'++import { WebhookController } from './webhook.controller'+import { UserModule } from '../user/user.module'+import { AppLoggerModule } from '../logger/logger.module'++@Module({+ imports: [+ forwardRef(() => UserModule),+ AppLoggerModule,+ ],+ controllers: [WebhookController],+})+export class AnalyticsModule {}diff --git a/src/webhook/webhook.controller.spec.ts b/src/webhook/webhook.controller.spec.tsnew file mode 100644index 000000000..c6dd163b5--- /dev/null+++ b/src/webhook/webhook.controller.spec.ts@@ -0,0 +1,18 @@+import { Test, TestingModule } from '@nestjs/testing'+import { WebhookController } from './webhook.controller'++describe('WebhookController', () => {+ let controller: WebhookController++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ controllers: [WebhookController],+ }).compile()++ controller = module.get<WebhookController>(WebhookController)+ })++ it('should be defined', () => {+ expect(controller).toBeDefined()+ })+})diff --git a/src/webhook/webhook.controller.ts b/src/webhook/webhook.controller.tsnew file mode 100644index 000000000..9d606de15--- /dev/null+++ b/src/webhook/webhook.controller.ts@@ -0,0 +1,89 @@+import {+ Controller, Body, Query, UseGuards, Get, Post, Headers, BadRequestException,+ InternalServerErrorException, NotImplementedException, UnprocessableEntityException, PreconditionFailedException,+} from '@nestjs/common'+import { ApiTags } from '@nestjs/swagger'++import { AppLoggerService } from '../logger/logger.service'+import { STRIPE_WH_SECRET, STRIPE_SECRET } from '../common/constants'++const stripe = require('stripe')(STRIPE_SECRET)++@ApiTags('Webhook')+@Controller('webhook')+export class WebhookController {+ constructor(+ private readonly logger: AppLoggerService,+ ) { }++ @Post('/')+ async logCustom(@Body() body: object, @Headers() headers): Promise<any> {+ this.logger.log({ body, headers }, 'POST /webhook')++ let event++ try {+ event = stripe.webhooks.constructEvent(body, headers['Stripe-Signature'], STRIPE_WH_SECRET)+ } catch (err) {+ this.logger.error(err)+ this.logger.error('Webhook signature verification failed.')+ this.logger.error('Check the .env file and enter the correct webhook secret.')+ throw new BadRequestException('Webhook signature verification failed')+ }++ // Extract the object from the event.+ const dataObject = event.data.object+ console.log(event.type, event.data)++ // 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 sample+ switch (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.+ break+ case '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+ const subscription_id = dataObject['subscription']+ const payment_intent_id = dataObject['payment_intent']++ // Retrieve the payment intent used to pay the subscription+ const payment_intent = await stripe.paymentIntents.retrieve(payment_intent_id)++ const subscription = 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)+ }++ break+ case '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.+ break+ case '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+ break+ default:+ throw new BadRequestException('Unexpected event type')+ }+ return+ }+}