perfect-postcode/frontend/src/hooks/useLicense.ts
2026-02-22 23:14:42 +00:00

40 lines
1.2 KiB
TypeScript

import { useState, useCallback } from 'react';
import { apiUrl, authHeaders, assertOk } from '../lib/api';
import { trackEvent } from '../lib/analytics';
export function useLicense() {
const [checkingOut, setCheckingOut] = useState(false);
const [error, setError] = useState<string | null>(null);
const startCheckout = useCallback(async (referralCode?: string) => {
trackEvent('Checkout Start', { has_referral: String(!!referralCode) });
setCheckingOut(true);
setError(null);
try {
const body: Record<string, string> = {};
if (referralCode) body.referral_code = referralCode;
const res = await fetch(apiUrl('checkout'), {
method: 'POST',
...authHeaders({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}),
});
assertOk(res, 'Checkout');
const data = await res.json();
if (data.url) {
trackEvent('Checkout Redirect');
window.location.href = data.url;
}
} catch (err) {
const msg = err instanceof Error ? err.message : 'Checkout failed';
setError(msg);
throw err;
} finally {
setCheckingOut(false);
}
}, []);
return { startCheckout, checkingOut, error };
}