-
Notifications
You must be signed in to change notification settings - Fork 12k
feat: BTCPay Server App #21197
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
feat: BTCPay Server App #21197
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
d4a1163
app initialization
TChukwuleta 07d4b9d
btcpay-calcom payment
TChukwuleta 464b796
include logo and images
TChukwuleta afd2dab
resolve comments
TChukwuleta a07d8cf
include USD and webhook cleaning
TChukwuleta d5de43a
currency display
TChukwuleta 9d204da
fix type error
TChukwuleta 2127f4f
payment service create error
TChukwuleta 463b1a0
type error fix
TChukwuleta eb25663
Merge branch 'main' into main
anikdhabal 9b2267a
icon update
TChukwuleta ade468d
bot feedback update
TChukwuleta c7182d2
Remove console
TChukwuleta 1db07dc
Remove currency suffix in price
TChukwuleta 53ee4ac
Merge branch 'main' into main
anikdhabal 33bafc4
Merge branch 'main' into main
anikdhabal ea5e61b
fix coderRabbit comment
TChukwuleta f5fffc0
resolve extra comments
TChukwuleta 4d164ab
Merge branch 'main' of https://github.com/calcom/cal.com into TChukwu…
hariombalhara f9700ec
Use repositories and declarative installation ocode for app
hariombalhara 6d19ed8
use PrismaBookingPaymentRepository as well as fix UI view
TChukwuleta 1d5d252
Avoid fetching booking just for title which is already passed to crea…
hariombalhara f706536
fix type issues
TChukwuleta 10d24fe
return 200 if payment is already processed
TChukwuleta 2e847be
Merge branch 'main' into main
zomars File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { default, config } from "@calcom/app-store/btcpayserver/api/webhook"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| --- | ||
| items: | ||
| - website.png | ||
| - integrations.png | ||
| - checkout.png | ||
| --- | ||
|
|
||
| {DESCRIPTION} | ||
TChukwuleta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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=")) | ||
TChukwuleta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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( | ||
TChukwuleta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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
150
packages/app-store/btcpayserver/components/BtcpayPaymentComponent.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'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(() => { | ||
TChukwuleta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| (async () => { | ||
TChukwuleta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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) {} | ||
TChukwuleta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| })(); | ||
| }, 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; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.