-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook-api-app.js
115 lines (92 loc) · 3.65 KB
/
webhook-api-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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const express = require('express');
const fetch = require('node-fetch');
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');
require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_API_KEY);
const app = express();
app.post(`/top-up`, bodyParser.json(), async (req, res) => {
const { amount, customer_id } = req.body;
const paymentMethods = await stripe.paymentMethods.list({
customer: customer_id,
type: 'card',
limit: 1
});
console.log(paymentMethods);
if(paymentMethods.data.length === 0) {
return res.status(400).json({ error: 'No payment method found for this customer. The customer needs to have a payment method added to their Stripe account.' });
}
const paymentID = paymentMethods.data[0].id;
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: 'usd',
customer: customer_id,
payment_method: paymentID,
off_session: true,
payment_method_types: ['card'],
confirm: true,
error_on_requires_action: true,
});
res.json({ client_secret: paymentIntent.client_secret });
});
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'));