// server.js
//
// Use this sample code to handle webhook events in your integration.
//
// 1) Paste this code into a new file (server.js)
//
// 2) Install dependencies
// npm install stripe
// npm install express
//
// 3) Run the server on http://localhost:4242
// node server.js
// The library needs to be configured with your account's secret key.
// Ensure the key is kept out of any version control system you might be using.
const stripe = require('stripe')('sk_test_...');
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_API_SECRET);
const app = express();
// This is your Stripe CLI webhook secret for testing your endpoint locally.
const endpointSecret = "whsec_56a0803c192ac48bfa740faf52f373912217e7cc32aa0a81b2e27a834a6f11ed";
app.post('/webhook', express.raw({type: 'application/json'}), (request, response) => {
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
} catch (err) {
response.status(400).send(`Webhook Error: ${err.message}`);
return;
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const pi = event.data.object; // schema: https://docs.stripe.com/api/payment_intents/object
// pi.description is formatted like this `Invoice {sid}`
const invoiceSid = pi.description.split(' ')[1];
// use a Storeganise API key https://help.storeganise.com/article/33-developer-settings#api-keys to load the invoice
try {
const invoice = await fetch(`https://yourbiz.storeganise.com/api/v1/admin/invoices/${invoiceSid}`).then(r => r.json());
const site = await fetch(`https://yourbiz.storeganise.com/api/v1/admin/sites/${invoice.siteId}?include=customFields`).then(r => r.json());
// call https://docs.stripe.com/api/transfers/create API
const transfer = await stripe.transfers.create({
amount: pi.amount_received,
currency: 'usd', // adjust to your Stripe currency
destination: site.customFields.stripeConnectAccountId,
});
} catch (e) {
return response.status(400).send(e.message);
}
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
// Return a 200 response to acknowledge receipt of the event
response.send();
});
app.listen(4242, () => console.log('Running on port 4242'));