· 5 years ago · May 19, 2020, 10:40 PM
1const https = require('https');
2const querystring = require('querystring');
3const MFRKey = event.bot.customAttributes.MFRKey
4
5class DirectPost {
6 constructor(security_key) {
7 this.security_key = MFRKey;
8 }
9
10 setBilling(billingInformation) {
11 // Validate that passed in information contains valid keys
12 const validBillingKeys = ['first_name', 'last_name', 'company', 'address1',
13 'address2', 'city', 'state', 'zip', 'country', 'phone', 'fax', 'email'];
14
15 for (let key in billingInformation) {
16 if (!validBillingKeys.includes(key)) {
17 throw new Error(`Invalid key provided in billingInformation. '${key}'
18 is not a valid billing parameter.`)
19 }
20 };
21
22 this.billing = billingInformation;
23 }
24
25 doSale(amount, ccNum, ccExp, cvv) {
26 let requestOptions = {
27 'type': 'sale',
28 'amount': amount,
29 'ccnumber': ccNum,
30 'ccexp': ccExp,
31 'cvv': cvv
32 };
33
34 // Merge together all request options into one object
35 Object.assign(requestOptions, this.billing, this.shipping);
36
37 // Make request
38 this._doRequest(requestOptions);
39 }
40
41 _doRequest(postData) {
42 const hostName = 'XXXXXXXXXXXXXXXXXXX';
43 const path = '/api/transact.php';
44
45 postData.security_key = this.security_key;
46 postData = querystring.stringify(postData);
47
48 const options = {
49 hostname: hostName,
50 path: path,
51 method: 'POST',
52 headers: {
53 'Content-Type': 'application/x-www-form-urlencoded',
54 'Content-Length': Buffer.byteLength(postData)
55 }
56 };
57
58 // Make request to Direct Post API
59 const req = https.request(options, (response) => {
60 console.log(`STATUS: ${response.statusCode}`);
61 console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
62
63 const chunks = [];
64 response.on('data', (chunk) => { chunks.push(chunk); });
65 response.on('end', () => { handleResponse(chunks.join()); });
66
67 req.on('error', (e) => {
68 console.error(`Problem with request: ${e.message}`);
69 });
70
71 // Write post data to request body
72 req.write(postData);
73 req.end();
74 }
75}
76
77//Define User Variables
78const first_name = event.user.first_name
79const last_name = event.user.last_name
80const orderTotal = event.conversation.variables.orderTotal
81const user_zip = event.conversation.variables.user_zip
82
83//Define Payment Variables
84const user_cc = event.conversation.variables.user_cc
85const user_cc_exp = event.conversation.variables.user_cc_exp
86const user_ccv = event.conversation.variables.user_ccv
87
88const dp = new DirectPost('{security_key}');
89const billingInfo = {
90 'first_name': first_name,
91 'last_name': last_name,
92 'zip' : user_zip,
93}
94
95dp.setBilling(billingInfo);
96// Set dummy data for sale
97dp.doSale(orderTotal , user_cc , user_cc_exp , user_ccv, handleResponse);
98
99
100function handleResponse() {
101 const submit = {
102 "actions": [{
103 "type": "set_variable",
104 "data": {
105 "apiResponse":
106 }
107 }]
108 };
109}
110
111done()