-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathDataService.php
More file actions
1985 lines (1764 loc) · 75.6 KB
/
DataService.php
File metadata and controls
1985 lines (1764 loc) · 75.6 KB
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*******************************************************************************
* Copyright (c) 2017 Intuit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
namespace QuickBooksOnline\API\DataService;
use QuickBooksOnline\API\Core\CoreHelper;
use QuickBooksOnline\API\Core\Http\Serialization\IEntitySerializer;
use QuickBooksOnline\API\Core\Http\Serialization\XmlObjectSerializer;
use QuickBooksOnline\API\Core\HttpClients\FaultHandler;
use QuickBooksOnline\API\Core\HttpClients\RestHandler;
use QuickBooksOnline\API\Core\ServiceContext;
use QuickBooksOnline\API\Core\CoreConstants;
use QuickBooksOnline\API\Core\HttpClients\SyncRestHandler;
use QuickBooksOnline\API\Core\HttpClients\RequestParameters;
use QuickBooksOnline\API\Core\Http\Serialization\JsonObjectSerializer;
use QuickBooksOnline\API\Core\Http\Serialization\SerializationFormat;
use QuickBooksOnline\API\Data\IPPAttachable;
use QuickBooksOnline\API\Data\IPPEntitlementsResponse;
use QuickBooksOnline\API\Data\IPPIntuitEntity;
use QuickBooksOnline\API\Data\IPPRecurringTransaction;
use QuickBooksOnline\API\Data\IPPTaxService;
use QuickBooksOnline\API\Data\IPPid;
use QuickBooksOnline\API\Exception\IdsException;
use QuickBooksOnline\API\Exception\ServiceException;
use QuickBooksOnline\API\Exception\IdsExceptionManager;
use QuickBooksOnline\API\Exception\SdkException;
use QuickBooksOnline\API\Diagnostics\TraceLevel;
use QuickBooksOnline\API\Diagnostics\ContentWriter;
use QuickBooksOnline\API\XSD2PHP\src\com\mikebevz\xsd2php\Php2Xml;
use QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2LoginHelper;
use QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken;
use QuickBooksOnline\API\Core\HttpClients\ClientFactory;
use QuickBooksOnline\API\Data\IPPCompanyInfo;
use QuickBooksOnline\API\Data\IPPPreferences;
/**
* Class DataServicd
*
* This file contains DataService performs CRUD operations on IPP REST APIs.
*/
class DataService
{
/**
* The METHOD UPDATE.
* @var String
*/
const UPDATE = 'update';
/**
* The METHOD FINDBYID.
* @var String
*/
const FINDBYID = 'FindById';
/**
* The METHOD ADD.
* @var String
*/
const ADD = 'Add';
/**
* The METHOD Delete.
* @var String
*/
const DELETE = 'Delete';
/**
* The METHOD VOID.
* @var String
*/
const VOID = 'Void';
/**
* The METHOD UPLOAD.
* @var String
*/
const UPLOAD = 'upload';
/**
* The METHOD SENDEMAIL.
* @var String
*/
const SENDEMAIL = 'SendEmail';
/**
* The Service context object.
* @var ServiceContext The service Context of the request
*/
private $serviceContext;
/**
* Rest Request Handler for actually sending the request
* @var SyncRestHandler
*/
private $restHandler;
/**
* Serializer needs to be used fore responce object
* @var IEntitySerializer
*/
private $responseSerializer;
/**
* Serializer needs to be used for request object
* @var IEntitySerializer
*/
private $requestSerializer;
/**
* If true, indicates a desire to echo verbose output
* @var bool
*/
private $verbose;
/**
* If not false, the request from last dataService did not return 2xx
* @var FaultHandler
*/
private $lastError = false;
/**
* The OAuth 2 Login helper for get RefreshToken
* @var OAuth2LoginHelper
*/
private $OAuth2LoginHelper;
/**
* A boolean value to decide if excetion will be thrown on non-200 request
* @var Boolean
*/
private $throwExceptionOnError = false;
/**
* The client to be used for HTTP request. You can choose either defaukt(cURL) or GuzzleHttpClient if that is available
* @var String
*/
private $clientName = CoreConstants::CLIENT_CURL;
/**
* Initializes a new instance of the DataService class. The old way to construct the dataService. Used by PHP SDK < 3.0.0
*
* @param ServiceContext $serviceContext IPP Service Context
* @throws SdkException
*/
public function __construct($serviceContext)
{
if (null == $serviceContext || !is_object($serviceContext)) {
throw new SdkException('Undefined ServiceContext. DataService constructor has NULL or Non_Object ServiceContext as Constructor');
}
$this->updateServiceContextSettingsForOthers($serviceContext);
}
/**
* Set the corresponding settings for the dataService based on ServiceContext
* @var ServiceContext $serviceContext The service Context for this DataService
*/
public function updateServiceContextSettingsForOthers($serviceContext)
{
$this->setupServiceContext($serviceContext);
$this->setupSerializers();
$this->useMinorVersion();
$this->setupRestHandler($serviceContext);
}
/**
* Set or Update the ServiceContext of this DataService.
*
* @var ServiceContext $serviceContext The new ServiceContext passed by.
* @return $this
*/
private function setupServiceContext($serviceContext)
{
$this->serviceContext = $serviceContext;
return $this;
}
/**
* Return the ServiceContext of this DataService
*
* @return ServiceContext
* @throws \Exception ServiceContext is NULL.
*/
public function getServiceContext()
{
if (isset($this->serviceContext)) {
return $this->serviceContext;
} else {
throw new SdkException("Trying to Return an Empty Service Context.");
}
}
/**
* Set the SyncRest Handler for the DataService. If the client Name changed, the underlying Client that SyncRestHandler used will also changed.
*
* @var ServiceContext $serviceContext The service Context for this DataService
* @return $this
*
*/
protected function setupRestHandler($serviceContext)
{
if(isset($serviceContext)){
$client = ClientFactory::createClient($this->getClientName());
$this->restHandler = new SyncRestHandler($serviceContext, $client);
}else{
throw new SdkException("Can not set the Rest Client based on null ServiceContext.");
}
return $this;
}
/**
* Return the current Client Name used by DataService
* @return String clientName
*/
public function getClientName(){
return $this->clientName;
}
/**
* PHP SDK currently only support XML for Object Serialization and Deserialization, except for Report Service
*
* @return $this
*/
public function useXml()
{
$serviceContext = $this->getServiceContext();
$serviceContext->useXml();
$this->updateServiceContextSettingsForOthers($serviceContext);
return $this;
}
/**
* PHP SDK currently only support XML for Object Serialization and Deserialization, except for Report Service
*
* @return $this
*/
public function useJson()
{
$serviceContext = $this->getServiceContext();
$serviceContext->useJson();
$this->updateServiceContextSettingsForOthers($serviceContext);
return $this;
}
/**
* Set a new directory for request and response log
*
* @param String $new_log_location The directory path for storing request and response log
*
* @return $this
*/
public function setLogLocation($new_log_location)
{
$restHandler = $this->restHandler;
$loggerUsedByRestHandler = $restHandler->getRequestLogger();
$loggerUsedByRestHandler->setLogDirectory($new_log_location);
return $this;
}
/**
* Set logging for OAuth calls
*
* @param Boolean $enableLogs Turns on logging for OAuthCalls
*
* @param Boolean $debugMode Turns on debug mode to log tokens
*
* @param String $new_log_location The directory path for storing request and response log
*
* @return $this
*/
public function setLogForOAuthCalls($enableLogs, $debugMode, $new_log_location)
{
$this->OAuth2LoginHelper->setLogForOAuthCalls($enableLogs, $debugMode, $new_log_location);
return $this;
}
/**
* Set a new Minor Version
*
* @param String $newMinorVersion The new minor version that passed
*
* @return $this
*/
public function setMinorVersion($newMinorVersion)
{
$serviceContext = $this->getServiceContext();
$serviceContext->setMinorVersion($newMinorVersion);
$this->updateServiceContextSettingsForOthers($serviceContext);
return $this;
}
/**
* Disable the logging function
*
* @return $this
*/
public function disableLog()
{
$restHandler = $this->restHandler;
$loggerUsedByRestHandler = $restHandler->getRequestLogger();
$loggerUsedByRestHandler->setLogStatus(false);
return $this;
}
/**
* Enable the logging function
*
* @return $this
*/
public function enableLog()
{
$restHandler = $this->restHandler;
$loggerUsedByRestHandler = $restHandler->getRequestLogger();
$loggerUsedByRestHandler->setLogStatus(true);
return $this;
}
/**
* Choose if want to throw exception when there is an non-200 http status code returned.
* @param Boolean $bool Turn on exception throwing error or not
*/
public function throwExceptionOnError($bool){
$this->throwExceptionOnError = $bool;
return $this;
}
/**
* Return the settings for thrown exception on non-200 error code
* @return Boolean Thrown Exception on Error or not
*/
public function isThrownExceptionOnError(){
return $this->throwExceptionOnError;
}
/**
* Return the client Name used by this DataSerivce
* @return String the Client Name. It can be curl or GuzzleHttpClient
* @deprecated since version 5.0.4
* @see $this->getClientName()
*/
public function getClinetName(){
return $this->getClientName();
}
/**
* The client Name can be either 'curl', 'guzzle', or 'guzzlehttp'.
*
* @param String $clientName The client Name used by the service
*
* @return $this
*/
public function setClientName($clientName){
$this->clientName = $clientName;
$serviceContext = $this->getServiceContext();
$this->setupRestHandler($serviceContext);
return $this;
}
/**
* New Static function for static Reading from Config or Passing Array
* The config needs to include
*
* @param $settings
* @return DataService
* @throws SdkException
* @throws SdkException
*/
public static function Configure($settings)
{
if (isset($settings)) {
if (is_array($settings)) {
$ServiceContext = ServiceContext::ConfigureFromPassedArray($settings);
if (!isset($ServiceContext)) {
throw new SdkException('Construct ServiceContext from OAuthSettigs failed.');
}
$DataServiceInstance = new DataService($ServiceContext);
} elseif (is_string($settings)) {
$ServiceContext = ServiceContext::ConfigureFromLocalFile($settings);
if (!isset($ServiceContext)) {
throw new SdkException('Construct ServiceContext from File failed.');
}
$DataServiceInstance = new DataService($ServiceContext);
}
if($ServiceContext->IppConfiguration->OAuthMode == CoreConstants::OAUTH2)
{
$oauth2Config = $ServiceContext->IppConfiguration->Security;
if($oauth2Config instanceof OAuth2AccessToken){
$DataServiceInstance->configureOAuth2LoginHelper($oauth2Config, $settings);
}else{
throw new SdkException("SDK Error. OAuth mode is not OAuth 2.");
}
}
return $DataServiceInstance;
} else {
throw new SdkException("Passed Null to Configure method. It expects either a file path for the config file or an array containing OAuth settings and BaseURL.");
}
}
/**
* After the ServiceContext is complete, also set the LoginHelper based on the ServiceContext.
* @param OAuth2AccessToken $oauth2Conifg OAuth 2 Token related information
* @param Array $settings The array that include the redirectURL, scope, state information
*/
private function configureOAuth2LoginHelper($oauth2Conifg, $settings)
{
$refreshToken = CoreConstants::getRefreshTokenFromArray($settings);
if(isset($refreshToken)){
//Login helper for refresh token API call
$this->OAuth2LoginHelper = new OAuth2LoginHelper(null,
null,
null,
null,
null,
$this->getServiceContext());
}else{
$redirectURL = CoreConstants::getRedirectURL($settings);
$scope = array_key_exists('scope', $settings) ? $settings['scope'] : null;
$state = array_key_exists('state', $settings) ? $settings['state'] : null;
$this->OAuth2LoginHelper = new OAuth2LoginHelper($oauth2Conifg->getClientID(),
$oauth2Conifg->getClientSecret(),
$redirectURL,
$scope,
$state);
}
}
/**
* Return the OAuth 2 Login Helper. The OAuth 2 Login helper can be used to generate OAuth code, get refresh Token, etc.
* @return $OAuth2LoginHelper A helper to get OAuth 2 related values.
*/
public function getOAuth2LoginHelper()
{
return $this->OAuth2LoginHelper;
}
/**
* Update the OAuth 2 Token that will be used for API calls later.
*
* @param OAuth2AccessToken $newOAuth2AccessToken The OAuth 2 Access Token that will be used later.
*
* @return $this
*/
public function updateOAuth2Token($newOAuth2AccessToken)
{
try{
$this->serviceContext->updateOAuth2Token($newOAuth2AccessToken);
$realmID = $newOAuth2AccessToken->getRealmID();
$this->serviceContext->realmId = $realmID;
$this->setupRestHandler($this->serviceContext);
} catch (SdkException $e){
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Error, "Encountered an error while updating OAuth2Token." . $e->getMessage());
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Error, "Stack Trace: " . $e->getTraceAsString());
}
return $this;
}
/**
* Get the error from last request
*
* @return FaultHandler lastError
*/
public function getLastError()
{
return $this->lastError;
}
/**
* Setups serializers objects for responces and requests based on service context
*/
public function setupSerializers()
{
$this->responseSerializer = CoreHelper::GetSerializer($this->serviceContext, false);
$this->requestSerializer = CoreHelper::GetSerializer($this->serviceContext, true);
}
private function useMinorVersion()
{
$version = $this->serviceContext->IppConfiguration->minorVersion;
if (is_numeric($version) && !empty($version)) {
$this->serviceContext->minorVersion = $version;
}
return $this;
}
/**
* @return string
*/
public function getMinorVersion()
{
return $this->serviceContext->minorVersion;
}
/**
* Force json serializers for request and response
*/
public function forceJsonSerializers()
{
$this->requestSerializer = new JsonObjectSerializer();
$this->responseSerializer = new JsonObjectSerializer();
}
/**
* Returns serializer for responce objects
* @return IEntitySerializer
*/
protected function getResponseSerializer()
{
return $this->responseSerializer;
}
/**
* Returns serializer for request objects
* @return IEntitySerializer
*/
protected function getRequestSerializer()
{
return $this->requestSerializer;
}
/**
* Marshall a POPO object to XML, presumably for inclusion on an IPP v3 API call
*
*
*
* @param object $phpObj inbound POPO object
* @return string XML output derived from POPO object
* @deprecated since version ?
*/
private function getXmlFromObj($phpObj)
{
if (!$phpObj) {
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Error, "getXmlFromObj NULL arg.");
return false;
}
$php2xml = new Php2Xml(CoreConstants::PHP_CLASS_PREFIX);
$php2xml->overrideAsSingleNamespace = 'http://schema.intuit.com/finance/v3';
try {
return $php2xml->getXml($phpObj);
} catch (\Exception $e) {
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Error, "Encountered an error parsing Object to XML." . $e->getMessage());
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Error, "Stack Trace: " . $e->getTraceAsString());
return false;
}
}
/**
* Decorate an IPP v3 Entity name (like 'Class') to be a POPO class name (like 'IPPClass')
*
* @param string Intuit Entity name
* @return string POPO class name
*/
private static function decorateIntuitEntityToPhpClassName($intuitEntityName)
{
$className = CoreConstants::PHP_CLASS_PREFIX . $intuitEntityName;
$className = trim($className);
return $className;
}
//Since we add the namespace, this one needs to be changed as well.
private static function getEntityResourceName($entity)
{
return strtolower(self::cleanPhpClassNameToIntuitEntityName(get_class($entity)));
}
/**
* Clean a POPO class name (like 'IPPClass') to be an IPP v3 Entity name (like 'Class')
*
* @param string $phpClassName POPO class name
* @return string|null Intuit Entity name
*/
private static function cleanPhpClassNameToIntuitEntityName($phpClassName)
{
$phpClassName = self::removeNameSpaceFromPhpClassName($phpClassName);
if (0 == strpos($phpClassName, CoreConstants::PHP_CLASS_PREFIX)) {
return substr($phpClassName, strlen(CoreConstants::PHP_CLASS_PREFIX));
}
return null;
}
/**
* Remove the Namespace from a php class name
*
* @param string $phpClassName QuickBooksOnline\API\Data\...
* @return string ipp...
*/
private static function removeNameSpaceFromPhpClassName($phpClassName)
{
$lists = explode('\\', $phpClassName);
$ippEntityName = end($lists);
return $ippEntityName;
}
/**
* Using the @entity and @uri to generate Request.
* Response will parsed. It will store any Error Code in 3xx to 5xx level.
*
* @param IPPIntuitEntity $entity
* @param string $uri
* @param string $httpsPostBody
* @param string $CALLINGMETHOD
* @param string|null $boundaryString
* @param string|null $email
* @return null|string
*/
private function sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, $httpsPostBody, $CALLINGMETHOD, $boundaryString = null, $email = null)
{
if ($this->isCreditCardPaymentTxn($entity)) {
$uri = str_replace("creditcardpaymenttxn", "creditcardpayment", $uri);
}
switch ($CALLINGMETHOD) {
case DataService::DELETE:
case DataService::ADD:
case DataService::VOID:
case DataService::UPDATE:
$requestParameters = $this->initPostRequest($entity, $uri);
break;
case DataService::FINDBYID:
if ($this->serviceContext->IppConfiguration->Message->Request->SerializationFormat == SerializationFormat::Json) {
$requestParameters = new RequestParameters($uri, 'GET', CoreConstants::CONTENTTYPE_APPLICATIONJSON, null);
} else {
$requestParameters = new RequestParameters($uri, 'GET', CoreConstants::CONTENTTYPE_APPLICATIONXML, null);
}
break;
case DataService::UPLOAD:
if (!isset($boundaryString)) {
throw new \Exception("Upload Image has unset value: boundaryString.");
}
// Creates request parameters
$requestParameters = $this->getPostRequestParameters($uri, "multipart/form-data; boundary={$boundaryString}");
break;
case DataService::SENDEMAIL:
$requestParameters = $this->getPostRequestParameters($uri . (is_null($email) ? '' : '?sendTo=' . urlencode($email)), CoreConstants::CONTENTTYPE_OCTETSTREAM);
break;
}
$restRequestHandler = $this->getRestHandler();
list($responseCode, $responseBody) = $restRequestHandler->sendRequest($requestParameters, $httpsPostBody, null, $this->isThrownExceptionOnError());
$faultHandler = $restRequestHandler->getFaultHandler();
if ($faultHandler) {
$this->lastError = $faultHandler;
return null;
} else {
$this->lastError = false;
if (strcmp($CALLINGMETHOD, DataService::ADD) == 0) {
$responseBody = $this->fixTaxServicePayload($entity, $responseBody);
}
try {
$parsedResponseBody = $this->getResponseSerializer()->Deserialize($responseBody, true);
} catch (\Exception $e) {
return new \Exception("Exception in deserialize ResponseBody.");
}
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Finished Executing Method " . $CALLINGMETHOD);
return $parsedResponseBody;
}
}
/**
* Updates an entity under the specified realm. The realm must be set in the context.
*
* @param IPPIntuitEntity $entity Entity to Update.
* @return IPPIntuitEntity Returns an updated version of the entity with updated identifier and sync token.
* @throws IdsException
*/
public function Update($entity)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method: Update.");
// Validate parameter
if (!$entity) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
$this->verifyOperationAccess($entity, __FUNCTION__);
$httpsPostBody = $this->executeObjectSerializer($entity, $urlResource);
// Builds resource Uri
// Handle some special cases
if ((strtolower('preferences') == strtolower($urlResource)) &&
(CoreConstants::IntuitServicesTypeQBO == $this->serviceContext->serviceType)
) {
// URL format for *QBO* prefs request is different than URL format for *QBD* prefs request
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource));
}
//We no longer support QBD on PHP SDK The code is removed.
/*else if ((strtolower('company') == strtolower($urlResource)) &&
(CoreConstants::IntuitServicesTypeQBO == $this->serviceContext->serviceType)) {
// URL format for *QBD* companyinfo request is different than URL format for *QBO* companyinfo request
$urlResource = 'companyInfo';
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource . '?operation=update'));
}*/ else {
// Normal case
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource . '?operation=update'));
}
// Send Request and return response
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, $httpsPostBody, DataService::UPDATE);
}
/**
* The Read request. You can either pass an object that contains the Id that you want to read, or
* pass the Entity Name and the Id.
* Before v4.0.0, it supports the read of CompanyInfo and Preferences.
* After v4.0.0, it DOES NOT support read of CompanyInfo or Preferences. Please use getCompanyInfo() or getCompanyPreferences() method instead.
* Only use this one to do READ request with ID.
*
* Developer has two ways to call the GET request. Take Invoice for an example:
* 1) FindById($invoice);
* or
* 2) FindById("invoice", 1);
*
* @param object|String $entity Entity to Find, or the String Name of the Entity
* @return IPPIntuitEntity Returns an entity of specified Id.
* @throws IdsException
*/
public function FindById($entity, $Id = null)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method FindById.");
if(is_object($entity)){
$httpsPostBody = $this->executeObjectSerializer($entity, $urlResource);
// Validate parameter
if (!$entity || !$entity->Id) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception when calling FindById for Endpoint:' . get_class($entity));
}
$this->verifyOperationAccess($entity, __FUNCTION__);
$entityId = $this->getIDString($entity->Id);
// Normal case
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource, $entityId));
// Send request
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, null, DataService::FINDBYID);
}else if(is_string($entity) && isset($Id)){
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, strtolower($entity), $Id));
if ($this->isCreditCardPaymentTxn($entity)) {
$uri = str_replace("creditcardpaymenttxn", "creditcardpayment", $uri);
}
$requestParameters = new RequestParameters($uri, 'GET', CoreConstants::CONTENTTYPE_APPLICATIONXML, null);
$restRequestHandler = $this->getRestHandler();
list($responseCode, $responseBody) = $restRequestHandler->sendRequest($requestParameters, null, null, $this->isThrownExceptionOnError());
$faultHandler = $restRequestHandler->getFaultHandler();
//$faultHandler now is true or false
if ($faultHandler) {
$this->lastError = $faultHandler;
return null;
} else {
//clean the error
$this->lastError = false;
$parsedResponseBody = $this->getResponseSerializer()->Deserialize($responseBody, true);
return $parsedResponseBody;
}
}
}
/**
* Creates an entity under the specified realm. The realm must be set in the context.
*
* @param IPPIntuitEntity $entity Entity to Create.
* @return IPPIntuitEntity Returns the created version of the entity.
* @throws IdsException
*/
public function Add($entity)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method Add.");
// Validate parameter
if (!$entity) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
$this->verifyOperationAccess($entity, __FUNCTION__);
if ($this->isJsonOnly($entity)) {
$this->forceJsonSerializers();
}
$httpsPostBody = $this->executeObjectSerializer($entity, $urlResource);
// Builds resource Uri
$resourceURI = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource));
$uri = $this->handleTaxService($entity, $resourceURI);
// Send request
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, $httpsPostBody, DataService::ADD);
}
/**
* Deletes an entity under the specified realm. The realm must be set in the context.
*
* @param IPPIntuitEntity $entity Entity to Delete.
* @return null|string
* @throws IdsException
*/
public function Delete($entity)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method Delete.");
// Validate parameter
if (!$entity) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
$this->verifyOperationAccess($entity, __FUNCTION__);
// Builds resource Uri
$httpsPostBody = $this->executeObjectSerializer($entity, $urlResource);
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource . '?operation=delete'));
// Creates request
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, $httpsPostBody, DataService::DELETE);
}
/**
* Voids an entity under the specified realm. The realm must be set in the context.
*
* @param IPPIntuitEntity $entity Entity to Void.
* @return null|string
* @throws IdsException
*/
public function Void($entity)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method Void.");
// Validate parameter
if (!$entity) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
$this->verifyOperationAccess($entity, __FUNCTION__);
// Builds resource Uri
$httpsPostBody = $this->executeObjectSerializer($entity, $urlResource);
$className = $this->getEntityResourceName($entity);
if(in_array($className, CoreConstants::PAYMENTCLASSNAME)) {
$appendString = CoreConstants::VOID_QUERYPARAMETER_PAYMENT;
} else{
$appendString = CoreConstants::VOID_QUERYPARAMETER_GENERAL;
}
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource . $appendString));
// Creates request
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, $httpsPostBody, DataService::VOID);
}
/**
* Uploads an attachment to an Entity on QuickBooks Online. For security reason, text file is not supported for uploading.
*
* @param string $bits Encoded Base64 bytes for the attachment
* @param string $fileName Filename to use for this file
* @param string $mimeType MIME type to send in the HTTP Headers
* @param IPPAttachable $objAttachable Entity including the attachment, it can be invoice, bill, etc
* @return array Returns an array of entities fulfilling the query.
* @throws IdsException
*/
public function Upload($imgBits, $fileName, $mimeType, $objAttachable)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method Upload.");
// Validate parameter
if (!$imgBits || !$mimeType || !$fileName) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
// Builds resource Uri
$urlResource = "upload";
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource));
$boundaryString = md5(time());
$MetaData = $this->executeObjectSerializer($objAttachable, $urlResource);
$desiredIdentifier = '0';
$newline = "\r\n";
$dataMultipart = '';
$dataMultipart .= '--' . $boundaryString . $newline;
$dataMultipart .= "Content-Disposition: form-data; name=\"file_metadata_{$desiredIdentifier}\"" . $newline;
$dataMultipart .= "Content-Type: " . CoreConstants::CONTENTTYPE_APPLICATIONXML . '; charset=UTF-8' . $newline;
$dataMultipart .= 'Content-Transfer-Encoding: 8bit' . $newline . $newline;
$dataMultipart .= $MetaData;
$dataMultipart .= '--' . $boundaryString . $newline;
$dataMultipart .= "Content-Disposition: form-data; name=\"file_content_{$desiredIdentifier}\"; filename=\"{$fileName}\"" . $newline;
$dataMultipart .= "Content-Type: {$mimeType}" . $newline;
$dataMultipart .= 'Content-Transfer-Encoding: base64' . $newline . $newline;
$dataMultipart .= chunk_split($imgBits) . $newline;
$dataMultipart .= "--" . $boundaryString . "--" . $newline . $newline; // finish with two eol's!!
return $this->sendRequestParseResponseBodyAndHandleHttpError(null, $uri, $dataMultipart, DataService::UPLOAD, $boundaryString);
}
/**
* Returns PDF for entities which can be downloaded as PDF
* @param IPPIntuitEntity $entity
* @param Directory a writable directory for the PDF to be saved.
* @return boolean
* @throws IdsException, SdkException
*
*/
public function DownloadPDF($entity, $dir=null, $returnPdfString = false)
{
$this->validateEntityId($entity);
$this->verifyOperationAccess($entity, __FUNCTION__);
//Find the ID
$entityID = $this->getIDString($entity->Id);
$uri = implode(CoreConstants::SLASH_CHAR, array('company',
$this->serviceContext->realmId,
self::getEntityResourceName($entity),
$entityID,
CoreConstants::getType(CoreConstants::CONTENTTYPE_APPLICATIONPDF)));
$requestParameters = $this->getGetRequestParameters($uri, CoreConstants::CONTENTTYPE_APPLICATIONPDF);
$restRequestHandler = $this->getRestHandler();
list($responseCode, $responseBody) = $restRequestHandler->sendRequest($requestParameters, null, null, $this->isThrownExceptionOnError());
$faultHandler = $restRequestHandler->getFaultHandler();
if ($faultHandler) {
$this->lastError = $faultHandler;
//Add allow for through exception if users set it up
return null;
} elseif ($returnPdfString) {
return $responseBody;
} else {
$this->lastError = false;
return $this->processDownloadedContent(new ContentWriter($responseBody), $responseCode, $dir, $this->getExportFileNameForPDF($entity, "pdf"));
}
}
/**
* Sends entity by email for entities that have this operation
*
* @param IPPIntuitEntity $entity
* @param string|null $email
* @return boolean
* @throws IdsException, SdkException
*
*/
public function SendEmail($entity, $email = null)
{
$this->validateEntityId($entity);
$this->verifyOperationAccess($entity, __FUNCTION__);
$entityId=$this->getIDString($entity->Id);
$uri = implode(CoreConstants::SLASH_CHAR, array('company',
$this->serviceContext->realmId,
self::getEntityResourceName($entity),
$entityId,
'send'));
if (is_null($email)) {
$this->logInfo("Entity " . get_class($entity) . " with id=" . $entityId . " is using default email");
} else {
$this->logInfo("Entity " . get_class($entity) . " with id=" . $entityId . " is using $email");
if (!$this->verifyEmailAddress($email)) {
$this->logError("Valid email is expected, but received $email");
throw new SdkException("Valid email is expected, but received $email");
}
}
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, null, DataService::SENDEMAIL, null, $email);
}
/**
* Retrieves specified entities based passed page number and page size and query
*
* @param string $query Query to issue
* @param int $startPosition Starting page number
* @param int $maxResults Page size
* @param string $includes A list of additional fields requested in the entities response
* @return array Returns an array of entities fulfilling the query. If the response is Empty, it will return NULL
*/
public function Query($query, $startPosition = null, $maxResults = null, $includes = null)
{