-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.php
352 lines (319 loc) · 10.8 KB
/
api.php
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
<?php
use GuzzleHttp\Client as GuzzleHttpClient;
use LeonardoTeixeira\Pushover\Client;
use LeonardoTeixeira\Pushover\Exceptions\PushoverException;
use LeonardoTeixeira\Pushover\Message;
use LeonardoTeixeira\Pushover\Priority;
include_once 'zettle.common.php';
include 'vendor/autoload.php';
# Add API resources to this file
function getEndpointsfppzettle()
{
$endpoints = array(
array(
'method' => 'GET',
'endpoint' => 'version',
'callback' => 'fppZettleVersion'
),
array(
'method' => 'POST',
'endpoint' => 'event',
'callback' => 'fppZettleEvent'
),
array(
'method' => 'POST',
'endpoint' => 'app',
'callback' => 'fppZettleApp'
)
);
return $endpoints;
}
// GET /api/plugin/fpp-zettle/version
function fppZettleVersion()
{
$result = array();
$result['version'] = 'fpp-zettle v1.0.0';
return json_encode($result);
}
# POST /api/plugin/fpp-zettle/event
# This is the endpoint we will need users to register with the Zettle dev portal
# https://my.zettle.com/apps/api-keys > click create api key > select READ:USER_INFO & READ:PURCHASE
# Copy The client id & secret to a notepad or something they are needed for the plugin.
function fppZettleEvent()
{
$event = json_decode(file_get_contents('php://input'), true);
header("Content-Type: application/json");
// Check for eventName in the post data
if (!isset($event['eventName'])) {
// eventName could not be found display message to user
return json_encode(
[
'error' => true,
'message' => 'eventName could not be found in request, please try again'
]
);
}
// Check if the right eventName has been sent
if ($event['eventName'] != 'PurchaseCreated') {
return json_encode(
[
'error' => true,
'message' => 'eventName needs to be PurchaseCreated',
]
);
}
// Get payload from zettle and turn in to an array
$payload = json_decode(json_decode(json_encode($event['payload']), true), true);
$amount = ($payload['amount'] / 100);
$currency = $payload['currency'];
// Other Feilds can be added to this
$paymentData = [
'formatted_amount' => number_format($amount, 2) . ' ' . $currency,
'amount' => $amount,
'timestamp' => $payload['timestamp'],
'userUuid' => $payload['userUuid'],
];
// Get currentTransactions
$currentTransactions = convertAndGetSettings('zettle-transactions');
// Push new transaction
array_push($currentTransactions, $paymentData);
// Store transaction to json file
writeToJsonFile('transactions', $currentTransactions);
// Store transation account
totalTransactions($amount);
// Write transaction to log file
custom_logs($payload);
// Get zettle config
$config = convertAndGetSettings('zettle');
// Check for multiple readers
if (isset($config['readers']) && count($config['readers']) > 0) {
// Reader run count
$reader_run = FALSE;
// Loop over readers
foreach ($config['readers'] as $reader) {
// Check if reader has a command set
if ($reader['command'] != '') {
// Check if a reader has the same product as the payload from zettle has
if ($reader['product'] == $payload['products'][0]['name']) {
// Add formatted_amount to reader array
$reader['formatted_amount'] = $paymentData['formatted_amount'];
// Reader has same product runCommand
custom_logs('Run reader command');
runCommand($reader);
$reader_run = TRUE;
}
}
}
// Check if a reader has been run
if ($reader_run == FALSE) {
// No reader found run default command
custom_logs('No reader found with assigned product (' . $payload['products'][0]['name'] . ') run default command');
runCommand([
'command' => $config['command'],
'args' => $config['args'],
'formatted_amount' => $paymentData['formatted_amount'],
]);
}
} else {
// No multiple readers found run default command
if ($config['effect_activate'] == 'yes' && $config['command'] != '') {
// Run default command
custom_logs('Run default command');
runCommand([
'command' => $config['command'],
'args' => $config['args'],
'formatted_amount' => $paymentData['formatted_amount'],
]);
}
}
// Check if pushover is active
if (isset($config['pushover']) && $config['pushover']['activate'] == 'yes') {
pushover($config, $paymentData);
}
// Check if publish is active
if (isset($config['publish']) && $config['publish']['activate'] == 'yes') {
publishTransactionDetails($payload);
}
// Store userUuid and if they have activated publish or not
storeCustomer($config, $paymentData);
return true;
}
function fppZettleApp()
{
$event = json_decode(file_get_contents('php://input'), true);
header("Content-Type: application/json");
$amount = ($event['amount'] / 100);
$currency = $event['currency'];
// Other Feilds can be added to this
$paymentData = [
'formatted_amount' => number_format($amount, 2) . ' ' . $currency,
'amount' => $amount,
'timestamp' => time(),
'userUuid' => "",
];
// Get currentTransactions
$currentTransactions = convertAndGetSettings('zettle-transactions');
// Push new transaction
array_push($currentTransactions, $paymentData);
// Store transaction to json file
writeToJsonFile('transactions', $currentTransactions);
// Store transation account
totalTransactions($amount);
return json_encode(
[
'error' => false,
'message' => 'fpp app api function',
]
);
}
/**
* Make pushover message and send it
*
* @param array $config
* @param array $paymentData
* @return void
*/
function pushover($config = [], $paymentData = [])
{
$build_message = buildMessage($paymentData, $config['pushover']['message']);
$client = new Client($config['pushover']['user_key'], $config['pushover']['app_token']);
$message = new Message($build_message, 'FPP CARD READER', Priority::HIGH);
try {
$client->push($message);
custom_logs('The pushover message has been pushed!');
} catch (PushoverException $e) {
custom_logs('PUSHOVER ERROR: ', $e->getMessage());
}
}
/**
* Publish Transaction Details to fpp-zettle.co.uk
*
* @param array $payload
* @return void
*/
function publishTransactionDetails($payload = [])
{
$client = new GuzzleHttpClient([
"base_uri" => "https://fpp-zettle.co.uk",
'headers' => [
'Content-Type' => 'application/json'
]
]);
$options = [
'form_params' => [
'amount' => $payload['amount'],
'currency' => $payload['currency'],
],
];
// if ($config['publish']['location'] == 'yes') {
// $gpsCoordinates = $payload['gpsCoordinates'];
// $options['latitude'] = $gpsCoordinates['latitude'];
// $options['longitude'] = $gpsCoordinates['longitude'];
// }
$response = $client->post("/api/transactions", $options);
custom_logs('Publish Transaction Details to fpp-zettle.co.uk');
// custom_logs($response->getBody());
}
/**
* Store custom data on fpp-zettle.co.uk
*
* @param array $config
* @param array $data
* @return void
*/
function storeCustomer($config = [], $data = [])
{
$client = new GuzzleHttpClient([
"base_uri" => "https://fpp-zettle.co.uk",
'headers' => [
'Content-Type' => 'application/json'
]
]);
$options = [
'form_params' => [
'user_uuid' => $data['userUuid'],
'active' => isset($config['publish']) && $config['publish']['activate'] == 'yes' ? TRUE : FALSE,
],
];
$client->post("/api/customers", $options);
}
/**
* Build message for Overlay Model Effect
*
* @param array $paymentData
* @param array $data command data
* @return string
*/
function buildMessage($paymentData = [], $data = [], $url_encode = false)
{
$replacement_values = [
$paymentData['formatted_amount'],
runningTotal('everything'),
runningTotal('today'),
runningTotal('this_month')
];
if ($url_encode) {
$replacement_values = array_map('urlencode', $replacement_values);
}
// Find and replace values in array as payment details
$text = str_replace([
'{{AMOUNT}}',
'{{EVERYTHING}}',
'{{TODAY}}',
'{{THIS_MONTH}}'
], $replacement_values, is_array($data) ? end($data) : $data);
custom_logs('Build Message Output: ' . $text);
return $text;
}
/**
* Run command
*
* @param array $data command details
* @return void
*/
function runCommand($data = [])
{
// Build command url from selected command
// $url = 'http://localhost/api/command/' . urlencode($data['command']);
$url = 'http://localhost/api/command/';
// Get command args
$command_args = $data['args'];
// Check if command is "Overlay Model Effect"
if ($data['command'] == 'Overlay Model Effect') {
$text = buildMessage([
'formatted_amount' => $data['formatted_amount']
], $command_args);
// Remove and replace last item from array
array_pop($command_args);
$command_args[] = $text;
}
else if ($data['command'] == 'URL') {
custom_logs("Is URL");
$updated_url = buildMessage([
'formatted_amount' => $data['formatted_amount']
], $command_args[0], true);
$command_args[0] = $updated_url;
$updated_post_body = buildMessage([
'formatted_amount' => $data['formatted_amount']
], $command_args[2]);
$command_args[2] = $updated_post_body;
}
if ($data['command'] != 'Overlay Model Effect') {
// Write command args back into $data, but only for commands other than Overlay Model Effect,
// which never used to do it - is this a bug that needs fixing?
$data['args'] = $command_args;
}
custom_logs('Sending command: ' . $data);
// Fire the command
$query = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_exec($ch);
curl_close($ch);
// Write to log file
custom_logs('command fired');
}