> ## Documentation Index
> Fetch the complete documentation index at: https://docs.creem.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Refunds and Cancellations

> Handle subscription cancellations and process refunds with flexible options for immediate or end-of-period cancellation.

Creem provides flexible options for managing subscription cancellations and processing refunds. You can cancel subscriptions immediately or at the end of the billing period, and process full or partial refunds through the dashboard or API.

## Canceling Subscriptions

### Cancellation Options

When canceling a subscription, you have two options:

* **Cancel Immediately** - Subscription ends right away and no further charges occur
* **Cancel at Period End** - Customer retains access until the end of the current billing period

### Programmatic Cancellation

Cancel subscriptions programmatically using the API:

> [tab] TypeScript SDK
>
> ```typescript theme={null}
> import { Creem } from "creem";
>
> const creem = new Creem({
>   apiKey: process.env.CREEM_API_KEY!,
>   server: process.env.NODE_ENV === "production" ? "prod" : "test",
> });
>
> // Cancel subscription
> const canceled = await creem.subscriptions.cancel("sub_YOUR_SUBSCRIPTION_ID", {
>   mode: "immediate",
> });
>
> console.log("Subscription canceled:", canceled);
> ```

> [tab] Better Auth
>
> ```typescript theme={null}
> "use client";
>
> import { authClient } from "@/lib/auth-client";
>
> export function CancelSubscriptionButton({ subscriptionId }: { subscriptionId: string }) {
>   const handleCancel = async () => {
>     const confirmed = confirm(
>       "Are you sure you want to cancel your subscription?"
>     );
>
>     if (!confirmed) return;
>
>     const { data, error } = await authClient.creem.cancelSubscription({
>       id: subscriptionId,
>     });
>
>     if (data?.success) {
>       alert("Subscription canceled successfully");
>       // Refresh the page or update UI
>     }
>   };
>
>   return (
>     <button onClick={handleCancel} className="text-red-600">
>       Cancel Subscription
>     </button>
>   );
> }
> ```

