-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
disabling db stuff as payment stuff isnot working in india
- Loading branch information
1 parent
5e0ef22
commit a723600
Showing
3 changed files
with
192 additions
and
190 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,61 +1,62 @@ | ||
import { drizzle } from 'drizzle-orm/postgres-js'; | ||
import postgres from 'postgres'; | ||
import { env } from '$env/dynamic/private'; | ||
import { DEV_ENVS, PROD_ENVS } from '$lib/constants'; | ||
|
||
export function checkEnvParam( | ||
variableName: string, | ||
raiseError: boolean = true | ||
): string | undefined { | ||
const value = env[variableName]; | ||
if (!value) { | ||
if (raiseError) { | ||
throw new Error(`${variableName} is not set`); | ||
} | ||
return; | ||
} | ||
return value; | ||
} | ||
|
||
export function getDbConfig( | ||
username?: string, | ||
password?: string, | ||
host?: string, | ||
port?: number, | ||
dbName?: string | ||
): { | ||
username: string; | ||
password: string; | ||
host: string; | ||
port: number; | ||
dbName: string; | ||
} { | ||
const _username = username || (checkEnvParam('DATABASE_USERNAME', true) as string); | ||
const _password = password || (checkEnvParam('DATABASE_PASSWORD', true) as string); | ||
const _host = host || (checkEnvParam('DATABASE_HOST', true) as string); | ||
const _port = port || parseInt(checkEnvParam('DATABASE_PORT', true) as string); | ||
const _dbName = dbName || (checkEnvParam('DATABASE_NAME', true) as string); | ||
return { username: _username, password: _password, host: _host, port: _port, dbName: _dbName }; | ||
} | ||
|
||
function getDatabaseUrl(): string { | ||
if (!env.DATABASE_URL) { | ||
const dbConfig = getDbConfig(); | ||
databaseUrl = `postgres://${dbConfig.username}:${dbConfig.password}@${dbConfig.host}:${dbConfig.port}/${dbConfig.dbName}`; | ||
} else { | ||
databaseUrl = env.DATABASE_URL; | ||
} | ||
return databaseUrl; | ||
} | ||
|
||
let databaseUrl: string; | ||
if (env.MY_ENV === 'local') { | ||
databaseUrl = 'postgres://postgres@localhost:5432/longpost'; | ||
} else if (PROD_ENVS.concat(DEV_ENVS).includes(env.MY_ENV)) { | ||
databaseUrl = getDatabaseUrl(); | ||
} else { | ||
throw new Error(`Environment not provided or unknown environment: ${env.MY_ENV}`); | ||
} | ||
|
||
const client = postgres(databaseUrl); | ||
export const db = drizzle(client); | ||
// TODO: disable db stuff as Stripe is not working in india | ||
// import { drizzle } from 'drizzle-orm/postgres-js'; | ||
// import postgres from 'postgres'; | ||
// import { env } from '$env/dynamic/private'; | ||
// import { DEV_ENVS, PROD_ENVS } from '$lib/constants'; | ||
// | ||
// export function checkEnvParam( | ||
// variableName: string, | ||
// raiseError: boolean = true | ||
// ): string | undefined { | ||
// const value = env[variableName]; | ||
// if (!value) { | ||
// if (raiseError) { | ||
// throw new Error(`${variableName} is not set`); | ||
// } | ||
// return; | ||
// } | ||
// return value; | ||
// } | ||
// | ||
// export function getDbConfig( | ||
// username?: string, | ||
// password?: string, | ||
// host?: string, | ||
// port?: number, | ||
// dbName?: string | ||
// ): { | ||
// username: string; | ||
// password: string; | ||
// host: string; | ||
// port: number; | ||
// dbName: string; | ||
// } { | ||
// const _username = username || (checkEnvParam('DATABASE_USERNAME', true) as string); | ||
// const _password = password || (checkEnvParam('DATABASE_PASSWORD', true) as string); | ||
// const _host = host || (checkEnvParam('DATABASE_HOST', true) as string); | ||
// const _port = port || parseInt(checkEnvParam('DATABASE_PORT', true) as string); | ||
// const _dbName = dbName || (checkEnvParam('DATABASE_NAME', true) as string); | ||
// return { username: _username, password: _password, host: _host, port: _port, dbName: _dbName }; | ||
// } | ||
// | ||
// function getDatabaseUrl(): string { | ||
// if (!env.DATABASE_URL) { | ||
// const dbConfig = getDbConfig(); | ||
// databaseUrl = `postgres://${dbConfig.username}:${dbConfig.password}@${dbConfig.host}:${dbConfig.port}/${dbConfig.dbName}`; | ||
// } else { | ||
// databaseUrl = env.DATABASE_URL; | ||
// } | ||
// return databaseUrl; | ||
// } | ||
// | ||
// let databaseUrl: string; | ||
// if (env.MY_ENV === 'local') { | ||
// databaseUrl = 'postgres://postgres@localhost:5432/longpost'; | ||
// } else if (PROD_ENVS.concat(DEV_ENVS).includes(env.MY_ENV)) { | ||
// databaseUrl = getDatabaseUrl(); | ||
// } else { | ||
// throw new Error(`Environment not provided or unknown environment: ${env.MY_ENV}`); | ||
// } | ||
// | ||
// const client = postgres(databaseUrl); | ||
// export const db = drizzle(client); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,127 +1,128 @@ | ||
import { json, error, type RequestHandler } from '@sveltejs/kit'; | ||
import Stripe from 'stripe'; | ||
import { checkEnvParam } from '$lib/server/db'; | ||
import { Logger } from '$lib/logger'; | ||
import { updateSubscriber, upsertSubscriber } from '$lib/server/db/utils'; | ||
import type { SubscriptionInsert } from '$lib/server/db/schema'; | ||
import { isEnvProd } from '$lib/lib-utils'; | ||
|
||
function createErrorMsg(error: Error): string { | ||
return isEnvProd() | ||
? `Error processing webhook, error message: ${error.message}` | ||
: `Error processing webhook, error stack: ${error.stack}`; | ||
} | ||
|
||
const logger = new Logger(); | ||
logger.info('Loading stripe secrets'); | ||
const STRIPE_SECRET_KEY = checkEnvParam('STRIPE_SECRET_KEY', true) as string; | ||
const STRIPE_WEBHOOK_SECRET = checkEnvParam('STRIPE_WEBHOOK_SECRET', true) as string; | ||
|
||
const stripe = new Stripe(STRIPE_SECRET_KEY); | ||
|
||
export const POST: RequestHandler = async (event) => { | ||
let stripeEvent: Stripe.Event; | ||
// Step 1: Get the raw request body as a buffer | ||
const request = event.request; | ||
const payload = await request.text(); | ||
const sig = request.headers.get('stripe-signature'); | ||
try { | ||
// Step 2: Verify the webhook signature to ensure it's from Stripe | ||
if (!sig || !STRIPE_WEBHOOK_SECRET) { | ||
throw new Error('Missing Stripe signature or webhook secret'); | ||
} | ||
|
||
stripeEvent = stripe.webhooks.constructEvent(payload, sig, STRIPE_WEBHOOK_SECRET); | ||
|
||
// Step 3: Handle the Stripe event | ||
switch (stripeEvent.type) { | ||
case 'customer.subscription.deleted': { | ||
logger.info(`stripeEvent type: ${stripeEvent.type}`); | ||
const subscription = stripeEvent.data.object as Stripe.Subscription; | ||
|
||
const subscriptionId = subscription.id; | ||
const stripeCustomerId = subscription.customer; | ||
const subscriptionStatus = subscription.status; | ||
|
||
logger.info(`Subscription deleted: ${subscriptionId}`); | ||
const subscriber: SubscriptionInsert = { | ||
stripeCustomerId: stripeCustomerId as string, | ||
subscriptionStatus: subscriptionStatus, | ||
subscriptionId: subscriptionId | ||
}; | ||
try { | ||
await updateSubscriber(stripeCustomerId as string, subscriber); | ||
} catch (err) { | ||
const _err = err as Error; | ||
logger.error(`Error updating subscriber: ${_err.stack}`); | ||
return error(502, createErrorMsg(_err)); | ||
} | ||
logger.info(`Subscription cancelled: ${subscriptionId} of customer: ${stripeCustomerId}`); | ||
break; | ||
} | ||
case 'customer.subscription.updated': { | ||
logger.info(`stripeEvent type: ${stripeEvent.type}`); | ||
const subscription = stripeEvent.data.object as Stripe.Subscription; | ||
|
||
const subscriber: SubscriptionInsert = { | ||
subscriptionId: subscription.id as string, | ||
stripeCustomerId: subscription.customer as string, | ||
subscriptionStatus: subscription.status, | ||
cancelAt: subscription.cancel_at, | ||
canceledAt: subscription.canceled_at, | ||
subscriptionEndDate: subscription.current_period_end, | ||
billingPeriodStartDate: subscription.current_period_start, | ||
subscriptionStartDate: subscription.start_date, | ||
cancelAtPeriodEnd: subscription.cancel_at_period_end, | ||
amount: subscription.items.data[0].plan.amount!.toString(), | ||
currency: subscription.items.data[0].plan.currency | ||
}; | ||
try { | ||
await upsertSubscriber(subscriber); | ||
} catch (err) { | ||
const _err = err as Error; | ||
logger.error(`Error updating subscriber: ${_err.stack}`); | ||
return error(502, `Error updating subscriber: ${_err}`); | ||
} | ||
logger.info( | ||
`Subscription updated: ${subscription.id} of customer: ${subscription.customer}` | ||
); | ||
break; | ||
} | ||
case 'checkout.session.completed': { | ||
logger.info(`stripeEvent type: ${stripeEvent.type}`); | ||
const session = stripeEvent.data.object as Stripe.Checkout.Session; | ||
|
||
const stripeCustomerId = session.customer as string; | ||
const dbCustomerId = session.client_reference_id as string; | ||
const subscriptionId = session.subscription as string; | ||
logger.info( | ||
`Customer Id: ${stripeCustomerId}, subscription id: ${subscriptionId}, db customer id: ${dbCustomerId}` | ||
); | ||
const subscriber: SubscriptionInsert = { | ||
userId: dbCustomerId, | ||
stripeCustomerId: stripeCustomerId, | ||
subscriptionId: subscriptionId | ||
}; | ||
try { | ||
await upsertSubscriber(subscriber); | ||
} catch (err) { | ||
const _err = err as Error; | ||
logger.error(`Error inserting subscriber: ${_err.stack}`); | ||
return error(502, `Error inserting subscriber: ${_err}`); | ||
} | ||
logger.info(`Checkout session completed: ${session.id}`); | ||
break; | ||
} | ||
default: | ||
logger.warn(`Unhandled stripeEvent type: ${stripeEvent.type}`); | ||
} | ||
|
||
// Step 4: Respond with success | ||
return json({ received: true }, { status: 200 }); | ||
} catch (err) { | ||
const _err = err as Error; | ||
logger.error(`Error verifying stripe webhook: ${_err.stack}`); | ||
return error(400, 'Webhook Error'); | ||
} | ||
}; | ||
// TODO: Stripe doesn't work in India, enable when it starts working | ||
// import { json, error, type RequestHandler } from '@sveltejs/kit'; | ||
// import Stripe from 'stripe'; | ||
// import { checkEnvParam } from '$lib/server/db'; | ||
// import { Logger } from '$lib/logger'; | ||
// import { updateSubscriber, upsertSubscriber } from '$lib/server/db/utils'; | ||
// import type { SubscriptionInsert } from '$lib/server/db/schema'; | ||
// import { isEnvProd } from '$lib/lib-utils'; | ||
// | ||
// function createErrorMsg(error: Error): string { | ||
// return isEnvProd() | ||
// ? `Error processing webhook, error message: ${error.message}` | ||
// : `Error processing webhook, error stack: ${error.stack}`; | ||
// } | ||
// | ||
// const logger = new Logger(); | ||
// logger.info('Loading stripe secrets'); | ||
// const STRIPE_SECRET_KEY = checkEnvParam('STRIPE_SECRET_KEY', true) as string; | ||
// const STRIPE_WEBHOOK_SECRET = checkEnvParam('STRIPE_WEBHOOK_SECRET', true) as string; | ||
// | ||
// const stripe = new Stripe(STRIPE_SECRET_KEY); | ||
// | ||
// export const POST: RequestHandler = async (event) => { | ||
// let stripeEvent: Stripe.Event; | ||
// // Step 1: Get the raw request body as a buffer | ||
// const request = event.request; | ||
// const payload = await request.text(); | ||
// const sig = request.headers.get('stripe-signature'); | ||
// try { | ||
// // Step 2: Verify the webhook signature to ensure it's from Stripe | ||
// if (!sig || !STRIPE_WEBHOOK_SECRET) { | ||
// throw new Error('Missing Stripe signature or webhook secret'); | ||
// } | ||
// | ||
// stripeEvent = stripe.webhooks.constructEvent(payload, sig, STRIPE_WEBHOOK_SECRET); | ||
// | ||
// // Step 3: Handle the Stripe event | ||
// switch (stripeEvent.type) { | ||
// case 'customer.subscription.deleted': { | ||
// logger.info(`stripeEvent type: ${stripeEvent.type}`); | ||
// const subscription = stripeEvent.data.object as Stripe.Subscription; | ||
// | ||
// const subscriptionId = subscription.id; | ||
// const stripeCustomerId = subscription.customer; | ||
// const subscriptionStatus = subscription.status; | ||
// | ||
// logger.info(`Subscription deleted: ${subscriptionId}`); | ||
// const subscriber: SubscriptionInsert = { | ||
// stripeCustomerId: stripeCustomerId as string, | ||
// subscriptionStatus: subscriptionStatus, | ||
// subscriptionId: subscriptionId | ||
// }; | ||
// try { | ||
// await updateSubscriber(stripeCustomerId as string, subscriber); | ||
// } catch (err) { | ||
// const _err = err as Error; | ||
// logger.error(`Error updating subscriber: ${_err.stack}`); | ||
// return error(502, createErrorMsg(_err)); | ||
// } | ||
// logger.info(`Subscription cancelled: ${subscriptionId} of customer: ${stripeCustomerId}`); | ||
// break; | ||
// } | ||
// case 'customer.subscription.updated': { | ||
// logger.info(`stripeEvent type: ${stripeEvent.type}`); | ||
// const subscription = stripeEvent.data.object as Stripe.Subscription; | ||
// | ||
// const subscriber: SubscriptionInsert = { | ||
// subscriptionId: subscription.id as string, | ||
// stripeCustomerId: subscription.customer as string, | ||
// subscriptionStatus: subscription.status, | ||
// cancelAt: subscription.cancel_at, | ||
// canceledAt: subscription.canceled_at, | ||
// subscriptionEndDate: subscription.current_period_end, | ||
// billingPeriodStartDate: subscription.current_period_start, | ||
// subscriptionStartDate: subscription.start_date, | ||
// cancelAtPeriodEnd: subscription.cancel_at_period_end, | ||
// amount: subscription.items.data[0].plan.amount!.toString(), | ||
// currency: subscription.items.data[0].plan.currency | ||
// }; | ||
// try { | ||
// await upsertSubscriber(subscriber); | ||
// } catch (err) { | ||
// const _err = err as Error; | ||
// logger.error(`Error updating subscriber: ${_err.stack}`); | ||
// return error(502, `Error updating subscriber: ${_err}`); | ||
// } | ||
// logger.info( | ||
// `Subscription updated: ${subscription.id} of customer: ${subscription.customer}` | ||
// ); | ||
// break; | ||
// } | ||
// case 'checkout.session.completed': { | ||
// logger.info(`stripeEvent type: ${stripeEvent.type}`); | ||
// const session = stripeEvent.data.object as Stripe.Checkout.Session; | ||
// | ||
// const stripeCustomerId = session.customer as string; | ||
// const dbCustomerId = session.client_reference_id as string; | ||
// const subscriptionId = session.subscription as string; | ||
// logger.info( | ||
// `Customer Id: ${stripeCustomerId}, subscription id: ${subscriptionId}, db customer id: ${dbCustomerId}` | ||
// ); | ||
// const subscriber: SubscriptionInsert = { | ||
// userId: dbCustomerId, | ||
// stripeCustomerId: stripeCustomerId, | ||
// subscriptionId: subscriptionId | ||
// }; | ||
// try { | ||
// await upsertSubscriber(subscriber); | ||
// } catch (err) { | ||
// const _err = err as Error; | ||
// logger.error(`Error inserting subscriber: ${_err.stack}`); | ||
// return error(502, `Error inserting subscriber: ${_err}`); | ||
// } | ||
// logger.info(`Checkout session completed: ${session.id}`); | ||
// break; | ||
// } | ||
// default: | ||
// logger.warn(`Unhandled stripeEvent type: ${stripeEvent.type}`); | ||
// } | ||
// | ||
// // Step 4: Respond with success | ||
// return json({ received: true }, { status: 200 }); | ||
// } catch (err) { | ||
// const _err = err as Error; | ||
// logger.error(`Error verifying stripe webhook: ${_err.stack}`); | ||
// return error(400, 'Webhook Error'); | ||
// } | ||
// }; |