Skip to content
Merged
74 changes: 59 additions & 15 deletions packages/app-store/stripepayment/lib/PaymentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { getErrorFromUnknown } from "@calcom/lib/errors";
import { ErrorWithCode } from "@calcom/lib/errors";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { BookingRepository } from "@calcom/lib/server/repository/booking";
import prisma from "@calcom/prisma";
import type { Booking, Payment, PaymentOption, Prisma } from "@calcom/prisma/client";
import type { EventTypeMetadata } from "@calcom/prisma/zod-utils";
Expand Down Expand Up @@ -86,17 +87,16 @@ export class PaymentService implements IAbstractPaymentService {
automatic_payment_methods: {
enabled: true,
},
metadata: {
identifier: "cal.com",
metadata: this.generateMetadata({
bookingId,
calAccountId: userId,
calUsername: username,
userId,
username,
bookerName,
bookerEmail: bookerEmail,
bookerPhoneNumber: bookerPhoneNumber ?? null,
eventTitle: eventTitle || "",
bookingTitle: bookingTitle || "",
},
}),
};

const paymentIntent = await this.stripe.paymentIntents.create(params, {
Expand Down Expand Up @@ -217,20 +217,18 @@ export class PaymentService implements IAbstractPaymentService {
}
}

async chargeCard(payment: Payment, _bookingId?: Booking["id"]): Promise<Payment> {
async chargeCard(payment: Payment, bookingId: Booking["id"]): Promise<Payment> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Signature change: ensure all call sites updated to required bookingId

chargeCard now requires bookingId (no optional param). Verify interface/type and usages are updated accordingly to avoid compile/runtime breaks.

Run:


🏁 Script executed:

#!/bin/bash
# 1) Check IAbstractPaymentService signature
rg -nP -C3 'IAbstractPaymentService' --type=ts --type=tsx

# 2) Find all call sites of chargeCard
rg -nP -C2 '\bchargeCard\s*\(' --type=ts --type=tsx

# 3) Sanity: ensure two args are passed (payment, bookingId)
rg -nP -C2 '\bchargeCard\s*\(\s*[^,]+,\s*[^)]+\)' --type=ts --type=tsx

Length of output: 268


🏁 Script executed:

#!/bin/bash
# 1) Check IAbstractPaymentService signature in TS files
rg -nP -C3 'interface\s+IAbstractPaymentService' -g '*.ts'

# 2) Find all call sites of chargeCard in TS files
rg -nP -C2 '\bchargeCard\s*\(' -g '*.ts'

# 3) Sanity: ensure two args are passed (payment, bookingId)
rg -nP -C2 '\bchargeCard\s*\(\s*[^,]+,\s*[^)]+\)' -g '*.ts'

Length of output: 5205


Require bookingId parameter across interface and all implementations

  • In packages/types/PaymentService.d.ts, change bookingId?: Booking["id"] to bookingId: Booking["id"]
  • Update stub in setupVitest.ts to async chargeCard(payment, bookingId)
  • In packages/app-store/paypal/lib/PaymentService.ts and packages/app-store/mock-payment-app/lib/PaymentService.ts, add (payment, bookingId) to chargeCard signature
  • Verify other store providers (hitpay, btcpayserver, alby) conform to the updated signature
🤖 Prompt for AI Agents
In packages/app-store/stripepayment/lib/PaymentService.ts around line 220, the
chargeCard method currently declares async chargeCard(payment: Payment,
bookingId is missing) — update the signature to async chargeCard(payment:
Payment, bookingId: Booking["id"]): Promise<Payment> to match the new required
bookingId in the interface; then update all call sites in this file to pass
bookingId. Also modify packages/types/PaymentService.d.ts to make bookingId
non-optional, change the stub in setupVitest.ts to async chargeCard(payment,
bookingId), and update chargeCard signatures in
packages/app-store/paypal/lib/PaymentService.ts and
packages/app-store/mock-payment-app/lib/PaymentService.ts; finally scan and
adjust other store providers (hitpay, btcpayserver, alby) and any tests or
usages to accept and forward the bookingId parameter.

try {
if (!this.credentials) {
throw new Error("Stripe credentials not found");
}

const stripeAppKeys = await prisma.app.findFirst({
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This variable is unused

select: {
keys: true,
},
where: {
slug: "stripe",
},
});
const bookingRepository = new BookingRepository(prisma);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We now need to get the booking to generate the metadata to send to Stripe

const booking = await bookingRepository.findByIdIncludeUserAndAttendees(bookingId);

if (!booking) {
throw new Error(`Booking ${bookingId} not found`);
}

const paymentObject = payment.data as unknown as StripeSetupIntentData;

Expand All @@ -252,13 +250,27 @@ export class PaymentService implements IAbstractPaymentService {
throw new Error(`Stripe paymentMethod does not exist for setupIntent ${setupIntent.id}`);
}

if (!booking.attendees[0]) {
throw new Error(`Booking attendees are empty for setupIntent ${setupIntent.id}`);
}

const params: Stripe.PaymentIntentCreateParams = {
amount: payment.amount,
currency: payment.currency,
customer: setupIntent.customer as string,
payment_method: setupIntent.payment_method as string,
off_session: true,
confirm: true,
metadata: this.generateMetadata({
bookingId,
userId: booking.user?.id,
username: booking.user?.username,
bookerName: booking.attendees[0].name,
bookerEmail: booking.attendees[0].email,
bookerPhoneNumber: booking.attendees[0].phoneNumber ?? null,
eventTitle: booking.eventType?.title || null,
bookingTitle: booking.title,
}),
Comment on lines +264 to +273
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Guard against empty/missing attendees to avoid runtime crash

booking.attendees[0] can be undefined (e.g., malformed data, edge imports). Add optional chaining and safe fallbacks.

Apply this diff:

-        metadata: this.generateMetadata({
-          bookingId,
-          userId: booking.user?.id,
-          username: booking.user?.username,
-          bookerName: booking.attendees[0].name,
-          bookerEmail: booking.attendees[0].email,
-          bookerPhoneNumber: booking.attendees[0].phoneNumber ?? null,
-          eventTitle: booking.eventType?.title || null,
-          bookingTitle: booking.title,
-        }),
+        metadata: this.generateMetadata({
+          bookingId,
+          userId: booking.user?.id ?? null,
+          username: booking.user?.username ?? null,
+          bookerName: booking.attendees?.[0]?.name ?? "",
+          bookerEmail: booking.attendees?.[0]?.email ?? "",
+          bookerPhoneNumber: booking.attendees?.[0]?.phoneNumber ?? null,
+          eventTitle: booking.eventType?.title ?? null,
+          bookingTitle: booking.title ?? "",
+        }),
🤖 Prompt for AI Agents
In packages/app-store/stripepayment/lib/PaymentService.ts around lines 260 to
269, metadata accesses booking.attendees[0] directly which can be undefined and
cause a runtime crash; change those accesses to use optional chaining and safe
fallbacks (e.g., booking.attendees?.[0]?.name ?? null,
booking.attendees?.[0]?.email ?? null, booking.attendees?.[0]?.phoneNumber ??
null) so bookerName, bookerEmail and bookerPhoneNumber always have defined safe
values before calling this.generateMetadata.

};

const paymentIntent = await this.stripe.paymentIntents.create(params, {
Expand All @@ -284,7 +296,7 @@ export class PaymentService implements IAbstractPaymentService {

return paymentData;
} catch (error) {
log.error("Stripe: Could not charge card for payment", _bookingId, safeStringify(error));
log.error("Stripe: Could not charge card for payment", bookingId, safeStringify(error));

const errorMappings = {
"your card was declined": "your_card_was_declined",
Expand Down Expand Up @@ -422,4 +434,36 @@ export class PaymentService implements IAbstractPaymentService {
isSetupAlready(): boolean {
return !!this.credentials;
}

private generateMetadata({
bookingId,
userId,
username,
bookerName,
bookerEmail,
bookerPhoneNumber,
eventTitle,
bookingTitle,
}: {
bookingId: number;
userId: number | null | undefined;
username: string | null | undefined;
bookerName: string;
bookerEmail: string;
bookerPhoneNumber: string | null;
eventTitle: string | null;
bookingTitle: string;
}) {
return {
identifier: "cal.com",
bookingId,
calAccountId: userId ?? null,
calUsername: username ?? null,
bookerName,
bookerEmail: bookerEmail,
bookerPhoneNumber: bookerPhoneNumber ?? null,
eventTitle: eventTitle || "",
bookingTitle: bookingTitle || "",
};
}
}
35 changes: 35 additions & 0 deletions packages/lib/server/repository/booking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,41 @@ export class BookingRepository {
});
}

async findByIdIncludeUserAndAttendees(bookingId: number) {
return await this.prismaClient.booking.findUnique({
where: {
id: bookingId,
},
select: {
...bookingMinimalSelect,
eventType: {
select: {
title: true,
},
},
user: {
select: {
id: true,
username: true,
},
},
attendees: {
select: {
name: true,
email: true,
phoneNumber: true,
},
// Ascending order ensures that the first attendee in the list is the booker and others are guests
// See why it is important https://github.com/calcom/cal.com/pull/20935
// TODO: Ideally we should return `booker` property directly from the booking
Comment on lines +414 to +416
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @joeauyeung made this change here

orderBy: {
id: "asc",
},
},
},
});
}

async findBookingForMeetingPage({ bookingUid }: { bookingUid: string }) {
return await this.prismaClient.booking.findUnique({
where: {
Expand Down
Loading
Loading