Skip to content

Commit

Permalink
Stripe-Ga-integration (#93)
Browse files Browse the repository at this point in the history
* add google analytics

* fix issue gtm cannot be added with ga in layout

* added GA events for stripe webhook route

* Leave Google Tag Manager

---------

Co-authored-by: Rodrigo Elizeu Cherutti <[email protected]>
  • Loading branch information
BrunoSette and PregoBS committed Oct 23, 2024
1 parent b39ad79 commit 0d4cd02
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 18 deletions.
8 changes: 1 addition & 7 deletions app/(dashboard)/pricing/submit-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,20 @@
import { Button } from "@/components/ui/button";
import { ArrowRight, Loader2 } from "lucide-react";
import { useFormStatus } from "react-dom";
import { sendGAEvent } from "@next/third-parties/google";

export function SubmitButton() {
const { pending } = useFormStatus();

const handleClick = () => {
sendGAEvent({ event: "conversion_event_begin_checkout", value: 1 });
};

return (
<Button
onClick={handleClick}
type="submit"
disabled={pending}
className="w-full bg-white hover:bg-orange-400 hover:text-white text-black border border-gray-200 rounded-full flex text-lg items-center justify-center"
>
{pending ? (
<div className="flex items-center">
<Loader2 className="animate-spin mr-2 h-4 w-4" />
Loading...
Loading..
</div>
) : (
<div className="flex items-center">
Expand Down
2 changes: 0 additions & 2 deletions app/(login)/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { Label } from "@/components/ui/label";
import { CircleIcon, Loader2 } from "lucide-react";
import { signIn, signUp, forgotPassword, resetPassword } from "./actions";
import { ActionState } from "@/lib/auth/middleware";
import { sendGAEvent } from "@next/third-parties/google";

const actionMap = {
signin: signIn,
Expand Down Expand Up @@ -161,7 +160,6 @@ export function Login({
type="submit"
className="w-full flex justify-center items-center py-2 px-4 border border-transparent rounded-full shadow-sm text-sm font-medium text-white bg-orange-600 hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500"
disabled={pending}
onClick={() => sendGAEvent("event", modeEvent)}
>
{pending ? (
<>
Expand Down
29 changes: 20 additions & 9 deletions app/api/stripe/webhook/route.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
import Stripe from 'stripe';
import { handleSubscriptionChange, stripe } from '@/lib/payments/stripe';
import { NextRequest, NextResponse } from 'next/server';
import Stripe from "stripe";
import {
handleSubscriptionChange,
handleSendGAEvent,
stripe,
} from "@/lib/payments/stripe";
import { NextRequest, NextResponse } from "next/server";

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

export async function POST(request: NextRequest) {
const payload = await request.text();
const signature = request.headers.get('stripe-signature') as string;
const signature = request.headers.get("stripe-signature") as string;

let event: Stripe.Event;

try {
event = stripe.webhooks.constructEvent(payload, signature, webhookSecret);
} catch (err) {
console.error('Webhook signature verification failed.', err);
console.error("Webhook signature verification failed.", err);
return NextResponse.json(
{ error: 'Webhook signature verification failed.' },
{ error: "Webhook signature verification failed." },
{ status: 400 }
);
}

const subscription = event.data.object as Stripe.Subscription;
const customerId = subscription.customer as string;
switch (event.type) {
case 'customer.subscription.updated':
case 'customer.subscription.deleted':
const subscription = event.data.object as Stripe.Subscription;
case "invoice.payment_failed":
await handleSendGAEvent(customerId, "purchase_failed");
break;
case "invoice.payment_succeeded":
await handleSendGAEvent(customerId, "manual_event_PURCHASE");
break;
case "customer.subscription.updated":
case "customer.subscription.deleted":
await handleSubscriptionChange(subscription);
break;
default:
Expand Down
21 changes: 21 additions & 0 deletions lib/payments/stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,27 @@ export async function createCustomerPortalSession(team: Team | null) {
});
}

export async function handleSendGAEvent(
customerId: string,
event: string,
) {
const MEASUREMENT_ID = process.env.GA_MEASUREMENT_ID; // GA4 Measurement ID
const API_SECRET = process.env.GA_MEASUREMENT_API_SECRET; // GA4 Measurement Protocol API secret

fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`, {
method: "POST",
body: JSON.stringify({
client_id: customerId,
events: [{
name: event,
params: {
customerId,
},
}]
})
});
}

export async function handleSubscriptionChange(
subscription: Stripe.Subscription
) {
Expand Down

0 comments on commit 0d4cd02

Please sign in to comment.