Skip to content
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

Migrate over to Postmark from SendGrid #291

Open
wants to merge 10 commits into
base: chat-everywhere
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"notion-client": "^6.16.0",
"notion-utils": "^6.16.0",
"posthog-js": "^1.96.1",
"postmark": "^4.0.2",
"puppeteer": "^19.11.1",
"raw-body": "^2.5.2",
"react": "18.2.0",
Expand Down
60 changes: 30 additions & 30 deletions pages/api/cron/update-pro-accounts-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { ServerClient } from 'postmark';

dayjs.extend(utc);
dayjs.extend(timezone);
Expand Down Expand Up @@ -41,37 +42,36 @@ const handler = async (req: Request): Promise<Response> => {
}
};

const sendOutTrialEndEmail = async (userEmail: string) => {
const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
},
body: JSON.stringify({
from: {
email: 'team@chateverywhere.app',
name: 'Chat Everywhere Team',
},
reply_to: {
email: 'jack@exploratorlabs.com',
name: 'Jack',
},
personalizations: [
{
to: [
{
email: userEmail,
},
],
},
],
template_id: 'd-e5fff0aa9b5948b4871c436812392134',
}),
});
const postmarkClient = new ServerClient(process.env.POSTMARK_SERVER_TOKEN || '');

if (!response.ok) {
throw new Error(`Failed to send email: ${response.statusText}`);
const sendOutTrialEndEmail = async (userEmail: string) => {
try {
const response = await postmarkClient.sendEmailWithTemplate({
From: "Chat Everywhere Team <team@chateverywhere.app>",
ReplyTo: 'Jack <jack@exploratorlabs.com>',
To: userEmail,
TemplateId: 35875013, // Replace with your actual numeric template ID
TemplateModel: {
// The properties here should match the variables in your Postmark template
"product_url": "product_url_Value",
"product_name": "Chat Everywhere",
"action_url": "action_url_Value",
"trial_extension_url": "trial_extension_url_Value",
"feedback_url": "feedback_url_Value",
"export_url": "export_url_Value",
"close_account_url": "close_account_url_Value",
"sender_name": "sender_name_Value",
"company_name": "company_name_Value",
"company_address": "company_address_Value"
}
});
console.log('Email sent successfully:', response);
} catch (error) {
if (error instanceof Error) {
console.error('Failed to send email:', error.message);
} else {
console.error('An unexpected error occurred:', error);
}
}
};

Expand Down
79 changes: 79 additions & 0 deletions pages/api/webhooks/postmark.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { serverSideTrackEvent } from '@/utils/app/eventTracking';
import { getAdminSupabaseClient } from '@/utils/server/supabase';

type PostmarkPayload = {
RecordType: string;
MessageStream: string;
FirstOpen: boolean;
Client: {
Name: string;
Company: string;
Family: string;
};
OS: {
Name: string;
Company: string;
Family: string;
};
Platform: string;
UserAgent: string;
Geo: {
CountryISOCode: string;
Country: string;
RegionISOCode: string;
Region: string;
City: string;
Zip: string;
Coords: string;
IP: string;
};
MessageID: string;
Metadata: {
[key: string]: string;
};
ReceivedAt: string;
Tag: string;
Recipient: string;
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const payload: PostmarkPayload = req.body;

// Verifying the authenticity of request
if (req.method !== 'POST') {
res.status(405).end('Method Not Allowed');
}
const tokenHeaderName = 'x-custom-auth-token';
const expectedToken = process.env.POSTMARK_WEBHOOK_KEY;
const providedToken = req.headers[tokenHeaderName];
// Check if the token matches the expected value
if (!providedToken || providedToken !== expectedToken) {
res.status(401).end('Unauthorized');
return;
}

// Check if the RecordType is 'Open'
if (payload.RecordType === 'Open') {
const supabase = getAdminSupabaseClient();
// Fetch the user from your database using the recipient's email
const { data: user, error } = await supabase
.from('profiles')
.select('id, email')
.eq('email', payload.Recipient)
.single();
// If a user is found, track the event and log it
if (user) {
// Replace `serverSideTrackEvent` with your actual event tracking function
await serverSideTrackEvent(user.id, `Trial end email opened`);
console.log('Trial end email opened on user with email', user.email);
} else if (error) {
console.error('Error fetching user:', error);
} else {
console.log('No user found for:', payload.Recipient);
}
}

// Respond to Postmark to acknowledge receipt of the webhook
res.status(200).json({ message: 'Webhook received' });
}
71 changes: 0 additions & 71 deletions pages/api/webhooks/sendgrid.ts

This file was deleted.