impl/typescript.ts
2,277 bytes · the TypeScript implementation · view raw
import { chooseProvider } from "./funeio.ts";
import type { PortalRequest, PortalSession } from "./payments_stripe_portal_types.ts";
import { stripePortal } from "./payments_stripe_portal_adapter_stripe.ts";
import { localPortal } from "./payments_stripe_portal_adapter_local.ts";
const PROVIDERS = ["stripe", "local"];
const FLOWS = ["payment_method_update", "subscription_cancel", "subscription_update"];
/**
* Open the customer portal through the provider PAYMENTS_PROVIDER names. The
* request is checked first, so a malformed one never reaches Stripe.
*/
export async function createPortalSession(request: PortalRequest): Promise<PortalSession> {
if (!request || typeof request.customer !== "string" || !/^cus_[A-Za-z0-9]+$/.test(request.customer)) {
throw new Error(`customer ${JSON.stringify(request?.customer)} is not a Customer id (cus_...)`);
}
if (typeof request.returnUrl !== "string" || !/^https?:\/\/[^\s]+$/.test(request.returnUrl)) {
throw new Error("returnUrl is an absolute http(s) URL");
}
if (request.configuration != null && (typeof request.configuration !== "string" || !/^bpc_[A-Za-z0-9]+$/.test(request.configuration))) {
throw new Error(`configuration ${JSON.stringify(request.configuration)} is not a portal configuration id (bpc_...)`);
}
if (request.locale != null && (typeof request.locale !== "string" || !/^(auto|[a-z]{2}(-[A-Z]{2}|-[0-9]{3})?)$/.test(request.locale))) {
throw new Error(`locale ${JSON.stringify(request.locale)} is not a locale such as en, en-GB or auto`);
}
if (request.flow != null && !FLOWS.includes(request.flow)) {
throw new Error(`flow is one of ${FLOWS.join(", ")}`);
}
if (request.subscription != null && (typeof request.subscription !== "string" || !/^sub_[A-Za-z0-9]+$/.test(request.subscription))) {
throw new Error(`subscription ${JSON.stringify(request.subscription)} is not a Subscription id (sub_...)`);
}
if ((request.flow === "subscription_cancel" || request.flow === "subscription_update") && request.subscription == null) {
throw new Error(`flow ${request.flow} needs the subscription (sub_...)`);
}
const provider = chooseProvider("PAYMENTS_PROVIDER", PROVIDERS);
return provider === "stripe" ? stripePortal(request) : localPortal(request);
}