forked from sumocoders/Factr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Factr.php
862 lines (738 loc) · 23.1 KB
/
Factr.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
<?php
namespace SumoCoders\Factr;
use InvalidArgumentException;
use SumoCoders\Factr\Exception;
use SumoCoders\Factr\Client\Client;
use SumoCoders\Factr\Invoice\Invoice;
use SumoCoders\Factr\Invoice\Mail;
use SumoCoders\Factr\Invoice\Payment;
use SumoCoders\Factr\Product\Product;
/**
* Factr class
*
* @author Tijs Verkoyen <[email protected]>
* @version 2.0.0
* @copyright Copyright (c), Tijs Verkoyen. All rights reserved.
* @license BSD License
*/
class Factr
{
// internal constant to enable/disable debugging
const DEBUG = false;
// url for the API
const API_URL = 'https://app.defactuur.be/api';
// port for the factr-API
const API_PORT = 443;
// version of the API
const API_VERSION = 'v1';
// current version
const VERSION = '2.5.1';
/**
* The token to use
*
* @var string
*/
private $apiToken;
/**
* cURL instance
*
* @var resource
*/
private $curl;
/**
* The timeout
*
* @var int
*/
private $timeOut = 30;
/**
* The user agent
*
* @var string
*/
private $userAgent;
// class methods
/**
* Default destructor
*/
public function __destruct()
{
// close the curl-instance if needed
if($this->curl != null) curl_close($this->curl);
}
/**
* Decode the response
*
* @param mixed $value
* @param string $key
*/
private function decodeResponse(&$value, $key)
{
// convert to float
if (in_array($key, array('amount', 'price', 'total_without_vat', 'total_with_vat', 'total_vat', 'total'), true)) {
$value = (float) $value;
}
}
/**
* Encode data for usage in the API
*
* @param mixed $data
* @param array $array
* @param string[optional] $prefix
* @return array
*/
private function encodeData($data, $array = array(), $prefix = null)
{
if (is_object($data)) {
$data = get_object_vars($data);
}
foreach ($data as $key => $value) {
if($value === null) continue;
$k = isset($prefix) ? $prefix . '[' . $key . ']' : $key;
if (is_array($value) || is_object($value)) {
$array = $this->encodeData($value, $array, $k);
} else {
$array[$k] = $value;
}
}
return $array;
}
/**
* Make the call
*
* @param string $url The URL to call.
* @param array[optional] $parameters The parameters that should be passed.
* @param string[optional] $method Which method should be used? Possible values are: GET, POST, DELETE, PUT.
* @param bool[optional] $returnHeaders Return the headers instead of the data?
* @return array
*/
private function doCall($url, array $parameters = null, $method = 'GET', $returnHeaders = false)
{
// redefine
$url = (string) $url;
$method = (string) $method;
$options = array();
// add credentials
$parameters['api_key'] = $this->getApiToken();
// through GET
if ($method == 'GET') {
// remove POST-specific stuff
unset($options[CURLOPT_HTTPHEADER]);
unset($options[CURLOPT_POST]);
unset($options[CURLOPT_POSTFIELDS]);
// build url
$url .= '?' . http_build_query($parameters, null, '&');
$url = $this->removeIndexFromArrayParameters($url);
} elseif ($method == 'POST') {
$data = $this->encodeData($parameters);
if ($this->areWeSendingAFile($data) === false) {
$data = http_build_query($data, null, '&');
$data = $this->removeIndexFromArrayParameters($data);
}
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $data;
} elseif ($method == 'DELETE') {
unset($options[CURLOPT_HTTPHEADER]);
unset($options[CURLOPT_POST]);
unset($options[CURLOPT_POSTFIELDS]);
$options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
// build url
$url .= '?' . http_build_query($parameters, null, '&');
} elseif ($method == 'PUT') {
$data = $this->encodeData($parameters);
$data = http_build_query($data, null, '&');
$data = $this->removeIndexFromArrayParameters($data);
$options[CURLOPT_POSTFIELDS] = $data;
$options[CURLOPT_CUSTOMREQUEST] = 'PUT';
} else throw new Exception('Unsupported method (' . $method . ')');
// prepend
$url = self::API_URL . '/' . self::API_VERSION . '/' . $url;
// set options
$options[CURLOPT_URL] = $url;
$options[CURLOPT_PORT] = self::API_PORT;
$options[CURLOPT_USERAGENT] = $this->getUserAgent();
$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_SSL_VERIFYPEER] = false;
$options[CURLOPT_SSL_VERIFYHOST] = false;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = (int) $this->getTimeOut();
// init
$this->curl = curl_init();
// set options
curl_setopt_array($this->curl, $options);
// execute
$response = curl_exec($this->curl);
$headers = curl_getinfo($this->curl);
// fetch errors
$errorNumber = curl_errno($this->curl);
$errorMessage = curl_error($this->curl);
// check status code
if ($headers['http_code'] >= 400) {
// try to read JSON
$json = @json_decode($response, true);
// throw
if ($json !== null && $json !== false) {
// errors?
if (is_array($json) && array_key_exists('errors', $json)) {
$message = '';
foreach($json['errors'] as $key => $value) $message .= $key . ': ' . implode(', ', $value) . "\n";
throw new Exception(trim($message));
} else {
if(is_array($json) && array_key_exists('message', $json)) $response = $json['message'];
throw new Exception($response, $headers['http_code']);
}
}
// unknown error
throw new Exception('Invalid response (' . $headers['http_code'] . ')', $headers['http_code']);
}
// error?
if($errorNumber !== 0) throw new Exception($errorMessage, $errorNumber);
// return the headers if needed
if($returnHeaders) return $headers;
if (stristr($url, '.pdf')) {
// Return pdf contents immediately without tampering with them
return $response;
}
// we expect JSON so decode it
$json = @json_decode($response, true);
// validate json
if($json === false) throw new Exception('Invalid JSON-response');
// decode the response
array_walk_recursive($json, array(__CLASS__, 'decodeResponse'));
// return
return $json;
}
/**
* Detect from flattened parameter array if we're sending a file
*
* @param array $parameters The flattened parameter array
*
* @return bool
*/
private function areWeSendingAFile($parameters)
{
foreach ($parameters as $key => $value) {
if (substr($value, 0, 1) === '@') {
return true;
}
}
return false;
}
/**
* Remove indexes from http array parameters
*
* The Factr application doesn't like numerical indexes in http parameters too much.
* We'll just remove them.
*
* ?foo[1]=bar becomes ?foo[]=bar
*
* @param mixed $query The query string or flattened array
*
* @return mixed the cleaned up query string or array
*/
private function removeIndexFromArrayParameters($query)
{
return preg_replace('/%5B([0-9]*)%5D/iU', '%5B%5D', $query);
}
/**
* Get the API token
*
* @return string
*/
public function getApiToken()
{
return $this->apiToken;
}
/**
* Get the timeout that will be used
*
* @return int
*/
public function getTimeOut()
{
return (int) $this->timeOut;
}
/**
* Get the user agent that will be used. Our version will be prepended to yours.
* It will look like: "PHP Factr/<version> <your-user-agent>"
*
* @return string
*/
public function getUserAgent()
{
return (string) 'PHP Factr/' . self::VERSION . ' ' . $this->userAgent;
}
/**
* Set the API token
*
* @param string $apiToken
*/
public function setApiToken($apiToken)
{
$this->apiToken = $apiToken;
}
/**
* Set the timeout
* After this time the request will stop. You should handle any errors triggered by this.
*
* @param int $seconds The timeout in seconds.
*/
public function setTimeOut($seconds)
{
$this->timeOut = (int) $seconds;
}
/**
* Set the user-agent for you application
* It will be appended to ours, the result will look like: "PHP Factr/<version> <your-user-agent>"
*
* @param string $userAgent Your user-agent, it should look like <app-name>/<app-version>.
*/
public function setUserAgent($userAgent)
{
$this->userAgent = (string) $userAgent;
}
// account methods
/**
* Get an API token
*
* @param string $username Your username
* @param string $password Tour password
* @return string
* @throws Exception
*/
public function accountApiToken($username, $password)
{
$url = self::API_URL . '/' . self::API_VERSION . '/account/api_token.json';
// set options
$options[CURLOPT_URL] = $url;
$options[CURLOPT_PORT] = self::API_PORT;
$options[CURLOPT_USERAGENT] = $this->getUserAgent();
$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_SSL_VERIFYPEER] = false;
$options[CURLOPT_SSL_VERIFYHOST] = false;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = (int) $this->getTimeOut();
$options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
$options[CURLOPT_USERPWD] = $username . ':' . $password;
// init
$this->curl = curl_init();
// set options
curl_setopt_array($this->curl, $options);
// execute
$response = curl_exec($this->curl);
$headers = curl_getinfo($this->curl);
// check status code
if ($headers['http_code'] != 200) {
throw new Exception('Could\'t authenticate you');
}
// we expect JSON so decode it
$json = @json_decode($response, true);
// validate json
if($json === false || !isset($json['api_token'])) throw new Exception('Invalid JSON-response');
// set the token
$this->setApiToken($json['api_token']);
// return
return $json['api_token'];
}
// client methods
/**
* Get a list of all the clients for the authenticating user.
*
* @return array
*/
public function clients()
{
$clients = array();
$rawData = $this->doCall('clients.json');
if (!empty($rawData)) {
foreach ($rawData as $data) {
$clients[] = Client::initializeWithRawData($data);
}
}
return $clients;
}
/**
* Get all of the available information for a single client. You 'll need the id of the client.
*
* @param string $id The id of the client.
* @return Client
*/
public function clientsGet($id)
{
$rawData = $this->doCall('clients/' . (string) $id . '.json');
if(empty($rawData)) return false;
return Client::initializeWithRawData($rawData);
}
/**
* Get all clients that are linked to an email address
*
* @param string $email The email of the client.
* @return Client[]
*/
public function clientsGetByEmail($email)
{
$rawData = $this->doCall('clients.json', array('email' => $email));
if (empty($rawData)) {
return false;
}
return array_map(
function (array $clientData) {
return Client::initializeWithRawData($clientData);
},
$rawData
);
}
/**
* Create a new client.
*
* @param Client $client The information of the client.
* @return Client|bool
*/
public function clientsCreate(Client $client)
{
$parameters['client'] = $client->toArray(true);
$rawData = $this->doCall('clients.json', $parameters, 'POST');
return Client::initializeWithRawData($rawData);
}
/**
* Update an existing client
*
* @param string $id The id of the client.
* @param Client $client The information of the client.
* @return bool
*/
public function clientsUpdate($id, Client $client)
{
$parameters['client'] = $client->toArray(true);
$rawData = $this->doCall('clients/' . (string) $id . '.json', $parameters, 'PUT', true);
return ($rawData['http_code'] == 204);
}
/**
* Check if country is European
*
* @param $countryCode
* @return bool
*/
public function clientsIsEuropean($countryCode)
{
$parameters['country_code'] = $countryCode;
$rawData = $this->doCall('clients/is_european.json', $parameters);
return $rawData['european'];
}
/**
* Delete a client
*
* @param string $id The id of the client.
* @return bool
*/
public function clientsDelete($id)
{
$rawData = $this->doCall('clients/' . (string) $id . '.json', null, 'DELETE', true);
return ($rawData['http_code'] == 204);
}
/**
* Disable client in favour of another client
*
* @param $id
* @param $replacedById
*
* @return bool
*/
public function clientsDisable($id, $replacedById)
{
$parameters['replaced_by_id'] = $replacedById;
$rawData = $this->doCall('clients/' . (string) $id . '/disable.json', $parameters, 'POST', true);
return ($rawData['http_code'] == 201);
}
/**
* Get the invoices for a client
*
* @param int $id
* @return array
*/
public function clientsInvoices($id)
{
$invoices = array();
$rawData = $this->doCall('clients/' . (string) $id . '/invoices.json');
if (!empty($rawData)) {
foreach ($rawData as $data) {
$invoices[] = Invoice::initializeWithRawData($data);
}
}
return $invoices;
}
// invoice methods
/**
* Get a list of all the invoices.
*
* @param array $filters A list of filters
*
* @return array
*/
public function invoices(array $filters = null)
{
$parameters = null;
if (!empty($filters)) {
$allowedFilters = array(
'sent',
'unpaid',
'paid',
'reminder_sent',
'partially_paid',
'unset',
'juridicial_proceedings',
'late'
);
array_walk(
$filters,
function($filter) use ($allowedFilters) {
if (!in_array($filter, $allowedFilters)) {
throw new InvalidArgumentException('Invalid filter');
}
}
);
$parameters = array('filters' => $filters);
}
$invoices = array();
$rawData = $this->doCall('invoices.json', $parameters);
if (!empty($rawData)) {
foreach ($rawData as $data) {
$invoices[] = Invoice::initializeWithRawData($data);
}
}
return $invoices;
}
/**
* Get all of the available information for a single invoice. You 'll need the id of the invoice.
*
* @param string $id The id of the invoice.
* @return Invoice
*/
public function invoicesGet($id)
{
$rawData = $this->doCall('invoices/' . (string) $id . '.json');
if(empty($rawData)) return false;
return Invoice::initializeWithRawData($rawData);
}
/**
* Get the pdf for an invoice
*
* @param string $id The id of the invoice.
*
* @return string Raw PDF contents
*/
public function invoicesGetAsPdf($id)
{
$rawData = $this->doCall('invoices/' . (string) $id . '.pdf');
if (empty($rawData)) {
return false;
}
return $rawData;
}
/**
* Get all of the available information for a single invoice. You 'll need the iid of the invoice.
*
* @param string $iid The iid of the invoice.
* @return Invoice
*/
public function invoicesGetByIid($iid)
{
$rawData = $this->doCall('invoices/by_iid/' . (string) $iid . '.json');
if(empty($rawData)) return false;
return Invoice::initializeWithRawData($rawData);
}
/**
* Create a new invoice.
*
* @param Invoice $invoice The invoice information.
* @return Invoice
*/
public function invoicesCreate(Invoice $invoice)
{
if (($invoice->getVatException() && !$invoice->getVatDescription())
|| (!$invoice->getVatException() && $invoice->getVatDescription())) {
throw new InvalidArgumentException('Vat exception and vat description are required if one of them is filled');
}
$parameters['invoice'] = $invoice->toArray(true);
$rawData = $this->doCall('invoices.json', $parameters, 'POST');
return Invoice::initializeWithRawData($rawData);
}
/**
* Create a new credit note on invoice.
*
* @param string $id
* @param Invoice $creditNote The credit note information.
* @return Invoice
*/
public function invoicesCreateCreditNote($id, Invoice $creditNote)
{
$parameters['credit_note'] = $creditNote->toArray(true);
$rawData = $this->doCall('invoices/' . (string) $id . '/credit_notes.json', $parameters, 'POST');
return Invoice::initializeWithRawData($rawData);
}
/**
* Update an existing invoice
*
* @param string $id
* @param Invoice $invoice
* @return bool
*/
public function invoicesUpdate($id, Invoice $invoice)
{
$parameters['invoice'] = $invoice->toArray(true);
$rawData = $this->doCall('invoices/' . (string) $id . '.json', $parameters, 'PUT', true);
return ($rawData['http_code'] == 204);
}
/**
* Delete an invoice
*
* @param int $id
* @return bool
*/
public function invoicesDelete($id)
{
$rawData = $this->doCall('invoices/' . (string) $id . '.json', null, 'DELETE', true);
return ($rawData['http_code'] == 204);
}
/**
* Sending an invoice by mail.
*
* @param string $id
* @param string[optional] $to
* @param string[optional] $cc
* @param string[optional] $bcc
* @param string[optional] $subject
* @param string[optional] $text
* @return Mail
*/
public function invoiceSendByMail($id, $to = null, $cc = null, $bcc = null, $subject = null, $text = null)
{
$parameters = array();
if($to !== null) $parameters['mail']['to'] = (string) $to;
if($cc !== null) $parameters['mail']['cc'] = (string) $cc;
if($bcc !== null) $parameters['mail']['bcc'] = (string) $bcc;
if($subject !== null) $parameters['mail']['subject'] = (string) $subject;
if($text !== null) $parameters['mail']['text'] = (string) $text;
$rawData = $this->doCall('invoices/' . (string) $id . '/mails.json', $parameters, 'POST');
if(empty($rawData)) return false;
return Mail::initializeWithRawData($rawData);
}
/**
* Marking invoice as sent by mail.
*
* @param string $id
* @param string $email
*/
public function invoiceMarkAsSentByMail($id, $email)
{
$parameters = array();
$parameters['by'] = 'mail';
$parameters['to'] = $email;
$this->doCall('invoices/' . (string) $id . '/sent', $parameters, 'POST');
}
/**
* Adding a payment to an invoice.
*
* @param string $id
* @param Payment $payment
* @return Payment
*/
public function invoicesAddPayment($id, Payment $payment)
{
$parameters['payment'] = $payment->toArray(true);
$rawData = $this->doCall('invoices/' . (string) $id . '/payments.json', $parameters, 'POST');
return Payment::initializeWithRawData($rawData);
}
/**
* Send a reminder for an invoice
*
* @param string $id The invoice id
*
* @return array
*/
public function invoiceSendReminder($id)
{
$rawData = $this->doCall('invoices/' . (string) $id . '/reminders', array(), 'POST');
return $rawData;
}
/**
* Check if vat is required
*
* @param string $countryCode
* @param boolean $isCompany
* @return boolean
*/
public function invoicesVatRequired($countryCode, $isCompany)
{
$parameters['country_code'] = $countryCode;
$parameters['company'] = (bool) $isCompany;
$rawData = $this->doCall('invoices/vat_required.json', $parameters);
return $rawData['vat_required'];
}
/**
* Check if valid vat number
*
* @param string $vatNumber
* @return boolean
*/
public function isValidVat($vatNumber)
{
$parameters['vat'] = $vatNumber;
$rawData = $this->doCall('vat/verify.json', $parameters);
return $rawData['valid'];
}
/**
* Upload a CODA file and let Factr interpret it
*
* @param string $filePath The file path
*
* @return array
*/
public function uploadCodaFile($filePath)
{
$parameters = array(
'file' => '@' . $filePath,
'file_type' => 'coda',
);
$rawData = $this->doCall('payments/process_file.json', $parameters, 'POST');
return $rawData;
}
/**
* @return array
*/
public function products()
{
$products = array();
$rawData = $this->doCall('products.json');
if (!empty($rawData)) {
foreach ($rawData as $data) {
$products[] = Product::initializeWithRawData($data);
}
}
return $products;
}
/**
* @param int $id
*
* @return Product|bool
*/
public function productsGet($id)
{
$rawData = $this->doCall('products/' . (string) $id . '.json');
if (empty($rawData)) {
return false;
}
return Product::initializeWithRawData($rawData);
}
/**
* @param Product $product
*
* @return Product
*/
public function productsCreate(Product $product)
{
$parameters['product'] = $product->toArray();
$rawData = $this->doCall('products.json', $parameters, 'POST');
return Product::initializeWithRawData($rawData);
}
}