Skip to content

Commit

Permalink
Functions: Handle "charge.updated" events to process updated balance …
Browse files Browse the repository at this point in the history
…transactions from Stripe
  • Loading branch information
mkue committed Jan 11, 2025
1 parent cf72cee commit 1089964
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
9 changes: 5 additions & 4 deletions functions/src/webhooks/stripe/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { DocumentReference, DocumentSnapshot } from 'firebase-admin/firestore';
import { logger } from 'firebase-functions';
import { onRequest } from 'firebase-functions/v2/https';
import Stripe from 'stripe';
import { FirestoreAdmin } from '../../../../shared/src/firebase/admin/FirestoreAdmin';
import { SendgridSubscriptionClient } from '../../../../shared/src/sendgrid/SendgridSubscriptionClient';
import { StripeEventHandler } from '../../../../shared/src/stripe/StripeEventHandler';
Expand Down Expand Up @@ -43,12 +42,14 @@ export default onRequest(async (request, response) => {
try {
const sig = request.headers['stripe-signature']!;
const event = stripeEventHandler.constructWebhookEvent(request.rawBody, sig, STRIPE_WEBHOOK_SECRET);
const charge = event.data.object as Stripe.Charge;
switch (event.type) {
case 'charge.succeeded':
// The charge.succeeded events do sometimes not contain the balance_transaction, so we need to listen to charge.updated event
// to get the final balance_transaction and update the contribution document with the final amount.
case 'charge.updated':
case 'charge.failed': {
const contributionRef = await stripeEventHandler.handleChargeEvent(charge);
logger.info(`Charge event ${event.type} handled for charge ${charge.id}.`);
const contributionRef = await stripeEventHandler.handleChargeEvent(event.data.object);
logger.info(`Charge event ${event.type} handled for charge ${event.data.object.id}.`);
if (contributionRef) {
logger.info(`Created contribution ${contributionRef.id}. Adding contributor to newsletter.`);
try {
Expand Down
17 changes: 9 additions & 8 deletions shared/src/stripe/StripeEventHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ export class StripeEventHandler {

const checkoutMetadata = await this.getCheckoutMetadata(charge);

// We only store non-successful charges if the user already exists.
// This prevents us from having users in the database that never made a successful contribution.
if (
fullCharge.status === 'succeeded' ||
(await this.findFirestoreUser(await this.retrieveStripeCustomer(fullCharge.customer as string)))
) {
const firestoreUser = await this.findFirestoreUser(
await this.retrieveStripeCustomer(fullCharge.customer as string),
);
if (fullCharge.status === 'succeeded' || firestoreUser) {
// We only store non-successful charges if the user already exists.
// This prevents us from having users in the database that never made a successful contribution.
return await this.storeCharge(fullCharge, checkoutMetadata);
}
return null;
Expand Down Expand Up @@ -101,6 +101,7 @@ export class StripeEventHandler {
const plan = (charge.invoice as Stripe.Invoice)?.lines?.data[0]?.plan;
const monthlyInterval = plan?.interval === 'month' ? plan?.interval_count : plan?.interval === 'year' ? 12 : 0;
const balanceTransaction = charge.balance_transaction as Stripe.BalanceTransaction;

const contribution = {
source: ContributionSourceKey.STRIPE,
created: toFirebaseAdminTimestamp(DateTime.fromSeconds(charge.created)),
Expand Down Expand Up @@ -205,8 +206,8 @@ export class StripeEventHandler {
const contributionRef = (
userRef.collection(CONTRIBUTION_FIRESTORE_PATH) as CollectionReference<StripeContribution>
).doc(charge.id);
await contributionRef.set(contribution);
console.info(`Ingested ${charge.id} into firestore for user ${userRef.id}`);
await contributionRef.set(contribution, { merge: true });
console.info(`Updated contribution document: ${contributionRef.path}`);
await this.maybeUpdateCampaign(contribution);
return contributionRef;
};
Expand Down

0 comments on commit 1089964

Please sign in to comment.