Billing get subscription enhancement (#36)

* Filter out metered line items from billing schema

This update refines the process of creating a billing schema by filtering out metered line items. The change is necessary as metered line items can be shared across different plans, potentially causing conflicts or duplicates in the schema.

* Update packages to newer versions

This update upgrades several packages across multiple project files to their latest version. These packages include "supabase-js", "react-query", "react-hook-form", and "pnpm". The commit ensures the project is up-to-date with recent package versions, potentially benefiting from bug fixes, new features, and performance improvements.

* Add subscription retrieval in billing services

Added a function to retrieve subscription info in both Stripe and LemonSqueezy billing services. To accomplish this, new methods were added to related services and types. This allows querying specific subscription data based on its id, and throws an error if it fails. Furthermore, PayloadBuilder classes were created to systematically build the subscription payload.

* Remove account ID retrieval from Lemon Squeezy billing service

The code that was querying the database to fetch the accountId has been removed from lemon-squeezy-billing-strategy.service.ts. It was unnecessary as the Lemon Squeezy API does not provide account ID and therefore it is always left empty. Also, adjustments have been made in billing-strategy-provider.service.ts to reflect that the target account ID can be optional.

* Extract 'next' parameter from callback URL

The update allows for the extraction of the 'next' parameter from the callback URL. If such a parameter is available, it is subsequently added to the search parameters. The enhancement improves URL parameter handling in the authentication callback service.

* Refactor URL redirection in auth-callback service

The update simplifies the redirection logic in the authentication callback service. This is achieved by setting the url pathname directly to the redirect path, instead of first setting it to the callback parameter. Moreover, the code handling the 'next' path has also been streamlined, setting the url pathname to the next path when available.
This commit is contained in:
Giancarlo Buomprisco
2024-06-19 23:00:00 +08:00
committed by GitHub
parent fbe7ca4c9e
commit 6a339a4b02
30 changed files with 738 additions and 456 deletions

View File

@@ -4,6 +4,7 @@ import {
cancelSubscription,
createUsageRecord,
getCheckout,
getSubscription,
getVariant,
listUsageRecords,
updateSubscriptionItem,
@@ -24,6 +25,7 @@ import { getLogger } from '@kit/shared/logger';
import { createLemonSqueezyBillingPortalSession } from './create-lemon-squeezy-billing-portal-session';
import { createLemonSqueezyCheckout } from './create-lemon-squeezy-checkout';
import { createLemonSqueezySubscriptionPayloadBuilderService } from './lemon-squeezy-subscription-payload-builder.service';
export class LemonSqueezyBillingStrategyService
implements BillingStrategyProviderService
@@ -340,6 +342,91 @@ export class LemonSqueezyBillingStrategyService
return { success: true };
}
async getSubscription(subscriptionId: string) {
const logger = await getLogger();
const ctx = {
name: this.namespace,
subscriptionId,
};
logger.info(ctx, 'Retrieving subscription...');
const { error, data } = await getSubscription(subscriptionId);
if (error) {
logger.error(
{
...ctx,
error,
},
'Failed to retrieve subscription',
);
throw new Error('Failed to retrieve subscription');
}
if (!data) {
logger.error(
{
...ctx,
},
'Subscription not found',
);
throw new Error('Subscription not found');
}
logger.info(ctx, 'Subscription retrieved successfully');
const payloadBuilderService =
createLemonSqueezySubscriptionPayloadBuilderService();
const subscription = data.data.attributes;
const customerId = subscription.customer_id.toString();
const status = subscription.status;
const variantId = subscription.variant_id;
const productId = subscription.product_id;
const createdAt = subscription.created_at;
const endsAt = subscription.ends_at;
const renewsAt = subscription.renews_at;
const trialEndsAt = subscription.trial_ends_at;
const intervalCount = subscription.billing_anchor;
const interval = intervalCount === 1 ? 'month' : 'year';
const subscriptionItemId =
data.data.attributes.first_subscription_item?.id.toString() as string;
const lineItems = [
{
id: subscriptionItemId.toString(),
product: productId.toString(),
variant: variantId.toString(),
quantity: subscription.first_subscription_item?.quantity ?? 1,
// not anywhere in the API
priceAmount: 0,
},
];
return payloadBuilderService.build({
customerId,
id: subscriptionId,
// not in the API
accountId: '',
lineItems,
status,
interval,
intervalCount,
// not in the API
currency: '',
periodStartsAt: new Date(createdAt).getTime(),
periodEndsAt: new Date(renewsAt ?? endsAt).getTime(),
cancelAtPeriodEnd: subscription.cancelled,
trialStartsAt: trialEndsAt ? new Date(createdAt).getTime() : null,
trialEndsAt: trialEndsAt ? new Date(trialEndsAt).getTime() : null,
});
}
/**
* @name queryUsage
* @description Queries the usage of the metered billing

View File

@@ -0,0 +1,141 @@
import { BillingConfig, getLineItemTypeById } from '@kit/billing';
import { UpsertSubscriptionParams } from '@kit/billing/types';
type SubscriptionStatus =
| 'on_trial'
| 'active'
| 'cancelled'
| 'paused'
| 'expired'
| 'unpaid'
| 'past_due';
/**
* @name createLemonSqueezySubscriptionPayloadBuilderService
* @description Create a new instance of the `LemonSqueezySubscriptionPayloadBuilderService` class
*/
export function createLemonSqueezySubscriptionPayloadBuilderService() {
return new LemonSqueezySubscriptionPayloadBuilderService();
}
/**
* @name LemonSqueezySubscriptionPayloadBuilderService
* @description This class is used to build the subscription payload for Lemon Squeezy
*/
class LemonSqueezySubscriptionPayloadBuilderService {
private config?: BillingConfig;
/**
* @name withBillingConfig
* @description Set the billing config for the subscription payload
* @param config
*/
withBillingConfig(config: BillingConfig) {
this.config = config;
return this;
}
/**
* @name build
* @description Build the subscription payload for Lemon Squeezy
* @param params
*/
build<
LineItem extends {
id: string;
quantity: number;
product: string;
variant: string;
priceAmount: number;
},
>(params: {
id: string;
accountId: string;
customerId: string;
lineItems: LineItem[];
interval: string;
intervalCount: number;
status: string;
currency: string;
cancelAtPeriodEnd: boolean;
periodStartsAt: number;
periodEndsAt: number;
trialStartsAt: number | null;
trialEndsAt: number | null;
}): UpsertSubscriptionParams {
const canceledAtPeriodEnd =
params.status === 'cancelled' && params.cancelAtPeriodEnd;
const active =
params.status === 'active' ||
params.status === 'trialing' ||
canceledAtPeriodEnd;
const lineItems = params.lineItems.map((item) => {
const quantity = item.quantity ?? 1;
return {
id: item.id,
subscription_item_id: item.id,
quantity,
interval: params.interval,
interval_count: params.intervalCount,
subscription_id: params.id,
product_id: item.product,
variant_id: item.variant,
price_amount: item.priceAmount,
type: this.config
? getLineItemTypeById(this.config, item.variant)
: undefined,
};
});
// otherwise we are updating a subscription
// and we only need to return the update payload
return {
target_subscription_id: params.id,
target_account_id: params.accountId,
target_customer_id: params.customerId,
billing_provider: 'lemon-squeezy',
status: this.getSubscriptionStatus(params.status as SubscriptionStatus),
line_items: lineItems,
active,
currency: params.currency,
cancel_at_period_end: params.cancelAtPeriodEnd ?? false,
period_starts_at: getISOString(params.periodStartsAt) as string,
period_ends_at: getISOString(params.periodEndsAt) as string,
trial_starts_at: params.trialStartsAt
? getISOString(params.trialStartsAt)
: undefined,
trial_ends_at: params.trialEndsAt
? getISOString(params.trialEndsAt)
: undefined,
};
}
private getSubscriptionStatus(status: SubscriptionStatus) {
switch (status) {
case 'active':
return 'active';
case 'cancelled':
return 'canceled';
case 'paused':
return 'paused';
case 'on_trial':
return 'trialing';
case 'past_due':
return 'past_due';
case 'unpaid':
return 'unpaid';
case 'expired':
return 'past_due';
default:
return 'active';
}
}
}
function getISOString(date: number | null) {
return date ? new Date(date).toISOString() : undefined;
}

View File

@@ -1,10 +1,6 @@
import { getOrder, getVariant } from '@lemonsqueezy/lemonsqueezy.js';
import {
BillingConfig,
BillingWebhookHandlerService,
getLineItemTypeById,
} from '@kit/billing';
import { BillingConfig, BillingWebhookHandlerService } from '@kit/billing';
import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
@@ -12,24 +8,31 @@ import { getLemonSqueezyEnv } from '../schema/lemon-squeezy-server-env.schema';
import { OrderWebhook } from '../types/order-webhook';
import { SubscriptionWebhook } from '../types/subscription-webhook';
import { initializeLemonSqueezyClient } from './lemon-squeezy-sdk';
import { createLemonSqueezySubscriptionPayloadBuilderService } from './lemon-squeezy-subscription-payload-builder.service';
import { createHmac } from './verify-hmac';
type UpsertSubscriptionParams =
Database['public']['Functions']['upsert_subscription']['Args'];
Database['public']['Functions']['upsert_subscription']['Args'] & {
line_items: Array<LineItem>;
};
type UpsertOrderParams =
Database['public']['Functions']['upsert_order']['Args'];
type OrderStatus = 'pending' | 'failed' | 'paid' | 'refunded';
interface LineItem {
id: string;
quantity: number;
subscription_id: string;
subscription_item_id: string;
product_id: string;
variant_id: string;
price_amount: number | null | undefined;
interval: string;
interval_count: number;
type: 'flat' | 'metered' | 'per_seat' | undefined;
}
type SubscriptionStatus =
| 'on_trial'
| 'active'
| 'cancelled'
| 'paused'
| 'expired'
| 'unpaid'
| 'past_due';
type OrderStatus = 'pending' | 'failed' | 'paid' | 'refunded';
export class LemonSqueezyWebhookHandlerService
implements BillingWebhookHandlerService
@@ -252,7 +255,10 @@ export class LemonSqueezyWebhookHandlerService
const interval = intervalCount === 1 ? 'month' : 'year';
const payload = this.buildSubscriptionPayload({
const payloadBuilderService =
createLemonSqueezySubscriptionPayloadBuilderService();
const payload = payloadBuilderService.withBillingConfig(this.config).build({
customerId,
id: subscriptionId,
accountId,
@@ -292,76 +298,6 @@ export class LemonSqueezyWebhookHandlerService
return onSubscriptionDeletedCallback(subscription.data.id);
}
private buildSubscriptionPayload<
LineItem extends {
id: string;
quantity: number;
product: string;
variant: string;
priceAmount: number;
},
>(params: {
id: string;
accountId: string;
customerId: string;
lineItems: LineItem[];
interval: string;
intervalCount: number;
status: string;
currency: string;
cancelAtPeriodEnd: boolean;
periodStartsAt: number;
periodEndsAt: number;
trialStartsAt: number | null;
trialEndsAt: number | null;
}): UpsertSubscriptionParams {
const canceledAtPeriodEnd =
params.status === 'cancelled' && params.cancelAtPeriodEnd;
const active =
params.status === 'active' ||
params.status === 'trialing' ||
canceledAtPeriodEnd;
const lineItems = params.lineItems.map((item) => {
const quantity = item.quantity ?? 1;
return {
id: item.id,
quantity,
interval: params.interval,
interval_count: params.intervalCount,
subscription_id: params.id,
product_id: item.product,
variant_id: item.variant,
price_amount: item.priceAmount,
type: getLineItemTypeById(this.config, item.variant),
};
});
// otherwise we are updating a subscription
// and we only need to return the update payload
return {
target_subscription_id: params.id,
target_account_id: params.accountId,
target_customer_id: params.customerId,
billing_provider: this.provider,
status: this.getSubscriptionStatus(params.status as SubscriptionStatus),
line_items: lineItems,
active,
currency: params.currency,
cancel_at_period_end: params.cancelAtPeriodEnd ?? false,
period_starts_at: getISOString(params.periodStartsAt) as string,
period_ends_at: getISOString(params.periodEndsAt) as string,
trial_starts_at: params.trialStartsAt
? getISOString(params.trialStartsAt)
: undefined,
trial_ends_at: params.trialEndsAt
? getISOString(params.trialEndsAt)
: undefined,
};
}
private getOrderStatus(status: OrderStatus) {
switch (status) {
case 'paid':
@@ -376,31 +312,6 @@ export class LemonSqueezyWebhookHandlerService
return 'pending';
}
}
private getSubscriptionStatus(status: SubscriptionStatus) {
switch (status) {
case 'active':
return 'active';
case 'cancelled':
return 'canceled';
case 'paused':
return 'paused';
case 'on_trial':
return 'trialing';
case 'past_due':
return 'past_due';
case 'unpaid':
return 'unpaid';
case 'expired':
return 'past_due';
default:
return 'active';
}
}
}
function getISOString(date: number | null) {
return date ? new Date(date).toISOString() : undefined;
}
async function isSigningSecretValid(rawBody: string, signatureHeader: string) {