Untitled

 avatar
unknown
plain_text
4 months ago
4.1 kB
4
Indexable
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

async function enrichMetadata(paymentIntent) {
  let enrichedMetadata = {};
  enrichedMetadata.id_activity = paymentIntent.metadata?.custom_param_id_activity || null

  // Check for Invoice and Subscription
  if (paymentIntent.invoice) {
      const invoice = await stripe.invoices.retrieve(paymentIntent.invoice);
      if (invoice.subscription) {
          const subscription = await stripe.subscriptions.retrieve(invoice.subscription);
          const subscriptionCustomer = await stripe.customers.retrieve(subscription.customer);
          enrichedMetadata.subscription = {
              id: subscription.id,
              plan: subscription.plan,
              customer: subscriptionCustomer
          };
          enrichedMetadata.id_project = subscription.metadata?.custom_param_id_project || null
          enrichedMetadata.subscription_id = subscription.id; // Include subscription ID for database
      }
  }

  return JSON.stringify(enrichedMetadata);
}

app.post('/stripe-webhook', bodyParser.raw({ type: 'application/json' }), async (req, res) => {
  console.log("webhook: sono dentro");
  
  const sig = req.headers['stripe-signature'];
  const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;

  let event;

  try {
      event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
  } catch (err) {
      console.error(`Webhook signature verification failed: ${err.message}`);
      return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  try {
    if (event.type === 'payment_intent.succeeded' || event.type === 'payment_intent.payment_failed') {
      const paymentIntent = event.data.object;

      // Attempt to retrieve customer email
      let customerEmail = paymentIntent.receipt_email;
      if (!customerEmail && paymentIntent.customer) {
          const customer = await stripe.customers.retrieve(paymentIntent.customer);
          customerEmail = customer.email;
      }

      // Enrich metadata with additional information
      const enrichedMetadata = await enrichMetadata(paymentIntent);

      // Extract payment intent information
      const paymentData = {
          idstripe: paymentIntent.id,
          created: new Date(paymentIntent.created * 1000),
          amount: paymentIntent.amount / 100,
          currency: paymentIntent.currency,
          status: paymentIntent.status,
          description: paymentIntent.description || 'Payment',
          customer: JSON.parse(enrichedMetadata).subscription?.customer?.email || JSON.parse(enrichedMetadata).subscription?.customer?.id || customerEmail,
          metadata: enrichedMetadata,
          subscription_id: JSON.parse(enrichedMetadata).subscription_id || null,
          id_activity: JSON.parse(enrichedMetadata).id_activity || null,
          id_project: JSON.parse(enrichedMetadata).id_project || null
      };

      // Insert or update payment intent data into MySQL
      const insertQuery = `INSERT INTO payments (
          idstripe, created, amount, currency, status, description,
          customer, metadata, subscription_id, id_activity, id_project
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE
          idstripe = VALUES(idstripe),
          amount = VALUES(amount),
          currency = VALUES(currency),
          status = VALUES(status),
          description = VALUES(description),
          customer = VALUES(customer),
          metadata = VALUES(metadata),
          subscription_id = VALUES(subscription_id),
          id_activity = VALUES(id_activity),
          id_project = VALUES(id_project)`;

      con.query(insertQuery, Object.values(paymentData), (err) => {
        if (err) {
            console.error('Error inserting payment intent into database:', err);
            return;
        }
      });

      console.log('Payment intent saved successfully:', paymentData.idstripe);
    }

  } catch (err) {
      console.error('Error handling event:', err.message || err);
      return res.status(500).send('Internal Server Error');
  }

  res.sendStatus(200);
});
Editor is loading...
Leave a Comment