Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
d4a1163
app initialization
TChukwuleta Apr 25, 2025
07d4b9d
btcpay-calcom payment
TChukwuleta Apr 26, 2025
464b796
include logo and images
TChukwuleta May 8, 2025
afd2dab
resolve comments
TChukwuleta May 10, 2025
a07d8cf
include USD and webhook cleaning
TChukwuleta May 12, 2025
d5de43a
currency display
TChukwuleta May 14, 2025
9d204da
fix type error
TChukwuleta May 29, 2025
2127f4f
payment service create error
TChukwuleta May 29, 2025
463b1a0
type error fix
TChukwuleta May 29, 2025
eb25663
Merge branch 'main' into main
anikdhabal Jun 16, 2025
9b2267a
icon update
TChukwuleta Jun 16, 2025
ade468d
bot feedback update
TChukwuleta Jun 19, 2025
c7182d2
Remove console
TChukwuleta Jun 19, 2025
1db07dc
Remove currency suffix in price
TChukwuleta Jun 19, 2025
53ee4ac
Merge branch 'main' into main
anikdhabal Jul 7, 2025
33bafc4
Merge branch 'main' into main
anikdhabal Jul 25, 2025
ea5e61b
fix coderRabbit comment
TChukwuleta Jul 25, 2025
f5fffc0
resolve extra comments
TChukwuleta Jul 25, 2025
4d164ab
Merge branch 'main' of https://github.com/calcom/cal.com into TChukwu…
hariombalhara Jul 28, 2025
f9700ec
Use repositories and declarative installation ocode for app
hariombalhara Jul 28, 2025
6d19ed8
use PrismaBookingPaymentRepository as well as fix UI view
TChukwuleta Jul 28, 2025
1d5d252
Avoid fetching booking just for title which is already passed to crea…
hariombalhara Jul 29, 2025
f706536
fix type issues
TChukwuleta Jul 29, 2025
10d24fe
return 200 if payment is already processed
TChukwuleta Jul 29, 2025
2e847be
Merge branch 'main' into main
zomars Jul 29, 2025
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
1 change: 1 addition & 0 deletions apps/web/pages/api/integrations/btcpayserver/webhook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default, config } from "@calcom/app-store/btcpayserver/api/webhook";
1 change: 1 addition & 0 deletions packages/app-store/_pages/setup/_getServerSideProps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const AppSetupPageMap = {
zapier: import("../../zapier/pages/setup/_getServerSideProps"),
stripe: import("../../stripepayment/pages/setup/_getServerSideProps"),
hitpay: import("../../hitpay/pages/setup/_getServerSideProps"),
btcpayserver: import("../../btcpayserver/pages/setup/_getServerSideProps"),
};

export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
Expand Down
1 change: 1 addition & 0 deletions packages/app-store/_pages/setup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const AppSetupMap = {
stripe: dynamic(() => import("../../stripepayment/pages/setup")),
paypal: dynamic(() => import("../../paypal/pages/setup")),
hitpay: dynamic(() => import("../../hitpay/pages/setup")),
btcpayserver: dynamic(() => import("../../btcpayserver/pages/setup")),
};

