How to automatically transfer to different Stripe accounts per site


  1. You'll need to have your own server, it can be free and easy using napkin.io for example
  2. Create a Stripe webhook: select charge.succeeded event, and add your server as URL

  3. Copy this generated code back to your server
const stripe = require('stripe')(process.env.STRIPE_KEY);
const endpointSecret = process.env.WEBHOOK_SECRET;

function fetchSg(path, opts) {
  return fetch(`https://your-business.storeganise.com/api/v1/admin/${path}`, {
    method,
    headers: {
      Authorization: `ApiKey ${process.env.SG_API_KEY}`,
      ...body && { 'Content-Type': 'application/json' },
    },
    body: body && JSON.stringify(body),
  })
    .then(async r => {
      const data = await r.json().catch(() => ({}));
      if (r.ok) return data;
      throw Object.assign(new Error('sg'), { status: r.status, ...data.error });
    });
}

export default async (req, res) => {
  const sig = req.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(JSON.stringify(req.body), sig, endpointSecret);
  } catch (err) {
    res.statusCode = 400;
    res.json({ message: err.message });
    return;
  }

  try {
    switch (event.type) {
      case 'charge.succeeded':
        const chargeSucceeded = event.data.object;
        const { invoiceId } = chargeSucceeded.metadata;

        const invoice = await fetchSg(`invoices/${invoiceId}`);
        const site = await fetchSg(`sites/${invoice.siteId}?include=customFields`);

        const transfer = await stripe.transfers.create({
          amount: chargeSucceeded.amount,
          currency: chargeSucceeded.currency,
          destination: site.customFields.stripeAcct,
          transfer_group: 'Test',
        });

        break;
      default:
        console.log(`Unhandled event type ${event.type}`);
    }

    res.json({ message: 'OK' });
  } catch (err) {
    console.log(err);
    res.statusCode = 400;
    res.json({ message: err.message });
  }
}
  1. Make sure to configure everything properly and test:
    1. Create and set Site custom field stripeAcct, it should reference the Stripe account to transfer to, e.g. 'acct_1MTfjCQ9PRzxEwkZ'
    2. SG_API_KEY env var should be set with a Storeganise API key in https://your-business.storeganise.com/admin/settings/developer#apiKeys
    3. STRIPE_KEY env var is found in your Stripe settings https://dashboard.stripe.com/apikeys
    4. WEBHOOK_SECRET env var is found in your Stripe setttings https://dashboard.stripe.com/webhooks
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us