-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook-app.js
84 lines (67 loc) · 2.69 KB
/
webhook-app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const express = require('express');
const fetch = require('node-fetch');
const { v4: uuidv4 } = require('uuid');
require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_API_KEY);
const app = express();
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
const stripeSignature = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, stripeSignature, process.env.STRIPE_ENDPOINT_SECRET);
} catch (err) {
console.error(`Webhook Error: ${err.message}`);
return response.status(400).send(`Webhook Error: ${err.message}`);
}
switch (event.type) {
case 'payment_intent.succeeded':
handleSuccessfulPaymentIntent(event.data);
break
default:
console.log(`Unhandled event type ${event.type}`);
}
response.json({ received: true });
});
async function handleSuccessfulPaymentIntent(data) {
const paymentIntent = data.object;
const customerId = paymentIntent.customer;
const transactionAmount = paymentIntent.amount_received;
const subscriptions = await stripe.subscriptions.list({
customer: customerId,
});
if (subscriptions.data.length === 0) {
console.error('No subscriptions found for this customer.');
return;
}
const subscriptionId = subscriptions.data[0].id;
console.log('Subscription ID:', subscriptionId);
const url = `${process.env.MOESIF_API_URL}`;
const transactionType = "credit";
const body = {
"company_id": customerId, // Assuming you want the Stripe customer ID here
"amount": transactionAmount, // Correct amount from the payment intent
"type": transactionType,
"subscription_id": subscriptionId,
"transaction_id": uuidv4().toString(),
"description": "Top-up from API, post Stripe top-up event"
};
console.log('Creating balance transaction:', body);
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.MOESIF_MANAGEMENT_TOKEN}`
},
body: JSON.stringify(body)
});
if (response.ok) {
console.log('Balance transaction created successfully');
} else {
console.error('Failed to create balance transaction!', response.status, response.statusText, await response.json());
}
} catch (error) {
console.error('An error occurred while creating balance transaction:', error);
}
}
app.listen(4242, () => console.log('Running on port 4242'));