Skip to content
This repository has been archived by the owner on Feb 3, 2022. It is now read-only.

refactor(webhooks): remove 'micro' dependency #4

Open
wants to merge 1 commit into
base: master
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
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
"@stripe/react-stripe-js": "1.1.2",
"@stripe/stripe-js": "1.5.0",
"dotenv": "latest",
"micro": "^9.3.4",
"micro-cors": "^0.1.1",
"next": "latest",
"react": "^16.12.0",
Expand All @@ -22,7 +21,6 @@
"use-shopping-cart": "2.1.0"
},
"devDependencies": {
"@types/micro": "^7.3.3",
"@types/micro-cors": "^0.1.0",
"@types/node": "^13.1.2",
"@types/react": "^16.9.17",
Expand Down
23 changes: 17 additions & 6 deletions pages/api/webhooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { buffer } from 'micro';
import Cors from 'micro-cors';
import { NextApiRequest, NextApiResponse } from 'next';

Expand All @@ -21,6 +20,22 @@ const cors = Cors({
allowMethods: ['POST', 'HEAD'],
});

const buffer: (req: NextApiRequest) => Promise<Buffer> = (req) => {
return new Promise((resolve, reject) => {
const body: Array<Buffer> = [];
req
.on('data', (chunk) => {
body.push(chunk);
})
.on('end', () => {
resolve(Buffer.concat(body));
})
.on('error', (err) => {
reject(err);
});
});
};

const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const buf = await buffer(req);
Expand All @@ -29,11 +44,7 @@ const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
let event: Stripe.Event;

try {
event = stripe.webhooks.constructEvent(
buf.toString(),
sig,
webhookSecret
);
event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
} catch (err) {
// On error, log and return the error message.
console.log(`❌ Error message: ${err.message}`);
Expand Down