This repository has been archived by the owner on Nov 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
102 lines (94 loc) · 2.56 KB
/
handler.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
const fs = require('fs');
const stripe = require('stripe')(process.env.STRIPE_API_KEY);
const Xero = require('xero');
const xeroPrivateKey = fs.readFileSync("./xero_keys/privatekey.pem");
const xero = new Xero(
process.env.XERO_CONSUMER_KEY,
process.env.XERO_CONSUMER_SECRET,
xeroPrivateKey
)
function handleCharge(data) {
customer = stripe.customers.retrieve(data.object.customer,
function(err, customer) {
var transactions = [
{
Type: "RECEIVE",
Reference: data.object.id,
BankAccount: {
Code: process.env.XERO_STRIPE_ACCOUNT_CODE,
},
Contact: {
Name: customer == undefined ?
data.object.source.name : customer.description,
},
LineItems: [
{
Description: data.object.description == undefined ?
customer.description : data.object.description,
UnitAmount: (data.object.amount / 100),
AccountCode: process.env.XERO_SALES_ACCOUNT_CODE,
},
],
},
{
Type: "Spend",
Reference: data.object.id,
BankAccount: {
Code: process.env.XERO_STRIPE_ACCOUNT_CODE,
},
Contact: {
Name: "Stripe",
},
LineItems: [
{
Description: data.object.fee_details[0].description,
UnitAmount: data.object.fee / 100,
AccountCode: process.env.XERO_STRIPE_FEE_ACCOUNT_CODE,
},
],
}
];
xero.call('POST', '/BankTransactions', transactions, function(err, json) {
if (err) {
console.log(err);
}
});
}
);
}
function handleTransfer(data) {
var transfer = [{
FromBankAccount: {
Code: process.env.XERO_STRIPE_ACCOUNT_CODE,
},
ToBankAccount: {
Code: process.env.XERO_STRIPE_TRANSFER_ACCOUNT_CODE,
},
Amount: (data.object.amount / 100),
}];
xero.call('POST', '/BankTransfers', transfer, function(err, json) {
if (err) {
console.log(err);
}
});
}
module.exports.stripeImporter = (event, context, callback) => {
stripe.events.retrieve(event.id, function(err, event) {
if (err) {
console.log(err);
callback(new Error('Invalid Stripe event sent.'));
return;
}
switch (event.type) {
case "charge.succeeded":
handleCharge(event.data);
break;
case "transfer.paid":
handleTransfer(event.data);
break;
default:
break;
}
callback(null, { statusCode: 200 });
});
};