📈 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
stripe integrations
Blue Mouse77347e17664c
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.tsindex 81b4c755b..dbcf7ee9c 100644--- a/backend/apps/cloud/src/project/entity/project.entity.ts+++ b/backend/apps/cloud/src/project/entity/project.entity.ts@@ -182,6 +182,12 @@ export class Project {@Column('text', { nullable: true, default: null })paddleApiKeyPermissions: string | null+ @Column('text', { nullable: true, default: null })+ stripeApiKeyEnc: string | null++ @Column('text', { nullable: true, default: null })+ stripeApiKeyPermissions: string | null+@Column('datetime', { nullable: true, default: null })revenueLastSyncAt: Date | null}diff --git a/backend/apps/cloud/src/revenue/adapters/stripe.adapter.ts b/backend/apps/cloud/src/revenue/adapters/stripe.adapter.tsnew file mode 100644index 000000000..5f07c3038--- /dev/null+++ b/backend/apps/cloud/src/revenue/adapters/stripe.adapter.ts@@ -0,0 +1,346 @@+import { Injectable } from '@nestjs/common'+import { AppLoggerService } from '../../logger/logger.service'+import { RevenueService } from '../revenue.service'+import {+ RevenueProvider,+ RevenueStatus,+ RevenueTransaction,+ RevenueType,+} from '../interfaces/revenue.interface'++interface StripeListResponse<T> {+ object: 'list'+ data: T[]+ has_more: boolean+}++interface StripePaymentIntent {+ id: string+ object: 'payment_intent'+ status: string+ amount: number+ amount_received: number+ currency: string+ created: number+ customer?: { id: string; email?: string | null } | string | null+ invoice?:+ | {+ id: string+ subscription?: string | null+ lines?: { data?: { description?: string | null }[] }+ }+ | string+ | null+ latest_charge?:+ | {+ id: string+ metadata?: Record<string, string>+ }+ | string+ | null+ metadata?: Record<string, string>+ description?: string | null+}++interface StripeRefund {+ id: string+ object: 'refund'+ status: string+ amount: number+ currency: string+ created: number+ payment_intent?: StripePaymentIntent | string | null+ charge?: { id: string } | string | null+ metadata?: Record<string, string>+}++@Injectable()+export class StripeAdapter {+ private readonly baseUrl = 'https://api.stripe.com/v1'++ constructor(+ private readonly logger: AppLoggerService,+ private readonly revenueService: RevenueService,+ ) {}++ async validateApiKey(apiKey: string): Promise<boolean> {+ try {+ const res = await fetch(`${this.baseUrl}/account`, {+ headers: {+ Authorization: `Bearer ${apiKey}`,+ },+ })++ return res.ok+ } catch (error) {+ this.logger.error({ error }, 'Failed to validate Stripe API key')+ return false+ }+ }++ async syncTransactions(+ projectId: string,+ apiKey: string,+ currency: string,+ lastSyncAt?: Date,+ ): Promise<number> {+ let syncedCount = 0++ // Small overlap window to avoid missing edge updates+ const effectiveLastSyncAt =+ lastSyncAt instanceof Date && !isNaN(lastSyncAt.getTime())+ ? new Date(lastSyncAt.getTime() - 60 * 1000)+ : undefined++ const createdGte = effectiveLastSyncAt+ ? Math.floor(effectiveLastSyncAt.getTime() / 1000)+ : undefined++ // Payment intents (sales/subscriptions)+ const intents = await this.fetchAll<StripePaymentIntent>(+ apiKey,+ '/payment_intents',+ {+ ...(createdGte ? { 'created[gte]': String(createdGte) } : {}),+ limit: '100',+ // Expansions for metadata + basic attribution+ 'expand[]': [+ 'data.customer',+ 'data.invoice',+ 'data.latest_charge',+ ] as any,+ },+ )++ for (const intent of intents) {+ if (intent.status !== 'succeeded') {+ continue+ }++ await this.processPaymentIntent(projectId, intent, currency)+ syncedCount+++ }++ // Refunds+ const refunds = await this.fetchAll<StripeRefund>(apiKey, '/refunds', {+ ...(createdGte ? { 'created[gte]': String(createdGte) } : {}),+ limit: '100',+ 'expand[]': ['data.payment_intent'] as any,+ })++ for (const refund of refunds) {+ if (refund.status !== 'succeeded' && refund.status !== 'pending') {+ // keep only meaningful states+ continue+ }++ await this.processRefund(projectId, refund, currency)+ syncedCount+++ }++ this.logger.log({ projectId, syncedCount }, 'Stripe sync completed')+ return syncedCount+ }++ private async fetchAll<T>(+ apiKey: string,+ path: string,+ params: Record<string, string | string[]>,+ ): Promise<T[]> {+ const results: T[] = []+ let startingAfter: string | undefined+ let hasMore = true++ // Stripe list pagination uses `starting_after`+ while (hasMore) {+ const url = new URL(`${this.baseUrl}${path}`)++ for (const [k, v] of Object.entries(params)) {+ if (Array.isArray(v)) {+ for (const item of v) {+ url.searchParams.append(k, item)+ }+ } else {+ url.searchParams.set(k, v)+ }+ }++ if (startingAfter) {+ url.searchParams.set('starting_after', startingAfter)+ }++ const res = await fetch(url.toString(), {+ headers: {+ Authorization: `Bearer ${apiKey}`,+ },+ })++ if (!res.ok) {+ const text = await res.text().catch(() => '')+ this.logger.error(+ { status: res.status, error: text, path },+ 'Stripe API error',+ )+ throw new Error(`Stripe API error: ${res.status}`)+ }++ const data: StripeListResponse<T> = await res.json()+ results.push(...data.data)++ if (!data.has_more || data.data.length === 0) {+ hasMore = false+ continue+ }++ startingAfter = (data.data[data.data.length - 1] as any).id+ }++ return results+ }++ private async processPaymentIntent(+ projectId: string,+ intent: StripePaymentIntent,+ targetCurrency: string,+ ): Promise<void> {+ const originalAmount =+ (typeof intent.amount_received === 'number'+ ? intent.amount_received+ : intent.amount) / 100+ const originalCurrency = (intent.currency || '').toUpperCase()++ const amount = this.convertCurrency(+ originalAmount,+ originalCurrency,+ targetCurrency,+ )++ const invoice =+ intent.invoice && typeof intent.invoice !== 'string'+ ? intent.invoice+ : null++ const type = invoice?.subscription+ ? RevenueType.SUBSCRIPTION+ : RevenueType.SALE++ const metadata = intent.metadata || {}+ const chargeMeta =+ intent.latest_charge && typeof intent.latest_charge !== 'string'+ ? intent.latest_charge.metadata || {}+ : {}++ const profileId =+ metadata.swetrix_profile_id || chargeMeta.swetrix_profile_id || null+ const sessionId =+ metadata.swetrix_session_id || chargeMeta.swetrix_session_id || null++ const customer =+ intent.customer && typeof intent.customer !== 'string'+ ? intent.customer+ : null++ const productName =+ invoice?.lines?.data?.[0]?.description || intent.description || null++ const revenueTransaction: RevenueTransaction = {+ pid: projectId,+ transactionId: intent.id,+ provider: RevenueProvider.STRIPE,+ type,+ status: RevenueStatus.COMPLETED,+ amount,+ originalAmount,+ originalCurrency,+ currency: targetCurrency,+ profileId,+ sessionId,+ customerEmail: customer?.email || null,+ productId: null,+ productName,+ metadata,+ created: new Date(intent.created * 1000),+ syncedAt: new Date(),+ }++ await this.revenueService.insertTransaction(revenueTransaction)+ }++ private async processRefund(+ projectId: string,+ refund: StripeRefund,+ targetCurrency: string,+ ): Promise<void> {+ const originalAmount = refund.amount / 100+ const originalCurrency = (refund.currency || '').toUpperCase()++ const amount = this.convertCurrency(+ originalAmount,+ originalCurrency,+ targetCurrency,+ )++ const paymentIntent =+ refund.payment_intent && typeof refund.payment_intent !== 'string'+ ? refund.payment_intent+ : null++ const meta = paymentIntent?.metadata || refund.metadata || {}++ const profileId = (meta as any).swetrix_profile_id || null+ const sessionId = (meta as any).swetrix_session_id || null++ const revenueTransaction: RevenueTransaction = {+ pid: projectId,+ transactionId: refund.id,+ provider: RevenueProvider.STRIPE,+ type: RevenueType.REFUND,+ status: RevenueStatus.REFUNDED,+ amount: -Math.abs(amount),+ originalAmount: -Math.abs(originalAmount),+ originalCurrency,+ currency: targetCurrency,+ profileId,+ sessionId,+ customerEmail: null,+ productId: null,+ productName: 'Refund',+ metadata: {+ ...(meta || {}),+ originalPaymentIntentId:+ paymentIntent && typeof paymentIntent !== 'string'+ ? paymentIntent.id+ : undefined,+ },+ created: new Date(refund.created * 1000),+ syncedAt: new Date(),+ }++ await this.revenueService.insertTransaction(revenueTransaction)+ }++ private convertCurrency(+ amount: number,+ fromCurrency: string,+ toCurrency: string,+ ): number {+ if (fromCurrency === toCurrency) {+ return amount+ }++ const rates: Record<string, number> = {+ USD: 1,+ EUR: 1.08,+ GBP: 1.27,+ CAD: 0.74,+ AUD: 0.66,+ JPY: 0.0067,+ }++ const fromRate = rates[fromCurrency] || 1+ const toRate = rates[toCurrency] || 1++ const usdAmount = amount * fromRate+ return usdAmount / toRate+ }+}diff --git a/backend/apps/cloud/src/revenue/dto/connect-revenue.dto.ts b/backend/apps/cloud/src/revenue/dto/connect-revenue.dto.tsnew file mode 100644index 000000000..07de452e8--- /dev/null+++ b/backend/apps/cloud/src/revenue/dto/connect-revenue.dto.ts@@ -0,0 +1,39 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, IsOptional, IsString, Length, IsIn } from 'class-validator'++export type RevenueProviderDto = 'stripe' | 'polar' | 'lemonsqueezy' | 'paddle'++export class ConnectRevenueDto {+ @ApiProperty({+ description: 'Revenue provider to connect',+ enum: ['stripe', 'paddle'],+ example: 'stripe',+ })+ @IsNotEmpty()+ @IsString()+ @IsIn(['stripe', 'paddle'])+ provider: RevenueProviderDto++ @ApiProperty({+ description:+ 'API key for the selected provider. Stripe: rk_live_* or rk_test_*. Paddle: pdl_live_*, pdl_test_* or pdl_sdbx_*.',+ examples: {+ stripe: { value: 'rk_live_xxxxxxxxxxxxxxxx' },+ paddle: { value: 'pdl_live_xxxxxxxxxxxxxxxx' },+ } as any,+ })+ @IsNotEmpty()+ @IsString()+ apiKey: string++ @ApiProperty({+ description: 'Currency code for revenue reporting (ISO 4217)',+ example: 'USD',+ default: 'USD',+ required: false,+ })+ @IsOptional()+ @IsString()+ @Length(3, 3)+ currency?: string+}diff --git a/backend/apps/cloud/src/revenue/dto/get-revenue.dto.ts b/backend/apps/cloud/src/revenue/dto/get-revenue.dto.tsindex e5ec9816a..97f9c3ec4 100644--- a/backend/apps/cloud/src/revenue/dto/get-revenue.dto.ts+++ b/backend/apps/cloud/src/revenue/dto/get-revenue.dto.ts@@ -7,7 +7,7 @@ import {Min,Max,} from 'class-validator'-import { Transform, Type } from 'class-transformer'+import { Type } from 'class-transformer'export class GetRevenueDto {@ApiProperty({ description: 'Project ID' })diff --git a/backend/apps/cloud/src/revenue/interfaces/revenue.interface.ts b/backend/apps/cloud/src/revenue/interfaces/revenue.interface.tsindex 99bb6da79..3e52d3d44 100644--- a/backend/apps/cloud/src/revenue/interfaces/revenue.interface.ts+++ b/backend/apps/cloud/src/revenue/interfaces/revenue.interface.ts@@ -1,6 +1,8 @@export enum RevenueProvider {- PADDLE = 'paddle',STRIPE = 'stripe',+ POLAR = 'polar',+ LEMONSQUEEZY = 'lemonsqueezy',+ PADDLE = 'paddle',}export enum RevenueType {@@ -72,3 +74,15 @@ export const PADDLE_REQUIRED_PERMISSIONS = [// TODO: Change to vendors.paddle.com when merging to mainexport const PADDLE_API_KEY_CREATE_URL = `https://sandbox-vendors.paddle.com/authentication-v2`++// Stripe restricted key permissions (rak_*) that we request+export const STRIPE_REQUIRED_PERMISSIONS = [+ 'rak_charge_read',+ 'rak_subscription_read',+ 'rak_customer_read',+ 'rak_payment_intent_read',+ 'rak_checkout_session_read',+ 'rak_invoice_read',+ 'rak_webhook_write',+ 'rak_product_read',+]diff --git a/backend/apps/cloud/src/revenue/revenue.controller.ts b/backend/apps/cloud/src/revenue/revenue.controller.tsindex bf0c5bcec..56af60a1f 100644--- a/backend/apps/cloud/src/revenue/revenue.controller.ts+++ b/backend/apps/cloud/src/revenue/revenue.controller.ts@@ -7,7 +7,6 @@ import {Param,Body,NotFoundException,- ForbiddenException,BadRequestException,} from '@nestjs/common'import { ApiTags, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'@@ -23,10 +22,9 @@ import { Auth } from '../auth/decorators'import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'import { RevenueService } from './revenue.service'import { PaddleAdapter } from './adapters/paddle.adapter'-import {- ConnectPaddleDto,- UpdateRevenueCurrencyDto,-} from './dto/connect-paddle.dto'+import { StripeAdapter } from './adapters/stripe.adapter'+import { UpdateRevenueCurrencyDto } from './dto/connect-paddle.dto'+import { ConnectRevenueDto } from './dto/connect-revenue.dto'import { GetRevenueDto, GetRevenueTransactionsDto } from './dto/get-revenue.dto'import {RevenueStatsDto,@@ -35,6 +33,7 @@ import {RevenueBreakdownDto,RevenueStatusDto,} from './dto/revenue-stats.dto'+import { STRIPE_REQUIRED_PERMISSIONS } from './interfaces/revenue.interface'@ApiTags('Revenue')@Controller('project')@@ -42,6 +41,7 @@ export class RevenueController {constructor(private readonly revenueService: RevenueService,private readonly paddleAdapter: PaddleAdapter,+ private readonly stripeAdapter: StripeAdapter,private readonly projectService: ProjectService,private readonly analyticsService: AnalyticsService,private readonly logger: AppLoggerService,@@ -72,10 +72,10 @@ export class RevenueController {@Post('/:pid/revenue/connect')@Auth()@ApiResponse({ status: 201 })- async connectPaddle(+ async connectRevenue(@CurrentUserId() userId: string,@Param('pid') pid: string,- @Body() dto: ConnectPaddleDto,+ @Body() dto: ConnectRevenueDto,) {this.logger.log({ userId, pid }, 'POST /project/:pid/revenue/connect')@@ -91,18 +91,43 @@ export class RevenueController {'You are not allowed to manage revenue settings for this project',)- // Validate API key with Paddle- const isValid = await this.paddleAdapter.validateApiKey(dto.apiKey)+ const currency = dto.currency || 'USD'++ if (dto.provider === 'paddle') {+ // Validate API key with Paddle+ const isValid = await this.paddleAdapter.validateApiKey(dto.apiKey)+ if (!isValid) {+ throw new BadRequestException(+ 'Invalid Paddle API key. Please check your key and try again.',+ )+ }++ const result = await this.revenueService.connectPaddle(+ pid,+ dto.apiKey,+ currency,+ )++ if (!result.success) {+ throw new BadRequestException(result.message)+ }++ return { success: true }+ }++ // Stripe+ const isValid = await this.stripeAdapter.validateApiKey(dto.apiKey)if (!isValid) {throw new BadRequestException(- 'Invalid Paddle API key. Please check your key and try again.',+ 'Invalid Stripe restricted API key. Please check your key and try again.',)}- const result = await this.revenueService.connectPaddle(+ const result = await this.revenueService.connectStripe(pid,dto.apiKey,- dto.currency || 'USD',+ currency,+ STRIPE_REQUIRED_PERMISSIONS,)if (!result.success) {@@ -116,7 +141,7 @@ export class RevenueController {@Delete('/:pid/revenue/disconnect')@Auth()@ApiResponse({ status: 204 })- async disconnectPaddle(+ async disconnectRevenue(@CurrentUserId() userId: string,@Param('pid') pid: string,) {@@ -134,7 +159,7 @@ export class RevenueController {'You are not allowed to manage revenue settings for this project',)- await this.revenueService.disconnectPaddle(pid)+ await this.revenueService.disconnectRevenue(pid)}@ApiBearerAuth()@@ -188,19 +213,41 @@ export class RevenueController {'You are not allowed to manage revenue settings for this project',)- if (!project.paddleApiKeyEnc) {- throw new BadRequestException('Paddle is not connected to this project')+ const currency = project.revenueCurrency || 'USD'++ if (!project.paddleApiKeyEnc && !project.stripeApiKeyEnc) {+ throw new BadRequestException(+ 'Revenue tracking is not connected to this project',+ )+ }++ if (project.paddleApiKeyEnc) {+ const apiKey = this.revenueService.getPaddleApiKey(project)+ if (!apiKey) {+ throw new BadRequestException('Failed to decrypt Paddle API key')+ }++ const count = await this.paddleAdapter.syncTransactions(+ pid,+ apiKey,+ currency,+ project.revenueLastSyncAt || undefined,+ )++ await this.revenueService.updateLastSyncAt(pid)+ return { success: true, transactionsSynced: count }}- const apiKey = this.revenueService.getPaddleApiKey(project)+ // Stripe+ const apiKey = this.revenueService.getStripeApiKey(project)if (!apiKey) {- throw new BadRequestException('Failed to decrypt Paddle API key')+ throw new BadRequestException('Failed to decrypt Stripe API key')}- const count = await this.paddleAdapter.syncTransactions(+ const count = await this.stripeAdapter.syncTransactions(pid,apiKey,- project.revenueCurrency || 'USD',+ currency,project.revenueLastSyncAt || undefined,)@@ -241,7 +288,7 @@ export class RevenueAnalyticsController {this.projectService.allowedToView(project, userId)- if (!project.paddleApiKeyEnc) {+ if (!project.paddleApiKeyEnc && !project.stripeApiKeyEnc) {throw new BadRequestException('Revenue tracking is not configured for this project',)diff --git a/backend/apps/cloud/src/revenue/revenue.module.ts b/backend/apps/cloud/src/revenue/revenue.module.tsindex 3fc5e54cd..9c6dad00f 100644--- a/backend/apps/cloud/src/revenue/revenue.module.ts+++ b/backend/apps/cloud/src/revenue/revenue.module.ts@@ -11,6 +11,7 @@ import {RevenueAnalyticsController,} from './revenue.controller'import { PaddleAdapter } from './adapters/paddle.adapter'+import { StripeAdapter } from './adapters/stripe.adapter'@Module({imports: [@@ -19,8 +20,8 @@ import { PaddleAdapter } from './adapters/paddle.adapter'AppLoggerModule,forwardRef(() => AnalyticsModule),],- providers: [RevenueService, PaddleAdapter],- exports: [RevenueService, PaddleAdapter],+ providers: [RevenueService, PaddleAdapter, StripeAdapter],+ exports: [RevenueService, PaddleAdapter, StripeAdapter],controllers: [RevenueController, RevenueAnalyticsController],})export class RevenueModule {}diff --git a/backend/apps/cloud/src/revenue/revenue.service.ts b/backend/apps/cloud/src/revenue/revenue.service.tsindex 499650997..09b943eef 100644--- a/backend/apps/cloud/src/revenue/revenue.service.ts+++ b/backend/apps/cloud/src/revenue/revenue.service.ts@@ -73,8 +73,10 @@ export class RevenueService {await this.projectRepository.update(projectId, {paddleApiKeyEnc: encryptedKey,+ stripeApiKeyEnc: null,revenueCurrency: currency,paddleApiKeyPermissions: JSON.stringify(PADDLE_REQUIRED_PERMISSIONS),+ stripeApiKeyPermissions: null,revenueLastSyncAt: null,})@@ -85,6 +87,31 @@ export class RevenueService {}}+ async connectStripe(+ projectId: string,+ apiKey: string,+ currency: string = 'USD',+ permissions: string[] = [],+ ): Promise<{ success: boolean; message?: string }> {+ try {+ const encryptedKey = this.encrypt(apiKey)++ await this.projectRepository.update(projectId, {+ stripeApiKeyEnc: encryptedKey,+ paddleApiKeyEnc: null,+ revenueCurrency: currency,+ stripeApiKeyPermissions: JSON.stringify(permissions),+ paddleApiKeyPermissions: null,+ revenueLastSyncAt: null,+ })++ return { success: true }+ } catch (error) {+ this.logger.error({ error, projectId }, 'Failed to connect Stripe')+ return { success: false, message: 'Failed to save Stripe configuration' }+ }+ }+async disconnectPaddle(projectId: string): Promise<void> {await this.projectRepository.update(projectId, {paddleApiKeyEnc: null,@@ -93,16 +120,38 @@ export class RevenueService {})}+ async disconnectStripe(projectId: string): Promise<void> {+ await this.projectRepository.update(projectId, {+ stripeApiKeyEnc: null,+ stripeApiKeyPermissions: null,+ revenueLastSyncAt: null,+ })+ }++ async disconnectRevenue(projectId: string): Promise<void> {+ await this.projectRepository.update(projectId, {+ paddleApiKeyEnc: null,+ paddleApiKeyPermissions: null,+ stripeApiKeyEnc: null,+ stripeApiKeyPermissions: null,+ revenueLastSyncAt: null,+ })+ }+async getRevenueStatus(project: Project): Promise<{connected: booleanprovider?: stringcurrency?: stringlastSyncAt?: string}> {- const connected = !!project.paddleApiKeyEnc+ const connected = !!project.paddleApiKeyEnc || !!project.stripeApiKeyEncreturn {connected,- provider: connected ? 'paddle' : undefined,+ provider: connected+ ? project.paddleApiKeyEnc+ ? 'paddle'+ : 'stripe'+ : undefined,currency: project.revenueCurrency || undefined,lastSyncAt: project.revenueLastSyncAt?.toISOString() || undefined,}@@ -125,6 +174,17 @@ export class RevenueService {}}+ getStripeApiKey(project: Project): string | null {+ if (!project.stripeApiKeyEnc) {+ return null+ }+ try {+ return this.decrypt(project.stripeApiKeyEnc)+ } catch {+ return null+ }+ }+async getRevenueStats(projectId: string,groupFromUTC: string,diff --git a/backend/migrations/mysql/2025_12_18_revenue_stripe.sql b/backend/migrations/mysql/2025_12_18_revenue_stripe.sqlnew file mode 100644index 000000000..60ad60065--- /dev/null+++ b/backend/migrations/mysql/2025_12_18_revenue_stripe.sql@@ -0,0 +1,3 @@+-- Add Stripe API key fields for revenue integration+ALTER TABLE `project` ADD COLUMN `stripeApiKeyEnc` text DEFAULT NULL;+ALTER TABLE `project` ADD COLUMN `stripeApiKeyPermissions` text DEFAULT NULL;diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 802248577..8daffeaf6 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -2467,20 +2467,32 @@ export const getRevenueStatus = async (pid: string): Promise<RevenueStatus> => {})}-export const connectPaddleRevenue = async (+export type RevenueProvider = 'stripe' | 'paddle'++export const connectRevenue = async (pid: string,+ provider: RevenueProvider,apiKey: string,currency: string = 'USD',): Promise<{ success: boolean }> => {return api- .post(`project/${pid}/revenue/connect`, { apiKey, currency })+ .post(`project/${pid}/revenue/connect`, { provider, apiKey, currency }).then((response): { success: boolean } => response.data).catch((error) => {throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message})}-export const disconnectPaddleRevenue = async (pid: string): Promise<void> => {+// Keep backward compatibility+export const connectPaddleRevenue = async (+ pid: string,+ apiKey: string,+ currency: string = 'USD',+): Promise<{ success: boolean }> => {+ return connectRevenue(pid, 'paddle', apiKey, currency)+}++export const disconnectRevenue = async (pid: string): Promise<void> => {return api.delete(`project/${pid}/revenue/disconnect`).then((response) => response.data)@@ -2489,6 +2501,9 @@ export const disconnectPaddleRevenue = async (pid: string): Promise<void> => {})}+// Keep backward compatibility+export const disconnectPaddleRevenue = disconnectRevenue+export const syncRevenue = async (pid: string): Promise<{ success: boolean; transactionsSynced: number }> => {return api.post(`project/${pid}/revenue/sync`)diff --git a/web/app/pages/Project/Settings/tabs/Revenue.tsx b/web/app/pages/Project/Settings/tabs/Revenue.tsxindex 8ad185e49..d2fe9066a 100644--- a/web/app/pages/Project/Settings/tabs/Revenue.tsx+++ b/web/app/pages/Project/Settings/tabs/Revenue.tsx@@ -1,18 +1,15 @@-import { useCallback, useEffect, useState } from 'react'+import { ArrowUpRightIcon, CheckCircle2Icon, LinkIcon } from 'lucide-react'+import React, { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'-import {- connectPaddleRevenue,- disconnectPaddleRevenue,- getRevenueStatus,- syncRevenue,- updateRevenueCurrency,-} from '~/api'+import { connectRevenue, disconnectRevenue, getRevenueStatus, updateRevenueCurrency } from '~/api'+import type { RevenueProvider } from '~/api'+import { DOCS_URL } from '~/lib/constants'import Button from '~/ui/Button'-import Input from '~/ui/Input'import Loader from '~/ui/Loader'import Select from '~/ui/Select'+import { Text } from '~/ui/Text'interface RevenueStatus {connected: boolean@@ -22,14 +19,66 @@ interface RevenueStatus {}const SUPPORTED_CURRENCIES = [- { code: 'USD', name: 'US Dollar' },- { code: 'EUR', name: 'Euro' },- { code: 'GBP', name: 'British Pound' },- { code: 'CAD', name: 'Canadian Dollar' },- { code: 'AUD', name: 'Australian Dollar' },+ { code: 'USD', symbol: '$', name: 'US Dollar' },+ { code: 'EUR', symbol: '€', name: 'Euro' },+ { code: 'GBP', symbol: '£', name: 'British Pound' },]-const PADDLE_DOCS_URL = 'https://developer.paddle.com/api-reference/about/authentication'+const STRIPE_REQUIRED_PERMISSIONS = [+ 'rak_charge_read',+ 'rak_subscription_read',+ 'rak_customer_read',+ 'rak_payment_intent_read',+ 'rak_checkout_session_read',+ 'rak_invoice_read',+ 'rak_webhook_write',+ 'rak_product_read',+]++const STRIPE_API_KEY_CREATE_URL = `https://dashboard.stripe.com/apikeys/create?name=Swetrix&permissions%5B%5D=${STRIPE_REQUIRED_PERMISSIONS.join('&permissions%5B%5D=')}`++interface ProviderConfig {+ label: string+ icon: React.ReactNode+ apiKeyPrefix: string+ apiKeyCreateUrl?: string+}++const PROVIDER_CONFIG: Record<RevenueProvider, ProviderConfig> = {+ stripe: {+ label: 'Stripe',+ icon: (+ <div className='flex h-5 w-5 items-center justify-center rounded bg-[#635BFF] text-xs font-bold text-white'>+ S+ </div>+ ),+ apiKeyPrefix: 'rk_live_',+ apiKeyCreateUrl: STRIPE_API_KEY_CREATE_URL,+ },+ paddle: {+ label: 'Paddle',+ icon: (+ <div className='flex h-5 w-5 items-center justify-center rounded bg-[#FFCE00] text-xs font-bold text-[#0E1B2B]'>+ P+ </div>+ ),+ apiKeyPrefix: 'pdl_live_',+ },+}++const REVENUE_PROVIDERS: RevenueProvider[] = ['stripe', 'paddle']++interface ProviderItem {+ id: RevenueProvider+ label: string+ icon: React.ReactNode+}++const PROVIDER_ITEMS: ProviderItem[] = REVENUE_PROVIDERS.map((p) => ({+ id: p,+ label: PROVIDER_CONFIG[p].label,+ icon: PROVIDER_CONFIG[p].icon,+}))interface Props {projectId: string@@ -41,15 +90,20 @@ const Revenue = ({ projectId }: Props) => {const [status, setStatus] = useState<RevenueStatus | null>(null)const [isLoading, setIsLoading] = useState(true)const [apiKey, setApiKey] = useState('')- const [selectedCurrency, setSelectedCurrency] = useState('USD')+ const [selectedProvider, setSelectedProvider] = useState<RevenueProvider>('stripe')+ const [selectedCurrency, setSelectedCurrency] = useState<'USD' | 'EUR' | 'GBP'>('USD')const [isConnecting, setIsConnecting] = useState(false)- const [isSyncing, setIsSyncing] = useState(false)+ const [isDisconnecting, setIsDisconnecting] = useState(false)+ const [isSavingCurrency, setIsSavingCurrency] = useState(false)const loadStatus = useCallback(async () => {try {const result = await getRevenueStatus(projectId)setStatus(result)- if (result.currency) {+ if (result.provider === 'stripe' || result.provider === 'paddle') {+ setSelectedProvider(result.provider)+ }+ if (result.currency === 'USD' || result.currency === 'EUR' || result.currency === 'GBP') {setSelectedCurrency(result.currency)}} catch (error) {@@ -71,7 +125,7 @@ const Revenue = ({ projectId }: Props) => {setIsConnecting(true)try {- await connectPaddleRevenue(projectId, apiKey, selectedCurrency)+ await connectRevenue(projectId, selectedProvider, apiKey, selectedCurrency)toast.success(t('project.settings.revenue.connected'))setApiKey('')await loadStatus()@@ -83,167 +137,225 @@ const Revenue = ({ projectId }: Props) => {}const handleDisconnect = async () => {+ setIsDisconnecting(true)try {- await disconnectPaddleRevenue(projectId)+ await disconnectRevenue(projectId)toast.success(t('project.settings.revenue.disconnected'))setStatus({ connected: false })} catch (error: any) {toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))+ } finally {+ setIsDisconnecting(false)}}- const handleSync = async () => {- setIsSyncing(true)+ const handleCurrencyChange = async () => {+ if (!status?.connected) return++ setIsSavingCurrency(true)try {- const result = await syncRevenue(projectId)- toast.success(t('project.settings.revenue.synced', { count: result.transactionsSynced }))- await loadStatus()+ await updateRevenueCurrency(projectId, selectedCurrency)+ toast.success(t('project.settings.revenue.currencyUpdated'))} catch (error: any) {toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))} finally {- setIsSyncing(false)- }- }-- const handleCurrencyChange = async (currency: string) => {- setSelectedCurrency(currency)- if (status?.connected) {- try {- await updateRevenueCurrency(projectId, currency)- toast.success(t('project.settings.revenue.currencyUpdated'))- } catch (error: any) {- toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))- }+ setIsSavingCurrency(false)}}if (isLoading) {return (- <div className='flex items-center justify-center py-8'>+ <div className='flex min-h-[200px] items-center justify-center'><Loader /></div>)}+ const providerConfig = PROVIDER_CONFIG[selectedProvider]+ const isConnected = Boolean(status?.connected)+ const isSelectedProviderConnected = isConnected && status?.provider === selectedProvider+ const apiKeyCreateUrl = providerConfig.apiKeyCreateUrl+ const apiKeyPlaceholder = `${providerConfig.apiKeyPrefix}********************`++ const selectedProviderItem = PROVIDER_ITEMS.find((p) => p.id === selectedProvider)+return (- <div className='space-y-6'>- <div className='rounded-lg border border-gray-200 p-4 dark:border-slate-800'>- <h3 className='mb-2 text-lg font-medium text-gray-900 dark:text-gray-50'>- {t('project.settings.revenue.title')}- </h3>- <p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>{t('project.settings.revenue.description')}</p>-- {status?.connected ? (- <div className='space-y-4'>- <div className='flex items-center gap-2'>- <div className='h-2.5 w-2.5 rounded-full bg-green-500' />- <span className='text-sm font-medium text-gray-900 dark:text-gray-50'>- {t('project.settings.revenue.connectedTo', { provider: 'Paddle' })}- </span>+ <div>+ <Text as='h3' size='lg' weight='bold' colour='primary'>+ {t('project.settings.revenue.title', { defaultValue: 'Revenue tracking' })}+ </Text>+ <Text as='p' size='sm' colour='muted' className='mt-1'>+ {t('project.settings.revenue.description', {+ defaultValue: 'Connect your payment provider to track revenue alongside your analytics.',+ })}+ </Text>++ <div className='mt-6 space-y-3'>+ {/* Step 1: Pick provider */}+ <div className='rounded-md border border-gray-200 p-3 dark:border-gray-800'>+ <div className='flex items-start'>+ <div className='flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-indigo-100 text-xs font-semibold text-indigo-600 dark:bg-indigo-900/50 dark:text-indigo-400'>+ 1+ </div>+ <div className='ml-3 flex-1'>+ <Text as='div' size='sm' weight='medium' colour='primary'>+ {t('project.settings.revenue.pickProvider', { defaultValue: 'Pick your payment provider' })}+ </Text>+ <div className='mt-2'>+ <Select+ className='max-w-xs'+ title={providerConfig.label}+ items={PROVIDER_ITEMS}+ labelExtractor={(item) => (+ <div className='flex items-center gap-2'>+ {item.icon}+ <span>{item.label}</span>+ </div>+ )}+ keyExtractor={(item) => item.id}+ iconExtractor={(item) => item.icon}+ selectedItem={selectedProviderItem}+ onSelect={(item: ProviderItem) => {+ setSelectedProvider(item.id)+ }}+ />+ </div></div>+ </div>+ </div>- {status.lastSyncAt && (- <p className='text-sm text-gray-600 dark:text-gray-300'>- {t('project.settings.revenue.lastSync', {- date: new Date(status.lastSyncAt).toLocaleString(),- })}- </p>- )}-- <div className='flex flex-wrap gap-2'>- <Button type='button' onClick={handleSync} loading={isSyncing} primary regular>- {t('project.settings.revenue.syncNow')}- </Button>- <Button type='button' onClick={handleDisconnect} semiDanger regular>- {t('common.disconnect')}- </Button>+ {/* Step 2: Connect */}+ <div className='rounded-md border border-gray-200 p-3 dark:border-gray-800'>+ <div className='flex items-start'>+ <div className='flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-indigo-100 text-xs font-semibold text-indigo-600 dark:bg-indigo-900/50 dark:text-indigo-400'>+ 2</div>+ <div className='ml-3 flex-1'>+ <Text as='div' size='sm' weight='medium' colour='primary'>+ {t('project.settings.revenue.connectProvider', {+ defaultValue: `Connect ${providerConfig.label}`,+ provider: providerConfig.label,+ })}+ </Text>+ <Text as='p' size='sm' colour='muted' className='mt-0.5'>+ {t('project.settings.revenue.createApiKey', { defaultValue: 'Create a' })}{' '}+ {apiKeyCreateUrl ? (+ <a+ href={apiKeyCreateUrl}+ target='_blank'+ rel='noreferrer noopener'+ className='inline-flex items-center text-indigo-600 underline decoration-dashed hover:decoration-solid dark:text-indigo-400'+ >+ {t('project.settings.revenue.restrictedApiKey', { defaultValue: 'restricted API key' })}+ <ArrowUpRightIcon className='ml-0.5 h-3 w-3' />+ </a>+ ) : (+ <span className='font-medium'>+ {t('project.settings.revenue.restrictedApiKey', { defaultValue: 'restricted API key' })}+ </span>+ )}{' '}+ {t('project.settings.revenue.pasteBelow', {+ defaultValue: '(do not change any permissions) and paste it below.',+ })}+ </Text>++ {isConnected && !isSelectedProviderConnected && status?.provider ? (+ <Text as='p' size='sm' colour='warning' className='mt-2'>+ {t('project.settings.revenue.replaceWarning', {+ defaultValue: `This project is connected to ${PROVIDER_CONFIG[status.provider as RevenueProvider]?.label || status.provider}. Connecting ${providerConfig.label} will replace the existing connection.`,+ })}+ </Text>+ ) : null}++ <div className='mt-3'>+ <input+ type='text'+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ placeholder={apiKeyPlaceholder}+ className='block w-full max-w-md rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm placeholder:text-gray-400 focus:border-indigo-500 focus:ring-indigo-500 dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:placeholder:text-gray-500'+ disabled={isConnecting}+ />+ </div>- <hr className='border-gray-200 dark:border-slate-700' />-- <div>- <Select- label={t('project.settings.revenue.currency')}- hint={t('project.settings.revenue.currencyHint')}- className='max-w-xs'- items={SUPPORTED_CURRENCIES}- keyExtractor={(item) => item.code}- labelExtractor={(item) => `${item.code} - ${item.name}`}- selectedItem={SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)}- onSelect={(item: { code: string; name: string }) => handleCurrencyChange(item.code)}- title={selectedCurrency}- />+ {!isSelectedProviderConnected ? (+ <Button className='mt-3' onClick={handleConnect} loading={isConnecting} primary regular>+ {t('common.connect')}+ </Button>+ ) : (+ <div className='mt-3 flex flex-wrap items-center gap-3'>+ <div className='flex items-center gap-1.5'>+ <CheckCircle2Icon className='h-4 w-4 text-green-600 dark:text-green-400' />+ <Text as='span' size='sm' colour='success' weight='medium'>+ {t('common.connected')}+ {status?.lastSyncAt ? ` · ${new Date(status.lastSyncAt).toLocaleString()}` : ''}+ </Text>+ </div>+ <Button onClick={handleDisconnect} loading={isDisconnecting} semiDanger semiSmall>+ {t('common.disconnect')}+ </Button>+ </div>+ )}</div></div>- ) : (- <div className='space-y-4'>- <div>- <h4 className='mb-2 text-base font-medium text-gray-900 dark:text-gray-50'>- {t('project.settings.revenue.connectPaddle')}- </h4>- <p className='mb-3 text-sm text-gray-600 dark:text-gray-300'>- {t('project.settings.revenue.connectPaddleDesc')}- </p>- <a- href={PADDLE_DOCS_URL}- target='_blank'- rel='noopener noreferrer'- className='text-sm font-medium text-indigo-600 hover:underline dark:text-indigo-400'- >- {t('project.settings.revenue.paddleDocsLink')}- </a>- </div>+ </div>- <Input- type='password'- label={t('project.settings.revenue.apiKey')}- hint={t('project.settings.revenue.apiKeyHint')}- placeholder='pdl_live_...'- value={apiKey}- onChange={(e) => setApiKey(e.target.value)}- className='max-w-md'- />-- <Select- label={t('project.settings.revenue.currency')}- hint={t('project.settings.revenue.currencyHint')}- className='max-w-xs'- items={SUPPORTED_CURRENCIES}- keyExtractor={(item) => item.code}- labelExtractor={(item) => `${item.code} - ${item.name}`}- selectedItem={SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)}- onSelect={(item: { code: string; name: string }) => setSelectedCurrency(item.code)}- title={selectedCurrency}- />-- <Button type='button' onClick={handleConnect} loading={isConnecting} primary regular>- {t('common.connect')}- </Button>+ {/* Step 3: Link with traffic */}+ <div className='rounded-md border border-gray-200 p-3 dark:border-gray-800'>+ <div className='flex items-start'>+ <div className='flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-indigo-100 text-xs font-semibold text-indigo-600 dark:bg-indigo-900/50 dark:text-indigo-400'>+ 3+ </div>+ <div className='ml-3 flex-1'>+ <Text as='div' size='sm' weight='medium' colour='primary'>+ {t('project.settings.revenue.linkWithTraffic', { defaultValue: 'Link with traffic' })}+ </Text>+ <Text as='p' size='sm' colour='muted' className='mt-0.5'>+ {t('project.settings.revenue.linkDescription', {+ defaultValue: 'Make revenue-driven decisions by linking your revenue data with your traffic data.',+ })}{' '}+ <a+ href={DOCS_URL}+ target='_blank'+ rel='noreferrer noopener'+ className='inline-flex items-center text-indigo-600 underline decoration-dashed hover:decoration-solid dark:text-indigo-400'+ >+ {t('project.settings.revenue.getStarted', { defaultValue: 'Get started here' })}+ <LinkIcon className='ml-0.5 h-3 w-3' />+ </a>{' '}+ <span className='text-gray-400 dark:text-gray-500'>+ {t('project.settings.revenue.timeEstimate', { defaultValue: '(takes ~2 minutes)' })}+ </span>+ </Text>+ </div></div>- )}+ </div></div>- <div className='rounded-lg border border-gray-200 p-4 dark:border-slate-800'>- <h3 className='mb-2 text-lg font-medium text-gray-900 dark:text-gray-50'>- {t('project.settings.revenue.attribution.title')}- </h3>- <p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>- {t('project.settings.revenue.attribution.description')}- </p>-- <div className='rounded-md bg-gray-100 p-4 dark:bg-slate-800'>- <p className='mb-2 text-sm font-medium text-gray-900 dark:text-gray-50'>- {t('project.settings.revenue.attribution.paddleExample')}- </p>- <pre className='overflow-x-auto text-xs text-gray-700 dark:text-gray-300'>- {`Paddle.Checkout.open({- items: [{ priceId: 'pri_...', quantity: 1 }],- customData: {- swetrix_profile_id: await swetrix.getProfileId(),- swetrix_session_id: await swetrix.getSessionId()- }-})`}- </pre>+ {/* Currency settings */}+ <div className='mt-6'>+ <Text as='h4' size='sm' weight='medium' colour='primary'>+ {t('project.settings.revenue.currency', { defaultValue: 'Currency' })}+ </Text>+ <Text as='p' size='sm' colour='muted' className='mt-0.5'>+ {t('project.settings.revenue.currencyDescription', {+ defaultValue: 'Used for all revenue reporting and payment conversion.',+ })}+ </Text>+ <div className='mt-2 flex flex-wrap items-center gap-3'>+ <Select+ className='max-w-xs'+ title={`${selectedCurrency} – ${SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)?.name} (${SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)?.symbol})`}+ items={SUPPORTED_CURRENCIES}+ keyExtractor={(item) => item.code}+ labelExtractor={(item) => `${item.code} – ${item.name} (${item.symbol})`}+ onSelect={(item: { code: string; name: string; symbol: string }) =>+ setSelectedCurrency(item.code as 'USD' | 'EUR' | 'GBP')+ }+ />+ <Button onClick={handleCurrencyChange} loading={isSavingCurrency} primary regular disabled={!isConnected}>+ {t('common.save')}+ </Button></div></div></div>