Skip to content

Implement Stripe portal to allow usage-based customers to manage their billing details #10555

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 10, 2022
Merged
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
36 changes: 26 additions & 10 deletions components/dashboard/src/teams/TeamUsageBasedBilling.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default function TeamUsageBasedBilling() {
const [showBillingSetupModal, setShowBillingSetupModal] = useState<boolean>(false);
const [pendingStripeCustomer, setPendingStripeCustomer] = useState<PendingStripeCustomer | undefined>();
const [pollStripeCustomerTimeout, setPollStripeCustomerTimeout] = useState<NodeJS.Timeout | undefined>();
const [stripePortalUrl, setStripePortalUrl] = useState<string | undefined>();

useEffect(() => {
if (!team) {
Expand All @@ -46,6 +47,16 @@ export default function TeamUsageBasedBilling() {
})();
}, [team]);

useEffect(() => {
if (!team || !stripeCustomerId) {
return;
}
(async () => {
const portalUrl = await getGitpodService().server.getStripePortalUrlForTeam(team.id);
setStripePortalUrl(portalUrl);
})();
}, [team, stripeCustomerId]);

useEffect(() => {
if (!team) {
return;
Expand Down Expand Up @@ -144,9 +155,11 @@ export default function TeamUsageBasedBilling() {
<div className="text-xl font-semibold flex-grow text-gray-600 dark:text-gray-400">
Active
</div>
{/* <button className="self-end secondary" disabled={true}>
Manage →
</button> */}
<a className="self-end" href={stripePortalUrl}>
<button className="secondary" disabled={!stripePortalUrl}>
Manage Billing →
</button>
</a>
</>
)}
</div>
Expand All @@ -156,6 +169,12 @@ export default function TeamUsageBasedBilling() {
);
}

function getStripeAppearance(isDark?: boolean): Appearance {
return {
theme: isDark ? "night" : "stripe",
};
}

function BillingSetupModal(props: { onClose: () => void }) {
const { isDark } = useContext(ThemeContext);
const [stripePromise, setStripePromise] = useState<Promise<Stripe | null> | undefined>();
Expand All @@ -169,20 +188,17 @@ function BillingSetupModal(props: { onClose: () => void }) {
]).then((setters) => setters.forEach((s) => s()));
}, []);

const getStripeAppearance = (): Appearance => {
return {
theme: isDark ? "night" : "stripe",
};
};

return (
<Modal visible={true} onClose={props.onClose}>
<h3 className="flex">Upgrade Billing</h3>
<div className="border-t border-gray-200 dark:border-gray-800 mt-4 pt-2 h-96 -mx-6 px-6 flex flex-col">
{!!stripePromise && !!stripeSetupIntentClientSecret && (
<Elements
stripe={stripePromise}
options={{ appearance: getStripeAppearance(), clientSecret: stripeSetupIntentClientSecret }}
options={{
appearance: getStripeAppearance(isDark),
clientSecret: stripeSetupIntentClientSecret,
}}
>
<CreditCardInputForm />
</Elements>
Expand Down
1 change: 1 addition & 0 deletions components/gitpod-protocol/src/gitpod-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ export interface GitpodServer extends JsonRpcServer<GitpodClient>, AdminServer,
getStripeSetupIntentClientSecret(): Promise<string>;
findStripeCustomerIdForTeam(teamId: string): Promise<string | undefined>;
subscribeTeamToStripe(teamId: string, setupIntentId: string): Promise<void>;
getStripePortalUrlForTeam(teamId: string): Promise<string>;

/**
* Analytics
Expand Down
12 changes: 12 additions & 0 deletions components/server/ee/src/user/stripe-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,16 @@ export class StripeService {
});
return customer;
}

async getPortalUrlForTeam(team: Team): Promise<string> {
const customer = await this.findCustomerByTeamId(team.id);
if (!customer) {
throw new Error(`No Stripe Customer ID found for team '${team.id}'`);
}
const session = await this.getStripe().billingPortal.sessions.create({
customer: customer.id,
return_url: this.config.hostUrl.with(() => ({ pathname: `/t/${team.slug}/billing` })).toString(),
});
return session.url;
}
}
17 changes: 17 additions & 0 deletions components/server/ee/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1906,6 +1906,23 @@ export class GitpodServerEEImpl extends GitpodServerImpl {
}
}

async getStripePortalUrlForTeam(ctx: TraceContext, teamId: string): Promise<string> {
const user = this.checkAndBlockUser("getStripePortalUrlForTeam");
await this.ensureIsUsageBasedFeatureFlagEnabled(user);
await this.guardTeamOperation(teamId, "update");
const team = await this.teamDB.findTeamById(teamId);
try {
const url = await this.stripeService.getPortalUrlForTeam(team!);
return url;
} catch (error) {
log.error(`Failed to get Stripe portal URL for team '${teamId}'`, error);
throw new ResponseError(
ErrorCodes.INTERNAL_SERVER_ERROR,
`Failed to get Stripe portal URL for team '${teamId}'`,
);
}
}

// (SaaS) – admin
async adminGetAccountStatement(ctx: TraceContext, userId: string): Promise<AccountStatement> {
traceAPIParams(ctx, { userId });
Expand Down
1 change: 1 addition & 0 deletions components/server/src/auth/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ function getConfig(config: RateLimiterConfig): RateLimiterConfig {
getStripeSetupIntentClientSecret: { group: "default", points: 1 },
findStripeCustomerIdForTeam: { group: "default", points: 1 },
subscribeTeamToStripe: { group: "default", points: 1 },
getStripePortalUrlForTeam: { group: "default", points: 1 },
trackEvent: { group: "default", points: 1 },
trackLocation: { group: "default", points: 1 },
identifyUser: { group: "default", points: 1 },
Expand Down
3 changes: 3 additions & 0 deletions components/server/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3045,6 +3045,9 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {
async subscribeTeamToStripe(ctx: TraceContext, teamId: string, setupIntentId: string): Promise<void> {
throw new ResponseError(ErrorCodes.SAAS_FEATURE, `Not implemented in this version`);
}
async getStripePortalUrlForTeam(ctx: TraceContext, teamId: string): Promise<string> {
throw new ResponseError(ErrorCodes.SAAS_FEATURE, `Not implemented in this version`);
}
//
//#endregion
}