create subscribe when wehbook
This commit is contained in:
parent
147cacb1e4
commit
1a0095f571
@ -3,7 +3,6 @@ import { createServerClient } from '@supabase/ssr'
|
||||
import { cookies } from 'next/headers'
|
||||
import { createOrGetStripeCustomer, createSubscriptionSession } from '@/lib/stripe'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { SubscriptionService } from '@/lib/subscription-service'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@ -71,13 +70,7 @@ export async function POST(request: NextRequest) {
|
||||
data: { stripeCustomerId: customer.id }
|
||||
})
|
||||
|
||||
// 创建初始的订阅记录(待激活状态)
|
||||
await SubscriptionService.createPendingSubscription(
|
||||
user.id,
|
||||
plan.id,
|
||||
undefined, // Stripe 订阅 ID 将在 webhook 中设置
|
||||
customer.id
|
||||
)
|
||||
// 订阅记录将在 customer.subscription.created webhook 中创建
|
||||
|
||||
return NextResponse.json({ sessionId: session.id, url: session.url })
|
||||
|
||||
|
@ -32,6 +32,9 @@ export async function POST(request: NextRequest) {
|
||||
break
|
||||
|
||||
case 'customer.subscription.created':
|
||||
await handleSubscriptionCreated(event.data.object as unknown as Record<string, unknown>)
|
||||
break
|
||||
|
||||
case 'customer.subscription.updated':
|
||||
await handleSubscriptionUpdate(event.data.object as unknown as Record<string, unknown>)
|
||||
break
|
||||
@ -89,6 +92,62 @@ async function handleCheckoutSessionCompleted(session: Record<string, unknown>)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubscriptionCreated(subscription: Record<string, unknown>) {
|
||||
try {
|
||||
console.log('🆕 Processing subscription created')
|
||||
const customerId = subscription.customer as string
|
||||
const status = subscription.status as string
|
||||
const stripeSubscriptionId = subscription.id as string
|
||||
const items = subscription.items as { data: Array<{ price: { id: string } }> }
|
||||
const priceId = items?.data[0]?.price?.id
|
||||
const currentPeriodStart = subscription.current_period_start as number
|
||||
const currentPeriodEnd = subscription.current_period_end as number
|
||||
|
||||
console.log(`📊 New subscription details:`, {
|
||||
customerId,
|
||||
status,
|
||||
stripeSubscriptionId,
|
||||
priceId
|
||||
})
|
||||
|
||||
// 查找用户
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { stripeCustomerId: customerId }
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
console.error('❌ User not found for customer:', customerId)
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`👤 Found user: ${user.id}`)
|
||||
|
||||
if (status === 'active' || status === 'trialing') {
|
||||
// 根据 Stripe 价格 ID 获取套餐 ID
|
||||
const planId = await SubscriptionService.getPlanIdByStripePriceId(priceId)
|
||||
|
||||
// 创建新的订阅记录
|
||||
const newSubscription = await SubscriptionService.createRenewalSubscription(
|
||||
user.id,
|
||||
planId,
|
||||
stripeSubscriptionId,
|
||||
new Date(currentPeriodStart * 1000),
|
||||
new Date(currentPeriodEnd * 1000),
|
||||
customerId,
|
||||
subscription
|
||||
)
|
||||
|
||||
console.log(`✅ Created new subscription ${newSubscription.id} for user ${user.id}`)
|
||||
|
||||
// 更新用户的默认订阅套餐(保持向后兼容)
|
||||
await SubscriptionService.updateUserSubscriptionPlan(user.id, planId)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error handling subscription created:', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubscriptionUpdate(subscription: Record<string, unknown>) {
|
||||
try {
|
||||
console.log('🔄 Processing subscription update')
|
||||
@ -123,22 +182,18 @@ async function handleSubscriptionUpdate(subscription: Record<string, unknown>) {
|
||||
// 根据 Stripe 价格 ID 获取套餐 ID
|
||||
const planId = await SubscriptionService.getPlanIdByStripePriceId(priceId)
|
||||
|
||||
// 检查是否已有待激活的订阅记录(通过用户 ID 查找)
|
||||
// 查找现有的订阅记录(通过 Stripe 订阅 ID)
|
||||
const existingSubscription = await prisma.subscription.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
status: 'pending',
|
||||
subscriptionPlanId: planId
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
stripeSubscriptionId,
|
||||
}
|
||||
})
|
||||
|
||||
if (existingSubscription) {
|
||||
// 激活现有的订阅记录,并设置 Stripe 订阅 ID
|
||||
// 更新现有的订阅记录
|
||||
await prisma.subscription.update({
|
||||
where: { id: existingSubscription.id },
|
||||
data: {
|
||||
stripeSubscriptionId,
|
||||
isActive: true,
|
||||
status: 'active',
|
||||
startDate: new Date(currentPeriodStart * 1000),
|
||||
@ -147,36 +202,12 @@ async function handleSubscriptionUpdate(subscription: Record<string, unknown>) {
|
||||
updatedAt: new Date()
|
||||
}
|
||||
})
|
||||
console.log(`✅ Activated existing subscription ${existingSubscription.id} for user ${user.id}`)
|
||||
} else {
|
||||
// 检查是否是续订(已有活跃订阅)
|
||||
const activeSubscription = await SubscriptionService.getUserActiveSubscription(user.id)
|
||||
console.log(`✅ Updated existing subscription ${existingSubscription.id} for user ${user.id}`)
|
||||
|
||||
if (activeSubscription) {
|
||||
// 这是续订,创建新的订阅记录
|
||||
await SubscriptionService.createRenewalSubscription(
|
||||
user.id,
|
||||
planId,
|
||||
stripeSubscriptionId,
|
||||
new Date(currentPeriodStart * 1000),
|
||||
new Date(currentPeriodEnd * 1000),
|
||||
customerId,
|
||||
subscription
|
||||
)
|
||||
console.log(`Created renewal subscription for user ${user.id}`)
|
||||
} else {
|
||||
// 直接创建并激活订阅(可能是通过其他方式创建的订阅)
|
||||
await SubscriptionService.createRenewalSubscription(
|
||||
user.id,
|
||||
planId,
|
||||
stripeSubscriptionId,
|
||||
new Date(currentPeriodStart * 1000),
|
||||
new Date(currentPeriodEnd * 1000),
|
||||
customerId,
|
||||
subscription
|
||||
)
|
||||
console.log(`Created new subscription for user ${user.id}`)
|
||||
}
|
||||
// 更新用户的默认订阅套餐(保持向后兼容)
|
||||
await SubscriptionService.updateUserSubscriptionPlan(user.id, planId)
|
||||
} else {
|
||||
console.log(`⚠️ No existing subscription found for Stripe subscription ${stripeSubscriptionId}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user