|
| 1 | +import { env } from '@/env.mjs'; |
| 2 | +import Stripe from 'stripe'; |
| 3 | + |
| 4 | +// Initialize Stripe client with secret key from environment |
| 5 | +const stripeSecretKey = env.STRIPE_SECRET_KEY; |
| 6 | + |
| 7 | +if (!stripeSecretKey) { |
| 8 | + console.warn('STRIPE_SECRET_KEY is not set - Stripe auto-approval will be disabled'); |
| 9 | +} |
| 10 | + |
| 11 | +export const stripe = stripeSecretKey |
| 12 | + ? new Stripe(stripeSecretKey, { |
| 13 | + apiVersion: '2025-11-17.clover', |
| 14 | + }) |
| 15 | + : null; |
| 16 | + |
| 17 | +/** |
| 18 | + * Extract domain from a website URL or email |
| 19 | + * @param input - URL (e.g., "https://example.com") or email (e.g., "user@example.com") |
| 20 | + * @returns Normalized domain (e.g., "example.com") |
| 21 | + */ |
| 22 | +export const extractDomain = (input: string): string | null => { |
| 23 | + if (!input) return null; |
| 24 | + |
| 25 | + try { |
| 26 | + // If it looks like an email, extract domain from after @ |
| 27 | + if (input.includes('@') && !input.includes('://')) { |
| 28 | + const domain = input.split('@')[1]?.toLowerCase().trim(); |
| 29 | + return domain || null; |
| 30 | + } |
| 31 | + |
| 32 | + // Otherwise, treat as URL |
| 33 | + let url = input.trim().toLowerCase(); |
| 34 | + |
| 35 | + // Add protocol if missing |
| 36 | + if (!url.startsWith('http://') && !url.startsWith('https://')) { |
| 37 | + url = `https://${url}`; |
| 38 | + } |
| 39 | + |
| 40 | + const parsed = new URL(url); |
| 41 | + return parsed.hostname.replace(/^www\./, ''); |
| 42 | + } catch { |
| 43 | + return null; |
| 44 | + } |
| 45 | +}; |
| 46 | + |
| 47 | +/** |
| 48 | + * Check if a domain belongs to an existing Stripe customer |
| 49 | + * Searches by customer email domain and metadata |
| 50 | + * |
| 51 | + * @param domain - The domain to check (e.g., "acme.com") |
| 52 | + * @returns Customer ID if found, null otherwise |
| 53 | + */ |
| 54 | +export const findStripeCustomerByDomain = async ( |
| 55 | + domain: string, |
| 56 | +): Promise<{ customerId: string; customerName: string | null } | null> => { |
| 57 | + if (!stripe) { |
| 58 | + console.warn('Stripe client not initialized - skipping customer lookup'); |
| 59 | + return null; |
| 60 | + } |
| 61 | + |
| 62 | + if (!domain) { |
| 63 | + return null; |
| 64 | + } |
| 65 | + |
| 66 | + const normalizedDomain = domain.toLowerCase().trim(); |
| 67 | + |
| 68 | + try { |
| 69 | + // Search for customers with emails matching this domain |
| 70 | + // Stripe's search supports email domain matching |
| 71 | + const customers = await stripe.customers.search({ |
| 72 | + query: `email~"@${normalizedDomain}"`, |
| 73 | + limit: 1, |
| 74 | + }); |
| 75 | + |
| 76 | + if (customers.data.length > 0) { |
| 77 | + const customer = customers.data[0]; |
| 78 | + return { |
| 79 | + customerId: customer.id, |
| 80 | + customerName: customer.name ?? null, |
| 81 | + }; |
| 82 | + } |
| 83 | + |
| 84 | + // Fallback: Check customers with domain in metadata |
| 85 | + // This handles cases where customer email might not match company domain |
| 86 | + const customersWithMetadata = await stripe.customers.search({ |
| 87 | + query: `metadata["domain"]:"${normalizedDomain}"`, |
| 88 | + limit: 1, |
| 89 | + }); |
| 90 | + |
| 91 | + if (customersWithMetadata.data.length > 0) { |
| 92 | + const customer = customersWithMetadata.data[0]; |
| 93 | + return { |
| 94 | + customerId: customer.id, |
| 95 | + customerName: customer.name ?? null, |
| 96 | + }; |
| 97 | + } |
| 98 | + |
| 99 | + return null; |
| 100 | + } catch (error) { |
| 101 | + console.error('Error searching Stripe customers:', error); |
| 102 | + return null; |
| 103 | + } |
| 104 | +}; |
| 105 | + |
| 106 | +/** |
| 107 | + * Check if a domain is an active Stripe customer with a valid subscription |
| 108 | + * |
| 109 | + * @param domain - The domain to check |
| 110 | + * @returns true if domain has an active subscription |
| 111 | + */ |
| 112 | +export const isDomainActiveStripeCustomer = async (domain: string): Promise<boolean> => { |
| 113 | + const customer = await findStripeCustomerByDomain(domain); |
| 114 | + |
| 115 | + if (!customer) { |
| 116 | + return false; |
| 117 | + } |
| 118 | + |
| 119 | + if (!stripe) { |
| 120 | + return false; |
| 121 | + } |
| 122 | + |
| 123 | + try { |
| 124 | + // Check if customer has an active subscription |
| 125 | + const subscriptions = await stripe.subscriptions.list({ |
| 126 | + customer: customer.customerId, |
| 127 | + status: 'active', |
| 128 | + limit: 1, |
| 129 | + }); |
| 130 | + |
| 131 | + return subscriptions.data.length > 0; |
| 132 | + } catch (error) { |
| 133 | + console.error('Error checking Stripe subscriptions:', error); |
| 134 | + return false; |
| 135 | + } |
| 136 | +}; |
0 commit comments