export const AppSetupPage = (props: { slug: string }) => {
Expand Down
2 changes: 2 additions & 0 deletions packages/app-store/apps.browser.generated.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const AppSettingsComponentsMap = {
export const EventTypeAddonMap = {
alby: dynamic(() => import("./alby/components/EventTypeAppCardInterface")),
basecamp3: dynamic(() => import("./basecamp3/components/EventTypeAppCardInterface")),
btcpayserver: dynamic(() => import("./btcpayserver/components/EventTypeAppCardInterface")),
closecom: dynamic(() => import("./closecom/components/EventTypeAppCardInterface")),
fathom: dynamic(() => import("./fathom/components/EventTypeAppCardInterface")),
ga4: dynamic(() => import("./ga4/components/EventTypeAppCardInterface")),
Expand Down Expand Up @@ -54,6 +55,7 @@ export const EventTypeAddonMap = {
export const EventTypeSettingsMap = {
alby: dynamic(() => import("./alby/components/EventTypeAppSettingsInterface")),
basecamp3: dynamic(() => import("./basecamp3/components/EventTypeAppSettingsInterface")),
btcpayserver: dynamic(() => import("./btcpayserver/components/EventTypeAppSettingsInterface")),
fathom: dynamic(() => import("./fathom/components/EventTypeAppSettingsInterface")),
ga4: dynamic(() => import("./ga4/components/EventTypeAppSettingsInterface")),
giphy: dynamic(() => import("./giphy/components/EventTypeAppSettingsInterface")),
Expand Down
2 changes: 2 additions & 0 deletions packages/app-store/apps.keys-schemas.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
**/
import { appKeysSchema as alby_zod_ts } from "./alby/zod";
import { appKeysSchema as basecamp3_zod_ts } from "./basecamp3/zod";
import { appKeysSchema as btcpayserver_zod_ts } from "./btcpayserver/zod";
import { appKeysSchema as closecom_zod_ts } from "./closecom/zod";
import { appKeysSchema as dailyvideo_zod_ts } from "./dailyvideo/zod";
import { appKeysSchema as dub_zod_ts } from "./dub/zod";
Expand Down Expand Up @@ -54,6 +55,7 @@ import { appKeysSchema as zoomvideo_zod_ts } from "./zoomvideo/zod";
export const appKeysSchemas = {
alby: alby_zod_ts,
basecamp3: basecamp3_zod_ts,
btcpayserver: btcpayserver_zod_ts,
closecom: closecom_zod_ts,
dailyvideo: dailyvideo_zod_ts,
dub: dub_zod_ts,
Expand Down
2 changes: 2 additions & 0 deletions packages/app-store/apps.metadata.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import autocheckin_config_json from "./autocheckin/config.json";
import baa_for_hipaa_config_json from "./baa-for-hipaa/config.json";
import basecamp3_config_json from "./basecamp3/config.json";
import bolna_config_json from "./bolna/config.json";
import btcpayserver_config_json from "./btcpayserver/config.json";
import { metadata as caldavcalendar__metadata_ts } from "./caldavcalendar/_metadata";
import campfire_config_json from "./campfire/config.json";
import chatbase_config_json from "./chatbase/config.json";
Expand Down Expand Up @@ -117,6 +118,7 @@ export const appStoreMetadata = {
"baa-for-hipaa": baa_for_hipaa_config_json,
basecamp3: basecamp3_config_json,
bolna: bolna_config_json,
btcpayserver: btcpayserver_config_json,
caldavcalendar: caldavcalendar__metadata_ts,
campfire: campfire_config_json,
chatbase: chatbase_config_json,
Expand Down
2 changes: 2 additions & 0 deletions packages/app-store/apps.schemas.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
**/
import { appDataSchema as alby_zod_ts } from "./alby/zod";
import { appDataSchema as basecamp3_zod_ts } from "./basecamp3/zod";
import { appDataSchema as btcpayserver_zod_ts } from "./btcpayserver/zod";
import { appDataSchema as closecom_zod_ts } from "./closecom/zod";
import { appDataSchema as dailyvideo_zod_ts } from "./dailyvideo/zod";
import { appDataSchema as dub_zod_ts } from "./dub/zod";
Expand Down Expand Up @@ -54,6 +55,7 @@ import { appDataSchema as zoomvideo_zod_ts } from "./zoomvideo/zod";
export const appDataSchemas = {
alby: alby_zod_ts,
basecamp3: basecamp3_zod_ts,
btcpayserver: btcpayserver_zod_ts,
closecom: closecom_zod_ts,
dailyvideo: dailyvideo_zod_ts,
dub: dub_zod_ts,
Expand Down
1 change: 1 addition & 0 deletions packages/app-store/apps.server.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const apiHandlers = {
"baa-for-hipaa": import("./baa-for-hipaa/api"),
basecamp3: import("./basecamp3/api"),
bolna: import("./bolna/api"),
btcpayserver: import("./btcpayserver/api"),
caldavcalendar: import("./caldavcalendar/api"),
campfire: import("./campfire/api"),
chatbase: import("./chatbase/api"),
Expand Down
8 changes: 8 additions & 0 deletions packages/app-store/btcpayserver/DESCRIPTION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
items:
- website.png
- integrations.png
- checkout.png
---

{DESCRIPTION}
19 changes: 19 additions & 0 deletions packages/app-store/btcpayserver/api/add.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { AppDeclarativeHandler } from "@calcom/types/AppHandler";

import { createDefaultInstallation } from "../../_utils/installation";
import appConfig from "../config.json";

const handler: AppDeclarativeHandler = {
appType: appConfig.type,
variant: appConfig.variant,
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
redirect: {
url: "/apps/btcpayserver/setup",
},
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
};

export default handler;
2 changes: 2 additions & 0 deletions packages/app-store/btcpayserver/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as add } from "./add";
export { default as webhook, config } from "./webhook";
100 changes: 100 additions & 0 deletions packages/app-store/btcpayserver/api/webhook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import crypto from "crypto";
import type { NextApiRequest, NextApiResponse } from "next";
import getRawBody from "raw-body";
import { z } from "zod";

import { IS_PRODUCTION } from "@calcom/lib/constants";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { HttpError as HttpCode } from "@calcom/lib/http-error";
import { handlePaymentSuccess } from "@calcom/lib/payment/handlePaymentSuccess";
import { PrismaBookingPaymentRepository as BookingPaymentRepository } from "@calcom/lib/server/repository/PrismaBookingPaymentRepository";

import appConfig from "../config.json";
import { btcpayCredentialKeysSchema } from "../lib/btcpayCredentialKeysSchema";

export const config = { api: { bodyParser: false } };

function verifyBTCPaySignature(rawBody: Buffer, expectedSignature: string, webhookSecret: string): string {
const hmac = crypto.createHmac("sha256", webhookSecret);
hmac.update(rawBody);
const computedSignature = hmac.digest("hex");
const hexRegex = /^[0-9a-fA-F]+$/;
if (!hexRegex.test(computedSignature) || !hexRegex.test(expectedSignature)) {
throw new HttpCode({ statusCode: 400, message: "signature mismatch" });
}
return computedSignature;
}

const btcpayWebhookSchema = z.object({
deliveryId: z.string(),
webhookId: z.string(),
originalDeliveryId: z.string().optional(),
isRedelivery: z.boolean(),
type: z.string(),
timestamp: z.number(),
storeId: z.string(),
invoiceId: z.string(),
metadata: z.object({}).optional(),
manuallyMarked: z.boolean().optional(),
overPaid: z.boolean(),
});
const SUPPORTED_INVOICE_EVENTS = ["InvoiceSettled", "InvoiceProcessing"];

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
if (req.method !== "POST") throw new HttpCode({ statusCode: 405, message: "Method Not Allowed" });
const rawBody = await getRawBody(req);
const bodyAsString = rawBody.toString();

const signature = req.headers["btcpay-sig"] || req.headers["BTCPay-Sig"];
if (!signature || typeof signature !== "string" || !signature.startsWith("sha256="))
throw new HttpCode({ statusCode: 401, message: "Missing or invalid signature format" });

const webhookData = btcpayWebhookSchema.safeParse(JSON.parse(bodyAsString));
if (!webhookData.success) return res.status(400).json({ message: "Invalid webhook payload" });

const data = webhookData.data;
if (!SUPPORTED_INVOICE_EVENTS.includes(data.type))
return res.status(200).send({ message: "Webhook received but ignored" });

const bookingPaymentRepository = new BookingPaymentRepository();
const payment = await bookingPaymentRepository.findByExternalIdIncludeBookingUserCredentials(
data.invoiceId,
appConfig.type
);
if (!payment) throw new HttpCode({ statusCode: 404, message: "Cal.com: payment not found" });
if (payment.success) return res.status(200).send({ message: "Payment already registered" });
const key = payment.booking?.user?.credentials?.[0].key;
if (!key) throw new HttpCode({ statusCode: 404, message: "Cal.com: credentials not found" });

const parsedKey = btcpayCredentialKeysSchema.safeParse(key);
if (!parsedKey.success)
throw new HttpCode({ statusCode: 400, message: "Cal.com: Invalid BTCPay credentials" });

const { webhookSecret, storeId } = parsedKey.data;
if (storeId !== data.storeId)
throw new HttpCode({ statusCode: 400, message: "Cal.com: Store ID mismatch" });

const expectedSignature = signature.split("=")[1];
const computedSignature = verifyBTCPaySignature(rawBody, expectedSignature, webhookSecret);

if (computedSignature.length !== expectedSignature.length) {
throw new HttpCode({ statusCode: 400, message: "signature mismatch" });
}
const isValid = crypto.timingSafeEqual(
Buffer.from(computedSignature, "hex"),
Buffer.from(expectedSignature, "hex")
);
if (!isValid) throw new HttpCode({ statusCode: 400, message: "signature mismatch" });

await handlePaymentSuccess(payment.id, payment.bookingId);
return res.status(200).json({ success: true });
} catch (_err) {
const err = getErrorFromUnknown(_err);
const statusCode = err instanceof HttpCode ? err.statusCode : 500;
return res.status(statusCode).send({
message: err.message,
stack: IS_PRODUCTION ? undefined : err.stack,
});
}
}
150 changes: 150 additions & 0 deletions packages/app-store/btcpayserver/components/BtcpayPaymentComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"use client";

import { useEffect, useState } from "react";
import z from "zod";

import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useCopy } from "@calcom/lib/hooks/useCopy";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { Button } from "@calcom/ui/components/button";
import { Spinner } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";

interface IPaymentComponentProps {
payment: {
// Will be parsed on render
data: unknown;
};
paymentPageProps: PaymentPageProps;
}

// Create zod schema for data
const PaymentBTCPayDataSchema = z.object({
invoice: z.object({ checkoutLink: z.string() }).required(),
});

export const BtcpayPaymentComponent = (props: IPaymentComponentProps) => {
const { payment } = props;
const { data } = payment;
const [iframeLoaded, setIframeLoaded] = useState(false);
const { copyToClipboard, isCopied } = useCopy();
const wrongUrl = (
<>
<p className="mt-3 text-center">Couldn&apos;t obtain payment URL</p>
</>
);

const parsedData = PaymentBTCPayDataSchema.safeParse(data);
if (!parsedData.success || !parsedData.data?.invoice?.checkoutLink) return wrongUrl;
const checkoutUrl = parsedData.data.invoice.checkoutLink;
const handleOpenInNewTab = () => {
window.open(checkoutUrl, "_blank", "noopener,noreferrer");
};

return (
<div className="mb-4 mt-8 flex h-full w-full flex-col items-center justify-center gap-4">
<PaymentChecker {...props.paymentPageProps} />

{!iframeLoaded && (
<div className="flex items-center justify-center">
<Spinner className="mr-2 h-5 w-5" />
<p>Loading payment page...</p>
</div>
)}

<div className={`w-full ${iframeLoaded ? "block" : "hidden"}`}>
<iframe
src={checkoutUrl}
title="BTCPay Payment"
className="h-[1000px] w-full rounded-md border-0"
onLoad={() => setIframeLoaded(true)}
/>
</div>

<div className="flex flex-row flex-wrap items-center justify-center gap-4">
<Button
size="sm"
color="secondary"
onClick={() => copyToClipboard(checkoutUrl)}
className="text-subtle rounded-md"
StartIcon={isCopied ? "clipboard-check" : "clipboard"}>
Copy Payment Link
</Button>

<Button onClick={handleOpenInNewTab}>Open in New Tab</Button>
</div>
</div>
);
};

type PaymentCheckerProps = PaymentPageProps;

function PaymentChecker(props: PaymentCheckerProps) {
// TODO: move booking success code to a common lib function
// TODO: subscribe rather than polling
const searchParams = useCompatSearchParams();
const bookingSuccessRedirect = useBookingSuccessRedirect();
const utils = trpc.useUtils();
const { t } = useLocale();

useEffect(() => {
if (searchParams === null) {
return;
}

// use closure to ensure non-nullability
const sp = searchParams;
const interval = setInterval(() => {
(async () => {
try {
if (props.booking.status === "ACCEPTED") {
return;
}
const { booking: bookingResult } = await utils.viewer.bookings.find.fetch({
bookingUid: props.booking.uid,
});

if (bookingResult?.paid) {
showToast("Payment successful", "success");

const params: {
uid: string;
email: string | null;
location: string;
} = {
uid: props.booking.uid,
email: sp.get("email"),
location: t("web_conferencing_details_to_follow"),
};

bookingSuccessRedirect({
successRedirectUrl: props.eventType.successRedirectUrl,
query: params,
booking: props.booking,
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect,
});
}
} catch (e) {}
})();
}, 2000);

return () => clearInterval(interval);
}, [
bookingSuccessRedirect,
props.booking,
props.booking.id,
props.booking.status,
props.eventType.id,
props.eventType.successRedirectUrl,
props.eventType.forwardParamsSuccessRedirect,
props.payment.success,
searchParams,
t,
utils.viewer.bookings,
]);

return null;
}
Loading
Loading