📈 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
Integrated Paddle payments processing platform
Blue Mouse769d6cbec1d2
diff --git a/.env.example b/.env.exampleindex 64f083c8c..a8902be17 100644--- a/.env.example+++ b/.env.example@@ -18,10 +18,6 @@ CLICKHOUSE_DATABASE=analytics# Leave empty for all originsAPI_ORIGINS=-# 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 67061e5e1..2a99541f6 100644--- a/package.json+++ b/package.json@@ -56,11 +56,9 @@"reflect-metadata": "^0.1.13","rimraf": "^3.0.2","rxjs": "^7.5.1",- "stripe": "^8.195.0","typeorm": "^0.2.41","ua-parser-js": "^0.7.31",- "uuid": "^8.3.2",- "verify-paddle-webhook": "^1.1.0"+ "uuid": "^8.3.2"},"devDependencies": {"@nestjs/cli": "^7.6.0",diff --git a/src/common/constants.ts b/src/common/constants.tsindex 313c218dc..a962bea93 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -158,14 +158,11 @@ const HEARTBEAT_SID_LIFE_TIME = 35// 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, REDIS_SESSION_SALT_KEY, HEARTBEAT_SID_LIFE_TIME, isSelfhosted, UUIDV5_NAMESPACE,- SELFHOSTED_EMAIL, SELFHOSTED_PASSWORD, SELFHOSTED_UUID, CLICKHOUSE_INIT_QUERIES, REDIS_USERS_COUNT_KEY, REDIS_PROJECTS_COUNT_KEY,+ REDIS_SESSION_SALT_KEY, HEARTBEAT_SID_LIFE_TIME, isSelfhosted, UUIDV5_NAMESPACE, SELFHOSTED_EMAIL,+ SELFHOSTED_PASSWORD, SELFHOSTED_UUID, CLICKHOUSE_INIT_QUERIES, REDIS_USERS_COUNT_KEY, REDIS_PROJECTS_COUNT_KEY,REDIS_PAGEVIEWS_COUNT_KEY,}diff --git a/src/user/dto/upgrade-user.dto.ts b/src/user/dto/upgrade-user.dto.tsdeleted file mode 100644index 96402777e..000000000--- a/src/user/dto/upgrade-user.dto.ts+++ /dev/null@@ -1,6 +0,0 @@-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 eb5f5d17c..b5dd1e5d7 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -2,39 +2,46 @@ import { Entity, Column, PrimaryGeneratedColumn, OneToMany, BeforeUpdate } fromimport { ActionToken } from 'src/action-tokens/action-token.entity'import { Project } from 'src/project/entity/project.entity'+export enum PlanCode {+ free = 'free',+ freelancer = 'freelancer',+ startup = 'startup',+ enterprise = 'enterprise',+}+export const ACCOUNT_PLANS = {free: {+ id: PlanCode.free,displayName: 'Free plan',monthlyUsageLimit: 5000,maxProjects: 10,},freelancer: {+ id: PlanCode.freelancer,displayName: 'Freelancer plan',monthlyUsageLimit: 100000,maxProjects: 20,priceId: 'price_1JORmHCQYBdiXzBatNEKQmP9',+ pid: 752316,},startup: {+ id: PlanCode.startup,displayName: 'Startup plan',monthlyUsageLimit: 500000,maxProjects: 20,priceId: 'price_1JORmfCQYBdiXzBawbn1yoeu',+ pid: 752317,},enterprise: {+ id: PlanCode.enterprise,displayName: 'Enterprise plan',monthlyUsageLimit: 1000000,maxProjects: 30,priceId: 'price_1JORn3CQYBdiXzBaOdcNvHHP',+ pid: 752318,},}-export enum PlanCode {- free = 'free',- freelancer = 'freelancer',- startup = 'startup',- enterprise = 'enterprise',-}-export enum UserType {CUSTOMER = 'customer',ADMIN = 'admin',@@ -95,8 +102,14 @@ export class User {@Column({ type: 'timestamp', nullable: true })exportedAt: Date- @Column('varchar', { length: 28, nullable: true })- stripeSubID: string+ @Column('int', { nullable: true })+ subID: number++ @Column('varchar', { length: 200, nullable: true })+ subUpdateURL: string++ @Column('varchar', { length: 200, nullable: true })+ subCancelURL: string@BeforeUpdate()updateTimestamp() {diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex 86d3828ff..456d78204 100644--- a/src/user/user.controller.ts+++ b/src/user/user.controller.ts@@ -13,17 +13,16 @@ import * as _isEmpty from 'lodash/isEmpty'import { UserService } from './user.service'import { ProjectService } from '../project/project.service'import {- User, UserType, MAX_EMAIL_REQUESTS, ACCOUNT_PLANS, PlanCode,+ User, UserType, MAX_EMAIL_REQUESTS,} from './entities/user.entity'import { Roles } from '../common/decorators/roles.decorator'import { Pagination } from '../common/pagination/pagination'import {- GDPR_EXPORT_TIMEFRAME, clickhouse, STRIPE_SECRET,+ GDPR_EXPORT_TIMEFRAME, clickhouse,} from '../common/constants'import { RolesGuard } from 'src/common/guards/roles.guard'import { SelfhostedGuard } from '../common/guards/selfhosted.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'@@ -33,8 +32,6 @@ 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')@@ -240,86 +237,6 @@ export class UserController {}}- @Post('/upgrade')- @UseGuards(RolesGuard)- @UseGuards(SelfhostedGuard)- @Roles(UserType.CUSTOMER, UserType.ADMIN)- 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', 'id', 'stripeSubID'],- })-- const { planCode } = body- const priceId = ACCOUNT_PLANS[planCode]?.priceId-- if (user.stripeSubID) {- if (planCode === PlanCode.free) {- await stripe.subscriptions.update(user.stripeSubID, {- cancel_at_period_end: true,- })-- return {- message: 'The subscription has been canceled. No more charges will be made to your card.',- }- }-- if (_isEmpty(priceId)) {- throw new BadRequestException('Incorrect planCode provided')- }-- await stripe.subscriptions.update(user.stripeSubID, {- cancel_at_period_end: false,- proration_behavior: 'always_invoice',- items: [{- price: priceId,- quantity: 1,- }]- })-- return {- message: 'The subscription has been upgraded.',- }- }-- // If user has no Stripe Subscription ID and wants to downgrade to free tier- if (planCode === PlanCode.free) {- await this.userService.update(user.id, {- planCode: PlanCode.free,- })-- return {- message: 'Your account have been downgraded to the free tier.',- }- }-- 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?sub_success=true',- cancel_url: 'https://swetrix.com/billing?sub_success=false',- subscription_data: {- metadata: { uid: user.id, planCode },- },- metadata: { uid: user.id, planCode },- })-- return {- url: session.url,- }- }-@Get('/export')@UseGuards(RolesGuard)@UseGuards(SelfhostedGuard)diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex 5e17a432b..b29fb0d9d 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -39,6 +39,10 @@ export class UserService {return this.usersRepository.update({ email }, update)}+ async updateBySubID(subID: number, update: Record<string, unknown>): Promise<any> {+ return this.usersRepository.update({ subID }, update)+ }+async delete(id: string): Promise<any> {return this.usersRepository.delete(id)}diff --git a/src/webhook/webhook.controller.ts b/src/webhook/webhook.controller.tsindex 95de22fcd..e4e882f6b 100644--- a/src/webhook/webhook.controller.ts+++ b/src/webhook/webhook.controller.ts@@ -5,20 +5,12 @@ import { ApiTags } from '@nestjs/swagger'import * as _isEmpty from 'lodash/isEmpty'import * as _keys from 'lodash/keys'import * as _find from 'lodash/find'-import { verifyPaddleWebhook } from 'verify-paddle-webhook'-import {- PlanCode, ACCOUNT_PLANS,-} from '../user/entities/user.entity'+import { PlanCode, ACCOUNT_PLANS } from '../user/entities/user.entity'import { UserService } from '../user/user.service'import { AppLoggerService } from '../logger/logger.service'import { WebhookService } from './webhook.service'import { SelfhostedGuard } from '../common/guards/selfhosted.guard'-import { STRIPE_WH_SECRET, STRIPE_SECRET } from '../common/constants'--const stripe = require('stripe')(STRIPE_SECRET)--const PLANS_LIST = _keys(ACCOUNT_PLANS)@ApiTags('Webhook')@Controller('webhook')@@ -30,90 +22,64 @@ export class WebhookController {) { }@UseGuards(SelfhostedGuard)- @Post('/')- async stripeWebhook(@Body() body: Buffer, @Headers() headers): Promise<any> {- 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')- }-- const dataObject = event.data.object+ @Post('/paddle')+ async paddleWebhook(@Body() body, @Headers() headers, @Ip() reqIP): Promise<any> {+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''+ console.log(body, headers, ip)- switch (event.type) {- case 'checkout.session.completed': {- const { uid, planCode } = dataObject.metadata- await this.userService.update(uid, { planCode })- break- }- case 'invoice.paid': {- if (dataObject['billing_reason'] == 'subscription_create') {- const { uid, planCode } = dataObject.lines.data[0].metadata+ this.webhookService.verifyIP(ip)+ this.webhookService.validateWebhook(body)- // Setting default payment method for subscription- const subscription_id = dataObject['subscription']- const payment_intent_id = dataObject['payment_intent']- const payment_intent = await stripe.paymentIntents.retrieve(payment_intent_id)- await stripe.subscriptions.update(subscription_id, {- default_payment_method: payment_intent.payment_method,- })- await this.userService.update(uid, {- planCode,- stripeSubID: subscription_id,- })+ switch (body.alert_name) {+ case 'subscription_created':+ case 'subscription_updated': {+ const {+ passthrough, email, subscription_id, subscription_plan_id, cancel_url, update_url,+ } = body+ let uid++ try {+ uid = JSON.parse(passthrough).uid+ } catch {+ this.logger.error(`[${body.alert_name}] Cannot parse the uid: ${body}`)}- if (dataObject['billing_reason'] == 'subscription_update') {- const { customer_email } = dataObject- const { id } = dataObject.lines.data[0].price+ const plan = _find(ACCOUNT_PLANS, (tier) => tier.pid === subscription_plan_id)- const planID = _find(PLANS_LIST, (pid) => ACCOUNT_PLANS[pid].priceId === id)+ if (!plan) {+ throw new NotFoundException(`The selected account plan (${subscription_plan_id}) is not available`)+ }- if (_isEmpty(planID)) {- throw new NotFoundException('The provided price ID seems to be incorrect..')- }+ const updateParams = {+ planCode: plan.id,+ subID: subscription_id,+ subUpdateURL: update_url,+ subCancelURL: cancel_url,+ }- await this.userService.updateByEmail(customer_email, {- planCode: planID,- })+ if (uid) {+ await this.userService.update(uid, updateParams)+ } else {+ await this.userService.updateByEmail(email, updateParams)}break}- case 'invoice.payment_failed': {- const { uid } = _isEmpty(dataObject.metadata) ? dataObject.lines.data[0].metadata : dataObject.metadata- await this.userService.update(uid, { planCode: PlanCode.free })- break- }- case 'customer.subscription.deleted': {- const { uid } = dataObject.metadata+ case 'subscription_cancelled':+ case 'subscription_payment_failed':+ case 'subscription_payment_refunded': {+ const { subscription_id } = body- await this.userService.update(uid, {+ await this.userService.updateBySubID(subscription_id, {planCode: PlanCode.free,- stripeSubID: null,})+break}default:throw new BadRequestException('Unexpected event type')}- return- }-- @UseGuards(SelfhostedGuard)- @Post('/paddle')- async paddleWebhook(@Body() body, @Headers() headers, @Ip() reqIP): Promise<any> {- const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''- console.log(body, headers, ip)-- this.webhookService.verifyIP(ip)- this.webhookService.validateWebhook(body)return}diff --git a/src/webhook/webhook.service.ts b/src/webhook/webhook.service.tsindex 4525e20c5..d0395f430 100644--- a/src/webhook/webhook.service.ts+++ b/src/webhook/webhook.service.ts@@ -45,24 +45,24 @@ export class WebhookService {return sortedObj}- validateWebhook(jsonObj) {+ validateWebhook(data) {// Grab p_signature- const mySig = Buffer.from(jsonObj.p_signature, 'base64')+ const mySig = Buffer.from(data.p_signature, 'base64')// Remove p_signature from object - not included in array of fields used in verification.- delete jsonObj.p_signature+ delete data.p_signature// Need to sort array by key in ascending order- jsonObj = this.ksort(jsonObj)- for (let property in jsonObj) {- if (jsonObj.hasOwnProperty(property) && (typeof jsonObj[property]) !== "string") {- if (Array.isArray(jsonObj[property])) { // is it an array- jsonObj[property] = jsonObj[property].toString()+ data = this.ksort(data)+ for (let property in data) {+ if (data.hasOwnProperty(property) && (typeof data[property]) !== "string") {+ if (Array.isArray(data[property])) { // is it an array+ data[property] = data[property].toString()} else { // if its not an array and not a string, then it is a JSON obj- jsonObj[property] = JSON.stringify(jsonObj[property])+ data[property] = JSON.stringify(data[property])}}}// Serialise remaining fields of jsonObj- const serialized = Serialize.serialize(jsonObj)+ const serialized = Serialize.serialize(data)// verify the serialized array against the signature using SHA1 with your public key.const verifier = crypto.createVerify('sha1')verifier.update(serialized)@@ -71,8 +71,7 @@ export class WebhookService {const verification = verifier.verify(PADDLE_PUB_KEY, mySig)if (!verification) {- this.logger.error('Webhook signature verification failed.')- this.logger.error('Check the .env file and enter the correct webhook secret.')+ this.logger.error(`Webhook signature verification failed: ${data}`)throw new BadRequestException('Webhook signature verification failed')}}