> [tab] REST API
>
> > [!WARNING]
> >
> > If you're in test mode, use `https://test-api.creem.io` instead of `https://api.creem.io`. Learn
> > more about [Test Mode](https://docs.creem.io/getting-started/test-mode.md).
>
> ```bash theme={null}
> curl -X POST https://api.creem.io/v1/subscriptions/sub_YOUR_SUBSCRIPTION_ID/cancel \
>   -H "x-api-key: YOUR_API_KEY" \
>   -H "Content-Type: application/json"
> ```
>
> ### Response
>
> ```json theme={null}
> {
>   "id": "sub_YOUR_SUBSCRIPTION_ID",
>   "status": "canceled",
>   "canceled_at": "2025-01-15T10:30:00.000Z",
>   "current_period_end_date": "2025-02-01T10:30:00.000Z"
> }
> ```
>
> > [card] [API Reference - Cancel Subscription](https://docs.creem.io/api-reference/endpoint/cancel-subscription.md)
> >
> > View the complete cancel subscription endpoint documentation.

### Customer Self-Service Cancellation

Customers can cancel their own subscriptions through the Customer Portal:

> [tab] Next.js
>
> ```tsx theme={null}
> import { CreemPortal } from "@creem_io/nextjs";
>
> export function ManageSubscriptionButton({ customerId }: { customerId: string }) {
>   return (
>     <CreemPortal customerId={customerId} className="btn-primary">
>       Manage Subscription
>     </CreemPortal>
>   );
> }
> ```

> [tab] TypeScript SDK
>
> ```typescript theme={null}
> // Create customer portal link
> const portal = await creem.customers.generateBillingLinks({
>   customerId: "cust_YOUR_CUSTOMER_ID",
> });
>
> // Redirect customer to portal
> window.location.href = portal.customerPortalLink;
> ```

> [tab] Better Auth
>
> ```typescript theme={null}
> "use client";
>
> import { authClient } from "@/lib/auth-client";
>
> export function ManageSubscriptionButton() {
>   const handlePortal = async () => {
>     const { data } = await authClient.creem.createPortal();
>
>     if (data?.url) {
>       window.location.href = data.url;
>     }
>   };
>
>   return (
>     <button onClick={handlePortal}>
>       Manage Subscription
>     </button>
>   );
> }
> ```

> [card] [Customer Portal](https://docs.creem.io/features/customer-portal.md)
>
> Learn more about enabling self-service subscription management.

***

## Processing Refunds

### Dashboard Refunds

The easiest way to process refunds is through the Creem Dashboard:

1. Navigate to **Transactions** or **Subscriptions**
2. Find the transaction you want to refund
3. Click on the transaction details
4. Select **Refund**
5. Choose full or partial refund amount
6. Confirm the refund

### Refund Types

> [card] Full Refund
>
> Refund the entire transaction amount to the customer

> [card] Partial Refund
>
> Refund a specific amount (less than the total transaction)

### Refund Processing

When you process a refund:

* **Immediate processing** - Refunds are processed immediately
* **Customer notification** - Customer receives an email notification
* **Webhook event** - A `refund.created` webhook is sent
* **5-10 business days** - Funds typically appear in customer's account within 5-10 business days

> [!NOTE]
>
> Refund availability depends on the payment method and may vary by region. Credit card refunds are
> generally processed within 5-10 business days.

***

## Cancellation Policies

### Best Practices

1. **Clear Communication**
   * Set clear expectations about cancellation policies
   * Communicate what happens to customer data after cancellation
   * Explain billing cycle and refund policies upfront

2. **Retention Strategies**
   * Offer to pause subscription instead of canceling
   * Provide downgrade options to lower-tier plans
   * Ask for feedback to improve your service

3. **Grace Periods**
   * Consider offering a grace period for failed payments
   * Allow customers to reactivate within a certain timeframe
   * Preserve customer data for a reasonable period

### Cancellation Flow Example

```typescript theme={null}
import { Creem } from "creem";

const creem = new Creem({
  apiKey: process.env.CREEM_API_KEY!,
});

async function handleCancellation(subscriptionId: string, reason?: string) {
  try {
    // Log cancellation reason for analytics
    console.log(`Canceling subscription: ${subscriptionId}`, { reason });

    // Cancel the subscription
    const canceled = await creem.subscriptions.cancel(subscriptionId, {
      mode: "immediate",
    });

    // Send cancellation email to customer when the response includes expanded customer data
    if (typeof canceled.customer !== "string") {
      await sendCancellationEmail(canceled.customer.email);
    }

    // Update internal database
    await db.subscription.update({
      where: { id: subscriptionId },
      data: { status: "canceled", canceledAt: new Date() },
    });

    return { success: true, subscription: canceled };
  } catch (error) {
    console.error("Cancellation failed:", error);
    throw error;
  }
}
```

***

## Handling Cancellation Events

Use webhooks to automatically respond to cancellation events:

> [tab] Next.js
>
> ```typescript theme={null}
> // app/api/webhook/creem/route.ts
> import { Webhook } from "@creem_io/nextjs";
>
> export const POST = Webhook({
>   webhookSecret: process.env.CREEM_WEBHOOK_SECRET!,
>   onSubscriptionCanceled: async ({ subscription, customer }) => {
>     console.log(`Subscription ${subscription.id} canceled`);
>
>     // Revoke access in your database
>     await revokeAccess(customer.email);
>
>     // Send cancellation confirmation email
>     await sendEmail({
>       to: customer.email,
>       subject: "Subscription Canceled",
>       body: "Your subscription has been canceled...",
>     });
>   },
> });
> ```

> [tab] TypeScript SDK
>
> ```typescript theme={null}
> import { constructWebhookEventEntity } from "creem/webhooks";
>
> // In your webhook endpoint
> const rawBody = await request.text();
> const event = await constructWebhookEventEntity(rawBody, request.headers, {
>   secret: process.env.CREEM_WEBHOOK_SECRET!,
> });
>
> switch (event.eventType) {
>   case "subscription.canceled": {
>     const subscription = event.object;
>     const customer = typeof subscription.customer === "string" ? undefined : subscription.customer;
>
>     console.log(`Subscription ${subscription.id} canceled`);
>
>     if (customer) {
>       // Revoke access in your database
>       await revokeAccess(customer.email);
>
>       // Send cancellation confirmation email
>       await sendEmail({
>         to: customer.email,
>         subject: "Subscription Canceled",
>         body: "Your subscription has been canceled...",
>       });
>     }
>
>     const userId = subscription.metadata?.userId;
>     if (userId) {
>       await db.user.update({
>         where: { id: userId },
>         data: { subscriptionActive: false },
>       });
>     }
>     break;
>   }
>
>   case "subscription.paused":
>   case "subscription.expired": {
>     const userId = event.object.metadata?.userId;
>     if (userId) {
>       await db.user.update({
>         where: { id: userId },
>         data: { subscriptionActive: false },
>       });
>     }
>     break;
>   }
> }
> ```

> [card] [Webhooks](https://docs.creem.io/code/webhooks.md)
>
> Learn more about handling subscription events with webhooks.

***

## Failed Payments

### Payment Retry Logic

When a subscription payment fails:

1. **Automatic retries** - Creem automatically retries failed payments
2. **Status changes** - Subscription moves to "unpaid" status
3. **Customer notification** - Customer receives email to update payment method
4. **Grace period** - Subscription remains active during retry period
5. **Final failure** - After all retries fail, subscription may be canceled

### Handling Failed Payments

```typescript theme={null}
// Handle failed payment webhook
import { constructWebhookEventEntity } from "creem/webhooks";

const rawBody = await request.text();
const event = await constructWebhookEventEntity(rawBody, request.headers, {
  secret: process.env.CREEM_WEBHOOK_SECRET!,
});

if (event.eventType === "subscription.past_due") {
  const customer = typeof event.object.customer === "string" ? undefined : event.object.customer;

  // Notify customer to update payment method
  if (customer) {
    await sendPaymentFailedEmail(customer.email, {
      portalLink: `https://yoursite.com/portal?customer=${customer.id}`,
    });

    // Optionally restrict access or show warning
    await showPaymentWarning(customer.email);
  }
}

if (event.eventType === "subscription.canceled") {
  const customer = typeof event.object.customer === "string" ? undefined : event.object.customer;

  // After all retries failed
  if (customer) {
    await revokeAccess(customer.email);
    await sendSubscriptionEndedEmail(customer.email);
  }
}
```

***

## Next Steps

> [card] [Customer Portal](https://docs.creem.io/features/customer-portal.md)
>
> Enable self-service subscription management

> [card] [Webhooks](https://docs.creem.io/code/webhooks.md)
>
> Handle subscription events automatically

> [card] [Managing Subscriptions](https://docs.creem.io/features/subscriptions/managing.md)
>
> Learn how to update and manage subscriptions

> [card] [API Reference](https://docs.creem.io/api-reference/endpoint/cancel-subscription.md)
>
> View the complete API documentation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.