-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-app.js
83 lines (67 loc) · 2.55 KB
/
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
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 MOESIF_MANAGEMENT_TOKEN = process.env.MOESIF_MANAGEMENT_TOKEN;
const app = express();
app.use(express.json());
app.post(`/top-up`, 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,
});
const subscriptions = await stripe.subscriptions.list({
customer: customer_id,
});
const subscriptionId = subscriptions.data[0].id;
console.log(subscriptionId);
const url = `${process.env.MOESIF_API_URL}`;
const transactionType = "credit";
const transactionAmount= amount;
const body = {
"company_id": customer_id,
"amount": transactionAmount,
"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': 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);
}
res.json({ client_secret: paymentIntent.client_secret });
});
app.listen(4242, () => console.log('Running on port 4242'));