The billing cycle on the Stripe invoice does not match up

I'm currently in the process of integrating Stripe into my SaaS platform, and I've encountered an issue with calculating the quota based on the payment period. Despite setting the plan as monthly, Stripe is returning a period from the 70s through the webhook, starting and ending on the same day.

// webhook

import Stripe from "stripe";
import { headers } from "next/headers";

import {
  processWebhookInvoiceSuccess,
  processWebhookSubscription,
  stripe,
} from "@/services/stripe";

export async function POST(req: Request) {
  const body = await req.text();
  const signature = headers().get("Stripe-Signature") as string;

  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET
    );
  } catch (error: any) {
    console.error(`Webhook Error: ${error.message}`);
    return new Response(`Webhook Error: ${error.message}`, { status: 400 });
  }

  switch (event.type) {
    case "customer.subscription.created":
    case "customer.subscription.updated":
      await processWebhookSubscription(event.data.object);
      break;
    case "invoice.payment_succeeded":
      await processWebhookInvoiceSuccess(event.data.object);
    default:
      console.log(`Unhandled event type ${event.type}`);
  }

  return Response.json({ ok: true }, { status: 200 });
}

Answer №1

Thanks for your help, I managed to figure it out on my own. I made some changes to the approach and it seems to be working fine

async function processWebhookInvoiceSuccess(obj: Stripe.Invoice) {
  if (!user) throw new Error("unable to find invoice user");

  await prisma.user.update({
    where: { id: user.id },
    data: {
      latestInvoiceStart: new Date(obj.lines.data[0].period.start * 1000),
      latestInvoiceEnds: new Date(obj.lines.data[0].period.end * 1000),
    },
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to extract the chosen option from a bound list within an Angular application

Our goal is to avoid using 2-way binding in our component setup: <select type="text" formControlName="region" (change)="regionChanged($event)"> <option *ngFor="let region of regionsDDL" [ngValue]="region">{{region.name}}</option> ...

Angular is throwing an error when trying to create a new service: "Workspace must be loaded before it can be used."

Having trouble adding pusher.js to my angular.json file. After trying to create a new service, I encountered the following error: Error: Workspace needs to be loaded before it is used. Any tips on how to resolve this? I attempted to update the angular cl ...

What is the best way to manage multiple directives from a parent component?

Within my app-landing component, I have implemented multiple typeOut directives. These directives are responsible for gradually writing out text within their respective elements. While this functionality is working as intended, I now seek to exert control ...

What is the best way to merge multiple nested angular flattening operators together?

I am facing a challenge in utilizing the outcomes of Observables from various functions. Some of these functions must be executed sequentially, while others can run independently. Additionally, I need to pass the result of the initial function to some nest ...

Developing a GraphQL application with NestJS integrating the Passport LinkedIn strategy

Currently, my nestjs application is up and running on typescript, Graphql, Postgres with Jwt strategy all set. Now, I am looking to integrate the LinkedIn strategy into it. However, I'm unsure about where to begin as most available packages like do no ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

Tips for creating parameterized keys for a specific type in Typescript

I've encountered a challenge while transitioning my react-native project from Flow to TypeScript. The stumbling block is recreating this specific type from Flow: declare type ApolloData<T, nodeName: string = 'node'> = { [nodeName]: ...

Issue encountered with Azure DevOps during TypeScript (TS) build due to a type mismatch error: 'false' being unable to be assigned to type 'Date'. Conversely, the build functions correctly when run locally, despite the type being defined as 'Date | boolean'

I am facing an issue with my NestJS API while trying to build it using Azure DevOps pipeline. The build fails with the following error: src/auth/auth.controller.ts(49,7): error TS2322: Type 'false' is not assignable to type 'Date'. src/ ...

Discover the seamless transformation of a class definition into a Vue 3 component definition utilizing the dazzling 'tc39' decorators

The proposed API in the tc39/proposal-decorators repository is significantly different from the previous decorators API. Although TypeScript 5 doesn't fully support the new API yet, it's only a matter of time before the old API becomes deprecated ...

The deletion by index feature seems to be malfunctioning in Angular

Is there a way to delete an item by its ID instead of just deleting the last element using this code? I want to create input fields with a delete button next to each one simultaneously. TS: public inputs: boolean[] = []; public addNew(): void { this ...

Implementing payment for multiple stripe accounts using node.js

I have a requirement to integrate multiple sellers' payments using Stripe. Each seller is connected to the master account, and I need to split the payment among them for items in the cart. const cart = await Cart.findById(record.cartId); const ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

Using `querySelector` in TypeScript with Vue 3

Encountered a TypeScript error while using the Vue Composition API let myElement = document.querySelectorAll('my-element') The TS error I'm getting when trying to access it like this: Property '_props' does not exist on type ...

Is there a way to dynamically change an icon based on certain conditions using typescript?

I am struggling with displaying icons in my TypeScript code using Material Icons. I need to dynamically change the icon based on a condition, for example if the power is false I want to display 'power_off', but if it's true then I want to di ...

Eliminate the "Potential 'undefined' Object" error without resorting to non-null assertion or optional chaining

Below is the code snippet I am working with: export type ConditionalItemType = [ { condition: string }, { [key: string]: FormItemDataType } ]; export type ConditionalItemDataType = ConditionalItemType[]; export type FormItemDataType = { required: bo ...

Using TypeScript to automatically deduce the output type of a function by analyzing the recursive input type

I am currently working on developing an ORM for a graph database using TypeScript. Specifically, I am focusing on enhancing the "find" method to retrieve a list of a specific entity. The goal is to allow the function to accept a structure detailing the joi ...

Encountered an issue with valid types while executing the following build

Encountering an error when attempting to run the next build process. https://i.stack.imgur.com/qM3Nm.png Tried various solutions including updating to ES6, switching the module to commonJs, downgrading webpack to version 4 with no success. The only worka ...

Converting a specific string format to a Date object in TypeScript

I am in need of a solution to convert strings with the given format into Date objects using TypeScript: var dateTimeString:string = "20231002-123343" I have created my own method as shown below: var dateTime:string[] = dateTimeString.split(" ...

Why do callbacks in Typescript fail to compile when their arguments don't match?

In my current project, I encountered a scenario where a React callback led to a contrived example. interface A { a: string b: string } interface B { a: string b: string c: string } function foo(fn: (a: A) => void, a: A) { fn( ...