Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(subscriptions): record a new tier unpaid until its first payment verifies, and send Subscribe to the agent's checkout

nirholasea86f7ca59cd
diff --git a/api/subscriptions/index.js b/api/subscriptions/index.js
index 6fd12d9b5..227fb98b5 100644
--- a/api/subscriptions/index.js
+++ b/api/subscriptions/index.js
@@ -89,8 +89,6 @@ async function handleSubscribe(req, res) {
if (plan.creator_id === user.id)
return error(res, 409, 'conflict', 'cannot subscribe to your own plan');
- const periodMs = plan.interval === 'weekly' ? 7 * 24 * 3600 * 1000 : 30 * 24 * 3600 * 1000;
- const periodEnd = new Date(Date.now() + periodMs).toISOString();
// Upsert guard: reject if already subscribed and active.
const [existing] = await sql`
@@ -101,14 +99,18 @@ async function handleSubscribe(req, res) {
return error(res, 409, 'conflict', 'already subscribed to this plan');
}
+ // The row is recorded UNPAID (past_due, period already over): this route
+ // verifies no payment, and writing 'active' here unlocked every skill in the
+ // tier for free (the column even defaults to 'active'). A tier becomes active
+ // only through the verified checkout (POST /api/subscriptions/subscribe, then
+ // /verify), which re-activates this same row once the transfer is on-chain.
let sub;
if (existing) {
- // Re-activate a cancelled subscription.
[sub] = await sql`
UPDATE creator_subscriptions
- SET status = 'active',
+ SET status = 'past_due',
current_period_start = now(),
- current_period_end = ${periodEnd},
+ current_period_end = now(),
wallet_address = ${body.wallet_address ?? null},
cancelled_at = NULL
WHERE id = ${existing.id}
@@ -117,8 +119,8 @@ async function handleSubscribe(req, res) {
} else {
[sub] = await sql`
INSERT INTO creator_subscriptions
- (plan_id, subscriber_user_id, current_period_end, wallet_address)
- VALUES (${plan.id}, ${user.id}, ${periodEnd}, ${body.wallet_address ?? null})
+ (plan_id, subscriber_user_id, status, current_period_end, wallet_address)
+ VALUES (${plan.id}, ${user.id}, 'past_due', now(), ${body.wallet_address ?? null})
RETURNING *
`;
}
diff --git a/src/agent-detail-market.js b/src/agent-detail-market.js
index 2702d9415..28b7bcec5 100644
--- a/src/agent-detail-market.js
+++ b/src/agent-detail-market.js
@@ -869,6 +869,23 @@ async function renderSubscriptionTiers(a) {
.join('');
bindTierDelegation();
+ openRequestedTier(a);
+}
+
+// The marketplace sends "Subscribe" here as /agents/:id?tier=<plan id>, because a
+// tier activates only through this page's verified checkout. Open that tier's
+// checkout once, if it is offered and the caller does not already hold it.
+let requestedTierOpened = false;
+function openRequestedTier(a) {
+ if (requestedTierOpened) return;
+ const tierId = new URLSearchParams(location.search).get('tier');
+ if (!tierId) return;
+ const btn = $('ad-tiers-body')?.querySelector(`.ad-subscribe-btn[data-tier-id="${CSS.escape(tierId)}"]`);
+ const tier = marketTiers.find((t) => t.id === tierId);
+ if (!btn || !tier) return;
+ requestedTierOpened = true;
+ $('ad-tiers-card')?.scrollIntoView({ block: 'start' });
+ openSubscribeFlow(a.id, tier).catch((err) => log.error('[agent-detail-market] subscribe', err));
}
// Active subscription plan_ids for the signed-in user (empty when anonymous).
diff --git a/src/marketplace.js b/src/marketplace.js
index 38d65d9d2..a500167fa 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -2033,68 +2033,14 @@ async function initiateSubscription(planId, btn) {
const agent = detailState.agent;
const tier = (agent.subscription_tiers || []).find((t) => t.id === planId);
if (!tier) return;
-
- const intervalLabel = tier.interval === 'weekly' ? 'week' : 'month';
- const price = Number(tier.price_usd || 0).toFixed(2);
- const status = $('d-subs-status');
-
- const confirmed = window.confirm(
- `Subscribe to "${tier.name}" for $${price} per ${intervalLabel}? You'll pay in USDC each ${intervalLabel} and can cancel anytime.`,
- );
- if (!confirmed) return;
-
+ // A tier activates only once its first payment is verified on-chain, which the
+ // agent page's checkout does (quote, wallet signature, verify). The old
+ // one-click POST here activated the tier before anything was paid.
if (btn) {
btn.disabled = true;
- btn.textContent = 'Subscribing…';
- }
- if (status) {
- status.textContent = '';
- status.className = 'd-subs-status';
- }
-
- try {
- const r = await apiPostWithCsrf('/api/subscriptions', { plan_id: planId });
- const j = await r.json().catch(() => ({}));
- if (!r.ok) {
- const msg = j.error_description || j.error || 'Could not start subscription. Try again.';
- if (status) {
- status.textContent = msg;
- status.className = 'd-subs-status err';
- }
- if (btn) {
- btn.disabled = false;
- btn.textContent = 'Subscribe';
- }
- return;
- }
-
- const payUrl = j?.payment?.payUrl || null;
- // Refresh detail so the tier flips to "Current plan" and the others lock.
- await loadDetail(agent.id);
-
- // Reuse the polished payment success card for the confirmation + the
- // real first-payment link (server builds an x402 checkout intent).
- const overlay = $('payment-modal-overlay');
- if (overlay) overlay.hidden = false;
- renderPaymentSuccess({
- title: 'Subscription started',
- message: payUrl
- ? `You're subscribed to ${tier.name}. Complete your first ${intervalLabel}'s payment to activate every perk.`
- : `You're subscribed to ${tier.name}.`,
- primaryHref: payUrl,
- primaryLabel: payUrl ? 'Complete payment' : null,
- secondaryLabel: 'Done',
- });
- } catch (err) {
- if (status) {
- status.textContent = err.message || 'Network error — try again.';
- status.className = 'd-subs-status err';
- }
- if (btn) {
- btn.disabled = false;
- btn.textContent = 'Subscribe';
- }
+ btn.textContent = 'Opening checkout…';
}
+ location.href = `/agents/${encodeURIComponent(agent.id)}?tier=${encodeURIComponent(tier.id)}#ad-tiers-card`;
}
async function manageSubscription(subId, btn) {
diff --git a/tests/subscriptions-endpoints.test.js b/tests/subscriptions-endpoints.test.js
index 97d32b920..a8a14756e 100644
--- a/tests/subscriptions-endpoints.test.js
+++ b/tests/subscriptions-endpoints.test.js
@@ -218,6 +218,22 @@ describe('subscriptions: unchanged contract', () => {
expect(parse(res).error_description).toMatch(/your own plan/);
});
+ it('POST /api/subscriptions records the tier unpaid, never active, until a verified payment', async () => {
+ const SUBSCRIBER = '00000000-0000-4000-8000-0000000000aa';
+ getSessionUserMock.mockResolvedValue({ id: SUBSCRIBER });
+ sqlQueue = [
+ [{ id: PLAN, creator_id: OWNER, price_usd: '9.99', interval: 'monthly', active: true }],
+ [],
+ [{ id: 'sub-1', status: 'past_due' }],
+ ];
+ const res = mkRes();
+ await subsHandler(jsonReq('POST', '/api/subscriptions', { plan_id: PLAN }), res);
+ expect(res.statusCode).toBe(201);
+ const insert = sqlMock.mock.calls.map((c) => c[0].join('?')).find((t) => /INSERT INTO creator_subscriptions/.test(t));
+ expect(insert).toMatch(/'past_due'/);
+ expect(insert).not.toMatch(/'active'/);
+ });
+
it('GET /api/subscriptions/plans still requires creator_id or agent_id', async () => {
const res = mkRes();
await plansHandler(mkReq({ url: '/api/subscriptions/plans' }), res);