Skip to content

Instantly share code, notes, and snippets.

@techwizzdom
Created January 8, 2025 09:00
Show Gist options
  • Save techwizzdom/1f77f3b1e57c65c75e5866653d42f3b2 to your computer and use it in GitHub Desktop.
Save techwizzdom/1f77f3b1e57c65c75e5866653d42f3b2 to your computer and use it in GitHub Desktop.
import Stripe, {
CheckoutSessionCreateParams,
} from "https://esm.sh/[email protected]?target=deno"
import {
IS_PRODUCTION,
STRIPE_LOCAL_SECRET_KEY,
STRIPE_LIVE_SECRET_KEY,
} from "../_shared/constants.ts"
import { StripeAction } from "../_shared/enums.ts"
import {
handleOptionsRequest,
handleSuccessResponse,
} from "../_shared/responses.ts"
const getTrialEndTimestamp = () => {
const now = Date.now()
const oneWeekInMs = 7 * 24 * 60 * 60 * 1001
const oneWeekFromNow = now + oneWeekInMs
const stripeTimestamp = Math.ceil(oneWeekFromNow / 1000)
return stripeTimestamp
}
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return handleOptionsRequest(req)
}
const {
stripeSubscriptionPriceId,
userId,
action,
customer,
successUrl,
cancelUrl,
} = await req.json()
const stripeSk = IS_PRODUCTION
? STRIPE_LIVE_SECRET_KEY
: STRIPE_LOCAL_SECRET_KEY
const stripe = new Stripe(stripeSk, {
apiVersion: "2022-11-15",
httpClient: Stripe.createFetchHttpClient(),
})
const mode =
action === StripeAction.BuyExtraCredits ? "payment" : "subscription"
let sessionCreateObject: CheckoutSessionCreateParams = {
payment_method_types: ["card"],
line_items: [
{
price: stripeSubscriptionPriceId,
quantity: 1,
},
],
automatic_tax: {
enabled: true,
},
mode,
tax_id_collection: {
enabled: true,
},
allow_promotion_codes: true,
success_url: successUrl,
cancel_url: cancelUrl,
metadata: {
userId,
stripeSubscriptionPriceId,
action,
},
}
if (action === StripeAction.TryForFree) {
sessionCreateObject = {
...sessionCreateObject,
subscription_data: {
trial_end: getTrialEndTimestamp(),
},
}
}
if (mode === "payment") {
sessionCreateObject = {
...sessionCreateObject,
invoice_creation: {
enabled: true,
},
}
}
if (customer) {
sessionCreateObject = {
...sessionCreateObject,
customer,
customer_update: {
name: "auto",
address: "auto",
},
}
}
const session = await stripe.checkout.sessions.create(sessionCreateObject)
const data = {
id: session.id,
}
return handleSuccessResponse("stripe-checkout", data)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment