Skip to content

Commit

Permalink
Merge pull request #1652 from stripe/richardm-koa-example
Browse files Browse the repository at this point in the history
Add koa example
  • Loading branch information
pakrym-stripe authored Feb 5, 2023
2 parents 5c44430 + 448b772 commit 22cc651
Show file tree
Hide file tree
Showing 6 changed files with 413 additions and 8 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
node_modules
lib
testProjects
examples/**
21 changes: 21 additions & 0 deletions examples/webhook-signing/node-koa/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
module.exports = {
env: {
node: true,
},
root: true,
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'prettier'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
rules: {
'@typescript-eslint/no-use-before-define': 0,
'@typescript-eslint/no-empty-interface': 0,
'@typescript-eslint/no-unused-vars': 0,
'@typescript-eslint/triple-slash-reference': 0,
'@typescript-eslint/ban-ts-ignore': 0,
},
};
65 changes: 65 additions & 0 deletions examples/webhook-signing/node-koa/koa.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const Stripe = require('stripe');
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const env = require('dotenv');

const app = new Koa();

env.config();
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2022-11-15',
});

const handleWebhook = async (ctx, next) => {
const sig = ctx.request.headers['stripe-signature'];

let event;

try {
event = stripe.webhooks.constructEvent(
ctx.request.rawBody,
sig,
webhookSecret
);
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`);
ctx.response.status = 400;
ctx.body = `Webhook Error: ${err.message}`;
return await next();
}

// Successfully constructed event
console.log('✅ Success:', event.id);

// Cast event data to Stripe object
if (event.type === 'payment_intent.succeeded') {
const stripeObject = event.data.object;
console.log(`💰 PaymentIntent status: ${stripeObject.status}`);
} else if (event.type === 'charge.succeeded') {
const charge = event.data.object;
console.log(`💵 Charge id: ${charge.id}`);
} else {
console.warn(`🤷‍♀️ Unhandled event type: ${event.type}`);
}

// Return a response to acknowledge receipt of the event
ctx.response.body = JSON.stringify({received: true});
ctx.response.set('Content-Type', 'application/json');
return await next();
};

app.use(bodyParser({enableTypes: ['json']}));
app.use(async (ctx, next) => {
if (ctx.request.path === '/webhook') {
return handleWebhook(ctx, next);
}
const name = ctx.request.body?.name ?? 'world';
ctx.body = `hello ${name}, you hit ${ctx.request.path}`;
});

app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
15 changes: 15 additions & 0 deletions examples/webhook-signing/node-koa/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"compilerOptions": {
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"target": "es5",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"module": "commonjs",

/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"esModuleInterop": true,

/* Advanced Options */
/* Disallow inconsistently-cased references to the same file. */
"forceConsistentCasingInFileNames": true
}
}
Loading

0 comments on commit 22cc651

Please sign in to comment.