How to cancel Stripe subscription using API?

Hi, I want to allow users to cancel their subscriptions directly via the API because the default authClient.subscription.cancel just redirects users to the Stripe Billing Portal, which doesn’t suit my needs. I just want users to be able to click a button and cancel their subscription - nothing more. Has anyone achieved this properly? Currently, I’ve implemented cancellation through the API, but now I’m thinking about how to synchronize it properly with Better-Auth. I noticed that the database isn’t updated after I cancel a subscription, etc. My logic:
"use server";

import { stripeClient } from "@/lib/stripe";

export async function cancelSubscription(stripeSubscriptionId: string) {
if (!stripeSubscriptionId) throw new Error("Missing subscriptionId");

try {
await stripeClient.subscriptions.cancel(stripeSubscriptionId);
return { success: true };
} catch (err) {
console.error("Błąd anulowania subskrypcji:", err);
return { success: false, error: (err as Error).message };
}
}

export async function reactivateSubscription(stripeSubscriptionId: string) {
if (!stripeSubscriptionId) throw new Error("Missing subscriptionId");

try {
await stripeClient.subscriptions.update(stripeSubscriptionId, {
cancel_at_period_end: false,
});
return { success: true };
} catch (err) {
console.error("Błąd przywracania subskrypcji:", err);
return { success: false, error: (err as Error).message };
}
}
"use server";

import { stripeClient } from "@/lib/stripe";

export async function cancelSubscription(stripeSubscriptionId: string) {
if (!stripeSubscriptionId) throw new Error("Missing subscriptionId");

try {
await stripeClient.subscriptions.cancel(stripeSubscriptionId);
return { success: true };
} catch (err) {
console.error("Błąd anulowania subskrypcji:", err);
return { success: false, error: (err as Error).message };
}
}

export async function reactivateSubscription(stripeSubscriptionId: string) {
if (!stripeSubscriptionId) throw new Error("Missing subscriptionId");

try {
await stripeClient.subscriptions.update(stripeSubscriptionId, {
cancel_at_period_end: false,
});
return { success: true };
} catch (err) {
console.error("Błąd przywracania subskrypcji:", err);
return { success: false, error: (err as Error).message };
}
}
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?