|
1 | 1 | import "server-only"; |
2 | 2 |
|
| 3 | +import { headers } from "next/headers"; |
3 | 4 | import Stripe from "stripe"; |
4 | 5 | import type { Team } from "@/api/team/get-team"; |
5 | | -import { STRIPE_SECRET_KEY } from "@/constants/server-envs"; |
| 6 | +import { |
| 7 | + GROWTH_PLAN_SKU, |
| 8 | + PAYMENT_METHOD_CONFIGURATION, |
| 9 | + STRIPE_SECRET_KEY, |
| 10 | +} from "@/constants/server-envs"; |
6 | 11 |
|
7 | 12 | let existingStripe: Stripe | undefined; |
8 | 13 |
|
@@ -72,3 +77,59 @@ export async function getStripeBalance(customerId: string) { |
72 | 77 | // Stripe returns a positive balance for credits, so we need to divide by -100 to get the actual balance (as long as the balance is not 0) |
73 | 78 | return customer.balance === 0 ? 0 : customer.balance / -100; |
74 | 79 | } |
| 80 | + |
| 81 | +export async function fetchClientSecret(team: Team) { |
| 82 | + "use server"; |
| 83 | + const origin = (await headers()).get("origin"); |
| 84 | + const stripe = getStripe(); |
| 85 | + const customerId = team.stripeCustomerId; |
| 86 | + |
| 87 | + if (!customerId) { |
| 88 | + throw new Error("No customer ID found"); |
| 89 | + } |
| 90 | + |
| 91 | + // Create Checkout Sessions from body params. |
| 92 | + const session = await stripe.checkout.sessions.create({ |
| 93 | + ui_mode: "embedded", |
| 94 | + line_items: [ |
| 95 | + { |
| 96 | + // Provide the exact Price ID (for example, price_1234) of |
| 97 | + // the product you want to sell |
| 98 | + price: GROWTH_PLAN_SKU, |
| 99 | + quantity: 1, |
| 100 | + }, |
| 101 | + ], |
| 102 | + mode: "subscription", |
| 103 | + |
| 104 | + return_url: `${origin}/get-started/team/${team.slug}/select-plan?session_id={CHECKOUT_SESSION_ID}`, |
| 105 | + automatic_tax: { enabled: true }, |
| 106 | + allow_promotion_codes: true, |
| 107 | + customer: customerId, |
| 108 | + customer_update: { |
| 109 | + address: "auto", |
| 110 | + }, |
| 111 | + payment_method_collection: "always", |
| 112 | + payment_method_configuration: PAYMENT_METHOD_CONFIGURATION, |
| 113 | + subscription_data: { |
| 114 | + trial_period_days: 14, |
| 115 | + trial_settings: { |
| 116 | + end_behavior: { |
| 117 | + missing_payment_method: "cancel", |
| 118 | + }, |
| 119 | + }, |
| 120 | + }, |
| 121 | + }); |
| 122 | + |
| 123 | + if (!session.client_secret) { |
| 124 | + throw new Error("No client secret found"); |
| 125 | + } |
| 126 | + |
| 127 | + return session.client_secret; |
| 128 | +} |
| 129 | + |
| 130 | +export async function getStripeSessionById(sessionId: string) { |
| 131 | + const session = await getStripe().checkout.sessions.retrieve(sessionId, { |
| 132 | + expand: ["line_items", "payment_intent"], |
| 133 | + }); |
| 134 | + return session; |
| 135 | +} |
0 commit comments