xiaohongshu
xiaohongshu
Complete guide for integrating Stripe payments (subscriptions or one-time) with Convex + Next.js. Includes user interviews, API setup, webhook configuration, testing phases, and production deployment. Use this skill when Adding payment functionality to a Convex + Next.js app
Full skill instructions
This skill guides you through integrating Stripe payments into a Convex + Next.js application. It covers both subscription and one-time payment flows, with hosted Stripe checkout for simplicity and reliability.
Use this skill when:
Before starting implementation, gather these requirements from the user:
Payment Type:
Backend Confirmation:
Checkout Preference:
Pricing Details:
Product Information:
Strongly recommend: Hosted Stripe Checkout for subscriptions
npm install stripe
Note: For hosted checkout, you only need the server-side stripe package. No need for @stripe/stripe-js or @stripe/react-stripe-js.
Add Stripe-related fields to your users table in convex/schema.ts:
users: defineTable({
// ... existing fields
membershipStatus: v.optional(v.union(
v.literal("free"),
v.literal("premium"), // or your membership tier name
v.literal("past_due") // For failed payments
)),
membershipExpiry: v.optional(v.number()), // Timestamp when membership expires
stripeCustomerId: v.optional(v.string()), // Stripe customer ID
stripeSubscriptionId: v.optional(v.string()), // Stripe subscription ID (for subscriptions)
})
.index("by_stripe_customer", ["stripeCustomerId"])
.index("by_stripe_subscription", ["stripeSubscriptionId"])
pk_test_...)sk_test_...)price_...)In Convex Dashboard (Settings → Environment Variables):
STRIPE_SECRET_KEY=sk_test_your_secret_key_here
STRIPE_PRICE_ID=price_your_price_id_here
STRIPE_WEBHOOK_SECRET=(we'll get this in Phase 4)
In .env.local (for Next.js frontend):
NEXT_PUBLIC_SITE_URL=http://localhost:3000
convex/stripe.ts)"use node";
import Stripe from "stripe";
import { action } from "./_generated/server";
import { v } from "convex/values";
import { internal } from "./_generated/api";
/**
* Create a Stripe Checkout Session
*/
export const createCheckoutSession = action({
args: {
clerkUserId: v.string(), // Or your auth user ID
mode: v.optional(v.union(v.literal("subscription"), v.literal("payment"))),
},
handler: async (ctx, args): Promise<{ url: string | null; sessionId: string }> => {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2025-08-27.basil" as any,
});
// Get user from database
const user: any = await ctx.runQuery(internal.stripeDb.getUserByClerkId, {
clerkId: args.clerkUserId,
});
if (!user) {
throw new Error("User not found");
}
// Create or retrieve Stripe customer
let customerId: string | undefined = user.stripeCustomerId;
if (!customerId) {
const customer = await stripe.customers.create({
email: user.email,
name: user.name,
metadata: {
clerkUserId: args.clerkUserId,
convexUserId: user._id,
},
});
customerId = customer.id;
// Update user with Stripe customer ID
await ctx.runMutation(internal.stripeDb.updateStripeCustomerId, {
userId: user._id,
stripeCustomerId: customerId,
});
}
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000";
const mode = args.mode || "subscription";
// Create checkout session
const session: Stripe.Checkout.Session = await stripe.checkout.sessions.create({
customer: customerId,
mode: mode, // "subscription" or "payment"
line_items: [
{
price: process.env.STRIPE_PRICE_ID!,
quantity: 1,
},
],
success_url: `${siteUrl}/checkout/return?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${siteUrl}`,
metadata: {
clerkUserId: args.clerkUserId,
userId: user._id,
},
});
return {
url: session.url,
sessionId: session.id,
};
},
});
/**
* Get checkout session status (for return page)
*/
export const getCheckoutSessionStatus = action({
args: {
sessionId: v.string(),
},
handler: async (ctx, args) => {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2025-08-27.basil" as any,
});
const session = await stripe.checkout.sessions.retrieve(args.sessionId);
return {
status: session.status,
customerEmail: session.customer_details?.email,
paymentStatus: session.payment_status,
};
},
});
/**
* Create Customer Portal Session
* Essential for letting users manage their subscriptions, payment methods, and invoices
*/
export const createCustomerPortalSession = action({
args: {
clerkUserId: v.string(),
},
handler: async (ctx, args): Promise<{ url: string }> => {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2025-08-27.basil" as any,
});
// Get user from database
const user: any = await ctx.runQuery(internal.stripeDb.getUserByClerkId, {
clerkId: args.clerkUserId,
});
if (!user || !user.stripeCustomerId) {
throw new Error("User not found or has no Stripe customer ID");
}
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000";
// Create portal session
const session = await stripe.billingPortal.sessions.create({
customer: user.stripeCustomerId,
return_url: `${siteUrl}/dashboard`,
});
return {
url: session.url,
};
},
});
convex/stripeDb.ts)import { internalMutation, internalQuery } from "./_generated/server";
import { v } from "convex/values";
/**
* Internal query to get user by Clerk ID
*/
export const getUserByClerkId = internalQuery({
args: {
clerkId: v.string(),
},
handler: async (ctx, args) => {
const user = await ctx.db
.query("users")
.withIndex("by_clerk_id", (q) => q.eq("clerkId", args.clerkId))
.unique();
return user;
},
});
/**
* Internal mutation to update user's Stripe customer ID
*/
export const updateStripeCustomerId = internalMutation({
args: {
userId: v.id("users"),
stripeCustomerId: v.string(),
},
handler: async (ctx, args) => {
await ctx.db.patch(args.userId, {
stripeCustomerId: args.stripeCustomerId,
});
},
});
/**
* Internal mutation to update user's membership status after successful payment
*/
export const updateMembershipStatus = internalMutation({
args: {
clerkUserId: v.string(),
stripeSubscriptionId: v.string(), // For subscriptions
currentPeriodEnd: v.number(), // Timestamp when current period ends
},
handler: async (ctx, args) => {
const user = await ctx.db
.query("users")
.withIndex("by_clerk_id", (q) => q.eq("clerkId", args.clerkUserId))
.unique();
if (!user) {
throw new Error("User not found");
}
await ctx.db.patch(user._id, {
membershipStatus: "premium",
membershipExpiry: args.currentPeriodEnd * 1000, // Convert to milliseconds
stripeSubscriptionId: args.stripeSubscriptionId,
});
return user._id;
},
});
/**
* Internal mutation to cancel user's membership
*/
export const cancelMembership = internalMutation({
args: {
stripeSubscriptionId: v.string(),
},
handler: async (ctx, args) => {
const user = await ctx.db
.query("users")
.withIndex("by_stripe_subscription", (q) =>
q.eq("stripeSubscriptionId", args.stripeSubscriptionId)
)
.unique();
if (!user) {
console.error("User not found for subscription:", args.stripeSubscriptionId);
return null;
}
await ctx.db.patch(user._id, {
membershipStatus: "free",
membershipExpiry: undefined,
stripeSubscriptionId: undefined,
});
return user._id;
},
});
/**
* Internal mutation to handle payment failure
*/
export const handlePaymentFailure = internalMutation({
args: {
stripeSubscriptionId: v.string(),
attemptCount: v.number(),
},
handler: async (ctx, args) => {
const user = await ctx.db
.query("users")
.withIndex("by_stripe_subscription", (q) =>
q.eq("stripeSubscriptionId", args.stripeSubscriptionId)
)
.unique();
if (!user) {
console.error("User not found for subscription:", args.stripeSubscriptionId);
return null;
}
// You can implement grace period logic here
// For example, keep access for 3 failed attempts
if (args.attemptCount >= 3) {
await ctx.db.patch(user._id, {
membershipStatus: "past_due",
});
}
return user._id;
},
});
convex/http.ts)⚠️ CRITICAL: Use .convex.site domain for webhooks, NOT .convex.cloud
import { httpRouter } from "convex/server";
import { httpAction } from "./_generated/server";
const http = httpRouter();
// Stripe webhook handler
http.route({
path: "/stripe/webhook",
method: "POST",
handler: httpAction(async (ctx, request: Request) => {
const Stripe = (await import("stripe")).default;
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2025-08-27.basil" as any,
});
const body = await request.text();
const sig = request.headers.get("stripe-signature");
if (!sig) {
return new Response(JSON.stringify({ error: "No signature" }), {
status: 400,
});
}
try {
// ⚠️ CRITICAL: Use constructEventAsync (NOT constructEvent)
const event = await stripe.webhooks.constructEventAsync(
body,
sig,
process.env.STRIPE_WEBHOOK_SECRET!
);
// Handle the event
switch (event.type) {
case "checkout.session.completed": {
const session = event.data.object as any;
const clerkUserId = session.metadata?.clerkUserId;
// Handle subscription checkout
if (session.mode === "subscription") {
const subscriptionId = session.subscription as string;
if (!clerkUserId || !subscriptionId) {
console.error("Missing clerkUserId or subscriptionId");
break;
}
// ⚠️ CRITICAL: current_period_end is in subscription.items.data[0]
const subscription: any = await stripe.subscriptions.retrieve(subscriptionId);
const currentPeriodEnd = subscription.items?.data?.[0]?.current_period_end;
if (!currentPeriodEnd) {
console.error("No current_period_end found");
break;
}
// Update user membership
const { internal } = await import("./_generated/api.js");
await ctx.runMutation(internal.stripeDb.updateMembershipStatus, {
clerkUserId,
stripeSubscriptionId: subscriptionId,
currentPeriodEnd,
});
console.log(`✅ Membership activated for user: ${clerkUserId}`);
}
// Handle one-time payment checkout
if (session.mode === "payment") {
// For one-time payments, you might want different logic
console.log(`✅ One-time payment completed for user: ${clerkUserId}`);
}
break;
}
case "customer.subscription.updated": {
// Handle subscription renewal/update
const subscription = event.data.object as any;
const clerkUserId = subscription.metadata?.clerkUserId;
if (!clerkUserId) {
console.error("Missing clerkUserId in subscription metadata");
break;
}
const currentPeriodEnd = subscription.items?.data?.[0]?.current_period_end;
if (!currentPeriodEnd) {
console.error("No current_period_end found");
break;
}
// Update membership expiry (handles renewals)
const { internal } = await import("./_generated/api.js");
await ctx.runMutation(internal.stripeDb.updateMembershipStatus, {
clerkUserId,
stripeSubscriptionId: subscription.id,
currentPeriodEnd,
});
console.log(`✅ Subscription updated for user: ${clerkUserId}`);
break;
}
case "customer.subscription.deleted": {
// Handle subscription cancellation
const subscription = event.data.object as any;
const { internal } = await import("./_generated/api.js");
await ctx.runMutation(internal.stripeDb.cancelMembership, {
stripeSubscriptionId: subscription.id,
});
console.log(`✅ Subscription canceled: ${subscription.id}`);
break;
}
case "invoice.payment_failed": {
// Handle failed payment
const invoice = event.data.object as any;
const subscriptionId = invoice.subscription;
if (!subscriptionId) {
console.error("No subscription ID in failed invoice");
break;
}
const attemptCount = invoice.attempt_count || 0;
const { internal } = await import("./_generated/api.js");
await ctx.runMutation(internal.stripeDb.handlePaymentFailure, {
stripeSubscriptionId: subscriptionId,
attemptCount,
});
console.log(`⚠️ Payment failed for subscription: ${subscriptionId}, attempt: ${attemptCount}`);
break;
}
case "invoice.paid": {
// Confirm successful payment (handles renewals)
const invoice = event.data.object as any;
const subscriptionId = invoice.subscription;
if (!subscriptionId) {
break; // One-time invoice, not subscription
}
const subscription: any = await stripe.subscriptions.retrieve(subscriptionId);
const clerkUserId = subscription.metadata?.clerkUserId;
const currentPeriodEnd = subscription.items?.data?.[0]?.current_period_end;
if (!clerkUserId || !currentPeriodEnd) {
console.error("Missing data for invoice.paid event");
break;
}
const { internal } = await import("./_generated/api.js");
await ctx.runMutation(internal.stripeDb.updateMembershipStatus, {
clerkUserId,
stripeSubscriptionId: subscriptionId,
currentPeriodEnd,
});
console.log(`✅ Invoice paid for user: ${clerkUserId}`);
break;
}
}
return new Response(JSON.stringify({ received: true }), {
status: 200,
});
} catch (err) {
console.error("Webhook error:", err);
return new Response(
JSON.stringify({ error: err instanceof Error ? err.message : "Webhook error" }),
{ status: 400 }
);
}
}),
});
export default http;
On your frontend, create a button that calls the createCheckoutSession action:
"use client";
import { useAction } from "convex/react";
import { api } from "@/convex/_generated/api";
import { useUser } from "@clerk/nextjs";
import { useState } from "react";
export function UpgradeButton() {
const { user } = useUser();
const createCheckoutSession = useAction(api.stripe.createCheckoutSession);
const [loading, setLoading] = useState(false);
const handleUpgrade = async () => {
if (!user) return;
setLoading(true);
try {
const result = await createCheckoutSession({
clerkUserId: user.id,
mode: "subscription", // or "payment" for one-time
});
if (result.url) {
window.open(result.url, "_blank");
}
} catch (error) {
console.error("Error creating checkout session:", error);
} finally {
setLoading(false);
}
};
return (
<button onClick={handleUpgrade} disabled={loading}>
{loading ? "Loading..." : "Upgrade to Premium"}
</button>
);
}
Allow users to manage their subscription, payment methods, and billing:
"use client";
import { useAction } from "convex/react";
import { api } from "@/convex/_generated/api";
import { useUser } from "@clerk/nextjs";
import { useState } from "react";
export function ManageBillingButton() {
const { user } = useUser();
const createPortalSession = useAction(api.stripe.createCustomerPortalSession);
const [loading, setLoading] = useState(false);
const handleManageBilling = async () => {
if (!user) return;
setLoading(true);
try {
const result = await createPortalSession({
clerkUserId: user.id,
});
if (result.url) {
window.open(result.url, "_blank");
}
} catch (error) {
console.error("Error creating portal session:", error);
} finally {
setLoading(false);
}
};
return (
<button onClick={handleManageBilling} disabled={loading}>
{loading ? "Loading..." : "Manage Billing"}
</button>
);
}
app/checkout/return/page.tsx)See resources/return-page-example.tsx for full implementation with success/error states.
⚠️ CRITICAL: Use the .convex.site domain
https://your-deployment.convex.site/stripe/webhook
.convex.cloud.convex.sitehttps://your-deployment.convex.site/stripe/webhookcheckout.session.completed (required - initial payment)customer.subscription.updated (required - renewals & updates)customer.subscription.deleted (required - cancellations)invoice.payment_failed (required - failed payments)invoice.paid (recommended - successful renewals)whsec_...)STRIPE_WEBHOOK_SECRET=whsec_...# Install Stripe CLI
brew install stripe/stripe-cli/stripe
# Login
stripe login
# Forward webhooks to your Convex endpoint
stripe listen --forward-to https://your-deployment.convex.site/stripe/webhook
npm run dev4242 4242 4242 4242Issue: Webhook not receiving events
.convex.site not .convex.cloudIssue: SubtleCryptoProvider cannot be used in a synchronous context
constructEventAsync not constructEventIssue: Membership status not updating
current_period_end is accessed from subscription.items.data[0]clerkUserId is in checkout session metadataThe Customer Portal is essential for any SaaS product. It allows users to self-manage their subscriptions without contacting support.
With the Customer Portal, your customers can:
This means less support work for you! Most billing questions can be self-served.
Where to place the Portal button:
When to show the Portal button:
stripeCustomerId (i.e., users who have subscribed)Example conditional rendering:
{user.stripeCustomerId && <ManageBillingButton />}
~9-15% of subscription payments fail initially, but most are recoverable. Proper handling is critical for revenue.
Smart Retries use AI to determine the best time to retry failed payments.
In Stripe Dashboard:
Your app should respond to payment failures:
// Already implemented in convex/stripeDb.ts!
export const handlePaymentFailure = internalMutation({
args: {
stripeSubscriptionId: v.string(),
attemptCount: v.number(),
},
handler: async (ctx, args) => {
// Grace period logic: keep access for 3 attempts
if (args.attemptCount >= 3) {
await ctx.db.patch(user._id, {
membershipStatus: "past_due",
});
}
},
});
User Experience Recommendations:
Why this matters: Automated emails recover 5-10% of failed payments without any manual work.
In your Dashboard:
Set up alerts:
Thorough testing prevents production issues and lost revenue.
Install Stripe CLI:
# macOS
brew install stripe/stripe-cli/stripe
# Windows (with Scoop)
scoop install stripe
# Or download from https://stripe.com/docs/stripe-cli
Forward webhooks to Convex:
# Login first
stripe login
# Forward webhooks to your Convex deployment
stripe listen --forward-to https://your-deployment.convex.site/stripe/webhook
# You'll see a webhook signing secret - add this to Convex env vars temporarily for testing
Test specific events:
# Test successful subscription creation
stripe trigger checkout.session.completed
# Test subscription renewal
stripe trigger customer.subscription.updated
# Test failed payment
stripe trigger invoice.payment_failed
# Test cancellation
stripe trigger customer.subscription.deleted
Use these test card numbers in test mode only:
| Card Number | Scenario | Use Case |
|---|---|---|
4242 4242 4242 4242 | Succeeds | Normal successful payment |
4000 0025 0000 3155 | Requires authentication | Test 3D Secure flow |
4000 0000 0000 9995 | Always declines | Test payment failure handling |
4000 0000 0000 0341 | Attaching requires auth | Test payment method updates |
4000 0082 6000 0000 | Expires in current year | Test expiring card emails |
Expiry & CVC: Any future date and any 3-digit CVC work for test cards.
Test all critical flows:
Initial Subscription Flow:
4242... successfully creates subscriptionmembershipStatus updates to "premium" in ConvexmembershipExpiry is set correctly (1 month from now for monthly)checkout.session.completed received and processedCustomer Portal Flow:
customer.subscription.deleted webhookmembershipStatus updates to "free" after cancellationPayment Failure Flow:
4000 0000 0000 9995 to trigger failureinvoice.payment_failed webhook receivedhandlePaymentFailure mutation runs correctlyRenewal Flow:
customer.subscription.updated or invoice.paid webhook firesmembershipExpiry extends by another monthTest Clocks let you simulate subscription renewals without waiting weeks/months.
Create Test Clock:
With Test Clocks you can test:
In Stripe Dashboard:
Debug failed webhooks:
STRIPE_SECRET_KEY=sk_live_...
STRIPE_PRICE_ID=price_live_...
STRIPE_WEBHOOK_SECRET=whsec_live_...
NEXT_PUBLIC_SITE_URL=https://yourdomain.com
https://your-prod-deployment.convex.site/stripe/webhookSTRIPE_WEBHOOK_SECRET in Convex production envTest with real payment method (refund immediately after):
Monitor for 24-48 hours:
Webhooks may be sent multiple times. Your handler must be idempotent:
// Add this to convex/stripeDb.ts
export const processedWebhookEvents = defineTable({
eventId: v.string(), // Stripe event ID
processedAt: v.number(),
}).index("by_event_id", ["eventId"]);
// Check before processing webhook
export const isEventProcessed = internalQuery({
args: { eventId: v.string() },
handler: async (ctx, args) => {
const existing = await ctx.db
.query("processedWebhookEvents")
.withIndex("by_event_id", (q) => q.eq("eventId", args.eventId))
.unique();
return !!existing;
},
});
export const markEventProcessed = internalMutation({
args: { eventId: v.string() },
handler: async (ctx, args) => {
await ctx.db.insert("processedWebhookEvents", {
eventId: args.eventId,
processedAt: Date.now(),
});
},
});
Update webhook handler to use idempotency:
// In convex/http.ts, before switch statement:
const { internal } = await import("./_generated/api.js");
// Check if already processed
const isProcessed = await ctx.runQuery(internal.stripeDb.isEventProcessed, {
eventId: event.id,
});
if (isProcessed) {
console.log(`Event ${event.id} already processed, skipping`);
return new Response(JSON.stringify({ received: true }), { status: 200 });
}
// ... handle event with switch statement ...
// After successful processing, mark as processed
await ctx.runMutation(internal.stripeDb.markEventProcessed, {
eventId: event.id,
});
Stripe doesn't guarantee event order. Handle events independently:
// ❌ DON'T rely on event order
// Assuming subscription.updated comes before invoice.paid
// ✅ DO handle each event independently
// Each event should have enough data to process standalone
Best practice: Always fetch the latest subscription state from Stripe if you need current data:
case "invoice.payment_failed": {
const invoice = event.data.object;
// Fetch current subscription state (don't assume from previous events)
const subscription = await stripe.subscriptions.retrieve(invoice.subscription);
// Now you have accurate current state
}
Webhook health checks:
// Create a simple health endpoint in convex/http.ts
http.route({
path: "/health",
method: "GET",
handler: httpAction(async () => {
return new Response(JSON.stringify({ status: "ok" }), { status: 200 });
}),
});
Monitor in Stripe Dashboard:
Monitor in Convex:
Critical alerts to implement:
Always sync from Stripe as source of truth:
// Good: Periodically sync subscription status from Stripe
export const syncSubscriptionStatus = internalMutation({
args: {
clerkUserId: v.string(),
},
handler: async (ctx, args) => {
const user = await ctx.db
.query("users")
.withIndex("by_clerk_id", (q) => q.eq("clerkId", args.clerkUserId))
.unique();
if (!user || !user.stripeSubscriptionId) return;
// Fetch current state from Stripe
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const subscription = await stripe.subscriptions.retrieve(user.stripeSubscriptionId);
// Update database to match Stripe
const currentPeriodEnd = subscription.items?.data?.[0]?.current_period_end;
const status = subscription.status === "active" ? "premium" : "free";
await ctx.db.patch(user._id, {
membershipStatus: status,
membershipExpiry: currentPeriodEnd ? currentPeriodEnd * 1000 : undefined,
});
},
});
Run this sync:
Protect your API keys:
STRIPE_SECRET_KEY to gitVerify webhook signatures:
constructEventAsync (already implemented)STRIPE_WEBHOOK_SECRET secureLimit webhook endpoint access:
Issue: Webhooks stopped working
STRIPE_WEBHOOK_SECRET is correctIssue: Subscriptions not updating after renewal
customer.subscription.updated or invoice.paid webhooks are enabledcurrent_period_end is being updated correctlyIssue: Users charged but no access granted
updateMembershipStatus mutationIssue: Duplicate charges
stripe.checkout.sessions.create multiple timesWeekly:
Monthly:
Quarterly:
.convex.cloud for webhooks → ✅ Use .convex.siteconstructEvent() → ✅ Use constructEventAsync()subscription.current_period_end → ✅ Use subscription.items.data[0].current_period_endSTRIPE_WEBHOOK_SECRET in Convexmetadata in checkout sessioncheckout.session.completed → ✅ Listen to all lifecycle eventsConvex Dashboard:
STRIPE_SECRET_KEY (sk_test_... for dev, sk_live_... for prod)STRIPE_PRICE_ID (price_... for your product)STRIPE_WEBHOOK_SECRET (whsec_... from webhook endpoint)Next.js .env.local:
NEXT_PUBLIC_SITE_URL (http://localhost:3000 for dev, https://yourdomain.com for prod)Phase 1-3: Setup
stripe packagePhase 4: Code Implementation
convex/stripe.ts with checkout and portal actionsconvex/stripeDb.ts with database helpersconvex/http.ts with webhook handlerPhase 5: Webhooks
.convex.site URLPhase 6: Testing
Phase 7: Customer Portal
Phase 8: Revenue Recovery
Phase 9: Comprehensive Testing
Phase 10: Production
Phase 11: Best Practices (Recommended)
Add a free trial period before charging customers:
// In convex/stripe.ts - createCheckoutSession
const session = await stripe.checkout.sessions.create({
customer: customerId,
mode: "subscription",
line_items: [{ price: process.env.STRIPE_PRICE_ID!, quantity: 1 }],
subscription_data: {
trial_period_days: 14, // 14-day free trial
},
success_url: `${siteUrl}/checkout/return?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${siteUrl}`,
metadata: { clerkUserId: args.clerkUserId, userId: user._id },
});
Trial best practices:
Handling trial end:
case "customer.subscription.trial_will_end": {
// Send reminder email 3 days before trial ends
const subscription = event.data.object;
// Email user about upcoming charge
}
Create and apply discount codes:
Create coupon in Stripe Dashboard:
Apply coupon to checkout:
const session = await stripe.checkout.sessions.create({
customer: customerId,
mode: "subscription",
line_items: [{ price: process.env.STRIPE_PRICE_ID!, quantity: 1 }],
discounts: [{
coupon: "SUMMER2024", // Your coupon code
}],
// ... rest of session config
});
Allow customers to enter codes:
const session = await stripe.checkout.sessions.create({
customer: customerId,
mode: "subscription",
line_items: [{ price: process.env.STRIPE_PRICE_ID!, quantity: 1 }],
allow_promotion_codes: true, // Shows coupon field in checkout
// ... rest of session config
});
For non-subscription purchases (e.g., credits, one-time features):
// Use mode: "payment" instead of "subscription"
const session = await stripe.checkout.sessions.create({
customer: customerId,
mode: "payment", // One-time payment
line_items: [{
price_data: {
currency: "usd",
product_data: {
name: "100 Credits",
description: "One-time credit purchase",
},
unit_amount: 999, // $9.99 in cents
},
quantity: 1,
}],
success_url: `${siteUrl}/checkout/return?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${siteUrl}`,
metadata: { clerkUserId: args.clerkUserId, userId: user._id },
});
Handle one-time payment webhook:
case "checkout.session.completed": {
const session = event.data.object;
if (session.mode === "payment") {
// One-time payment completed
const clerkUserId = session.metadata?.clerkUserId;
// Grant one-time purchase (e.g., add credits)
await ctx.runMutation(internal.stripeDb.addCredits, {
clerkUserId,
amount: 100,
});
}
}
One-time vs Subscription - When to use which:
Support different pricing tiers (Basic, Pro, Enterprise):
Setup in Stripe:
STRIPE_PRICE_ID_BASIC=price_basic...
STRIPE_PRICE_ID_PRO=price_pro...
STRIPE_PRICE_ID_ENTERPRISE=price_enterprise...
Pass tier in frontend:
const result = await createCheckoutSession({
clerkUserId: user.id,
mode: "subscription",
priceId: "price_pro...", // User selected Pro tier
});
Update createCheckoutSession action:
export const createCheckoutSession = action({
args: {
clerkUserId: v.string(),
mode: v.optional(v.union(v.literal("subscription"), v.literal("payment"))),
priceId: v.optional(v.string()), // Allow custom price ID
},
handler: async (ctx, args) => {
// ... existing code ...
const priceId = args.priceId || process.env.STRIPE_PRICE_ID!;
const session = await stripe.checkout.sessions.create({
customer: customerId,
mode: args.mode || "subscription",
line_items: [{ price: priceId, quantity: 1 }],
// ... rest of config
});
},
});
Store tier in database:
// Update schema
membershipTier: v.optional(v.union(
v.literal("basic"),
v.literal("pro"),
v.literal("enterprise")
)),
// Update in webhook
await ctx.db.patch(user._id, {
membershipStatus: "premium",
membershipTier: "pro", // Store which tier
membershipExpiry: currentPeriodEnd * 1000,
stripeSubscriptionId: subscriptionId,
});
Customer Portal upgrades/downgrades:
resources/common-mistakes.md for detailed error solutionsresources/return-page-example.tsx for full return page codexiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience