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

feat(api): stripe donations workflow #124

Merged
merged 4 commits into from
May 20, 2024
Merged
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
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ NEXT_PUBLIC_ATHLONIX_STORAGE_URL=
SUPABASE_DOMAIN=
API_URL=
NEXT_PUBLIC_API_URL=

STRIPE_API_KEY=sk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
7 changes: 4 additions & 3 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@
"dependencies": {
"@hono/node-server": "^1.11.1",
"@hono/swagger-ui": "^0.2.2",
"@hono/zod-openapi": "0.12.1",
"@hono/zod-openapi": "0.13.0",
"@hono/zod-validator": "^0.2.1",
"@repo/types": "workspace:*",
"@supabase/supabase-js": "^2.43.2",
"hono": "^4.3.7",
"hono": "^4.3.8",
"stripe": "^15.7.0",
"zod": "^3.23.8",
"zod-validation-error": "^3.3.0"
},
Expand All @@ -31,7 +32,7 @@
"@types/node": "^20.12.12",
"@types/swagger-ui-dist": "^3.30.4",
"supabase": "^1.167.4",
"tsx": "^4.10.4",
"tsx": "^4.10.5",
"typescript": "^5.4.5",
"vitest": "^1.6.0"
}
Expand Down
87 changes: 87 additions & 0 deletions apps/api/src/handlers/stripe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import type { Context } from 'hono';
import Stripe from 'stripe';
import { handleDonations } from '../libs/stripe.js';
import { supabase } from '../libs/supabase.js';
import { zodErrorHook } from '../libs/zodError.js';
import { listDonations, webhook } from '../routes/stripe.js';
import { checkRole } from '../utils/context.js';
import { getPagination } from '../utils/pagnination.js';
import type { Variables } from '../validators/general.js';

export const stripe = new OpenAPIHono<{ Variables: Variables }>({
defaultHook: zodErrorHook,
});

stripe.openapi(webhook, async (context: Context) => {
const STRIPE_SECRET_API_KEY = process.env.STRIPE_SECRET_API_KEY as string;
const STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET as string;
const stripe = new Stripe(STRIPE_SECRET_API_KEY);
const signature = context.req.header('stripe-signature');
try {
if (!signature) {
return context.json({ error: 'No signature' }, 400);
}
const payload = await context.req.text();
const event = await stripe.webhooks.constructEventAsync(payload, signature, STRIPE_WEBHOOK_SECRET);

switch (event.type) {
case 'charge.succeeded': {
const email = event.data.object.receipt_email || 'test@email.com';
const amount = event.data.object.amount / 100;
const receipt_url = event.data.object.receipt_url as string;
const data = await handleDonations(email, amount, receipt_url);
if (data.error) {
return context.json({ error: data.error }, 400);
}
break;
}
default:
break;
}
return context.json({ message: 'Received' }, 200);
} catch (err) {
const errorMessage = `⚠️ Webhook signature verification failed. ${
err instanceof Error ? err.message : 'Internal server error'
}`;
return context.json({ error: errorMessage }, 500);
}
});

stripe.openapi(listDonations, async (c) => {
const user = c.get('user');
const roles = user.roles;
await checkRole(roles, false);
const { startDate, endDate, skip, take, all, search } = c.req.valid('query');
const query = supabase.from('DONATIONS').select('*').order('created_at', { ascending: true });

if (startDate) {
query.gte('created_at', startDate);
}

if (endDate) {
query.lte('created_at', endDate);
}

if (search) {
const isNumber = !Number.isNaN(Number(search));
if (isNumber) {
query.eq('amount', Number(search));
}
}

if (!all) {
const { from, to } = getPagination(skip, take - 1);
query.range(from, to);
}

const { data, error, count } = await query.range(skip, take);

if (error) {
return c.json({ error: error.message }, 500);
}

const total = data.reduce((acc, curr) => acc + curr.amount, 0);

return c.json({ data, total, count: count || 0 }, 200);
});
2 changes: 2 additions & 0 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { matches } from './handlers/matches.js';
import { reasons } from './handlers/reasons.js';
import { reports } from './handlers/reports.js';
import { sports } from './handlers/sports.js';
import { stripe } from './handlers/stripe.js';
import { tournaments } from './handlers/tournaments.js';
import { users } from './handlers/users.js';
import { polls } from './handlers/votes.js';
Expand Down Expand Up @@ -58,6 +59,7 @@ app.route('/', reasons);
app.route('/', reports);
app.route('/', matches);
app.route('/', tournaments);
app.route('/', stripe);

app.doc('/doc', (c: Context) => ({
openapi: '3.0.0',
Expand Down
26 changes: 26 additions & 0 deletions apps/api/src/libs/stripe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { supabase } from './supabase.js';

export async function handleDonations(email: string, amount: number, receipt_url: string) {
if (!email || !amount || !receipt_url) {
return { error: 'Missing required fields' };
}

if (amount < 1) {
return { error: 'Invalid amount' };
}

const { data: user } = await supabase.from('USERS').select('id').eq('email', email).single();

let id_user = null;
if (user) {
id_user = user.id;
}

const { error, data } = await supabase.from('DONATIONS').insert({ amount, receipt_url, id_user }).select();

if (error) {
return { error: error.message };
}

return { data };
}
68 changes: 68 additions & 0 deletions apps/api/src/routes/stripe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { createRoute } from '@hono/zod-openapi';
import { z } from 'zod';
import authMiddleware from '../middlewares/auth.js';
import { queryAllSchema } from '../utils/pagnination.js';
import { badRequestSchema, serverErrorSchema } from '../validators/general.js';

export const donationSchema = z.object({
id: z.number().min(1),
amount: z.number().positive(),
receipt_url: z.string().url(),
id_user: z.number().min(1).nullable(),
});

const query = queryAllSchema.extend({
startDate: z.string().date().optional(),
endDate: z.string().date().optional(),
});

export const webhook = createRoute({
method: 'post',
path: '/stripe/webhook',
summary: 'Stripe webhook',
description: 'Stripe webhook',
responses: {
200: {
description: 'Successful response',
content: {
'application/json': {
schema: z.object({
message: z.string(),
}),
},
},
},
500: serverErrorSchema,
400: badRequestSchema,
},
tags: ['stripe'],
});

export const listDonations = createRoute({
method: 'get',
path: '/stripe/donations',
summary: 'List donations',
description: 'List donations',
security: [{ Bearer: [] }],
middleware: authMiddleware,
request: {
query,
},
responses: {
200: {
description: 'Successful response',
content: {
'application/json': {
schema: z.object({
data: z.array(donationSchema),
total: z.number().positive(),
count: z.number().positive(),
}),
},
},
},
400: badRequestSchema,
500: serverErrorSchema,
},
tags: ['stripe'],
});
15 changes: 9 additions & 6 deletions packages/types/src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,22 +381,25 @@ export type Database = {
};
DONATIONS: {
Row: {
amount: number;
created_at: string;
id: number;
id_user: number;
money: number | null;
id_user: number | null;
receipt_url: string;
};
Insert: {
amount: number;
created_at?: string;
id?: number;
id_user: number;
money?: number | null;
id_user?: number | null;
receipt_url: string;
};
Update: {
amount?: number;
created_at?: string;
id?: number;
id_user?: number;
money?: number | null;
id_user?: number | null;
receipt_url?: string;
};
Relationships: [
{
Expand Down
Loading
Loading