Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/provider-subscriptions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"@dashcommerce/core": minor
---

Add a provider-neutral subscription seam.

- `PaymentProvider` gains optional `getSubscription`, `cancelSubscription` and `resumeSubscription`. Stripe keeps its existing Billing path; providers that manage billing themselves can use these.
- `charge.succeeded` and `PaymentStatusResult` can carry `ProviderSubscriptionInfo`, so a provider can identify the subscription/plan behind a charge.
- A normalised `subscription.updated` event lets a provider report a cancellation or status change outside a charge; core updates the local row.
- New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The provider id is part of the unique storage key for both subscriptions and invoices (`${providerId}:${id}`), so two providers cannot collide on a numeric plan or transaction id. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders.
- `subscriptions/lifecycle.ts` dispatches cancel/resume to a provider-managed subscription. Pause and in-place plan changes are refused for providers that do not support them. The admin and customer portal hide pause and the Stripe billing portal for those subscriptions.
- Stripe's `stripeSubscriptionId`/`stripeInvoiceId` fields keep their names for compatibility; they now hold the provider's subscription/plan and invoice id.
2 changes: 2 additions & 0 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ For provider authors, `PaymentProvider` can declare:
- `credentialFields`: the label, accepted prefixes and help text for the settings form.
- `webhookHeaders`: the headers that identify its webhooks, besides `x-<id>-signature`. `verifyWebhook` receives every request header, and `credentials` (the provider's saved secret key and webhook secret) for headers signed with the API key rather than the webhook secret.
- `checkConnection`: one read-only call with the saved keys, behind a "Test connection" button in Settings. Return `{ ok, message }`, with `ok: false` and a message the merchant can act on for a wrong or under-permitted key.
- `capabilities.subscriptions` plus optional `getSubscription`, `cancelSubscription` and `resumeSubscription`: core stores the provider's subscription/plan id from the first `charge.succeeded` that carries `subscription`, records later charges as invoices, and dispatches cancel/resume. Return `ProviderSubscriptionInfo`. A provider that cannot pause or change plans in place can omit those methods; core refuses the action with a readable error.
- `parseWebhookEvent` may return `subscription.updated` for a cancellation or status change outside a charge. Core updates the local row and does not create an order.

`parseWebhookEvent` may return `refund.updated` to move a pending refund to `succeeded` or `failed`. A failed refund stops counting against its order: the refunded total, payment status and order status are worked out again, and stock the refund put back is taken back off.

Expand Down
101 changes: 45 additions & 56 deletions packages/core/src/admin/pages/SubscriptionsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
* `useListControls`, plus cancel/pause/resume with confirm dialogs,
* per-row pending states, and toast feedback.
*
* Stripe is the source of truth for subscription state, so we deliberately
* avoid optimistic updates: after every action we reload the list so the
* row reflects whatever webhook response came back.
* The payment provider is the source of truth for subscription state, so we
* deliberately avoid optimistic updates: after every action we reload the
* list so the row reflects whatever webhook response came back.
*/

import { useCallback, useMemo, useState } from "react";
Expand Down Expand Up @@ -64,19 +64,21 @@ function isCancellable(sub: Subscription): boolean {
return !cancelled.includes(sub.status) && !sub.cancelAtPeriodEnd;
}

function isProviderManaged(sub: Subscription): boolean {
return Boolean(sub.providerId && sub.providerId !== "stripe");
}

function isPausable(sub: Subscription): boolean {
return sub.status === "active" || sub.status === "trialing";
return (sub.status === "active" || sub.status === "trialing") && !isProviderManaged(sub);
}

function isResumable(sub: Subscription): boolean {
return sub.status === "paused";
return sub.status === "paused" || (isProviderManaged(sub) && sub.status === "canceled");
}

export function SubscriptionsPage() {
const api = usePluginAPI();
const [pending, setPending] = useState<{ id: string; action: Action } | null>(
null,
);
const [pending, setPending] = useState<{ id: string; action: Action } | null>(null);

const buildQuery = useMemo(
() => (f: SubscriptionsFilters) => ({
Expand All @@ -89,23 +91,14 @@ export function SubscriptionsPage() {
[],
);

const {
filters,
setFilter,
resetFilters,
items,
loading,
error,
hasMore,
loadMore,
reload,
} = useListControls<SubscriptionsFilters, Subscription>({
api,
endpoint: "admin/subscriptions",
initialFilters: INITIAL,
buildQuery,
limit: 50,
});
const { filters, setFilter, resetFilters, items, loading, error, hasMore, loadMore, reload } =
useListControls<SubscriptionsFilters, Subscription>({
api,
endpoint: "admin/subscriptions",
initialFilters: INITIAL,
buildQuery,
limit: 50,
});

const act = useCallback(
async (sub: Subscription, action: Action): Promise<void> => {
Expand All @@ -116,7 +109,7 @@ export function SubscriptionsPage() {
title: immediate ? "Cancel subscription now?" : "Cancel at period end?",
description: immediate
? "The customer loses access immediately. Any remaining time in the current period is not refunded automatically."
: `Access continues until ${new Date(sub.currentPeriodEnd).toLocaleDateString()}, then Stripe will cancel the subscription.`,
: `Access continues until ${new Date(sub.currentPeriodEnd).toLocaleDateString()}, then the payment provider will cancel the subscription.`,
confirmLabel: immediate ? "Cancel now" : "Cancel at period end",
destructive: true,
});
Expand All @@ -126,7 +119,7 @@ export function SubscriptionsPage() {
const ok = await confirm({
title: "Pause subscription?",
description:
"Stripe stops generating invoices until the subscription is resumed. The customer keeps their record but won't be billed.",
"The payment provider stops generating invoices until the subscription is resumed. The customer keeps their record but won't be billed.",
confirmLabel: "Pause",
});
if (!ok) return;
Expand All @@ -153,10 +146,7 @@ export function SubscriptionsPage() {
}
await reload();
} catch (err) {
toast.error(
"Action failed",
err instanceof Error ? err.message : String(err),
);
toast.error("Action failed", err instanceof Error ? err.message : String(err));
} finally {
setPending(null);
}
Expand Down Expand Up @@ -186,12 +176,7 @@ export function SubscriptionsPage() {
label="Status"
value={filters.status}
options={STATUS_FILTERS}
onChange={(e) =>
setFilter(
"status",
e.currentTarget.value as SubscriptionStatus | "",
)
}
onChange={(e) => setFilter("status", e.currentTarget.value as SubscriptionStatus | "")}
/>
<Input
label="Customer email"
Expand Down Expand Up @@ -244,9 +229,7 @@ export function SubscriptionsPage() {

{items.length === 0 && !loading ? (
<EmptyState
title={
activeFilters > 0 ? "No subscriptions match" : "No subscriptions yet"
}
title={activeFilters > 0 ? "No subscriptions match" : "No subscriptions yet"}
description={
activeFilters > 0
? "Try widening your filters."
Expand All @@ -259,6 +242,16 @@ export function SubscriptionsPage() {
data={items}
getRowKey={(s) => s.id}
columns={[
{
key: "provider",
header: "Provider",
render: (s) => {
const provider = s.providerId ?? "stripe";
if (provider === "stripe") return "Stripe";
if (provider === "flutterwave") return "Flutterwave";
return provider;
},
},
{
key: "status",
header: "Status",
Expand All @@ -272,9 +265,7 @@ export function SubscriptionsPage() {
>
<StatusBadge status={s.status} />
{s.cancelAtPeriodEnd && (
<span style={{ fontSize: 12, color: T.warning }}>
Cancels at period end
</span>
<span style={{ fontSize: 12, color: T.warning }}>Cancels at period end</span>
)}
</div>
),
Expand Down Expand Up @@ -306,11 +297,7 @@ export function SubscriptionsPage() {
key: "act",
header: "",
render: (s) => (
<SubscriptionActions
sub={s}
pending={pending}
onAct={(a) => act(s, a)}
/>
<SubscriptionActions sub={s} pending={pending} onAct={(a) => act(s, a)} />
),
},
]}
Expand Down Expand Up @@ -379,14 +366,16 @@ function SubscriptionActions({
)}
{isCancellable(sub) && (
<>
<Button
size="sm"
variant="secondary"
disabled={isPendingHere}
onClick={() => onAct("cancel-eop")}
>
{label("cancel-eop", "Cancel at period end")}
</Button>
{!isProviderManaged(sub) && (
<Button
size="sm"
variant="secondary"
disabled={isPendingHere}
onClick={() => onAct("cancel-eop")}
>
{label("cancel-eop", "Cancel at period end")}
</Button>
)}
<Button
size="sm"
variant="danger"
Expand Down
57 changes: 28 additions & 29 deletions packages/core/src/astro/islands/SubscriptionPortalIsland.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import { useEffect, useState } from "react";
* proves ownership; no login is required (DashCommerce uses
* email-gated accounts).
*
* In addition to the local Cancel / Pause / Resume actions (which
* forward to Stripe), we expose a "Manage billing" button that
* redirects to the Stripe-hosted Billing Portal — customers can
* update their card, download invoices, and manage billing there
* without us having to implement those screens ourselves.
* Cancel / Pause / Resume forward to the subscription's provider. For
* Stripe we also expose a "Manage billing" button that redirects to the
* Stripe-hosted Billing Portal, where customers can update their card and
* download invoices. Provider-managed subscriptions (Flutterwave) use the
* local actions only.
*/

interface Money {
Expand All @@ -28,6 +28,7 @@ interface Subscription {
intervalCount: number;
currentPeriodEnd: string;
cancelAtPeriodEnd: boolean;
providerId?: string;
}

export interface SubscriptionPortalIslandProps {
Expand All @@ -47,19 +48,16 @@ function formatMoney(m: Money, locale = "en-US") {

const API = "/_emdash/api/plugins/dashcommerce";

export default function SubscriptionPortalIsland({
token,
}: SubscriptionPortalIslandProps) {
export default function SubscriptionPortalIsland({ token }: SubscriptionPortalIslandProps) {
const [sub, setSub] = useState<Subscription | null>(null);
const [error, setError] = useState<string | null>(null);
const [pending, setPending] = useState(false);

async function reload() {
try {
const res = await fetch(
`${API}/subscriptions/state?token=${encodeURIComponent(token)}`,
{ credentials: "include" },
);
const res = await fetch(`${API}/subscriptions/state?token=${encodeURIComponent(token)}`, {
credentials: "include",
});
const body = (await res.json()) as {
subscription?: Subscription;
error?: string;
Expand All @@ -78,6 +76,8 @@ export default function SubscriptionPortalIsland({
reload();
}, []);

const providerManaged = Boolean(sub?.providerId && sub.providerId !== "stripe");

async function act(action: "cancel" | "pause" | "resume") {
setPending(true);
setError(null);
Expand All @@ -88,7 +88,7 @@ export default function SubscriptionPortalIsland({
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
token,
...(action === "cancel" ? { mode: "at_period_end" } : {}),
...(action === "cancel" ? { mode: providerManaged ? "immediate" : "at_period_end" } : {}),
}),
});
const body = (await res.json()) as { error?: string };
Expand Down Expand Up @@ -142,38 +142,37 @@ export default function SubscriptionPortalIsland({
{sub.interval}
</p>
<p>
<strong>Next billed:</strong>{" "}
{new Date(sub.currentPeriodEnd).toLocaleDateString()}
<strong>Next billed:</strong> {new Date(sub.currentPeriodEnd).toLocaleDateString()}
</p>
{sub.cancelAtPeriodEnd && (
<p className="dc-notice">
This subscription is set to cancel at the end of the period.
</p>
<p className="dc-notice">This subscription is set to cancel at the end of the period.</p>
)}
<div className="dc-actions">
{!sub.cancelAtPeriodEnd && sub.status !== "canceled" && (
<button type="button" onClick={() => act("cancel")} disabled={pending}>
Cancel at period end
{providerManaged ? "Cancel subscription" : "Cancel at period end"}
</button>
)}
{sub.status !== "canceled" && sub.status !== "paused" && (
{!providerManaged && sub.status !== "canceled" && sub.status !== "paused" && (
<button type="button" onClick={() => act("pause")} disabled={pending}>
Pause
</button>
)}
{sub.status === "paused" && (
{(sub.status === "paused" || (providerManaged && sub.status === "canceled")) && (
<button type="button" onClick={() => act("resume")} disabled={pending}>
Resume
</button>
)}
<button
type="button"
onClick={openPortal}
disabled={pending}
className="dc-actions-secondary"
>
Manage billing on Stripe →
</button>
{!providerManaged && (
<button
type="button"
onClick={openPortal}
disabled={pending}
className="dc-actions-secondary"
>
Manage billing on Stripe →
</button>
)}
</div>
</section>
);
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/payment-provider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export type {
PaymentProviderRuntimeContext,
PaymentProviderShippingOption,
PaymentStatusResult,
ProviderSubscriptionInfo,
RefundResult,
VerifyWebhookInput,
VerifyWebhookResult,
Expand Down
Loading